mirror of
https://github.com/OpenListTeam/OpenList.git
synced 2026-10-10 21:13:10 +08:00
Compare commits
240 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 136e107463 | |||
| 7b4d4454a8 | |||
| 23164ac7f2 | |||
| f18b4acc76 | |||
| d6109a7940 | |||
| 0463da4034 | |||
| 2d51c9ab4b | |||
| d9d8aa24e6 | |||
| 55530ff171 | |||
| 6247cf7be2 | |||
| eee910babb | |||
| 6b55a82ffe | |||
| 93dac1655f | |||
| 6ad44605c0 | |||
| d90d84906e | |||
| c3d3da9286 | |||
| 2bdf16d596 | |||
| f8ebaec4f1 | |||
| fc23f4e781 | |||
| 3ea9984aea | |||
| cc11f354f1 | |||
| 8869874b76 | |||
| 523af855ba | |||
| bba3516693 | |||
| f244adf60e | |||
| ce87b45d2d | |||
| 4031b31837 | |||
| 9b34ca5bf1 | |||
| 666b1a039d | |||
| 8f9a09d359 | |||
| 394bb8f80e | |||
| 819fdbd518 | |||
| d220b8b005 | |||
| d12bd4c71e | |||
| 4c611ef8de | |||
| eea8fee7f1 | |||
| c06656958c | |||
| 0d277b8550 | |||
| e0e4de5e82 | |||
| 39fcaf488b | |||
| 31ae0f5bc9 | |||
| 3943180898 | |||
| b1cc7c6a93 | |||
| f6557f3d62 | |||
| 9dc6cb29d9 | |||
| b86e4cb8dc | |||
| fd7fb04ed1 | |||
| 80795b8ec3 | |||
| c2b3666818 | |||
| edbf42898b | |||
| ab51cd6eae | |||
| 4619aa2bc5 | |||
| 376cada3d4 | |||
| 1a6cabf45a | |||
| 0b1e9d0943 | |||
| 18823a23d5 | |||
| 150a90f2ac | |||
| e80ee006ad | |||
| 89077c35a7 | |||
| cc87e88f03 | |||
| 7e9082f90e | |||
| 6d4ad58678 | |||
| d8ad28f5b7 | |||
| 2e27852952 | |||
| 194f941f15 | |||
| ec1f968de1 | |||
| c97173286c | |||
| cca773f07b | |||
| a4ae2acb65 | |||
| f68f3e9f4a | |||
| 6f80df2827 | |||
| 940b69fe38 | |||
| f2f7ee4107 | |||
| cf931d4760 | |||
| be708292eb | |||
| 78f2f0b25d | |||
| 6b92cbd21f | |||
| 84ecda35aa | |||
| 2deb16b26e | |||
| 8495470e63 | |||
| fe56ca483d | |||
| e83835dd80 | |||
| 791a27e2ac | |||
| 28cea1fb2b | |||
| 0a9e71ae67 | |||
| a21bc8bd0f | |||
| bacd087096 | |||
| e1ded83d5f | |||
| ff3cb8b931 | |||
| 7aea393a6d | |||
| 36168c86a0 | |||
| 24332e371f | |||
| 6b702afc0f | |||
| 78db0f7aff | |||
| e469693114 | |||
| 5961289b83 | |||
| 0527dc41af | |||
| b1d298d192 | |||
| 651b5cea1c | |||
| 5aeaf7a8c8 | |||
| 651da18da4 | |||
| 5a5d8d6e0e | |||
| 061c1e2e1e | |||
| caed356200 | |||
| 74af297471 | |||
| 7c54b0e3e4 | |||
| a632356902 | |||
| 82ea8d0d01 | |||
| eb48671202 | |||
| f3e74fbdf1 | |||
| e670322ee3 | |||
| 8930e1945e | |||
| daaba0d7ea | |||
| a81f54488f | |||
| 59bd343140 | |||
| 757f9d383d | |||
| 7ded6dfe2c | |||
| a283f2b52a | |||
| bb3bc31609 | |||
| 744021d80d | |||
| 94eac2e91e | |||
| a92d59d35c | |||
| fcae009bd3 | |||
| f63a5e15ee | |||
| d85980d3d9 | |||
| c8306256ff | |||
| 5273a77854 | |||
| cc3d8a06a7 | |||
| 925a2422d6 | |||
| 33015eee9f | |||
| 1be74776f6 | |||
| 31810f556c | |||
| 30922b6d52 | |||
| 759adfca21 | |||
| bfbc441fa6 | |||
| 866793f485 | |||
| 40b39000ab | |||
| 6eedff851c | |||
| aea77c5967 | |||
| 009d834e71 | |||
| e9ea991584 | |||
| d4aa8b6a15 | |||
| 9e55a0111b | |||
| f869afc71f | |||
| e960035b65 | |||
| a0f001c168 | |||
| c8e7f35761 | |||
| 6ed7db1ee7 | |||
| 5a12c8d2ba | |||
| b86d10fa2f | |||
| aa534a955b | |||
| d403f75da2 | |||
| 3abdf7990b | |||
| 3b017c2b5c | |||
| a42e367660 | |||
| f45473357e | |||
| dcfefce85d | |||
| d349765617 | |||
| ace7482bc2 | |||
| eadf03a4f8 | |||
| da84a800ab | |||
| b05a51a062 | |||
| ffe3f3cfa3 | |||
| 7e55f11e4a | |||
| e7bccc636a | |||
| b7f9e8ef0a | |||
| d7c332ca13 | |||
| 64d39114ee | |||
| 88d256de73 | |||
| 5a92dc2834 | |||
| 726bbf4bd2 | |||
| bd6cf5bc1e | |||
| 089315118d | |||
| 9737006a8d | |||
| 054db9f5eb | |||
| 9b587ee165 | |||
| 9282e8ef09 | |||
| ac80fe19bf | |||
| cd6643a642 | |||
| ba6f96ca4e | |||
| 9cc5dd969b | |||
| 98c32d3be4 | |||
| 4c77b9c7bf | |||
| 3b1760e959 | |||
| b28208bd76 | |||
| ffbbc1ccdf | |||
| 1d071c0fd8 | |||
| 948e87159d | |||
| c3df8da577 | |||
| 7cfb25558f | |||
| 31b41f99f8 | |||
| 9eae62581a | |||
| daad21ef91 | |||
| 219564b56c | |||
| ea19bed247 | |||
| b6db83ed5e | |||
| 0726d16632 | |||
| 7feec2b7d9 | |||
| c7c0cfaeb7 | |||
| d3a6b06566 | |||
| e87e028a49 | |||
| bfda719e64 | |||
| 7e37c40516 | |||
| e28406fa2c | |||
| 9033b5502d | |||
| 07506b003e | |||
| 201a206ed9 | |||
| 2d2d9ae213 | |||
| 376638978a | |||
| 29ec90e8e8 | |||
| ece1518eac | |||
| a5ba6a0e9d | |||
| 331f575c17 | |||
| b31ae9c9f6 | |||
| 8d39d636be | |||
| da26e72bee | |||
| e11b8a82e7 | |||
| 12c9bdbd56 | |||
| 9e49adc353 | |||
| 9fdba3a730 | |||
| 7bea29c18e | |||
| 29447a41a3 | |||
| d85f084acb | |||
| d598ef7569 | |||
| e41b683efb | |||
| 9a2ba1dabe | |||
| f3428e65bc | |||
| 5eaef96078 | |||
| b5626b275b | |||
| 795a18b565 | |||
| 82ae2d5890 | |||
| db0e2ec103 | |||
| e0ee737080 | |||
| 0673a74302 | |||
| a8d1c0ddbf | |||
| 8431c1b1e3 | |||
| a121f861dc | |||
| 6861cb4c3b | |||
| 5d9fc8359d | |||
| f542187654 |
@@ -13,7 +13,7 @@ body:
|
||||
attributes:
|
||||
label: 请确认以下事项
|
||||
description: |
|
||||
您必须阅读并检查以下内容,否则您的问题一定会被直接关闭。
|
||||
您必须阅读、检查、确认、同意以下内容,否则您的问题一定会被直接关闭。
|
||||
或者您可以去[讨论区](https://github.com/OpenListTeam/OpenList/discussions)。
|
||||
options:
|
||||
- label: |
|
||||
@@ -35,8 +35,7 @@ body:
|
||||
- label: |
|
||||
我已确认这个问题在最新版本中没有被修复。
|
||||
- label: |
|
||||
我没有阅读这个清单,只是闭眼选中了所有的复选框,请关闭这个 Issue
|
||||
|
||||
我没有阅读这个清单,只是闭眼选中了所有的复选框,请关闭这个 Issue 。
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
@@ -83,3 +82,17 @@ body:
|
||||
label: 复现链接(可选)
|
||||
description: |
|
||||
请提供能复现此问题的链接。
|
||||
- type: checkboxes
|
||||
id: aigenerated
|
||||
attributes:
|
||||
label: AI生成内容
|
||||
description: 必须且只能勾选一项,请勿删除或修改声明文字。
|
||||
options:
|
||||
- label: 我使用了AI工具生成此内容
|
||||
- label: 我没有使用AI工具生成此内容
|
||||
- type: input
|
||||
id: ai-model
|
||||
attributes:
|
||||
label: AI模型是
|
||||
description: 如果使用了AI工具,请填写模型名称;未使用则留空。
|
||||
placeholder: xxx
|
||||
|
||||
@@ -13,7 +13,7 @@ body:
|
||||
attributes:
|
||||
label: Please confirm the following
|
||||
description: |
|
||||
You must read and check all the following, otherwise your issue will definitely be closed directly.
|
||||
You must read, check, confirm, and agree to all the following, otherwise your issue will definitely be closed directly.
|
||||
Or you can go to the [discussions](https://github.com/OpenListTeam/OpenList/discussions).
|
||||
options:
|
||||
- label: |
|
||||
@@ -35,8 +35,7 @@ body:
|
||||
- label: |
|
||||
I confirm this issue is not fixed in the latest version.
|
||||
- label: |
|
||||
I have not read these checkboxes and therefore I just ticked them all, Please close this issue
|
||||
|
||||
I have not read these checkboxes and therefore I just ticked them all, Please close this issue.
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
@@ -83,3 +82,17 @@ body:
|
||||
label: Reproduction Link (optional)
|
||||
description: |
|
||||
Please provide a link to a repo or page that can reproduce this issue.
|
||||
- type: checkboxes
|
||||
id: aigenerated
|
||||
attributes:
|
||||
label: AI Generated Content
|
||||
description: Select exactly one option. Do not delete or modify the disclosure text.
|
||||
options:
|
||||
- label: I used AI tools to generate this content
|
||||
- label: I did not use AI tools to generate this content
|
||||
- type: input
|
||||
id: ai-model
|
||||
attributes:
|
||||
label: AI model used
|
||||
description: If you used AI tools, enter the model name; otherwise leave this blank.
|
||||
placeholder: xxx
|
||||
|
||||
@@ -7,7 +7,7 @@ body:
|
||||
attributes:
|
||||
label: 请确认以下事项
|
||||
description: |
|
||||
您必须勾选以下内容,否则您的问题可能会被直接关闭。
|
||||
您必须阅读、检查、确认、同意以下内容,否则您的问题可能会被直接关闭。
|
||||
或者您可以去[讨论区](https://github.com/OpenListTeam/OpenList/discussions)。
|
||||
options:
|
||||
- label: |
|
||||
@@ -28,6 +28,8 @@ body:
|
||||
我已确认此功能尚未被实现。
|
||||
- label: |
|
||||
我已确认此功能是合理的,且有普遍需求,并非我个人需要。
|
||||
- label: |
|
||||
我没有阅读这个清单,只是闭眼选中了所有的复选框,请关闭这个 Issue 。
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
attributes:
|
||||
@@ -46,3 +48,17 @@ body:
|
||||
label: 附加信息
|
||||
description: |
|
||||
相关的任何其他上下文或截图,或者你觉得有帮助的信息
|
||||
- type: checkboxes
|
||||
id: aigenerated
|
||||
attributes:
|
||||
label: AI生成内容
|
||||
description: 必须且只能勾选一项,请勿删除或修改声明文字。
|
||||
options:
|
||||
- label: 我使用了AI工具生成此内容
|
||||
- label: 我没有使用AI工具生成此内容
|
||||
- type: input
|
||||
id: ai-model
|
||||
attributes:
|
||||
label: AI模型是
|
||||
description: 如果使用了AI工具,请填写模型名称;未使用则留空。
|
||||
placeholder: xxx
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
name: "Feature Request"
|
||||
description: Feature Request / Enhancement
|
||||
title: "[Feature] Please change the title to your feature name"
|
||||
title: "[Feature] Please modify the title to your feature name"
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Please confirm the following
|
||||
description: |
|
||||
You must check all the following, otherwise your request may be closed directly.
|
||||
You must read, check, confirm, and agree to all the following, otherwise your request may be closed directly.
|
||||
Or you can go to the [discussions](https://github.com/OpenListTeam/OpenList/discussions).
|
||||
options:
|
||||
- label: |
|
||||
@@ -28,6 +28,8 @@ body:
|
||||
I confirm this feature has not been implemented yet.
|
||||
- label: |
|
||||
I confirm this feature is reasonable and has general demand, not just my personal need.
|
||||
- label: |
|
||||
I have not read these checkboxes and therefore I just ticked them all, Please close this issue.
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
attributes:
|
||||
@@ -46,3 +48,17 @@ body:
|
||||
label: Additional Information
|
||||
description: |
|
||||
Any other context or screenshots related to this feature request, or information you find helpful.
|
||||
- type: checkboxes
|
||||
id: aigenerated
|
||||
attributes:
|
||||
label: AI Generated Content
|
||||
description: Select exactly one option. Do not delete or modify the disclosure text.
|
||||
options:
|
||||
- label: I used AI tools to generate this content
|
||||
- label: I did not use AI tools to generate this content
|
||||
- type: input
|
||||
id: ai-model
|
||||
attributes:
|
||||
label: AI model used
|
||||
description: If you used AI tools, enter the model name; otherwise leave this blank.
|
||||
placeholder: xxx
|
||||
|
||||
@@ -1,56 +1,114 @@
|
||||
<!--
|
||||
Provide a general summary of your changes in the Title above.
|
||||
The PR title must start with `feat(): `, `docs(): `, `fix(): `, `style(): `, or `refactor(): `, `chore(): `. For example: `feat(component): add new feature`.
|
||||
If it spans multiple components, use the main component as the prefix and enumerate in the title, describe in the body.
|
||||
-->
|
||||
<!--
|
||||
在上方标题中提供您更改的总体摘要。
|
||||
PR 标题需以 `feat(): `, `docs(): `, `fix(): `, `style(): `, `refactor(): `, `chore(): ` 其中之一开头,例如:`feat(component): 新增功能`。
|
||||
如果跨多个组件,请使用主要组件作为前缀,并在标题中枚举、描述中说明。
|
||||
PR title / PR 标题:
|
||||
- Use Conventional Commits: `type(scope): summary`
|
||||
- Allowed types: `feat`, `docs`, `fix`, `style`, `refactor`, `chore`
|
||||
- Scope is required by the current PR title check.
|
||||
- For breaking changes, add `!`: `feat(driver)!: change auth flow`
|
||||
-->
|
||||
|
||||
## Description / 描述
|
||||
## Summary / 摘要
|
||||
|
||||
<!-- Describe your changes in detail -->
|
||||
<!-- 详细描述您的更改 -->
|
||||
<!--
|
||||
Briefly describe what changed and why.
|
||||
简要说明改了什么,以及为什么需要改。
|
||||
-->
|
||||
|
||||
## Motivation and Context / 背景
|
||||
<!--
|
||||
- List user-visible behavior changes.
|
||||
- List important implementation changes.
|
||||
- Mention config, storage, API, or compatibility changes if any.
|
||||
|
||||
<!-- Why is this change required? What problem does it solve? -->
|
||||
<!-- 为什么需要此更改?它解决了什么问题? -->
|
||||
- 列出用户可感知的行为变化。
|
||||
- 列出重要实现变化。
|
||||
- 如涉及配置、存储、API 或兼容性变化,请明确说明。
|
||||
-->
|
||||
|
||||
<!-- If it fixes an open issue, please link to the issue here. -->
|
||||
<!-- 如果修复了一个打开的issue,请在此处链接到该issue -->
|
||||
- [ ] This PR has breaking changes.
|
||||
/ 此 PR 包含破坏性变更。
|
||||
- [ ] This PR changes public API, config, storage format, or migration behavior.
|
||||
/ 此 PR 修改了公开 API、配置、存储格式或迁移行为。
|
||||
- [ ] This PR requires corresponding changes in related repositories.
|
||||
/ 此 PR 需要关联仓库同步修改。
|
||||
|
||||
Closes #XXXX
|
||||
Related repository PRs / 关联仓库 PR:
|
||||
|
||||
<!-- or -->
|
||||
<!-- 或者 -->
|
||||
- OpenList-Frontend:
|
||||
- OpenList-Docs:
|
||||
|
||||
Relates to #XXXX
|
||||
## Related Issues / 关联 Issue
|
||||
|
||||
## How Has This Been Tested? / 测试
|
||||
<!--
|
||||
Use `Closes #123`, `Fixes #123`, or `Relates to #123`.
|
||||
Remove this section if not applicable.
|
||||
使用 `Closes #123`、`Fixes #123` 或 `Relates to #123`。
|
||||
不适用时请删除本节。
|
||||
-->
|
||||
|
||||
<!-- Please describe in detail how you tested your changes. -->
|
||||
<!-- 请详细描述您如何测试更改 -->
|
||||
## Testing / 测试
|
||||
|
||||
<!--
|
||||
Describe commands, platforms, and manual checks.
|
||||
If not tested, explain why.
|
||||
|
||||
说明执行过的命令、测试平台和手动验证。
|
||||
如果未测试,请说明原因。
|
||||
-->
|
||||
|
||||
- [ ] `go test ./...`
|
||||
- [ ] Manual test / 手动测试:
|
||||
|
||||
## Checklist / 检查清单
|
||||
|
||||
<!-- Go over all the following points, and put an `x` in all the boxes that apply. -->
|
||||
<!-- 检查以下所有要点,并在所有适用的框中打`x` -->
|
||||
- [ ] I have read [CONTRIBUTING](https://github.com/OpenListTeam/OpenList/blob/main/CONTRIBUTING.md).
|
||||
/ 我已阅读 [CONTRIBUTING](https://github.com/OpenListTeam/OpenList/blob/main/CONTRIBUTING.md)。
|
||||
- [ ] I confirm this contribution follows the repository license, contribution policy, and code of conduct.
|
||||
/ 我确认此贡献符合仓库许可证、贡献规范和行为准则。
|
||||
- [ ] I have formatted the changed code with `gofmt`, `go fmt`, or `prettier` where applicable.
|
||||
/ 我已按适用情况使用 `gofmt`、`go fmt` 或 `prettier` 格式化变更代码。
|
||||
- [ ] I have requested review from relevant maintainers or code owners where applicable.
|
||||
/ 我已在适用情况下请求相关维护者或代码所有者审查。
|
||||
|
||||
<!-- If you're unsure about any of these, don't hesitate to ask. We're here to help! -->
|
||||
<!-- 如果您对其中任何一项不确定,请不要犹豫提问。我们会帮助您! -->
|
||||
## AI Disclosure / AI 使用声明
|
||||
|
||||
- [ ] I have read the [CONTRIBUTING](https://github.com/OpenListTeam/OpenList/blob/main/CONTRIBUTING.md) document.
|
||||
我已阅读 [CONTRIBUTING](https://github.com/OpenListTeam/OpenList/blob/main/CONTRIBUTING.md) 文档。
|
||||
- [ ] I have formatted my code with `go fmt` or [prettier](https://prettier.io/).
|
||||
我已使用 `go fmt` 或 [prettier](https://prettier.io/) 格式化提交的代码。
|
||||
- [ ] I have added appropriate labels to this PR (or mentioned needed labels in the description if lacking permissions).
|
||||
我已为此 PR 添加了适当的标签(如无权限或需要的标签不存在,请在描述中说明,管理员将后续处理)。
|
||||
- [ ] I have requested review from relevant code authors using the "Request review" feature when applicable.
|
||||
我已在适当情况下使用"Request review"功能请求相关代码作者进行审查。
|
||||
- [ ] I have updated the repository accordingly (If it’s needed).
|
||||
我已相应更新了相关仓库(若适用)。
|
||||
- [ ] [OpenList-Frontend](https://github.com/OpenListTeam/OpenList-Frontend) #XXXX
|
||||
- [ ] [OpenList-Docs](https://github.com/OpenListTeam/OpenList-Docs) #XXXX
|
||||
<!--
|
||||
Please disclose any substantial AI assistance used in this PR.
|
||||
Minor AI assistance, such as typo fixes, autocomplete, formatting suggestions,
|
||||
or wording polish, does not need to be disclosed.
|
||||
Remove this section if not applicable.
|
||||
|
||||
请披露此 PR 中使用的重要 AI 辅助内容。
|
||||
轻微 AI 辅助,例如拼写修正、自动补全、格式建议或文字润色,无需披露。
|
||||
如不适用,请删除本节。
|
||||
|
||||
Deliberate non-disclosure may be treated as a trust and compliance issue.
|
||||
|
||||
故意隐瞒 AI 使用情况可能被视为信任与合规问题。
|
||||
-->
|
||||
|
||||
- [ ] This PR includes AI-assisted content.
|
||||
/ 此 PR 包含 AI 辅助内容。
|
||||
|
||||
Tools used / 使用工具:
|
||||
|
||||
- [ ] ChatGPT
|
||||
- [ ] Codex
|
||||
- [ ] GitHub Copilot
|
||||
- [ ] Claude
|
||||
- [ ] Gemini
|
||||
- [ ] Other (please specify) / 其他(请注明):
|
||||
|
||||
Usage scope / 使用范围:
|
||||
|
||||
- [ ] Code generation / 代码生成
|
||||
- [ ] Refactoring / 重构
|
||||
- [ ] Documentation / 文档
|
||||
- [ ] Tests / 测试
|
||||
- [ ] Translation / 翻译
|
||||
- [ ] Review assistance / 审查辅助
|
||||
|
||||
- [ ] I have reviewed and validated all AI-assisted content included in this PR.
|
||||
/ 我已审核并验证此 PR 中的所有 AI 辅助内容。
|
||||
- [ ] I have ensured that all AI-assisted commits include `Co-Authored-By` attribution.
|
||||
/ 我已确保所有 AI 辅助提交都包含 `Co-Authored-By` 归属信息。
|
||||
- [ ] I can reproduce all AI-assisted content included in this PR without any AI tools.
|
||||
/ 我可以在没有任何 AI 工具的情况下重现此 PR 中包含的所有 AI 辅助内容。
|
||||
|
||||
@@ -18,13 +18,13 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Create or update ref
|
||||
id: create-or-update-ref
|
||||
uses: ovsds/create-or-update-ref-action@v1
|
||||
uses: ovsds/create-or-update-ref-action@1157b2991820188d5a8e6f22656775d1d171f762 # v1
|
||||
with:
|
||||
ref: tags/beta
|
||||
sha: ${{ github.sha }}
|
||||
@@ -40,15 +40,18 @@ jobs:
|
||||
npx changelogithub --output CHANGELOG.md
|
||||
|
||||
- name: Upload assets to beta release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
body_path: CHANGELOG.md
|
||||
files: CHANGELOG.md
|
||||
prerelease: true
|
||||
tag_name: beta
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
if ! gh release view beta; then
|
||||
gh release create beta --prerelease --notes-file CHANGELOG.md
|
||||
else
|
||||
gh release edit beta --prerelease --notes-file CHANGELOG.md
|
||||
fi
|
||||
gh release upload beta "CHANGELOG.md" --clobber
|
||||
|
||||
- name: Upload assets to github artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: beta changelog
|
||||
path: ${{ github.workspace }}/CHANGELOG.md
|
||||
@@ -61,33 +64,58 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- target: "!(*musl*|*windows-arm64*|*windows7-*|*android*|*freebsd*)" # xgo and loongarch
|
||||
- target: "!(*musl*|*windows-arm64*|*windows7-*|*android*|*freebsd*)" # xgo and loongarch (exclude mips64le)
|
||||
hash: "md5"
|
||||
- target: "linux-!(arm*)-musl*" #musl-not-arm
|
||||
flags: ""
|
||||
goflags: ""
|
||||
- target: "linux-(mips|mips64|mipsle|mips64le|loong64)-musl*" # musl-compat-family
|
||||
hash: "md5-linux-musl-mips"
|
||||
flags: "-ldflags=-linkmode external -extldflags '-static -fpic'"
|
||||
goflags: ""
|
||||
musl_static: "true"
|
||||
- target: "linux-!(arm*|mips|mips64|mipsle|mips64le|loong64)-musl*" # musl-not-arm (exclude compat-family)
|
||||
hash: "md5-linux-musl"
|
||||
flags: "-ldflags=-linkmode external -extldflags '-static -fpic'"
|
||||
goflags: ""
|
||||
musl_static: "true"
|
||||
- target: "linux-arm*-musl*" #musl-arm
|
||||
hash: "md5-linux-musl-arm"
|
||||
flags: "-ldflags=-linkmode external -extldflags '-static -fpic'"
|
||||
goflags: ""
|
||||
musl_static: "true"
|
||||
- target: "windows-arm64" #win-arm64
|
||||
hash: "md5-windows-arm64"
|
||||
flags: ""
|
||||
goflags: ""
|
||||
musl_static: "false"
|
||||
- target: "windows7-*" #win7
|
||||
hash: "md5-windows7"
|
||||
flags: ""
|
||||
goflags: "-tags=sqlite_cgo_compat"
|
||||
musl_static: "false"
|
||||
- target: "android-*" #android
|
||||
hash: "md5-android"
|
||||
flags: ""
|
||||
goflags: ""
|
||||
musl_static: "false"
|
||||
- target: "freebsd-*" #freebsd
|
||||
hash: "md5-freebsd"
|
||||
flags: ""
|
||||
goflags: ""
|
||||
musl_static: "false"
|
||||
|
||||
name: Beta Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
go-version: "1.27.1"
|
||||
|
||||
- name: Setup web
|
||||
run: bash build.sh dev web
|
||||
@@ -96,9 +124,11 @@ jobs:
|
||||
FRONTEND_REPO: ${{ vars.FRONTEND_REPO }}
|
||||
|
||||
- name: Build
|
||||
uses: OpenListTeam/cgo-actions@v1.2.2
|
||||
uses: OpenListTeam/cgo-actions@6fcace5934c36d70503dba06e2396bb58b766130 # v1.2.5
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
flags: ${{ matrix.flags || '-ldflags=' }}
|
||||
static-link-for-musl: true
|
||||
musl-target-format: $os-$musl-$arch
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
out-dir: build
|
||||
@@ -110,6 +140,26 @@ jobs:
|
||||
github.com/OpenListTeam/OpenList/v4/internal/conf.GitCommit=$git_commit
|
||||
github.com/OpenListTeam/OpenList/v4/internal/conf.Version=$tag
|
||||
github.com/OpenListTeam/OpenList/v4/internal/conf.WebVersion=rolling
|
||||
env:
|
||||
GOFLAGS: ${{ matrix.goflags }}
|
||||
|
||||
- name: Verify musl binaries are static
|
||||
if: matrix.musl_static == 'true'
|
||||
run: |
|
||||
set -e
|
||||
shopt -s nullglob
|
||||
files=(build/openlist-*-musl-*)
|
||||
if [ ${#files[@]} -eq 0 ]; then
|
||||
echo "No musl binaries found"
|
||||
exit 1
|
||||
fi
|
||||
for f in "${files[@]}"; do
|
||||
if readelf -l "$f" | grep -q "Requesting program interpreter"; then
|
||||
echo "Dynamic binary detected: $f"
|
||||
readelf -l "$f" | grep "Requesting program interpreter" || true
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Compress
|
||||
run: |
|
||||
@@ -117,13 +167,13 @@ jobs:
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
# See above
|
||||
- name: Upload assets to beta release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: build/compress/*
|
||||
prerelease: true
|
||||
tag_name: beta
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
for file in build/compress/*; do
|
||||
gh release upload beta "$file" --clobber
|
||||
done
|
||||
|
||||
- name: Clean illegal characters from matrix.target
|
||||
id: clean_target_name
|
||||
@@ -135,7 +185,7 @@ jobs:
|
||||
echo "cleaned_target=$CLEANED_TARGET" >> $GITHUB_ENV
|
||||
|
||||
- name: Upload assets to github artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: beta builds for ${{ env.cleaned_target }}
|
||||
path: ${{ github.workspace }}/build/compress/*
|
||||
|
||||
@@ -25,15 +25,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: benjlevesque/short-sha@v3.0
|
||||
- uses: benjlevesque/short-sha@dbe07338b37c456ce06d23409b35a56a7815eef4 # v4.0
|
||||
id: short-sha
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
|
||||
with:
|
||||
go-version: "1.25.0"
|
||||
go-version: "1.27.1"
|
||||
|
||||
- name: Setup web
|
||||
run: bash build.sh dev web
|
||||
@@ -42,9 +42,11 @@ jobs:
|
||||
FRONTEND_REPO: ${{ vars.FRONTEND_REPO }}
|
||||
|
||||
- name: Build
|
||||
uses: OpenListTeam/cgo-actions@v1.2.2
|
||||
uses: OpenListTeam/cgo-actions@6fcace5934c36d70503dba06e2396bb58b766130 # v1.2.5
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
flags: ${{ contains(matrix.target, '-musl') && '-ldflags=-linkmode external -extldflags ''-static -fpic''' || '-ldflags=' }}
|
||||
static-link-for-musl: true
|
||||
musl-target-format: $os-$musl-$arch
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
out-dir: build
|
||||
@@ -56,8 +58,18 @@ jobs:
|
||||
github.com/OpenListTeam/OpenList/v4/internal/conf.WebVersion=rolling
|
||||
output: openlist$ext
|
||||
|
||||
- name: Verify musl binary is static
|
||||
if: contains(matrix.target, '-musl')
|
||||
run: |
|
||||
set -e
|
||||
if readelf -l build/openlist | grep -q "Requesting program interpreter"; then
|
||||
echo "Dynamic binary detected: build/openlist"
|
||||
readelf -l build/openlist | grep "Requesting program interpreter" || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: openlist_${{ steps.short-sha.outputs.sha }}_${{ matrix.target }}
|
||||
path: build/*
|
||||
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
name: Container Registry Cleanup
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
package:
|
||||
description: 'The name of the package to clean up'
|
||||
required: true
|
||||
default: 'openlist-git'
|
||||
owner:
|
||||
description: 'The owner of the package (user or organization)'
|
||||
required: false
|
||||
default: 'openlistteam'
|
||||
older_than:
|
||||
description: 'Delete untagged images older than this many days'
|
||||
required: false
|
||||
default: '-1'
|
||||
untagged_timestamp_tolerance:
|
||||
description: 'Tolerance in milliseconds for untagged images close to tagged ones'
|
||||
required: false
|
||||
# We do this because multi-arch docker containers will be pushed as separate untagged images
|
||||
# to the container registry and GitHub cannot recognize them as part of a tagged image.
|
||||
# Setting this option large enough prevents accidental deletion of one of these images.
|
||||
# Here we set it to 10 seconds
|
||||
default: '10000'
|
||||
token:
|
||||
description: 'GitHub token with permissions to delete packages (leave empty to use default GITHUB_TOKEN)'
|
||||
required: false
|
||||
default: ''
|
||||
|
||||
jobs:
|
||||
cleanup:
|
||||
runs-on: ubuntu-slim
|
||||
|
||||
steps:
|
||||
- name: Check inputs and tools
|
||||
id: setup
|
||||
shell: bash
|
||||
run: |
|
||||
PACKAGE="${{ github.event.inputs.package || 'openlist-git' }}"
|
||||
OLDER="${{ github.event.inputs.older_than || '-1' }}"
|
||||
TOLERANCE_VAL="${{ github.event.inputs.untagged_timestamp_tolerance || '10000' }}"
|
||||
TOKEN_INPUT="${{ github.event.inputs.token || '' }}"
|
||||
OWNER="${{ github.event.inputs.owner || 'openlistteam' }}"
|
||||
|
||||
echo "package_name=$PACKAGE" >> "$GITHUB_OUTPUT"
|
||||
echo "older_than=$OLDER" >> "$GITHUB_OUTPUT"
|
||||
echo "tolerance=$TOLERANCE_VAL" >> "$GITHUB_OUTPUT"
|
||||
echo "owner=$OWNER" >> "$GITHUB_OUTPUT"
|
||||
|
||||
if [[ -z "$TOKEN_INPUT" ]]; then
|
||||
echo "::notice:: No token provided, using GITHUB_TOKEN instead."
|
||||
echo "token=${{ secrets.GITHUB_TOKEN }}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "::add-mask::$TOKEN_INPUT"
|
||||
echo "token=$TOKEN_INPUT" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
if [[ -z "$PACKAGE" || -z "$OWNER" || ( -z "$TOKEN_INPUT" && -z "${{ secrets.GITHUB_TOKEN }}" ) ]]; then
|
||||
echo "::error:: Missing required inputs (package, token, or owner context)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
command -v curl >/dev/null 2>&1 || { echo "::error::curl is required but not installed."; exit 1; }
|
||||
command -v jq >/dev/null 2>&1 || { echo "::error::jq is required but not installed."; exit 1; }
|
||||
|
||||
- name: Determine owner type (user or organization)
|
||||
id: owner_type
|
||||
shell: bash
|
||||
run: |
|
||||
OWNER="${{ steps.setup.outputs.owner }}"
|
||||
TOKEN="${{ steps.setup.outputs.token }}"
|
||||
|
||||
TYPE=$(curl -s -H "Authorization: token $TOKEN" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"https://api.github.com/users/${OWNER}" | jq -r '.type')
|
||||
|
||||
if [[ "$TYPE" == "Organization" ]]; then
|
||||
OWNER_PATH="orgs"
|
||||
else
|
||||
OWNER_PATH="users"
|
||||
fi
|
||||
|
||||
echo "owner_path=$OWNER_PATH" >> "$GITHUB_OUTPUT"
|
||||
echo "Detected owner type: $TYPE (using /${OWNER_PATH}/)"
|
||||
|
||||
- name: Access all versions from GitHub
|
||||
id: fetch
|
||||
shell: bash
|
||||
run: |
|
||||
PACKAGE_NAME="${{ steps.setup.outputs.package_name }}"
|
||||
OWNER="${{ steps.setup.outputs.owner }}"
|
||||
TOKEN="${{ steps.setup.outputs.token }}"
|
||||
OWNER_PATH="${{ steps.owner_type.outputs.owner_path }}"
|
||||
|
||||
BASE_URL="https://api.github.com/${OWNER_PATH}/${OWNER}/packages/container/${PACKAGE_NAME}/versions"
|
||||
URL="${BASE_URL}?per_page=100"
|
||||
TEMP_FILE="/tmp/all_versions.ndjson"
|
||||
|
||||
> "$TEMP_FILE"
|
||||
PAGE=1
|
||||
while [[ -n "$URL" && $PAGE -le 10 ]]; do
|
||||
echo "Fetching: $URL"
|
||||
|
||||
curl -s -H "Authorization: token $TOKEN" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
-D headers.txt \
|
||||
"$URL" > page.json
|
||||
|
||||
jq -c '.[]' page.json >> "$TEMP_FILE"
|
||||
|
||||
URL=$(grep -i '^link:' headers.txt | grep -o '<[^>]*>;\s*rel="next"' | sed 's/<\(.*\)>.*/\1/' || true)
|
||||
PAGE=$((PAGE + 1))
|
||||
done
|
||||
rm -f headers.txt page.json
|
||||
|
||||
echo "temp_file=$TEMP_FILE" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Filter untagged versions
|
||||
id: filter
|
||||
shell: bash
|
||||
run: |
|
||||
OLDER_THAN="${{ steps.setup.outputs.older_than }}"
|
||||
TOLERANCE="${{ steps.setup.outputs.tolerance }}"
|
||||
TEMP_FILE="${{ steps.fetch.outputs.temp_file }}"
|
||||
|
||||
TO_DELETE=$(jq -c -s \
|
||||
--arg older_than "$OLDER_THAN" \
|
||||
--arg tolerance "$TOLERANCE" \
|
||||
'
|
||||
def abs: if . < 0 then -. else . end;
|
||||
def to_ms: sub("\\.[0-9]+Z$"; "Z") | strptime("%Y-%m-%dT%H:%M:%SZ") | mktime * 1000;
|
||||
|
||||
. as $all |
|
||||
($older_than | tonumber) as $older_than_val |
|
||||
($tolerance | tonumber) as $tolerance_val |
|
||||
now as $now |
|
||||
(if $older_than_val > 0 then ($now - ($older_than_val * 86400)) * 1000 else 0 end) as $cutoff_ms |
|
||||
|
||||
[ $all[] | select((.metadata.container.tags // []) | length > 0) | .created_at | to_ms ] as $tagged_times |
|
||||
|
||||
$all[] |
|
||||
select((.metadata.container.tags // []) | length == 0) |
|
||||
. as $item |
|
||||
(.created_at | to_ms) as $created_ms |
|
||||
|
||||
(if $older_than_val > 0 then $created_ms < $cutoff_ms else true end) as $pass_age |
|
||||
|
||||
(if $tolerance_val <= 0 then true
|
||||
else [ $tagged_times[] | select(($created_ms - .) | abs < $tolerance_val) ] | length == 0
|
||||
end) as $pass_tolerance |
|
||||
|
||||
select($pass_age and $pass_tolerance) |
|
||||
{id, name}
|
||||
' "$TEMP_FILE")
|
||||
|
||||
rm -f "$TEMP_FILE"
|
||||
|
||||
if [[ -z "$TO_DELETE" ]]; then
|
||||
DELETE_COUNT=0
|
||||
else
|
||||
DELETE_COUNT=$(echo "$TO_DELETE" | wc -l | tr -d ' ')
|
||||
fi
|
||||
|
||||
echo "Found $DELETE_COUNT untagged images no longer necessary"
|
||||
|
||||
{
|
||||
echo 'to_delete<<EOF'
|
||||
echo "$TO_DELETE"
|
||||
echo 'EOF'
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
|
||||
echo "delete_count=$DELETE_COUNT" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Delete untagged versions
|
||||
id: delete
|
||||
shell: bash
|
||||
run: |
|
||||
PACKAGE_NAME="${{ steps.setup.outputs.package_name }}"
|
||||
OWNER="${{ steps.setup.outputs.owner }}"
|
||||
TOKEN="${{ steps.setup.outputs.token }}"
|
||||
OWNER_PATH="${{ steps.owner_type.outputs.owner_path }}"
|
||||
DELETE_COUNT="${{ steps.filter.outputs.delete_count }}"
|
||||
TO_DELETE='${{ steps.filter.outputs.to_delete }}'
|
||||
|
||||
if [[ "$DELETE_COUNT" -gt 0 && -n "$TO_DELETE" ]]; then
|
||||
while IFS= read -r item; do
|
||||
[[ -z "$item" ]] && continue
|
||||
|
||||
# $item 是完整的单行 JSON,如 {"id":123,"name":"sha256:..."}
|
||||
ID=$(echo "$item" | jq -r '.id')
|
||||
NAME=$(echo "$item" | jq -r '.name')
|
||||
|
||||
DELETE_URL="https://api.github.com/${OWNER_PATH}/${OWNER}/packages/container/${PACKAGE_NAME}/versions/${ID}"
|
||||
|
||||
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -X DELETE \
|
||||
-H "Authorization: token $TOKEN" \
|
||||
-H "Accept: application/vnd.github.v3+json" \
|
||||
"$DELETE_URL")
|
||||
|
||||
if [[ "$HTTP_CODE" == "204" ]]; then
|
||||
echo "Deleted untagged container image '${NAME}'"
|
||||
else
|
||||
echo "::warning:: Failed to delete ${NAME} (ID: ${ID}). HTTP Status: ${HTTP_CODE}"
|
||||
fi
|
||||
done <<< "$TO_DELETE"
|
||||
else
|
||||
echo "No images to delete."
|
||||
fi
|
||||
|
||||
echo "Cleanup completed."
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Issue Auto Reply
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
auto-reply:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check issue for unchecked tasks and reply
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
|
||||
with:
|
||||
script: |
|
||||
if (context.payload.issue.title.startsWith('[Announcements]')) return;
|
||||
const titleNotEdited = /(请修改标题|Please modify the title)/i.test(context.payload.issue.title);
|
||||
const issueBody = context.payload.issue.body || "";
|
||||
const aiSection = issueBody.match(/^### (AI生成内容|AI Generated Content)\r?\n([\s\S]*?)(?=^### |$(?![\s\S]))/m);
|
||||
const aiOptionsPattern = aiSection?.[1] === 'AI生成内容'
|
||||
? /^\s*- \[([ xX])\] 我使用了AI工具生成此内容\r?\n- \[([ xX])\] 我没有使用AI工具生成此内容\s*$/
|
||||
: /^\s*- \[([ xX])\] I used AI tools to generate this content\r?\n- \[([ xX])\] I did not use AI tools to generate this content\s*$/;
|
||||
const aiOptions = (aiSection?.[2] || '').match(aiOptionsPattern);
|
||||
const validAiDisclosure = aiOptions !== null && (aiOptions[1] !== ' ') !== (aiOptions[2] !== ' ');
|
||||
const aiModelSection = issueBody.match(/^### (AI模型是|AI model used)\r?\n([\s\S]*?)(?=^### |$(?![\s\S]))/m);
|
||||
const aiModel = (aiModelSection?.[2] || '').trim();
|
||||
const missingAiModel = validAiDisclosure && aiOptions[1] !== ' ' && (aiModel === '' || aiModel === '_No response_');
|
||||
const confirmNotRead = /- \[[xX]\] (?:我没有阅读这个清单|I have not read these checkboxes)/.test(issueBody);
|
||||
const closeIssue = titleNotEdited || confirmNotRead || !validAiDisclosure || missingAiModel;
|
||||
let comment;
|
||||
if (titleNotEdited) {
|
||||
comment = `⚠️ 请修改标题以更好地描述您的问题或需求,并删除示例提示。当前 Issue 将被自动关闭并锁定。如需继续提交,请创建新的 Issue。
|
||||
⚠️ Please modify the title to better describe your issue or request, and remove the example prompt. This issue will be automatically closed and locked. If you wish to proceed, please create a new issue.
|
||||
`;
|
||||
} else if (confirmNotRead || !validAiDisclosure || missingAiModel) {
|
||||
comment = `⚠️ 你的 Issue 不符合提交规则。请先阅读相关规范后再重新提交。当前 Issue 将被自动关闭并锁定。如需继续提交,请确认已了解规则后创建新的 Issue。
|
||||
⚠️ Your issue does not comply with the submission rules. Please read the guidelines before submitting again. This issue will be automatically closed and locked. If you wish to proceed, please confirm that you have reviewed the rules before creating a new issue.
|
||||
`;
|
||||
} else if (/- \[ \] (?!我没有阅读这个清单|I have not read these checkboxes)/.test(issueBody.replace(aiSection[0], ''))) {
|
||||
comment = `感谢您联系OpenList。我们会尽快回复您。
|
||||
Thanks for contacting OpenList. We will reply to you as soon as possible.
|
||||
|
||||
由于您提出的 Issue 中包含部分未确认的项目,为了更好地管理项目,在人工审核后可能会直接关闭此问题。
|
||||
如果您能确认并补充相关未确认项目的信息,欢迎随时重新提交。我们会及时关注并处理。感谢您的理解与支持!
|
||||
Since your issue contains some unchecked tasks, it may be closed after manual review.
|
||||
If you can confirm and provide information for the unchecked tasks, feel free to resubmit.
|
||||
We will pay attention and handle it in a timely manner.
|
||||
|
||||
感谢您的理解与支持!
|
||||
Thank you for your understanding and support!
|
||||
`;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
await github.rest.issues.createComment({
|
||||
...context.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: comment
|
||||
});
|
||||
if (closeIssue) {
|
||||
await github.rest.issues.update({
|
||||
...context.repo,
|
||||
issue_number: context.issue.number,
|
||||
state: 'closed',
|
||||
state_reason: 'not_planned',
|
||||
labels: ['invalid']
|
||||
});
|
||||
await github.rest.issues.lock({
|
||||
...context.repo,
|
||||
issue_number: context.issue.number
|
||||
});
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
name: Issue or PR Auto Reply
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [opened]
|
||||
pull_request:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
auto-reply:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'issues'
|
||||
steps:
|
||||
- name: Check issue for unchecked tasks and reply
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const issueBody = context.payload.issue.body || "";
|
||||
const unchecked = /- \[ \] (?!我没有阅读这个清单|I have not read these checkboxes)/.test(issueBody);
|
||||
let comment = "感谢您联系OpenList。我们会尽快回复您。\n";
|
||||
comment += "Thanks for contacting OpenList. We will reply to you as soon as possible.\n\n";
|
||||
if (unchecked) {
|
||||
comment += "由于您提出的 Issue 中包含部分未确认的项目,为了更好地管理项目,在人工审核后可能会直接关闭此问题。\n";
|
||||
comment += "如果您能确认并补充相关未确认项目的信息,欢迎随时重新提交。我们会及时关注并处理。感谢您的理解与支持!\n";
|
||||
comment += "Since your issue contains some unchecked tasks, it may be closed after manual review.\n";
|
||||
comment += "If you can confirm and provide information for the unchecked tasks, feel free to resubmit.\n";
|
||||
comment += "We will pay attention and handle it in a timely manner.\n\n";
|
||||
comment += "感谢您的理解与支持!\n";
|
||||
comment += "Thank you for your understanding and support!\n";
|
||||
}
|
||||
await github.rest.issues.createComment({
|
||||
...context.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: comment
|
||||
});
|
||||
|
||||
pr-title-check:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'pull_request'
|
||||
steps:
|
||||
- name: Check PR title for required prefix and comment
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const title = context.payload.pull_request.title || "";
|
||||
const ok = /^(feat|docs|fix|style|refactor|chore)\(.+?\): /i.test(title);
|
||||
if (!ok) {
|
||||
let comment = "⚠️ PR 标题需以 `feat(): `, `docs(): `, `fix(): `, `style(): `, `refactor(): `, `chore(): ` 其中之一开头,例如:`feat(component): 新增功能`。\n";
|
||||
comment += "⚠️ The PR title must start with `feat(): `, `docs(): `, `fix(): `, `style(): `, or `refactor(): `, `chore(): `. For example: `feat(component): add new feature`.\n\n";
|
||||
comment += "如果跨多个组件,请使用主要组件作为前缀,并在标题中枚举、描述中说明。\n";
|
||||
comment += "If it spans multiple components, use the main component as the prefix and enumerate in the title, describe in the body.\n\n";
|
||||
await github.rest.issues.createComment({
|
||||
...context.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: comment
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
name: PR Title Check
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
|
||||
permissions:
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
pr-title-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check PR title for required prefix and comment
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
|
||||
with:
|
||||
script: |
|
||||
const title = context.payload.pull_request.title;
|
||||
if (/^(feat|docs|fix|style|refactor|chore)\(.+?\)!?: /i.test(title)) return;
|
||||
const comment = `⚠️ PR 标题需以 \`feat(): \`, \`docs(): \`, \`fix(): \`, \`style(): \`, \`refactor(): \`, \`chore(): \` 其中之一开头,例如:\`feat(component): 新增功能\`。
|
||||
⚠️ The PR title must start with \`feat(): \`, \`docs(): \`, \`fix(): \`, \`style(): \`, or \`refactor(): \`, \`chore(): \`. For example: \`feat(component): add new feature\`.
|
||||
|
||||
如果跨多个组件,请使用主要组件作为前缀,并在标题中枚举、描述中说明。
|
||||
If it spans multiple components, use the main component as the prefix and enumerate in the title, describe in the body.
|
||||
|
||||
如果是破坏性变更,请在类型后添加 \`!\`,例如 \`feat(component)!: 破坏性变更\`。
|
||||
For breaking changes, add \`!\` after the type, e.g., \`feat(component)!: breaking change\`.
|
||||
|
||||
`;
|
||||
await github.rest.issues.createComment({
|
||||
...context.repo,
|
||||
issue_number: context.issue.number,
|
||||
body: comment
|
||||
});
|
||||
@@ -14,7 +14,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Prerelease
|
||||
uses: irongut/EditRelease@v1.2.0
|
||||
uses: irongut/EditRelease@ccf529ad26dddf9996e7dd0f24ca5da4ea507cc2 # v1.2.0
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
id: ${{ github.event.release.id }}
|
||||
@@ -33,7 +33,7 @@ jobs:
|
||||
|
||||
- name: Free Disk Space (Ubuntu)
|
||||
if: matrix.target-platform == ''
|
||||
uses: jlumbroso/free-disk-space@main
|
||||
uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be # main
|
||||
with:
|
||||
tool-cache: false
|
||||
android: true
|
||||
@@ -44,14 +44,15 @@ jobs:
|
||||
swap-storage: true
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
|
||||
with:
|
||||
go-version: '1.25.0'
|
||||
go-version: '1.27.1'
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-depth: 1
|
||||
fetch-tags: true
|
||||
|
||||
- name: Install dependencies
|
||||
if: matrix.target-platform == ''
|
||||
@@ -69,9 +70,9 @@ jobs:
|
||||
FRONTEND_REPO: ${{ vars.FRONTEND_REPO }}
|
||||
|
||||
- name: Upload assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: build/compress/*
|
||||
prerelease: false
|
||||
tag_name: ${{ github.event.release.tag_name }}
|
||||
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
for file in build/compress/*; do
|
||||
gh release upload "${{ github.event.release.tag_name }}" "$file" --clobber
|
||||
done
|
||||
|
||||
@@ -43,15 +43,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
|
||||
with:
|
||||
go-version: '1.25.0'
|
||||
go-version: '1.27'
|
||||
|
||||
- name: Cache Musl
|
||||
id: cache-musl
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||
with:
|
||||
path: build/musl-libs
|
||||
key: docker-musl-libs-v2
|
||||
@@ -69,7 +69,7 @@ jobs:
|
||||
FRONTEND_REPO: ${{ vars.FRONTEND_REPO }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ${{ env.ARTIFACT_NAME }}
|
||||
overwrite: true
|
||||
@@ -83,15 +83,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
|
||||
with:
|
||||
go-version: '1.25.0'
|
||||
go-version: '1.27.1'
|
||||
|
||||
- name: Cache Musl
|
||||
id: cache-musl
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||
with:
|
||||
path: build/musl-libs
|
||||
key: docker-musl-libs-v2
|
||||
@@ -109,7 +109,7 @@ jobs:
|
||||
FRONTEND_REPO: ${{ vars.FRONTEND_REPO }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ${{ env.ARTIFACT_NAME_LITE }}
|
||||
overwrite: true
|
||||
@@ -146,21 +146,21 @@ jobs:
|
||||
tag_favor: "suffix=-aio,onlatest=true"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ${{ env.ARTIFACT_NAME }}
|
||||
path: 'build/'
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
if: env.IMAGE_PUSH == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -168,14 +168,14 @@ jobs:
|
||||
|
||||
- name: Login to DockerHub Container Registry
|
||||
if: env.IMAGE_PUSH == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_ORG_NAME_BACKUP || env.DOCKERHUB_ORG_NAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.GHCR_ORG_NAME }}/${{ env.IMAGE_NAME }}
|
||||
@@ -190,7 +190,7 @@ jobs:
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.ci
|
||||
@@ -230,21 +230,21 @@ jobs:
|
||||
tag_favor: "suffix=-lite-aio,onlatest=true"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ${{ env.ARTIFACT_NAME_LITE }}
|
||||
path: 'build/'
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
if: env.IMAGE_PUSH == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -252,14 +252,14 @@ jobs:
|
||||
|
||||
- name: Login to DockerHub Container Registry
|
||||
if: env.IMAGE_PUSH == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_ORG_NAME_BACKUP || env.DOCKERHUB_ORG_NAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.GHCR_ORG_NAME }}/${{ env.IMAGE_NAME }}
|
||||
@@ -274,7 +274,7 @@ jobs:
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.ci
|
||||
|
||||
@@ -12,7 +12,7 @@ jobs:
|
||||
name: Sync GitHub to Gitee
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
||||
@@ -32,15 +32,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7
|
||||
with:
|
||||
go-version: '1.25.0'
|
||||
go-version: '1.27.1'
|
||||
|
||||
- name: Cache Musl
|
||||
id: cache-musl
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6
|
||||
with:
|
||||
path: build/musl-libs
|
||||
key: docker-musl-libs-v2
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
FRONTEND_REPO: ${{ vars.FRONTEND_REPO }}
|
||||
|
||||
- name: Upload artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: ${{ env.ARTIFACT_NAME }}
|
||||
overwrite: true
|
||||
@@ -97,21 +97,21 @@ jobs:
|
||||
tag_favor: "suffix=-aio,onlatest=true"
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- uses: actions/download-artifact@v4
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: ${{ env.ARTIFACT_NAME }}
|
||||
path: 'build/'
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
if: env.IMAGE_PUSH == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
@@ -119,14 +119,14 @@ jobs:
|
||||
|
||||
- name: Login to DockerHub Container Registry
|
||||
if: env.IMAGE_PUSH == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4
|
||||
with:
|
||||
username: ${{ vars.DOCKERHUB_ORG_NAME_BACKUP || env.DOCKERHUB_ORG_NAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Docker meta
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6
|
||||
with:
|
||||
images: |
|
||||
${{ env.REGISTRY }}/${{ env.GHCR_ORG_NAME }}/${{ env.IMAGE_NAME }}
|
||||
@@ -137,7 +137,7 @@ jobs:
|
||||
|
||||
- name: Build and push
|
||||
id: docker_build
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
|
||||
with:
|
||||
context: .
|
||||
file: Dockerfile.ci
|
||||
|
||||
@@ -16,20 +16,33 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger Makefile hash update
|
||||
uses: peter-evans/repository-dispatch@v3
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
|
||||
with:
|
||||
token: ${{ secrets.EXTERNAL_REPO_TOKEN_LUCI_APP_OPENLIST }}
|
||||
repository: ${{ vars.HOOK_REPO || 'OpenListTeam/OpenList-OpenWRT' }}
|
||||
event-type: update-hashes
|
||||
client-payload: |
|
||||
{
|
||||
"source_repository": "${{ github.repository }}",
|
||||
"release_tag": "${{ inputs.tag || github.ref_name }}",
|
||||
"release_name": "${{ inputs.tag || github.ref_name }}",
|
||||
"release_url": "${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ inputs.tag || github.ref_name }}",
|
||||
"triggered_by": "${{ github.actor }}",
|
||||
"trigger_reason": "${{ github.event_name }}"
|
||||
}
|
||||
github-token: ${{ secrets.EXTERNAL_REPO_TOKEN_LUCI_APP_OPENLIST }}
|
||||
script: |
|
||||
const repository = process.env.REPOSITORY;
|
||||
const [owner, repo] = repository.split('/');
|
||||
|
||||
await github.rest.repos.createDispatchEvent({
|
||||
owner: owner,
|
||||
repo: repo,
|
||||
event_type: 'update-hashes',
|
||||
client_payload: {
|
||||
source_repository: process.env.SOURCE_REPOSITORY,
|
||||
release_tag: process.env.RELEASE_TAG,
|
||||
release_name: process.env.RELEASE_TAG,
|
||||
release_url: process.env.RELEASE_URL,
|
||||
triggered_by: process.env.ACTOR,
|
||||
trigger_reason: process.env.EVENT_NAME
|
||||
}
|
||||
});
|
||||
env:
|
||||
REPOSITORY: ${{ vars.HOOK_REPO || 'OpenListTeam/OpenList-OpenWRT' }}
|
||||
SOURCE_REPOSITORY: ${{ github.repository }}
|
||||
RELEASE_TAG: ${{ inputs.tag || github.ref_name }}
|
||||
RELEASE_URL: ${{ github.server_url }}/${{ github.repository }}/releases/tag/${{ inputs.tag || github.ref_name }}
|
||||
ACTOR: ${{ github.actor }}
|
||||
EVENT_NAME: ${{ github.event_name }}
|
||||
|
||||
- name: Log trigger information
|
||||
run: |
|
||||
|
||||
+4
-2
@@ -22,6 +22,7 @@ output/
|
||||
# vendor/
|
||||
/bin/*
|
||||
*.json
|
||||
!renovate.json
|
||||
/build
|
||||
/data/
|
||||
/tmp/
|
||||
@@ -29,6 +30,7 @@ output/
|
||||
/lang/
|
||||
/daemon/
|
||||
/public/dist/*
|
||||
/!public/dist/README.md
|
||||
!/public/dist/README.md
|
||||
|
||||
.VSCodeCounter
|
||||
.VSCodeCounter
|
||||
*.syso
|
||||
@@ -0,0 +1,60 @@
|
||||
# Agent Instructions
|
||||
|
||||
## Issues
|
||||
|
||||
Before creating an issue, review the available issue templates in the `.github` directory.
|
||||
|
||||
When drafting the issue:
|
||||
|
||||
- Use the most appropriate template.
|
||||
- Follow the template structure.
|
||||
- Fill in all required sections.
|
||||
- Remove sections that the template explicitly marks as optional or not applicable.
|
||||
- Do not invent reproduction steps, logs, screenshots, or expected behavior.
|
||||
|
||||
## Pull Requests
|
||||
|
||||
Before creating a pull request, read `.github/PULL_REQUEST_TEMPLATE.md`.
|
||||
|
||||
When drafting the pull request:
|
||||
|
||||
- Follow the template structure.
|
||||
- Use the title format required by the template.
|
||||
- Fill in or remove each section according to the template guidance.
|
||||
- Include testing details, or explain why testing was not run.
|
||||
- Do not invent testing results.
|
||||
- Do not claim validation, verification, or review steps that were not actually performed.
|
||||
|
||||
## Automated Contributions
|
||||
|
||||
Fully automated contributions are not considered equivalent to normal community participation.
|
||||
|
||||
A contribution may be considered fully automated if it is submitted through an automated agent, or if the submitting account participates in project discussions through an automated agent, without meaningful human review or intervention.
|
||||
|
||||
When making this determination, maintainers may consider the overall behavior of the account, including but not limited to disclosed agent usage, interaction patterns, response characteristics, and other available evidence. No single factor is determinative.
|
||||
|
||||
Maintainers reserve the right to accept, reject, modify, or reimplement any contribution independently of any action taken against the submitting account. Acceptance of a contribution does not imply acceptance of the submitting account or its contribution method. If an account is determined to be primarily operated through automated processes, we may need to restrict its future participation in contributions until that determination is rescinded.
|
||||
|
||||
## Git Commits
|
||||
|
||||
When creating commits, follow the repository `git-commit` skill rules:
|
||||
|
||||
- Use Conventional Commits title format: `type(scope): subject`.
|
||||
- Allowed types: `feat`, `fix`, `refactor`, `perf`, `docs`, `style`, `test`, `build`, `ci`, `chore`, `revert`.
|
||||
- Use a meaningful scope based on the main module, package, or feature.
|
||||
- Write the subject in imperative mood and describe the actual change.
|
||||
- Use a concise Markdown list in the commit body, with each item describing one key change.
|
||||
- Do not invent changes that are not present in the diff.
|
||||
- Do not describe behavior, refactors, fixes, or tests that are not reflected in the commit.
|
||||
|
||||
Include at most one `Co-authored-by` trailer that matches the AI assistant actually used to produce the change.
|
||||
|
||||
Examples:
|
||||
|
||||
- `Co-authored-by: Codex <267193182+codex@users.noreply.github.com>`
|
||||
- `Co-authored-by: GitHub Copilot <copilot@github.com>`
|
||||
- `Co-authored-by: Claude <81847+claude@users.noreply.github.com>`
|
||||
|
||||
If you are not one of the listed assistants, do not add a `Co-authored-by` trailer.
|
||||
|
||||
Instead, ask the human collaborator to provide the exact `Co-authored-by` trailer to use. Do not invent, infer, or generate one yourself.
|
||||
+4
-4
@@ -106,7 +106,7 @@ Violating these terms may lead to a permanent ban.
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
@@ -116,7 +116,7 @@ the community.
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
<https://www.contributor-covenant.org/version/2/0/code_of_conduct.html>.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
@@ -124,5 +124,5 @@ enforcement ladder](https://github.com/mozilla/diversity).
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
<https://www.contributor-covenant.org/faq>. Translations are available at
|
||||
<https://www.contributor-covenant.org/translations>.
|
||||
|
||||
+40
-7
@@ -7,7 +7,7 @@
|
||||
Prerequisites:
|
||||
|
||||
- [git](https://git-scm.com)
|
||||
- [Go 1.24+](https://golang.org/doc/install)
|
||||
- [Go](https://golang.org/doc/install) version declared in [`go.mod`](./go.mod)
|
||||
- [gcc](https://gcc.gnu.org/)
|
||||
- [nodejs](https://nodejs.org/)
|
||||
|
||||
@@ -16,8 +16,8 @@ Prerequisites:
|
||||
Fork and clone `OpenList` and `OpenList-Frontend` anywhere:
|
||||
|
||||
```shell
|
||||
$ git clone https://github.com/<your-username>/OpenList.git
|
||||
$ git clone --recurse-submodules https://github.com/<your-username>/OpenList-Frontend.git
|
||||
git clone https://github.com/<your-username>/OpenList.git
|
||||
git clone --recurse-submodules https://github.com/<your-username>/OpenList-Frontend.git
|
||||
```
|
||||
|
||||
## Creating a branch
|
||||
@@ -25,7 +25,7 @@ $ git clone --recurse-submodules https://github.com/<your-username>/OpenList-Fro
|
||||
Create a new branch from the `main` branch, with an appropriate name.
|
||||
|
||||
```shell
|
||||
$ git checkout -b <branch-name>
|
||||
git checkout -b <branch-name>
|
||||
```
|
||||
|
||||
## Preview your change
|
||||
@@ -33,26 +33,36 @@ $ git checkout -b <branch-name>
|
||||
### backend
|
||||
|
||||
```shell
|
||||
$ go run main.go
|
||||
go run main.go
|
||||
```
|
||||
|
||||
### frontend
|
||||
|
||||
```shell
|
||||
$ pnpm dev
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
## Add a new driver
|
||||
|
||||
Copy `drivers/template` folder and rename it, and follow the comments in it.
|
||||
|
||||
## Community and policies
|
||||
|
||||
By contributing, you agree to follow the repository's code of conduct and license terms.
|
||||
|
||||
- Code of conduct: [CODE_OF_CONDUCT.md](./CODE_OF_CONDUCT.md)
|
||||
- License: [LICENSE](./LICENSE)
|
||||
- Security issues: please report privately according to [SECURITY.md](./SECURITY.md)
|
||||
|
||||
If your contribution includes substantial AI-assisted content, disclose the tools used and the scope of assistance in the pull request.
|
||||
|
||||
## Create a commit
|
||||
|
||||
Commit messages should be well formatted, and to make that "standardized".
|
||||
|
||||
Submit your pull request. For PR titles, follow [Conventional Commits](https://www.conventionalcommits.org).
|
||||
|
||||
https://github.com/OpenListTeam/OpenList/issues/376
|
||||
<https://github.com/OpenListTeam/OpenList/issues/376>
|
||||
|
||||
It's suggested to sign your commits. See: [How to sign commits](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits)
|
||||
|
||||
@@ -72,6 +82,29 @@ At least 1 approving review is required by reviewers with write access. You can
|
||||
|
||||
(Optional) After your pull request is merged, you can delete your branch.
|
||||
|
||||
## AI Disclosure
|
||||
|
||||
If your pull request includes substantial AI-assisted content, disclose it in the PR description.
|
||||
|
||||
The pull request description must follow the repository's pull request template.
|
||||
|
||||
Fully automated contributions are not considered equivalent to normal community participation.
|
||||
|
||||
A contribution may be considered fully automated if it is submitted through an automated agent, or if the submitting account participates in project discussions through an automated agent, without meaningful human review or intervention.
|
||||
|
||||
When making this determination, maintainers may consider the overall behavior of the account, including but not limited to disclosed agent usage, interaction patterns, response characteristics, and other available evidence. No single factor is determinative.
|
||||
|
||||
Maintainers reserve the right to accept, reject, modify, or reimplement any contribution independently of any action taken against the submitting account. Acceptance of a contribution does not imply acceptance of the submitting account or its contribution method. If an account is determined to be primarily operated through automated processes, we may need to restrict its future participation in contributions until that determination is rescinded.
|
||||
|
||||
Please include:
|
||||
|
||||
- Tools used, such as ChatGPT, GitHub Copilot, Claude, Cursor, or other AI tools.
|
||||
- Usage scope, such as code generation, refactoring, documentation, tests, translation, or review assistance.
|
||||
- Confirmation that you have reviewed and validated all AI-assisted content before submission.
|
||||
- Confirmation that the submitted content complies with this repository's license and contribution policies.
|
||||
|
||||
Minor AI assistance, such as typo fixes, autocomplete, formatting suggestions, or wording polish, does not need to be disclosed.
|
||||
|
||||
---
|
||||
|
||||
Thank you for your contribution! Let's make OpenList better together!
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<img style="width: 128px; height: 128px;" src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" alt="logo" />
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList is a resilient, long-term governance, community-driven fork of AList — built to defend open source against trust-based attacks.</em></p>
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
---
|
||||
|
||||
- English | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md)
|
||||
- English | [中文](./README/README_cn.md) | [日本語](./README/README_ja.md) | [Dutch](./README/README_nl.md) | [한국어](./README/README_ko.md) | [Deutsch](./README/README_de.md) | [Русский](./README/README_ru.md) | [Français](./README/README_fr.md) | [Español](./README/README_es.md) | [العربية](./README/README_ar.md)
|
||||
|
||||
- [Contributing](./CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](./CODE_OF_CONDUCT.md)
|
||||
@@ -67,7 +67,7 @@ Thank you for your support and understanding of the OpenList project.
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
@@ -95,6 +95,7 @@ Thank you for your support and understanding of the OpenList project.
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
@@ -116,9 +117,10 @@ Thank you for your support and understanding of the OpenList project.
|
||||
|
||||
## Document
|
||||
|
||||
- 📘 [Global Site](https://doc.oplist.org)
|
||||
- 📚 [Backup Site](https://doc.openlist.team)
|
||||
- 🌏 [CN Site](https://doc.oplist.org.cn)
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## Demo
|
||||
|
||||
@@ -133,6 +135,14 @@ Please refer to [*Discussions*](https://github.com/OpenListTeam/OpenList/discuss
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## Donors
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## License
|
||||
|
||||
The `OpenList` is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
@@ -162,3 +172,4 @@ We sincerely thank the author [Xhofe](https://github.com/Xhofe) of the original
|
||||
Thanks goes to these wonderful people:
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList هو تفرّع من AList يتميز بالمرونة والحوكمة طويلة الأمد ويقوده المجتمع، وقد بُني للدفاع عن البرمجيات مفتوحة المصدر ضد الهجمات القائمة على الثقة.</em></p>
|
||||
|
||||
<img src="https://goreportcard.com/badge/github.com/OpenListTeam/OpenList/v3" alt="latest version" />
|
||||
<a href="https://github.com/OpenListTeam/OpenList/blob/main/LICENSE"><img src="https://img.shields.io/github/license/OpenListTeam/OpenList" alt="License" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/actions/workflow/status/OpenListTeam/OpenList/build.yml?branch=main" alt="Build status" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/release/OpenListTeam/OpenList" alt="latest version" /></a>
|
||||
|
||||
<a href="https://github.com/OpenListTeam/OpenList/discussions"><img src="https://img.shields.io/github/discussions/OpenListTeam/OpenList?color=%23ED8936" alt="discussions" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/downloads/OpenListTeam/OpenList/total?color=%239F7AEA&logo=github" alt="Downloads" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | [Français](./README_fr.md) | [Español](./README_es.md) | العربية
|
||||
|
||||
- [Contributing](../CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](../CODE_OF_CONDUCT.md)
|
||||
- [LICENSE](../LICENSE)
|
||||
|
||||
## إخلاء المسؤولية
|
||||
|
||||
OpenList is an open-source project independently maintained by the OpenList Team under the AGPL-3.0 license, with a commitment to code openness and modification transparency.
|
||||
|
||||
OpenList has no official association with third-party derivative projects that use similar names, including OpenListApp/OpenListApp or paid proprietary software using the same or similar names.
|
||||
|
||||
- All software, code, and services of this project are maintained by the OpenList Team and are freely available on GitHub.
|
||||
- Project documentation and API services primarily rely on charitable resources provided by Cloudflare. There are currently no paid plans or commercial deployments.
|
||||
- Downstream projects should not use the "OpenList" name for impersonation or commercial confusion, and must not distribute OpenList-based code as closed source in violation of the AGPL license.
|
||||
- This software is provided "as is" without warranties. Please comply with applicable laws and regulations when using it.
|
||||
|
||||
## الميزات
|
||||
|
||||
- [x] Multiple storages
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.alipan.com)
|
||||
- [x] OneDrive / Sharepoint ([Global](https://www.microsoft.com/en-us/microsoft-365/onedrive/online-cloud-storage), [CN](https://portal.partner.microsoftonline.cn), DE, US)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com)
|
||||
- [x] [123pan](https://www.123pan.com)
|
||||
- [x] [FTP / SFTP](https://en.wikipedia.org/wiki/File_Transfer_Protocol)
|
||||
- [x] [PikPak](https://www.mypikpak.com)
|
||||
- [x] [S3](https://aws.amazon.com/s3)
|
||||
- [x] [Seafile](https://seafile.com)
|
||||
- [x] [UPYUN Storage Service](https://www.upyun.com/products/file-storage)
|
||||
- [x] [WebDAV](https://en.wikipedia.org/wiki/WebDAV)
|
||||
- [x] Teambition([China](https://www.teambition.com), [International](https://us.teambition.com))
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
- [x] [UC](https://drive.uc.cn)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [Thunder](https://pan.xunlei.com)
|
||||
- [x] [Lanzou](https://www.lanzou.com)
|
||||
- [x] [ILanzou](https://www.ilanzou.com)
|
||||
- [x] [Google photo](https://photos.google.com)
|
||||
- [x] [Mega.nz](https://mega.nz)
|
||||
- [x] [Baidu photo](https://photo.baidu.com)
|
||||
- [x] [SMB](https://en.wikipedia.org/wiki/Server_Message_Block)
|
||||
- [x] [115](https://115.com)
|
||||
- [x] [Cloudreve](https://cloudreve.org)
|
||||
- [x] [Dropbox](https://www.dropbox.com)
|
||||
- [x] [FeijiPan](https://www.feijipan.com)
|
||||
- [x] [dogecloud](https://www.dogecloud.com/product/oss)
|
||||
- [x] [Azure Blob Storage](https://azure.microsoft.com/products/storage/blobs)
|
||||
- [x] [Chaoxing](https://www.chaoxing.com)
|
||||
- [x] [CNB](https://cnb.cool/)
|
||||
- [x] [Degoo](https://degoo.com)
|
||||
- [x] [Doubao](https://www.doubao.com)
|
||||
- [x] [Febbox](https://www.febbox.com)
|
||||
- [x] [GitHub](https://github.com)
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
- [x] Video and audio preview, with lyrics and subtitles support
|
||||
- [x] Office document preview (docx, pptx, xlsx, ...)
|
||||
- [x] `README.md` preview rendering
|
||||
- [x] File permalink copy and direct file download
|
||||
- [x] Dark mode and i18n
|
||||
- [x] Protected routes, WebDAV, Docker deploy, and Cloudflare Workers proxy
|
||||
- [x] File/folder package download and web upload operations
|
||||
- [x] Offline download, cross-storage copy, and multi-thread download acceleration
|
||||
|
||||
## الوثائق
|
||||
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## العرض التجريبي
|
||||
|
||||
- 🌎 [Global Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [CN Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## النقاش
|
||||
|
||||
Please refer to [Discussions](https://github.com/OpenListTeam/OpenList/discussions) for general questions; Issues are for bug reports and feature requests only.
|
||||
|
||||
## الراعي
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## المتبرعون
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## الترخيص
|
||||
|
||||
OpenList is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
|
||||
## تواصل معنا
|
||||
|
||||
- [@GitHub](https://github.com/OpenListTeam)
|
||||
- [Telegram Group](https://t.me/OpenListTeam)
|
||||
- [Telegram Channel](https://t.me/OpenListOfficial)
|
||||
|
||||
## المساهمون
|
||||
|
||||
We sincerely thank [Xhofe](https://github.com/Xhofe), author of the original project [AlistGo/alist](https://github.com/AlistGo/alist), and all other contributors.
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
@@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<img style="width: 128px; height: 128px;" src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" alt="logo" />
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList 是一个有韧性、长期治理、社区驱动的 AList 分支,旨在防御基于信任的开源攻击。</em></p>
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
|
||||
---
|
||||
|
||||
- [English](./README.md) | 中文 | [日本語](./README_ja.md) | [Dutch](./README_nl.md)
|
||||
- [English](../README.md) | 中文 | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | [Français](./README_fr.md) | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [贡献指南](./CONTRIBUTING.md)
|
||||
- [行为准则](./CODE_OF_CONDUCT.md)
|
||||
- [许可证](./LICENSE)
|
||||
- [贡献指南](../CONTRIBUTING.md)
|
||||
- [行为准则](../CODE_OF_CONDUCT.md)
|
||||
- [许可证](../LICENSE)
|
||||
|
||||
## 免责声明
|
||||
|
||||
@@ -67,7 +67,7 @@ OpenList 是一个由 OpenList 团队独立维护的开源项目,遵循 AGPL-3
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [分秒帧](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [和彩云](https://yun.139.com)(个人、家庭、群组)
|
||||
- [x] [和彩云](https://yun.139.com)(个人、家庭、群组、分享)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [百度网盘](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
@@ -95,6 +95,7 @@ OpenList 是一个由 OpenList 团队独立维护的开源项目,遵循 AGPL-3
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [微云](https://www.weiyun.com)
|
||||
- [x] [钉钉文档](https://alidocs.dingtalk.com/)
|
||||
- [x] 部署方便,开箱即用
|
||||
- [x] 文件预览(PDF、markdown、代码、纯文本等)
|
||||
- [x] 画廊模式下的图片预览
|
||||
@@ -116,14 +117,15 @@ OpenList 是一个由 OpenList 团队独立维护的开源项目,遵循 AGPL-3
|
||||
|
||||
## 文档
|
||||
|
||||
- 🌏 [国内站点](https://doc.oplist.org.cn)
|
||||
- 📘 [海外站点](https://doc.oplist.org)
|
||||
- 📚 [备用站点](https://doc.openlist.team)
|
||||
- 📘 [文档](https://doc.oplist.org)
|
||||
- 🌏 [中国镜像](https://doc.oplist.org.cn)
|
||||
- ⚖️ [使用条款](https://doc.oplist.org/terms)
|
||||
- 🔒 [隐私政策](https://doc.oplist.org/privacy)
|
||||
|
||||
## 演示
|
||||
## Demo
|
||||
|
||||
- 🇨🇳 [国内演示站](https://demo.oplist.org.cn)
|
||||
- 🌎 [海外演示站](https://demo.oplist.org)
|
||||
- 🌎 [全球 Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [中国 Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## 讨论
|
||||
|
||||
@@ -133,6 +135,14 @@ OpenList 是一个由 OpenList 团队独立维护的开源项目,遵循 AGPL-3
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## 捐赠者
|
||||
|
||||
感谢以下捐赠者的慷慨支持:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## 许可证
|
||||
|
||||
`OpenList` 是基于 [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) 许可证的开源软件。
|
||||
@@ -147,7 +157,7 @@ OpenList 是一个由 OpenList 团队独立维护的开源项目,遵循 AGPL-3
|
||||
- 本软件按“原样”提供,不附带任何明示或暗示的担保,包括但不限于适销性或特定用途的适用性。
|
||||
- 维护者不对因使用或无法使用本软件而导致的任何直接或间接损失负责。
|
||||
- 您需自行承担使用本软件的所有风险,包括但不限于账号被封、下载限速等。
|
||||
- 本项目遵循 [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) 许可证,详情请参见 [LICENSE](./LICENSE) 文件。
|
||||
- 本项目遵循 [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) 许可证,详情请参见 [LICENSE](../LICENSE) 文件。
|
||||
|
||||
## 联系我们
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList ist ein widerstandsfähiger, langfristig verwalteter und Community-getriebener Fork von AList, entwickelt zum Schutz von Open Source vor vertrauensbasierten Angriffen.</em></p>
|
||||
|
||||
<img src="https://goreportcard.com/badge/github.com/OpenListTeam/OpenList/v3" alt="latest version" />
|
||||
<a href="https://github.com/OpenListTeam/OpenList/blob/main/LICENSE"><img src="https://img.shields.io/github/license/OpenListTeam/OpenList" alt="License" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/actions/workflow/status/OpenListTeam/OpenList/build.yml?branch=main" alt="Build status" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/release/OpenListTeam/OpenList" alt="latest version" /></a>
|
||||
|
||||
<a href="https://github.com/OpenListTeam/OpenList/discussions"><img src="https://img.shields.io/github/discussions/OpenListTeam/OpenList?color=%23ED8936" alt="discussions" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/downloads/OpenListTeam/OpenList/total?color=%239F7AEA&logo=github" alt="Downloads" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | Deutsch | [Русский](./README_ru.md) | [Français](./README_fr.md) | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [Contributing](../CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](../CODE_OF_CONDUCT.md)
|
||||
- [LICENSE](../LICENSE)
|
||||
|
||||
## Haftungsausschluss
|
||||
|
||||
OpenList is an open-source project independently maintained by the OpenList Team under the AGPL-3.0 license, with a commitment to code openness and modification transparency.
|
||||
|
||||
OpenList has no official association with third-party derivative projects that use similar names, including OpenListApp/OpenListApp or paid proprietary software using the same or similar names.
|
||||
|
||||
- All software, code, and services of this project are maintained by the OpenList Team and are freely available on GitHub.
|
||||
- Project documentation and API services primarily rely on charitable resources provided by Cloudflare. There are currently no paid plans or commercial deployments.
|
||||
- Downstream projects should not use the "OpenList" name for impersonation or commercial confusion, and must not distribute OpenList-based code as closed source in violation of the AGPL license.
|
||||
- This software is provided "as is" without warranties. Please comply with applicable laws and regulations when using it.
|
||||
|
||||
## Funktionen
|
||||
|
||||
- [x] Multiple storages
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.alipan.com)
|
||||
- [x] OneDrive / Sharepoint ([Global](https://www.microsoft.com/en-us/microsoft-365/onedrive/online-cloud-storage), [CN](https://portal.partner.microsoftonline.cn), DE, US)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com)
|
||||
- [x] [123pan](https://www.123pan.com)
|
||||
- [x] [FTP / SFTP](https://en.wikipedia.org/wiki/File_Transfer_Protocol)
|
||||
- [x] [PikPak](https://www.mypikpak.com)
|
||||
- [x] [S3](https://aws.amazon.com/s3)
|
||||
- [x] [Seafile](https://seafile.com)
|
||||
- [x] [UPYUN Storage Service](https://www.upyun.com/products/file-storage)
|
||||
- [x] [WebDAV](https://en.wikipedia.org/wiki/WebDAV)
|
||||
- [x] Teambition([China](https://www.teambition.com), [International](https://us.teambition.com))
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
- [x] [UC](https://drive.uc.cn)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [Thunder](https://pan.xunlei.com)
|
||||
- [x] [Lanzou](https://www.lanzou.com)
|
||||
- [x] [ILanzou](https://www.ilanzou.com)
|
||||
- [x] [Google photo](https://photos.google.com)
|
||||
- [x] [Mega.nz](https://mega.nz)
|
||||
- [x] [Baidu photo](https://photo.baidu.com)
|
||||
- [x] [SMB](https://en.wikipedia.org/wiki/Server_Message_Block)
|
||||
- [x] [115](https://115.com)
|
||||
- [x] [Cloudreve](https://cloudreve.org)
|
||||
- [x] [Dropbox](https://www.dropbox.com)
|
||||
- [x] [FeijiPan](https://www.feijipan.com)
|
||||
- [x] [dogecloud](https://www.dogecloud.com/product/oss)
|
||||
- [x] [Azure Blob Storage](https://azure.microsoft.com/products/storage/blobs)
|
||||
- [x] [Chaoxing](https://www.chaoxing.com)
|
||||
- [x] [CNB](https://cnb.cool/)
|
||||
- [x] [Degoo](https://degoo.com)
|
||||
- [x] [Doubao](https://www.doubao.com)
|
||||
- [x] [Febbox](https://www.febbox.com)
|
||||
- [x] [GitHub](https://github.com)
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
- [x] Video and audio preview, with lyrics and subtitles support
|
||||
- [x] Office document preview (docx, pptx, xlsx, ...)
|
||||
- [x] `README.md` preview rendering
|
||||
- [x] File permalink copy and direct file download
|
||||
- [x] Dark mode and i18n
|
||||
- [x] Protected routes, WebDAV, Docker deploy, and Cloudflare Workers proxy
|
||||
- [x] File/folder package download and web upload operations
|
||||
- [x] Offline download, cross-storage copy, and multi-thread download acceleration
|
||||
|
||||
## Dokumentation
|
||||
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## Demo
|
||||
|
||||
- 🌎 [Global Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [CN Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## Diskussion
|
||||
|
||||
Please refer to [Discussions](https://github.com/OpenListTeam/OpenList/discussions) for general questions; Issues are for bug reports and feature requests only.
|
||||
|
||||
## Sponsor
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## Spender
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## Lizenz
|
||||
|
||||
OpenList is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
|
||||
## Kontakt
|
||||
|
||||
- [@GitHub](https://github.com/OpenListTeam)
|
||||
- [Telegram Group](https://t.me/OpenListTeam)
|
||||
- [Telegram Channel](https://t.me/OpenListOfficial)
|
||||
|
||||
## Mitwirkende
|
||||
|
||||
We sincerely thank [Xhofe](https://github.com/Xhofe), author of the original project [AlistGo/alist](https://github.com/AlistGo/alist), and all other contributors.
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList es un fork de AList resiliente, con gobernanza a largo plazo e impulsado por la comunidad, creado para defender el código abierto frente a ataques basados en la confianza.</em></p>
|
||||
|
||||
<img src="https://goreportcard.com/badge/github.com/OpenListTeam/OpenList/v3" alt="latest version" />
|
||||
<a href="https://github.com/OpenListTeam/OpenList/blob/main/LICENSE"><img src="https://img.shields.io/github/license/OpenListTeam/OpenList" alt="License" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/actions/workflow/status/OpenListTeam/OpenList/build.yml?branch=main" alt="Build status" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/release/OpenListTeam/OpenList" alt="latest version" /></a>
|
||||
|
||||
<a href="https://github.com/OpenListTeam/OpenList/discussions"><img src="https://img.shields.io/github/discussions/OpenListTeam/OpenList?color=%23ED8936" alt="discussions" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/downloads/OpenListTeam/OpenList/total?color=%239F7AEA&logo=github" alt="Downloads" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | [Français](./README_fr.md) | Español | [العربية](./README_ar.md)
|
||||
|
||||
- [Contributing](../CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](../CODE_OF_CONDUCT.md)
|
||||
- [LICENSE](../LICENSE)
|
||||
|
||||
## Aviso legal
|
||||
|
||||
OpenList is an open-source project independently maintained by the OpenList Team under the AGPL-3.0 license, with a commitment to code openness and modification transparency.
|
||||
|
||||
OpenList has no official association with third-party derivative projects that use similar names, including OpenListApp/OpenListApp or paid proprietary software using the same or similar names.
|
||||
|
||||
- All software, code, and services of this project are maintained by the OpenList Team and are freely available on GitHub.
|
||||
- Project documentation and API services primarily rely on charitable resources provided by Cloudflare. There are currently no paid plans or commercial deployments.
|
||||
- Downstream projects should not use the "OpenList" name for impersonation or commercial confusion, and must not distribute OpenList-based code as closed source in violation of the AGPL license.
|
||||
- This software is provided "as is" without warranties. Please comply with applicable laws and regulations when using it.
|
||||
|
||||
## Características
|
||||
|
||||
- [x] Multiple storages
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.alipan.com)
|
||||
- [x] OneDrive / Sharepoint ([Global](https://www.microsoft.com/en-us/microsoft-365/onedrive/online-cloud-storage), [CN](https://portal.partner.microsoftonline.cn), DE, US)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com)
|
||||
- [x] [123pan](https://www.123pan.com)
|
||||
- [x] [FTP / SFTP](https://en.wikipedia.org/wiki/File_Transfer_Protocol)
|
||||
- [x] [PikPak](https://www.mypikpak.com)
|
||||
- [x] [S3](https://aws.amazon.com/s3)
|
||||
- [x] [Seafile](https://seafile.com)
|
||||
- [x] [UPYUN Storage Service](https://www.upyun.com/products/file-storage)
|
||||
- [x] [WebDAV](https://en.wikipedia.org/wiki/WebDAV)
|
||||
- [x] Teambition([China](https://www.teambition.com), [International](https://us.teambition.com))
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
- [x] [UC](https://drive.uc.cn)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [Thunder](https://pan.xunlei.com)
|
||||
- [x] [Lanzou](https://www.lanzou.com)
|
||||
- [x] [ILanzou](https://www.ilanzou.com)
|
||||
- [x] [Google photo](https://photos.google.com)
|
||||
- [x] [Mega.nz](https://mega.nz)
|
||||
- [x] [Baidu photo](https://photo.baidu.com)
|
||||
- [x] [SMB](https://en.wikipedia.org/wiki/Server_Message_Block)
|
||||
- [x] [115](https://115.com)
|
||||
- [x] [Cloudreve](https://cloudreve.org)
|
||||
- [x] [Dropbox](https://www.dropbox.com)
|
||||
- [x] [FeijiPan](https://www.feijipan.com)
|
||||
- [x] [dogecloud](https://www.dogecloud.com/product/oss)
|
||||
- [x] [Azure Blob Storage](https://azure.microsoft.com/products/storage/blobs)
|
||||
- [x] [Chaoxing](https://www.chaoxing.com)
|
||||
- [x] [CNB](https://cnb.cool/)
|
||||
- [x] [Degoo](https://degoo.com)
|
||||
- [x] [Doubao](https://www.doubao.com)
|
||||
- [x] [Febbox](https://www.febbox.com)
|
||||
- [x] [GitHub](https://github.com)
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
- [x] Video and audio preview, with lyrics and subtitles support
|
||||
- [x] Office document preview (docx, pptx, xlsx, ...)
|
||||
- [x] `README.md` preview rendering
|
||||
- [x] File permalink copy and direct file download
|
||||
- [x] Dark mode and i18n
|
||||
- [x] Protected routes, WebDAV, Docker deploy, and Cloudflare Workers proxy
|
||||
- [x] File/folder package download and web upload operations
|
||||
- [x] Offline download, cross-storage copy, and multi-thread download acceleration
|
||||
|
||||
## Documentación
|
||||
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## Demo
|
||||
|
||||
- 🌎 [Global Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [CN Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## Discusión
|
||||
|
||||
Please refer to [Discussions](https://github.com/OpenListTeam/OpenList/discussions) for general questions; Issues are for bug reports and feature requests only.
|
||||
|
||||
## Patrocinador
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## Donantes
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## Licencia
|
||||
|
||||
OpenList is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
|
||||
## Contacto
|
||||
|
||||
- [@GitHub](https://github.com/OpenListTeam)
|
||||
- [Telegram Group](https://t.me/OpenListTeam)
|
||||
- [Telegram Channel](https://t.me/OpenListOfficial)
|
||||
|
||||
## Colaboradores
|
||||
|
||||
We sincerely thank [Xhofe](https://github.com/Xhofe), author of the original project [AlistGo/alist](https://github.com/AlistGo/alist), and all other contributors.
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList est un fork d’AList résilient, gouverné sur le long terme et porté par la communauté, conçu pour protéger l’open source contre les attaques fondées sur la confiance.</em></p>
|
||||
|
||||
<img src="https://goreportcard.com/badge/github.com/OpenListTeam/OpenList/v3" alt="latest version" />
|
||||
<a href="https://github.com/OpenListTeam/OpenList/blob/main/LICENSE"><img src="https://img.shields.io/github/license/OpenListTeam/OpenList" alt="License" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/actions/workflow/status/OpenListTeam/OpenList/build.yml?branch=main" alt="Build status" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/release/OpenListTeam/OpenList" alt="latest version" /></a>
|
||||
|
||||
<a href="https://github.com/OpenListTeam/OpenList/discussions"><img src="https://img.shields.io/github/discussions/OpenListTeam/OpenList?color=%23ED8936" alt="discussions" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/downloads/OpenListTeam/OpenList/total?color=%239F7AEA&logo=github" alt="Downloads" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | Français | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [Contributing](../CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](../CODE_OF_CONDUCT.md)
|
||||
- [LICENSE](../LICENSE)
|
||||
|
||||
## Avertissement
|
||||
|
||||
OpenList is an open-source project independently maintained by the OpenList Team under the AGPL-3.0 license, with a commitment to code openness and modification transparency.
|
||||
|
||||
OpenList has no official association with third-party derivative projects that use similar names, including OpenListApp/OpenListApp or paid proprietary software using the same or similar names.
|
||||
|
||||
- All software, code, and services of this project are maintained by the OpenList Team and are freely available on GitHub.
|
||||
- Project documentation and API services primarily rely on charitable resources provided by Cloudflare. There are currently no paid plans or commercial deployments.
|
||||
- Downstream projects should not use the "OpenList" name for impersonation or commercial confusion, and must not distribute OpenList-based code as closed source in violation of the AGPL license.
|
||||
- This software is provided "as is" without warranties. Please comply with applicable laws and regulations when using it.
|
||||
|
||||
## Fonctionnalités
|
||||
|
||||
- [x] Multiple storages
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.alipan.com)
|
||||
- [x] OneDrive / Sharepoint ([Global](https://www.microsoft.com/en-us/microsoft-365/onedrive/online-cloud-storage), [CN](https://portal.partner.microsoftonline.cn), DE, US)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com)
|
||||
- [x] [123pan](https://www.123pan.com)
|
||||
- [x] [FTP / SFTP](https://en.wikipedia.org/wiki/File_Transfer_Protocol)
|
||||
- [x] [PikPak](https://www.mypikpak.com)
|
||||
- [x] [S3](https://aws.amazon.com/s3)
|
||||
- [x] [Seafile](https://seafile.com)
|
||||
- [x] [UPYUN Storage Service](https://www.upyun.com/products/file-storage)
|
||||
- [x] [WebDAV](https://en.wikipedia.org/wiki/WebDAV)
|
||||
- [x] Teambition([China](https://www.teambition.com), [International](https://us.teambition.com))
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
- [x] [UC](https://drive.uc.cn)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [Thunder](https://pan.xunlei.com)
|
||||
- [x] [Lanzou](https://www.lanzou.com)
|
||||
- [x] [ILanzou](https://www.ilanzou.com)
|
||||
- [x] [Google photo](https://photos.google.com)
|
||||
- [x] [Mega.nz](https://mega.nz)
|
||||
- [x] [Baidu photo](https://photo.baidu.com)
|
||||
- [x] [SMB](https://en.wikipedia.org/wiki/Server_Message_Block)
|
||||
- [x] [115](https://115.com)
|
||||
- [x] [Cloudreve](https://cloudreve.org)
|
||||
- [x] [Dropbox](https://www.dropbox.com)
|
||||
- [x] [FeijiPan](https://www.feijipan.com)
|
||||
- [x] [dogecloud](https://www.dogecloud.com/product/oss)
|
||||
- [x] [Azure Blob Storage](https://azure.microsoft.com/products/storage/blobs)
|
||||
- [x] [Chaoxing](https://www.chaoxing.com)
|
||||
- [x] [CNB](https://cnb.cool/)
|
||||
- [x] [Degoo](https://degoo.com)
|
||||
- [x] [Doubao](https://www.doubao.com)
|
||||
- [x] [Febbox](https://www.febbox.com)
|
||||
- [x] [GitHub](https://github.com)
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
- [x] Video and audio preview, with lyrics and subtitles support
|
||||
- [x] Office document preview (docx, pptx, xlsx, ...)
|
||||
- [x] `README.md` preview rendering
|
||||
- [x] File permalink copy and direct file download
|
||||
- [x] Dark mode and i18n
|
||||
- [x] Protected routes, WebDAV, Docker deploy, and Cloudflare Workers proxy
|
||||
- [x] File/folder package download and web upload operations
|
||||
- [x] Offline download, cross-storage copy, and multi-thread download acceleration
|
||||
|
||||
## Documentation
|
||||
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## Démo
|
||||
|
||||
- 🌎 [Global Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [CN Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## Discussion
|
||||
|
||||
Please refer to [Discussions](https://github.com/OpenListTeam/OpenList/discussions) for general questions; Issues are for bug reports and feature requests only.
|
||||
|
||||
## Sponsor
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## Donateurs
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## Licence
|
||||
|
||||
OpenList is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
|
||||
## Nous contacter
|
||||
|
||||
- [@GitHub](https://github.com/OpenListTeam)
|
||||
- [Telegram Group](https://t.me/OpenListTeam)
|
||||
- [Telegram Channel](https://t.me/OpenListOfficial)
|
||||
|
||||
## Contributeurs
|
||||
|
||||
We sincerely thank [Xhofe](https://github.com/Xhofe), author of the original project [AlistGo/alist](https://github.com/AlistGo/alist), and all other contributors.
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
@@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<img style="width: 128px; height: 128px;" src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" alt="logo" />
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList は、信頼ベースの攻撃からオープンソースを守るために構築された、レジリエントで長期ガバナンス、コミュニティ主導の AList フォークです。</em></p>
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
|
||||
---
|
||||
|
||||
- [English](./README.md) | [中文](./README_cn.md) | 日本語 | [Dutch](./README_nl.md)
|
||||
- [English](../README.md) | [中文](./README_cn.md) | 日本語 | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | [Français](./README_fr.md) | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [コントリビュート](./CONTRIBUTING.md)
|
||||
- [行動規範](./CODE_OF_CONDUCT.md)
|
||||
- [ライセンス](./LICENSE)
|
||||
- [コントリビュート](../CONTRIBUTING.md)
|
||||
- [行動規範](../CODE_OF_CONDUCT.md)
|
||||
- [ライセンス](../LICENSE)
|
||||
|
||||
## 免責事項
|
||||
|
||||
@@ -66,7 +66,7 @@ OpenListプロジェクトへのご支援とご理解をありがとうござい
|
||||
- [x] Teambition([中国](https://www.teambition.com), [国際](https://us.teambition.com))
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com)(個人、家族、グループ)
|
||||
- [x] [139yun](https://yun.139.com)(個人、家族、グループ、共有)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
@@ -94,6 +94,7 @@ OpenListプロジェクトへのご支援とご理解をありがとうござい
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk ドキュメント](https://alidocs.dingtalk.com/)
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] 簡単にデプロイでき、すぐに使える
|
||||
- [x] ファイルプレビュー(PDF、markdown、コード、テキストなど)
|
||||
@@ -116,14 +117,15 @@ OpenListプロジェクトへのご支援とご理解をありがとうござい
|
||||
|
||||
## ドキュメント
|
||||
|
||||
- 📘 [グローバルサイト](https://doc.oplist.org)
|
||||
- 📚 [バックアップサイト](https://doc.openlist.team)
|
||||
- 🌏 [CNサイト](https://doc.oplist.org.cn)
|
||||
- 📘 [ドキュメント](https://doc.oplist.org)
|
||||
- 🌏 [中国ミラー](https://doc.oplist.org.cn)
|
||||
- ⚖️ [利用規約](https://doc.oplist.org/terms)
|
||||
- 🔒 [プライバシーポリシー](https://doc.oplist.org/privacy)
|
||||
|
||||
## デモ
|
||||
## Demo
|
||||
|
||||
- 🌎 [グローバルデモ](https://demo.oplist.org)
|
||||
- 🇨🇳 [CNデモ](https://demo.oplist.org.cn)
|
||||
- 🌎 [グローバル Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [中国 Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## ディスカッション
|
||||
|
||||
@@ -133,6 +135,14 @@ OpenListプロジェクトへのご支援とご理解をありがとうござい
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## 寄付者
|
||||
|
||||
以下の方々の寛大なご支援に感謝いたします:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## ライセンス
|
||||
|
||||
「OpenList」は [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) ライセンスの下で公開されているオープンソースソフトウェアです。
|
||||
@@ -147,7 +157,7 @@ OpenListプロジェクトへのご支援とご理解をありがとうござい
|
||||
- 本ソフトウェアは「現状有姿」で提供されており、商品性や特定目的への適合性を含むいかなる保証もありません。
|
||||
- 本ソフトウェアの使用または使用不能によるいかなる直接的・間接的損害についても、メンテナは責任を負いません。
|
||||
- 本ソフトウェアの利用に伴うすべてのリスク(アカウントの凍結やダウンロード速度制限などを含む)は、利用者自身が負うものとします。
|
||||
- 本プロジェクトは [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) ライセンスに従います。詳細は [LICENSE](./LICENSE) ファイルをご覧ください。
|
||||
- 本プロジェクトは [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) ライセンスに従います。詳細は [LICENSE](../LICENSE) ファイルをご覧ください。
|
||||
|
||||
## お問い合わせ
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList는 신뢰 기반 공격으로부터 오픈 소스를 보호하기 위해 만들어진, 탄력적이고 장기 거버넌스를 지향하는 커뮤니티 주도 AList 포크입니다.</em></p>
|
||||
|
||||
<img src="https://goreportcard.com/badge/github.com/OpenListTeam/OpenList/v3" alt="latest version" />
|
||||
<a href="https://github.com/OpenListTeam/OpenList/blob/main/LICENSE"><img src="https://img.shields.io/github/license/OpenListTeam/OpenList" alt="License" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/actions/workflow/status/OpenListTeam/OpenList/build.yml?branch=main" alt="Build status" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/release/OpenListTeam/OpenList" alt="latest version" /></a>
|
||||
|
||||
<a href="https://github.com/OpenListTeam/OpenList/discussions"><img src="https://img.shields.io/github/discussions/OpenListTeam/OpenList?color=%23ED8936" alt="discussions" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/downloads/OpenListTeam/OpenList/total?color=%239F7AEA&logo=github" alt="Downloads" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | 한국어 | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | [Français](./README_fr.md) | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [Contributing](../CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](../CODE_OF_CONDUCT.md)
|
||||
- [LICENSE](../LICENSE)
|
||||
|
||||
## 면책 조항
|
||||
|
||||
OpenList is an open-source project independently maintained by the OpenList Team under the AGPL-3.0 license, with a commitment to code openness and modification transparency.
|
||||
|
||||
OpenList has no official association with third-party derivative projects that use similar names, including OpenListApp/OpenListApp or paid proprietary software using the same or similar names.
|
||||
|
||||
- All software, code, and services of this project are maintained by the OpenList Team and are freely available on GitHub.
|
||||
- Project documentation and API services primarily rely on charitable resources provided by Cloudflare. There are currently no paid plans or commercial deployments.
|
||||
- Downstream projects should not use the "OpenList" name for impersonation or commercial confusion, and must not distribute OpenList-based code as closed source in violation of the AGPL license.
|
||||
- This software is provided "as is" without warranties. Please comply with applicable laws and regulations when using it.
|
||||
|
||||
## 기능
|
||||
|
||||
- [x] Multiple storages
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.alipan.com)
|
||||
- [x] OneDrive / Sharepoint ([Global](https://www.microsoft.com/en-us/microsoft-365/onedrive/online-cloud-storage), [CN](https://portal.partner.microsoftonline.cn), DE, US)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com)
|
||||
- [x] [123pan](https://www.123pan.com)
|
||||
- [x] [FTP / SFTP](https://en.wikipedia.org/wiki/File_Transfer_Protocol)
|
||||
- [x] [PikPak](https://www.mypikpak.com)
|
||||
- [x] [S3](https://aws.amazon.com/s3)
|
||||
- [x] [Seafile](https://seafile.com)
|
||||
- [x] [UPYUN Storage Service](https://www.upyun.com/products/file-storage)
|
||||
- [x] [WebDAV](https://en.wikipedia.org/wiki/WebDAV)
|
||||
- [x] Teambition([China](https://www.teambition.com), [International](https://us.teambition.com))
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
- [x] [UC](https://drive.uc.cn)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [Thunder](https://pan.xunlei.com)
|
||||
- [x] [Lanzou](https://www.lanzou.com)
|
||||
- [x] [ILanzou](https://www.ilanzou.com)
|
||||
- [x] [Google photo](https://photos.google.com)
|
||||
- [x] [Mega.nz](https://mega.nz)
|
||||
- [x] [Baidu photo](https://photo.baidu.com)
|
||||
- [x] [SMB](https://en.wikipedia.org/wiki/Server_Message_Block)
|
||||
- [x] [115](https://115.com)
|
||||
- [x] [Cloudreve](https://cloudreve.org)
|
||||
- [x] [Dropbox](https://www.dropbox.com)
|
||||
- [x] [FeijiPan](https://www.feijipan.com)
|
||||
- [x] [dogecloud](https://www.dogecloud.com/product/oss)
|
||||
- [x] [Azure Blob Storage](https://azure.microsoft.com/products/storage/blobs)
|
||||
- [x] [Chaoxing](https://www.chaoxing.com)
|
||||
- [x] [CNB](https://cnb.cool/)
|
||||
- [x] [Degoo](https://degoo.com)
|
||||
- [x] [Doubao](https://www.doubao.com)
|
||||
- [x] [Febbox](https://www.febbox.com)
|
||||
- [x] [GitHub](https://github.com)
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
- [x] Video and audio preview, with lyrics and subtitles support
|
||||
- [x] Office document preview (docx, pptx, xlsx, ...)
|
||||
- [x] `README.md` preview rendering
|
||||
- [x] File permalink copy and direct file download
|
||||
- [x] Dark mode and i18n
|
||||
- [x] Protected routes, WebDAV, Docker deploy, and Cloudflare Workers proxy
|
||||
- [x] File/folder package download and web upload operations
|
||||
- [x] Offline download, cross-storage copy, and multi-thread download acceleration
|
||||
|
||||
## 문서
|
||||
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## 데모
|
||||
|
||||
- 🌎 [Global Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [CN Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## 토론
|
||||
|
||||
Please refer to [Discussions](https://github.com/OpenListTeam/OpenList/discussions) for general questions; Issues are for bug reports and feature requests only.
|
||||
|
||||
## 후원
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## 후원자
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## 라이선스
|
||||
|
||||
OpenList is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
|
||||
## 문의
|
||||
|
||||
- [@GitHub](https://github.com/OpenListTeam)
|
||||
- [Telegram Group](https://t.me/OpenListTeam)
|
||||
- [Telegram Channel](https://t.me/OpenListOfficial)
|
||||
|
||||
## 기여자
|
||||
|
||||
We sincerely thank [Xhofe](https://github.com/Xhofe), author of the original project [AlistGo/alist](https://github.com/AlistGo/alist), and all other contributors.
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
@@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<img style="width: 128px; height: 128px;" src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" alt="logo" />
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList is een veerkrachtige, langetermijn, door de gemeenschap geleide fork van AList — gebouwd om open source te beschermen tegen op vertrouwen gebaseerde aanvallen.</em></p>
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
|
||||
---
|
||||
|
||||
- [English](./README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | Dutch
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | Dutch | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | [Русский](./README_ru.md) | [Français](./README_fr.md) | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [Bijdragen](./CONTRIBUTING.md)
|
||||
- [Gedragscode](./CODE_OF_CONDUCT.md)
|
||||
- [Licentie](./LICENSE)
|
||||
- [Bijdragen](../CONTRIBUTING.md)
|
||||
- [Gedragscode](../CODE_OF_CONDUCT.md)
|
||||
- [Licentie](../LICENSE)
|
||||
|
||||
## Disclaimer
|
||||
|
||||
@@ -67,7 +67,7 @@ Dank u voor uw ondersteuning en begrip
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Persoonlijk, Familie, Groep)
|
||||
- [x] [139yun](https://yun.139.com) (Persoonlijk, Familie, Groep, Delen)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
@@ -95,6 +95,7 @@ Dank u voor uw ondersteuning en begrip
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk-documenten](https://alidocs.dingtalk.com/)
|
||||
- [x] Eenvoudig te implementeren en direct te gebruiken
|
||||
- [x] Bestandsvoorbeeld (PDF, markdown, code, platte tekst, ...)
|
||||
- [x] Afbeeldingsvoorbeeld in galerijweergave
|
||||
@@ -116,9 +117,10 @@ Dank u voor uw ondersteuning en begrip
|
||||
|
||||
## Documentatie
|
||||
|
||||
- 📘 [Global Site](https://doc.oplist.org)
|
||||
- 📚 [Backup Site](https://doc.openlist.team)
|
||||
- 🌏 [CN Site](https://doc.oplist.org.cn)
|
||||
- 📘 [Documentatie](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Gebruiksvoorwaarden](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacybeleid](https://doc.oplist.org/privacy)
|
||||
|
||||
## Demo
|
||||
|
||||
@@ -133,6 +135,14 @@ Stel algemene vragen in [*Discussions*](https://github.com/OpenListTeam/OpenList
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## Donatie Bijdragers
|
||||
|
||||
Dank aan de volgende donateurs voor hun steun:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## Licentie
|
||||
|
||||
`OpenList` is open-source software onder de [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) licentie.
|
||||
@@ -147,7 +157,7 @@ Stel algemene vragen in [*Discussions*](https://github.com/OpenListTeam/OpenList
|
||||
- De software wordt geleverd "zoals deze is", zonder enige vorm van garantie, expliciet of impliciet, inclusief maar niet beperkt tot garanties van verkoopbaarheid of geschiktheid voor een bepaald doel.
|
||||
- De beheerders zijn niet aansprakelijk voor enige directe of indirecte schade die voortvloeit uit het gebruik van of het onvermogen om deze software te gebruiken.
|
||||
- U bent zelf verantwoordelijk voor alle risico's die gepaard gaan met het gebruik van deze software, inclusief maar niet beperkt tot accountblokkades of downloadbeperkingen.
|
||||
- Dit project valt onder de [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) licentie. Zie het [LICENSE](./LICENSE) bestand voor details.
|
||||
- Dit project valt onder de [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) licentie. Zie het [LICENSE](../LICENSE) bestand voor details.
|
||||
|
||||
## Contact
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/OpenListTeam/Logo/main/logo.svg" width="128" height="128" alt="logo" />
|
||||
|
||||
<p><em>OpenList — устойчивый, управляемый сообществом форк AList с долгосрочным управлением, созданный для защиты open source от атак, основанных на доверии.</em></p>
|
||||
|
||||
<img src="https://goreportcard.com/badge/github.com/OpenListTeam/OpenList/v3" alt="latest version" />
|
||||
<a href="https://github.com/OpenListTeam/OpenList/blob/main/LICENSE"><img src="https://img.shields.io/github/license/OpenListTeam/OpenList" alt="License" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/actions/workflow/status/OpenListTeam/OpenList/build.yml?branch=main" alt="Build status" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/release/OpenListTeam/OpenList" alt="latest version" /></a>
|
||||
|
||||
<a href="https://github.com/OpenListTeam/OpenList/discussions"><img src="https://img.shields.io/github/discussions/OpenListTeam/OpenList?color=%23ED8936" alt="discussions" /></a>
|
||||
<a href="https://github.com/OpenListTeam/OpenList/releases"><img src="https://img.shields.io/github/downloads/OpenListTeam/OpenList/total?color=%239F7AEA&logo=github" alt="Downloads" /></a>
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
- [English](../README.md) | [中文](./README_cn.md) | [日本語](./README_ja.md) | [Dutch](./README_nl.md) | [한국어](./README_ko.md) | [Deutsch](./README_de.md) | Русский | [Français](./README_fr.md) | [Español](./README_es.md) | [العربية](./README_ar.md)
|
||||
|
||||
- [Contributing](../CONTRIBUTING.md)
|
||||
- [CODE OF CONDUCT](../CODE_OF_CONDUCT.md)
|
||||
- [LICENSE](../LICENSE)
|
||||
|
||||
## Отказ от ответственности
|
||||
|
||||
OpenList is an open-source project independently maintained by the OpenList Team under the AGPL-3.0 license, with a commitment to code openness and modification transparency.
|
||||
|
||||
OpenList has no official association with third-party derivative projects that use similar names, including OpenListApp/OpenListApp or paid proprietary software using the same or similar names.
|
||||
|
||||
- All software, code, and services of this project are maintained by the OpenList Team and are freely available on GitHub.
|
||||
- Project documentation and API services primarily rely on charitable resources provided by Cloudflare. There are currently no paid plans or commercial deployments.
|
||||
- Downstream projects should not use the "OpenList" name for impersonation or commercial confusion, and must not distribute OpenList-based code as closed source in violation of the AGPL license.
|
||||
- This software is provided "as is" without warranties. Please comply with applicable laws and regulations when using it.
|
||||
|
||||
## Возможности
|
||||
|
||||
- [x] Multiple storages
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.alipan.com)
|
||||
- [x] OneDrive / Sharepoint ([Global](https://www.microsoft.com/en-us/microsoft-365/onedrive/online-cloud-storage), [CN](https://portal.partner.microsoftonline.cn), DE, US)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com)
|
||||
- [x] [123pan](https://www.123pan.com)
|
||||
- [x] [FTP / SFTP](https://en.wikipedia.org/wiki/File_Transfer_Protocol)
|
||||
- [x] [PikPak](https://www.mypikpak.com)
|
||||
- [x] [S3](https://aws.amazon.com/s3)
|
||||
- [x] [Seafile](https://seafile.com)
|
||||
- [x] [UPYUN Storage Service](https://www.upyun.com/products/file-storage)
|
||||
- [x] [WebDAV](https://en.wikipedia.org/wiki/WebDAV)
|
||||
- [x] Teambition([China](https://www.teambition.com), [International](https://us.teambition.com))
|
||||
- [x] [MediaFire](https://www.mediafire.com)
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn)
|
||||
- [x] [ProtonDrive](https://proton.me/drive)
|
||||
- [x] [139yun](https://yun.139.com) (Personal, Family, Group, Share)
|
||||
- [x] [YandexDisk](https://disk.yandex.com)
|
||||
- [x] [BaiduNetdisk](http://pan.baidu.com)
|
||||
- [x] [Terabox](https://www.terabox.com/main)
|
||||
- [x] [UC](https://drive.uc.cn)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [Thunder](https://pan.xunlei.com)
|
||||
- [x] [Lanzou](https://www.lanzou.com)
|
||||
- [x] [ILanzou](https://www.ilanzou.com)
|
||||
- [x] [Google photo](https://photos.google.com)
|
||||
- [x] [Mega.nz](https://mega.nz)
|
||||
- [x] [Baidu photo](https://photo.baidu.com)
|
||||
- [x] [SMB](https://en.wikipedia.org/wiki/Server_Message_Block)
|
||||
- [x] [115](https://115.com)
|
||||
- [x] [Cloudreve](https://cloudreve.org)
|
||||
- [x] [Dropbox](https://www.dropbox.com)
|
||||
- [x] [FeijiPan](https://www.feijipan.com)
|
||||
- [x] [dogecloud](https://www.dogecloud.com/product/oss)
|
||||
- [x] [Azure Blob Storage](https://azure.microsoft.com/products/storage/blobs)
|
||||
- [x] [Chaoxing](https://www.chaoxing.com)
|
||||
- [x] [CNB](https://cnb.cool/)
|
||||
- [x] [Degoo](https://degoo.com)
|
||||
- [x] [Doubao](https://www.doubao.com)
|
||||
- [x] [Febbox](https://www.febbox.com)
|
||||
- [x] [GitHub](https://github.com)
|
||||
- [x] [OpenList](https://github.com/OpenListTeam/OpenList)
|
||||
- [x] [Teldrive](https://github.com/tgdrive/teldrive)
|
||||
- [x] [Weiyun](https://www.weiyun.com)
|
||||
- [x] [DingTalk Docs](https://alidocs.dingtalk.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
- [x] Video and audio preview, with lyrics and subtitles support
|
||||
- [x] Office document preview (docx, pptx, xlsx, ...)
|
||||
- [x] `README.md` preview rendering
|
||||
- [x] File permalink copy and direct file download
|
||||
- [x] Dark mode and i18n
|
||||
- [x] Protected routes, WebDAV, Docker deploy, and Cloudflare Workers proxy
|
||||
- [x] File/folder package download and web upload operations
|
||||
- [x] Offline download, cross-storage copy, and multi-thread download acceleration
|
||||
|
||||
## Документация
|
||||
|
||||
- 📘 [Docs](https://doc.oplist.org)
|
||||
- 🌏 [CN Mirror](https://doc.oplist.org.cn)
|
||||
- ⚖️ [Terms of Use](https://doc.oplist.org/terms)
|
||||
- 🔒 [Privacy Policy](https://doc.oplist.org/privacy)
|
||||
|
||||
## Демо
|
||||
|
||||
- 🌎 [Global Demo](https://demo.oplist.org)
|
||||
- 🇨🇳 [CN Demo](https://demo.oplist.org.cn)
|
||||
|
||||
## Обсуждение
|
||||
|
||||
Please refer to [Discussions](https://github.com/OpenListTeam/OpenList/discussions) for general questions; Issues are for bug reports and feature requests only.
|
||||
|
||||
## Спонсор
|
||||
|
||||
[](https://vps.town "VPS.Town - Trust, Effortlessly. Your Cloud, Reimagined.")
|
||||
|
||||
## Доноры
|
||||
|
||||
Thanks to the following donors for their generous support:
|
||||
|
||||
- [HisAtri](https://github.com/HisAtri)
|
||||
- 爱发电用户_7jTh
|
||||
- suka
|
||||
|
||||
## Лицензия
|
||||
|
||||
OpenList is open-source software licensed under the [AGPL-3.0](https://www.gnu.org/licenses/agpl-3.0.txt) license.
|
||||
|
||||
## Связаться с нами
|
||||
|
||||
- [@GitHub](https://github.com/OpenListTeam)
|
||||
- [Telegram Group](https://t.me/OpenListTeam)
|
||||
- [Telegram Channel](https://t.me/OpenListOfficial)
|
||||
|
||||
## Участники
|
||||
|
||||
We sincerely thank [Xhofe](https://github.com/Xhofe), author of the original project [AlistGo/alist](https://github.com/AlistGo/alist), and all other contributors.
|
||||
|
||||
[](https://github.com/OpenListTeam/OpenList/graphs/contributors)
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
Only the latest stable release receives security patches. We strongly recommend always keeping OpenList up to date.
|
||||
|
||||
| Version | Supported |
|
||||
| -------------------- | ------------------ |
|
||||
| Latest stable (v4.x) | :white_check_mark: |
|
||||
| Older versions | :x: |
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Please do NOT report security vulnerabilities through public GitHub Issues.**
|
||||
|
||||
If you discover a security vulnerability in OpenList, please report it responsibly by using one of the following channels:
|
||||
|
||||
- **GitHub Private Security Advisory** (preferred): [Submit here](https://github.com/OpenListTeam/OpenList/security/advisories/new)
|
||||
- **Telegram**: Contact a maintainer privately via [@OpenListTeam](https://t.me/OpenListTeam)
|
||||
|
||||
When reporting, please include as much of the following as possible:
|
||||
|
||||
- A description of the vulnerability and its potential impact
|
||||
- The affected version(s)
|
||||
- Step-by-step instructions to reproduce the issue
|
||||
- Any proof-of-concept code or screenshots (if applicable)
|
||||
- Suggested mitigation or fix (optional but appreciated)
|
||||
|
||||
## Security Best Practices for Users
|
||||
|
||||
To keep your OpenList instance secure:
|
||||
|
||||
- Always update to the latest release.
|
||||
- Use a strong, unique admin password and change it after first login.
|
||||
- Enable HTTPS (TLS) for your deployment — do **not** expose OpenList over plain HTTP on the public internet.
|
||||
- Limit exposed ports using a reverse proxy (e.g., Nginx, Caddy).
|
||||
- Set up access controls and avoid enabling guest access unless necessary.
|
||||
- Regularly review mounted storage permissions and revoke unused API tokens.
|
||||
- When using Docker, avoid running the container as root if possible.
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
We sincerely thank all security researchers and community members who responsibly disclose vulnerabilities and help make OpenList safer for everyone.
|
||||
|
||||
---
|
||||
|
||||
# 安全政策
|
||||
|
||||
## 支持的版本
|
||||
|
||||
我们仅对最新稳定版本提供安全补丁。强烈建议始终保持 OpenList 为最新版本。
|
||||
|
||||
| 版本 | 是否支持 |
|
||||
| ------------------ | ------------------ |
|
||||
| 最新稳定版(v4.x) | :white_check_mark: |
|
||||
| 旧版本 | :x: |
|
||||
|
||||
## 报告漏洞
|
||||
|
||||
**请勿通过公开的 GitHub Issues 报告安全漏洞。**
|
||||
|
||||
如果您在 OpenList 中发现安全漏洞,请通过以下渠道之一负责任地进行报告:
|
||||
|
||||
- **GitHub 私密安全公告**(推荐):[点击提交](https://github.com/OpenListTeam/OpenList/security/advisories/new)
|
||||
- **Telegram**:通过 [@OpenListTeam](https://t.me/OpenListTeam) 私信联系维护者
|
||||
|
||||
报告时,请尽量提供以下信息:
|
||||
|
||||
- 漏洞描述及其潜在影响
|
||||
- 受影响的版本
|
||||
- 复现问题的详细步骤
|
||||
- 概念验证代码或截图(如有)
|
||||
- 建议的缓解措施或修复方案(可选,但非常欢迎)
|
||||
|
||||
## 用户安全最佳实践
|
||||
|
||||
为保障您的 OpenList 实例安全:
|
||||
|
||||
- 始终更新至最新版本。
|
||||
- 使用强且唯一的管理员密码,并在首次登录后立即修改。
|
||||
- 为您的部署启用 HTTPS(TLS)—— **请勿**在公网上以明文 HTTP 方式暴露 OpenList。
|
||||
- 使用反向代理(如 Nginx、Caddy)限制对外暴露的端口。
|
||||
- 配置访问控制,非必要情况下不要开启访客访问。
|
||||
- 定期检查已挂载存储的权限,并撤销未使用的 API 令牌。
|
||||
- 使用 Docker 部署时,尽可能避免以 root 用户运行容器。
|
||||
|
||||
## 致谢
|
||||
|
||||
我们衷心感谢所有负责任地披露漏洞、帮助 OpenList 变得更加安全的安全研究人员和社区成员。
|
||||
@@ -48,8 +48,56 @@ ldflags="\
|
||||
-X 'github.com/OpenListTeam/OpenList/v4/internal/conf.WebVersion=$webVersion' \
|
||||
"
|
||||
|
||||
# Keep sqlite driver tag selection centralized to avoid target drift.
|
||||
GetBuildTagsForTarget() {
|
||||
local target="$1"
|
||||
case "$target" in
|
||||
linux-loong64|linux-mips|linux-mips64|linux-mips64le|linux-mipsle|linux-musl-loong64|linux-musl-mips|linux-musl-mips64|linux-musl-mips64le|linux-musl-mipsle|windows-386|windows7-386|windows7-amd64)
|
||||
echo "jsoniter,sqlite_cgo_compat"
|
||||
;;
|
||||
*)
|
||||
echo "jsoniter"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Keep musl static link flags centralized for all musl build paths.
|
||||
GetMuslStaticLdflags() {
|
||||
echo "-linkmode external -extldflags '-static -fpic' $ldflags"
|
||||
}
|
||||
|
||||
# Fail fast if a musl build artifact is not fully static.
|
||||
AssertStaticBinary() {
|
||||
local binary="$1"
|
||||
if [ ! -f "$binary" ]; then
|
||||
echo "Error: binary not found: $binary"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if command -v readelf >/dev/null 2>&1; then
|
||||
if readelf -l "$binary" 2>/dev/null | grep -q "Requesting program interpreter"; then
|
||||
echo "Error: binary is not fully static: $binary"
|
||||
readelf -l "$binary" | grep "Requesting program interpreter" || true
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
if command -v file >/dev/null 2>&1; then
|
||||
if file "$binary" | grep -qi "dynamically linked"; then
|
||||
echo "Error: binary is dynamically linked: $binary"
|
||||
file "$binary"
|
||||
return 1
|
||||
fi
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "Warning: readelf/file not found, skip static verification for $binary"
|
||||
return 0
|
||||
}
|
||||
|
||||
FetchWebRolling() {
|
||||
pre_release_json=$(eval "curl -fsSL --max-time 2 $githubAuthArgs -H \"Accept: application/vnd.github.v3+json\" \"https://api.github.com/repos/$frontendRepo/releases/tags/rolling\"")
|
||||
pre_release_json=$(eval "curl -fsSL --max-time 2 $githubAuthArgs -H \"Accept: application/vnd.github.v3+json\" \"https://api.github.com/repos/$frontendRepo/releases/tags/edge\"")
|
||||
pre_release_assets=$(echo "$pre_release_json" | jq -r '.assets[].browser_download_url')
|
||||
|
||||
# There is no lite for rolling
|
||||
@@ -110,6 +158,7 @@ BuildWin7() {
|
||||
# Build for both 386 and amd64 architectures
|
||||
for arch in "386" "amd64"; do
|
||||
echo "building for windows7-${arch}"
|
||||
build_tags=$(GetBuildTagsForTarget "windows7-${arch}")
|
||||
export GOOS=windows
|
||||
export GOARCH=${arch}
|
||||
export CGO_ENABLED=1
|
||||
@@ -124,14 +173,13 @@ BuildWin7() {
|
||||
fi
|
||||
|
||||
# Use the patched Go compiler for Win7 compatibility
|
||||
$(pwd)/go-win7/bin/go build -o "${1}-${arch}.exe" -ldflags="$ldflags" -tags=jsoniter .
|
||||
$(pwd)/go-win7/bin/go build -o "${1}-${arch}.exe" -ldflags="$ldflags" -tags="$build_tags" .
|
||||
done
|
||||
}
|
||||
|
||||
BuildDev() {
|
||||
rm -rf .git/
|
||||
mkdir -p "dist"
|
||||
muslflags="--extldflags '-static -fpic' $ldflags"
|
||||
muslflags="$(GetMuslStaticLdflags)"
|
||||
BASE="https://github.com/OpenListTeam/musl-compilers/releases/latest/download/"
|
||||
FILES=(x86_64-linux-musl-cross aarch64-linux-musl-cross)
|
||||
for i in "${FILES[@]}"; do
|
||||
@@ -149,7 +197,8 @@ BuildDev() {
|
||||
export GOARCH=${os_arch##*-}
|
||||
export CC=${cgo_cc}
|
||||
export CGO_ENABLED=1
|
||||
go build -o ./dist/$appName-$os_arch -ldflags="$muslflags" -tags=jsoniter .
|
||||
CGO_LDFLAGS="-static" go build -o ./dist/$appName-$os_arch -ldflags="$muslflags" -tags=jsoniter .
|
||||
AssertStaticBinary "./dist/$appName-$os_arch"
|
||||
done
|
||||
xgo -targets=windows/amd64,darwin/amd64,darwin/arm64 -out "$appName" -ldflags="$ldflags" -tags=jsoniter .
|
||||
mv "$appName"-* dist
|
||||
@@ -183,7 +232,7 @@ BuildDockerMultiplatform() {
|
||||
# run PrepareBuildDockerMusl before build
|
||||
export PATH=$PATH:$PWD/build/musl-libs/bin
|
||||
|
||||
docker_lflags="--extldflags '-static -fpic' $ldflags"
|
||||
docker_lflags="$(GetMuslStaticLdflags)"
|
||||
export CGO_ENABLED=1
|
||||
|
||||
OS_ARCHES=(linux-amd64 linux-arm64 linux-386 linux-riscv64 linux-ppc64le linux-loong64) ## Disable linux-s390x builds
|
||||
@@ -193,11 +242,13 @@ BuildDockerMultiplatform() {
|
||||
cgo_cc=${CGO_ARGS[$i]}
|
||||
os=${os_arch%%-*}
|
||||
arch=${os_arch##*-}
|
||||
build_tags=$(GetBuildTagsForTarget "$os_arch")
|
||||
export GOOS=$os
|
||||
export GOARCH=$arch
|
||||
export CC=${cgo_cc}
|
||||
echo "building for $os_arch"
|
||||
go build -o build/$os/$arch/"$appName" -ldflags="$docker_lflags" -tags=jsoniter .
|
||||
CGO_LDFLAGS="-static" go build -o build/$os/$arch/"$appName" -ldflags="$docker_lflags" -tags="$build_tags" .
|
||||
AssertStaticBinary "build/$os/$arch/$appName"
|
||||
done
|
||||
|
||||
DOCKER_ARM_ARCHES=(linux-arm/v6 linux-arm/v7)
|
||||
@@ -211,12 +262,12 @@ BuildDockerMultiplatform() {
|
||||
export GOARM=${GO_ARM[$i]}
|
||||
export CC=${cgo_cc}
|
||||
echo "building for $docker_arch"
|
||||
go build -o build/${docker_arch%%-*}/${docker_arch##*-}/"$appName" -ldflags="$docker_lflags" -tags=jsoniter .
|
||||
CGO_LDFLAGS="-static" go build -o build/${docker_arch%%-*}/${docker_arch##*-}/"$appName" -ldflags="$docker_lflags" -tags=jsoniter .
|
||||
AssertStaticBinary "build/${docker_arch%%-*}/${docker_arch##*-}/$appName"
|
||||
done
|
||||
}
|
||||
|
||||
BuildRelease() {
|
||||
rm -rf .git/
|
||||
mkdir -p "build"
|
||||
BuildWinArm64 ./build/"$appName"-windows-arm64.exe
|
||||
BuildWin7 ./build/"$appName"-windows7
|
||||
@@ -236,7 +287,9 @@ BuildRelease() {
|
||||
BuildLoongGLIBC() {
|
||||
local target_abi="$2"
|
||||
local output_file="$1"
|
||||
local oldWorldGoVersion="1.25.0"
|
||||
local oldWorldGoVersion="1.26.4"
|
||||
local loong_tags
|
||||
loong_tags=$(GetBuildTagsForTarget "linux-loong64")
|
||||
|
||||
if [ "$target_abi" = "abi1.0" ]; then
|
||||
echo building for linux-loong64-abi1.0
|
||||
@@ -254,13 +307,13 @@ BuildLoongGLIBC() {
|
||||
|
||||
# Download and setup patched Go compiler for old-world
|
||||
if ! curl -fsSL --retry 3 -H "Authorization: Bearer $GITHUB_TOKEN" \
|
||||
"https://github.com/loong64/loong64-abi1.0-toolchains/releases/download/20250821/go${oldWorldGoVersion}.linux-amd64.tar.gz" \
|
||||
"https://github.com/loong64-abi1-0/golang/releases/download/go${oldWorldGoVersion}/go${oldWorldGoVersion}.linux-amd64.tar.gz" \
|
||||
-o go-loong64-abi1.0.tar.gz; then
|
||||
echo "Error: Failed to download patched Go compiler for old-world ABI1.0"
|
||||
if [ -n "$GITHUB_TOKEN" ]; then
|
||||
echo "Error output from curl:"
|
||||
curl -fsSL --retry 3 -H "Authorization: Bearer $GITHUB_TOKEN" \
|
||||
"https://github.com/loong64/loong64-abi1.0-toolchains/releases/download/20250821/go${oldWorldGoVersion}.linux-amd64.tar.gz" \
|
||||
"https://github.com/loong64-abi1-0/golang/releases/download/go${oldWorldGoVersion}/go${oldWorldGoVersion}.linux-amd64.tar.gz" \
|
||||
-o go-loong64-abi1.0.tar.gz || true
|
||||
fi
|
||||
return 1
|
||||
@@ -311,7 +364,7 @@ BuildLoongGLIBC() {
|
||||
CXX="$(pwd)/gcc8-loong64-abi1.0/bin/loongarch64-linux-gnu-g++" \
|
||||
CGO_ENABLED=1 \
|
||||
GOCACHE="$abi1_cache_dir" \
|
||||
$(pwd)/go-loong64-abi1.0/bin/go build -a -o "$output_file" -ldflags="$ldflags" -tags=jsoniter .; then
|
||||
$(pwd)/go-loong64-abi1.0/bin/go build -a -o "$output_file" -ldflags="$ldflags" -tags="$loong_tags" .; then
|
||||
echo "Error: Build failed with patched Go compiler"
|
||||
echo "Attempting retry with cache cleanup..."
|
||||
env GOCACHE="$abi1_cache_dir" $(pwd)/go-loong64-abi1.0/bin/go clean -cache
|
||||
@@ -320,7 +373,7 @@ BuildLoongGLIBC() {
|
||||
CXX="$(pwd)/gcc8-loong64-abi1.0/bin/loongarch64-linux-gnu-g++" \
|
||||
CGO_ENABLED=1 \
|
||||
GOCACHE="$abi1_cache_dir" \
|
||||
$(pwd)/go-loong64-abi1.0/bin/go build -a -o "$output_file" -ldflags="$ldflags" -tags=jsoniter .; then
|
||||
$(pwd)/go-loong64-abi1.0/bin/go build -a -o "$output_file" -ldflags="$ldflags" -tags="$loong_tags" .; then
|
||||
echo "Error: Build failed again after cache cleanup"
|
||||
echo "Build environment details:"
|
||||
echo "GOOS=linux"
|
||||
@@ -366,11 +419,11 @@ BuildLoongGLIBC() {
|
||||
|
||||
# Use standard Go compiler for new-world build
|
||||
echo "Building with standard Go compiler for new-world ABI2.0..."
|
||||
if ! go build -a -o "$output_file" -ldflags="$ldflags" -tags=jsoniter .; then
|
||||
if ! go build -a -o "$output_file" -ldflags="$ldflags" -tags="$loong_tags" .; then
|
||||
echo "Error: Build failed with standard Go compiler"
|
||||
echo "Attempting retry with cache cleanup..."
|
||||
go clean -cache
|
||||
if ! go build -a -o "$output_file" -ldflags="$ldflags" -tags=jsoniter .; then
|
||||
if ! go build -a -o "$output_file" -ldflags="$ldflags" -tags="$loong_tags" .; then
|
||||
echo "Error: Build failed again after cache cleanup"
|
||||
echo "Build environment details:"
|
||||
echo "GOOS=$GOOS"
|
||||
@@ -387,10 +440,10 @@ BuildLoongGLIBC() {
|
||||
}
|
||||
|
||||
BuildReleaseLinuxMusl() {
|
||||
rm -rf .git/
|
||||
mkdir -p "build"
|
||||
muslflags="--extldflags '-static -fpic' $ldflags"
|
||||
muslflags="$(GetMuslStaticLdflags)"
|
||||
BASE="https://github.com/OpenListTeam/musl-compilers/releases/latest/download/"
|
||||
# Keep mips-family targets enabled; sqlite driver selection is handled by Go build tags.
|
||||
FILES=(x86_64-linux-musl-cross aarch64-linux-musl-cross mips-linux-musl-cross mips64-linux-musl-cross mips64el-linux-musl-cross mipsel-linux-musl-cross powerpc64le-linux-musl-cross s390x-linux-musl-cross loongarch64-linux-musl-cross)
|
||||
for i in "${FILES[@]}"; do
|
||||
url="${BASE}${i}.tgz"
|
||||
@@ -403,19 +456,20 @@ BuildReleaseLinuxMusl() {
|
||||
for i in "${!OS_ARCHES[@]}"; do
|
||||
os_arch=${OS_ARCHES[$i]}
|
||||
cgo_cc=${CGO_ARGS[$i]}
|
||||
build_tags=$(GetBuildTagsForTarget "$os_arch")
|
||||
echo building for ${os_arch}
|
||||
export GOOS=${os_arch%%-*}
|
||||
export GOARCH=${os_arch##*-}
|
||||
export CC=${cgo_cc}
|
||||
export CGO_ENABLED=1
|
||||
go build -o ./build/$appName-$os_arch -ldflags="$muslflags" -tags=jsoniter .
|
||||
CGO_LDFLAGS="-static" go build -o ./build/$appName-$os_arch -ldflags="$muslflags" -tags="$build_tags" .
|
||||
AssertStaticBinary "./build/$appName-$os_arch"
|
||||
done
|
||||
}
|
||||
|
||||
BuildReleaseLinuxMuslArm() {
|
||||
rm -rf .git/
|
||||
mkdir -p "build"
|
||||
muslflags="--extldflags '-static -fpic' $ldflags"
|
||||
muslflags="$(GetMuslStaticLdflags)"
|
||||
BASE="https://github.com/OpenListTeam/musl-compilers/releases/latest/download/"
|
||||
FILES=(arm-linux-musleabi-cross arm-linux-musleabihf-cross armel-linux-musleabi-cross armel-linux-musleabihf-cross armv5l-linux-musleabi-cross armv5l-linux-musleabihf-cross armv6-linux-musleabi-cross armv6-linux-musleabihf-cross armv7l-linux-musleabihf-cross armv7m-linux-musleabi-cross armv7r-linux-musleabihf-cross)
|
||||
for i in "${FILES[@]}"; do
|
||||
@@ -437,13 +491,13 @@ BuildReleaseLinuxMuslArm() {
|
||||
export CC=${cgo_cc}
|
||||
export CGO_ENABLED=1
|
||||
export GOARM=${arm}
|
||||
go build -o ./build/$appName-$os_arch -ldflags="$muslflags" -tags=jsoniter .
|
||||
CGO_LDFLAGS="-static" go build -o ./build/$appName-$os_arch -ldflags="$muslflags" -tags=jsoniter .
|
||||
AssertStaticBinary "./build/$appName-$os_arch"
|
||||
done
|
||||
}
|
||||
|
||||
|
||||
BuildReleaseAndroid() {
|
||||
rm -rf .git/
|
||||
mkdir -p "build"
|
||||
wget https://dl.google.com/android/repository/android-ndk-r26b-linux.zip
|
||||
unzip android-ndk-r26b-linux.zip
|
||||
@@ -464,7 +518,6 @@ BuildReleaseAndroid() {
|
||||
}
|
||||
|
||||
BuildReleaseFreeBSD() {
|
||||
rm -rf .git/
|
||||
mkdir -p "build/freebsd"
|
||||
|
||||
# Get latest FreeBSD 14.x release version from GitHub
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ type options struct {
|
||||
|
||||
pwd string //de/encrypt password
|
||||
salt string
|
||||
filenameEncryption string //reference drivers\crypt\meta.go Addtion
|
||||
filenameEncryption string //reference drivers\crypt\meta.go Addition
|
||||
dirnameEncryption string
|
||||
filenameEncode string
|
||||
suffix string
|
||||
|
||||
+17
-7
@@ -8,6 +8,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
@@ -31,14 +32,23 @@ func start() {
|
||||
return
|
||||
}
|
||||
}
|
||||
args := os.Args
|
||||
args[1] = "server"
|
||||
args = append(args, "--force-bin-dir")
|
||||
cmd := &exec.Cmd{
|
||||
Path: args[0],
|
||||
Args: args,
|
||||
Env: os.Environ(),
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
log.Fatal("failed to resolve executable path: ", err)
|
||||
}
|
||||
childArgs := append([]string{"server"}, os.Args[2:]...)
|
||||
hasForceBinDir := false
|
||||
for _, arg := range childArgs {
|
||||
if arg == "--force-bin-dir" || strings.HasPrefix(arg, "--force-bin-dir=") {
|
||||
hasForceBinDir = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasForceBinDir {
|
||||
childArgs = append(childArgs, "--force-bin-dir")
|
||||
}
|
||||
cmd := exec.Command(exe, childArgs...)
|
||||
cmd.Env = os.Environ()
|
||||
stdout, err := os.OpenFile(filepath.Join(filepath.Dir(pidFile), "start.log"), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
|
||||
if err != nil {
|
||||
log.Fatal(os.Getpid(), ": failed to open start log file:", err)
|
||||
|
||||
@@ -68,8 +68,7 @@ func (d *Pan115) Link(ctx context.Context, file model.Obj, args model.LinkArgs)
|
||||
return nil, err
|
||||
}
|
||||
userAgent := args.Header.Get("User-Agent")
|
||||
downloadInfo, err := d.
|
||||
DownloadWithUA(file.(*FileObj).PickCode, userAgent)
|
||||
downloadInfo, err := d.client.DownloadWithUA(file.(*FileObj).PickCode, userAgent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ func (f *FileObj) GetHash() utils.HashInfo {
|
||||
return utils.NewHashInfo(utils.SHA1, f.Sha1)
|
||||
}
|
||||
|
||||
func (f *FileObj) Thumb() string {
|
||||
return f.ThumbURL
|
||||
}
|
||||
|
||||
type UploadResult struct {
|
||||
driver.BasicResp
|
||||
Data struct {
|
||||
|
||||
+10
-63
@@ -9,7 +9,6 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -20,13 +19,12 @@ import (
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/conf"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
netutil "github.com/OpenListTeam/OpenList/v4/internal/net"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/http_range"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
"github.com/aliyun/aliyun-oss-go-sdk/oss"
|
||||
|
||||
cipher "github.com/SheltonZhu/115driver/pkg/crypto/ec115"
|
||||
crypto "github.com/SheltonZhu/115driver/pkg/crypto/m115"
|
||||
driver115 "github.com/SheltonZhu/115driver/pkg/driver"
|
||||
"github.com/aliyun/aliyun-oss-go-sdk/oss"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
@@ -108,60 +106,6 @@ func (d *Pan115) getUA() string {
|
||||
return fmt.Sprintf("Mozilla/5.0 115Browser/%s", appVer)
|
||||
}
|
||||
|
||||
func (d *Pan115) DownloadWithUA(pickCode, ua string) (*driver115.DownloadInfo, error) {
|
||||
key := crypto.GenerateKey()
|
||||
result := driver115.DownloadResp{}
|
||||
params, err := utils.Json.Marshal(map[string]string{"pick_code": pickCode})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data := crypto.Encode(params, key)
|
||||
|
||||
bodyReader := strings.NewReader(url.Values{"data": []string{data}}.Encode())
|
||||
reqUrl := fmt.Sprintf("%s?t=%s", driver115.AndroidApiDownloadGetUrl, driver115.Now().String())
|
||||
req, _ := http.NewRequest(http.MethodPost, reqUrl, bodyReader)
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Cookie", d.Cookie)
|
||||
req.Header.Set("User-Agent", ua)
|
||||
|
||||
resp, err := d.client.Client.GetClient().Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := utils.Json.Unmarshal(body, &result); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = result.Err(string(body)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
b, err := crypto.Decode(string(result.EncodedData), key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
downloadInfo := struct {
|
||||
Url string `json:"url"`
|
||||
}{}
|
||||
if err := utils.Json.Unmarshal(b, &downloadInfo); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
info := &driver115.DownloadInfo{}
|
||||
info.PickCode = pickCode
|
||||
info.Header = resp.Request.Header
|
||||
info.Url.Url = downloadInfo.Url
|
||||
return info, nil
|
||||
}
|
||||
|
||||
func (c *Pan115) GenerateToken(fileID, preID, timeStamp, fileSize, signKey, signVal string) string {
|
||||
userID := strconv.FormatInt(c.client.UserID, 10)
|
||||
userIDMd5 := md5.Sum([]byte(userID))
|
||||
@@ -279,7 +223,7 @@ func (c *Pan115) UploadByOSS(ctx context.Context, params *driver115.UploadOSSPar
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ossClient, err := oss.New(driver115.OSSEndpoint, ossToken.AccessKeyID, ossToken.AccessKeySecret)
|
||||
ossClient, err := netutil.NewOSSClient(driver115.OSSEndpoint, ossToken.AccessKeyID, ossToken.AccessKeySecret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -309,7 +253,8 @@ func (c *Pan115) UploadByOSS(ctx context.Context, params *driver115.UploadOSSPar
|
||||
|
||||
// UploadByMultipart upload by mutipart blocks
|
||||
func (d *Pan115) UploadByMultipart(ctx context.Context, params *driver115.UploadOSSParams, fileSize int64, s model.FileStreamer,
|
||||
dirID string, up driver.UpdateProgress, opts ...driver115.UploadMultipartOption) (*UploadResult, error) {
|
||||
dirID string, up driver.UpdateProgress, opts ...driver115.UploadMultipartOption,
|
||||
) (*UploadResult, error) {
|
||||
var (
|
||||
chunks []oss.FileChunk
|
||||
parts []oss.UploadPart
|
||||
@@ -339,7 +284,7 @@ func (d *Pan115) UploadByMultipart(ctx context.Context, params *driver115.Upload
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if ossClient, err = oss.New(driver115.OSSEndpoint, ossToken.AccessKeyID, ossToken.AccessKeySecret, oss.EnableMD5(true), oss.EnableCRC(true)); err != nil {
|
||||
if ossClient, err = netutil.NewOSSClient(driver115.OSSEndpoint, ossToken.AccessKeyID, ossToken.AccessKeySecret, oss.EnableMD5(true), oss.EnableCRC(true)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -392,9 +337,11 @@ func (d *Pan115) UploadByMultipart(ctx context.Context, params *driver115.Upload
|
||||
for chunk := range chunksCh {
|
||||
var part oss.UploadPart // 出现错误就继续尝试,共尝试3次
|
||||
for retry := 0; retry < 3; retry++ {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if utils.IsCanceled(ctx) {
|
||||
err = ctx.Err()
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if ossToken, err = d.client.GetOSSToken(); err != nil { // 到时重新获取ossToken
|
||||
errCh <- errors.Wrap(err, "刷新token时出现错误")
|
||||
|
||||
+102
-17
@@ -2,8 +2,11 @@ package _115_open
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
stdpath "path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -12,6 +15,7 @@ import (
|
||||
"github.com/OpenListTeam/OpenList/v4/cmd/flags"
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/errs"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/op"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/stream"
|
||||
@@ -23,8 +27,9 @@ import (
|
||||
type Open115 struct {
|
||||
model.Storage
|
||||
Addition
|
||||
client *sdk.Client
|
||||
limiter *rate.Limiter
|
||||
client *sdk.Client
|
||||
limiter *rate.Limiter
|
||||
parentPath string
|
||||
}
|
||||
|
||||
func (d *Open115) Config() driver.Config {
|
||||
@@ -59,6 +64,28 @@ func (d *Open115) Init(ctx context.Context) error {
|
||||
d.PageSize = 1150
|
||||
}
|
||||
|
||||
// add parent path
|
||||
d.parentPath = "/"
|
||||
if d.GetRootId() != d.Config().DefaultRoot {
|
||||
folderInfo, err := d.client.GetFolderInfo(ctx, d.GetRootId())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if folderInfo.FileID != d.Config().DefaultRoot {
|
||||
d.parentPath = stdpath.Join(d.parentPath, folderInfo.FileName)
|
||||
}
|
||||
|
||||
parentPaths := folderInfo.Paths
|
||||
slices.Reverse(parentPaths)
|
||||
for _, parentPathInfo := range parentPaths {
|
||||
if parentPathInfo.FileID == d.Config().DefaultRoot {
|
||||
d.parentPath = stdpath.Join("/", d.parentPath)
|
||||
} else {
|
||||
d.parentPath = stdpath.Join("/", parentPathInfo.FileName, d.parentPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -137,6 +164,69 @@ func (d *Open115) Link(ctx context.Context, file model.Obj, args model.LinkArgs)
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Open115) Get(ctx context.Context, path string) (model.Obj, error) {
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path = stdpath.Join(d.parentPath, path)
|
||||
resp, err := d.client.GetFolderInfoByPath(ctx, path)
|
||||
if err != nil {
|
||||
if errors.Is(err, sdk.ErrObjectNotFound) {
|
||||
return d.getFromParent(ctx, path, "")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
obj := &Obj{
|
||||
Fid: resp.FileID,
|
||||
Fn: resp.FileName,
|
||||
Fc: resp.FileCategory,
|
||||
Sha1: resp.Sha1,
|
||||
Pc: resp.PickCode,
|
||||
FS: resp.SizeByte,
|
||||
Upt: parseTime(resp.UTime),
|
||||
UpPt: parseTime(resp.PTime),
|
||||
}
|
||||
if !obj.IsDir() && obj.ModTime().Unix() <= 0 {
|
||||
return d.getFromParent(ctx, path, obj.GetID())
|
||||
}
|
||||
return obj, nil
|
||||
}
|
||||
|
||||
func (d *Open115) getFromParent(ctx context.Context, path, id string) (model.Obj, error) {
|
||||
path = stdpath.Clean(path)
|
||||
parent, name := stdpath.Split(path)
|
||||
parent = stdpath.Clean(parent)
|
||||
parentID := d.GetRootId()
|
||||
if stdpath.Clean(parent) != stdpath.Clean(d.parentPath) {
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parentInfo, err := d.client.GetFolderInfoByPath(ctx, parent)
|
||||
if err != nil {
|
||||
if !errors.Is(err, sdk.ErrObjectNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
parentObj, err := d.getFromParent(ctx, parent, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parentID = parentObj.GetID()
|
||||
} else {
|
||||
parentID = parentInfo.FileID
|
||||
}
|
||||
}
|
||||
files, err := d.List(ctx, &Obj{Fid: parentID, Fc: "0"}, model.ListArgs{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if (id != "" && file.GetID() == id) || (id == "" && file.GetName() == name) {
|
||||
return file, nil
|
||||
}
|
||||
}
|
||||
return nil, errs.ObjectNotFound
|
||||
}
|
||||
|
||||
func (d *Open115) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) (model.Obj, error) {
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -156,18 +246,15 @@ func (d *Open115) MakeDir(ctx context.Context, parentDir model.Obj, dirName stri
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Open115) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj, error) {
|
||||
func (d *Open115) Move(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
_, err := d.client.Move(ctx, &sdk.MoveReq{
|
||||
FileIDs: srcObj.GetID(),
|
||||
ToCid: dstDir.GetID(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return srcObj, nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Open115) Rename(ctx context.Context, srcObj model.Obj, newName string) (model.Obj, error) {
|
||||
@@ -175,8 +262,8 @@ func (d *Open115) Rename(ctx context.Context, srcObj model.Obj, newName string)
|
||||
return nil, err
|
||||
}
|
||||
_, err := d.client.UpdateFile(ctx, &sdk.UpdateFileReq{
|
||||
FileID: srcObj.GetID(),
|
||||
FileNma: newName,
|
||||
FileID: srcObj.GetID(),
|
||||
FileName: newName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -184,23 +271,21 @@ func (d *Open115) Rename(ctx context.Context, srcObj model.Obj, newName string)
|
||||
obj, ok := srcObj.(*Obj)
|
||||
if ok {
|
||||
obj.Fn = newName
|
||||
return srcObj, nil
|
||||
}
|
||||
return srcObj, nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d *Open115) Copy(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj, error) {
|
||||
func (d *Open115) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
return err
|
||||
}
|
||||
_, err := d.client.Copy(ctx, &sdk.CopyReq{
|
||||
PID: dstDir.GetID(),
|
||||
FileID: srcObj.GetID(),
|
||||
NoDupli: "1",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return srcObj, nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Open115) Remove(ctx context.Context, obj model.Obj) error {
|
||||
|
||||
@@ -3,9 +3,9 @@ package _115_open
|
||||
import (
|
||||
"time"
|
||||
|
||||
sdk "github.com/OpenListTeam/115-sdk-go"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
sdk "github.com/OpenListTeam/115-sdk-go"
|
||||
)
|
||||
|
||||
type Obj sdk.GetFilesResp_File
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
sdk "github.com/OpenListTeam/115-sdk-go"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
netutil "github.com/OpenListTeam/OpenList/v4/internal/net"
|
||||
streamPkg "github.com/OpenListTeam/OpenList/v4/internal/stream"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
"github.com/aliyun/aliyun-oss-go-sdk/oss"
|
||||
@@ -36,7 +37,7 @@ func calPartSize(fileSize int64) int64 {
|
||||
}
|
||||
|
||||
func (d *Open115) singleUpload(ctx context.Context, tempF model.File, tokenResp *sdk.UploadGetTokenResp, initResp *sdk.UploadInitResp) error {
|
||||
ossClient, err := oss.New(tokenResp.Endpoint, tokenResp.AccessKeyId, tokenResp.AccessKeySecret, oss.SecurityToken(tokenResp.SecurityToken))
|
||||
ossClient, err := netutil.NewOSSClient(tokenResp.Endpoint, tokenResp.AccessKeyId, tokenResp.AccessKeySecret, oss.SecurityToken(tokenResp.SecurityToken))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -70,7 +71,7 @@ func (d *Open115) singleUpload(ctx context.Context, tempF model.File, tokenResp
|
||||
// }
|
||||
|
||||
func (d *Open115) multpartUpload(ctx context.Context, stream model.FileStreamer, up driver.UpdateProgress, tokenResp *sdk.UploadGetTokenResp, initResp *sdk.UploadInitResp) error {
|
||||
ossClient, err := oss.New(tokenResp.Endpoint, tokenResp.AccessKeyId, tokenResp.AccessKeySecret, oss.SecurityToken(tokenResp.SecurityToken))
|
||||
ossClient, err := netutil.NewOSSClient(tokenResp.Endpoint, tokenResp.AccessKeyId, tokenResp.AccessKeySecret, oss.SecurityToken(tokenResp.SecurityToken))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package _115_open
|
||||
|
||||
import "encoding/json"
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func ParseInt64(v json.Number) (int64, error) {
|
||||
i, err := v.Int64()
|
||||
@@ -13,3 +16,8 @@ func ParseInt64(v json.Number) (int64, error) {
|
||||
}
|
||||
return int64(0), err
|
||||
}
|
||||
|
||||
func parseTime(value string) int64 {
|
||||
timestamp, _ := strconv.ParseInt(value, 10, 64)
|
||||
return timestamp
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ package _115_share
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/errs"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
@@ -49,9 +51,16 @@ func (d *Pan115Share) List(ctx context.Context, dir model.Obj, args model.ListAr
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ua string
|
||||
// TODO: will use user agent from header
|
||||
// if args.Header != nil {
|
||||
// ua = args.Header.Get("User-Agent")
|
||||
// }
|
||||
if ua == "" {
|
||||
ua = base.UserAgentNT
|
||||
}
|
||||
files := make([]driver115.ShareFile, 0)
|
||||
fileResp, err := d.client.GetShareSnap(d.ShareCode, d.ReceiveCode, dir.GetID(), driver115.QueryLimit(int(d.PageSize)))
|
||||
fileResp, err := d.client.GetShareSnapWithUA(ua, d.ShareCode, d.ReceiveCode, dir.GetID(), driver115.QueryLimit(int(d.PageSize)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -77,12 +86,20 @@ func (d *Pan115Share) Link(ctx context.Context, file model.Obj, args model.LinkA
|
||||
if err := d.WaitLimit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
downloadInfo, err := d.client.DownloadByShareCode(d.ShareCode, d.ReceiveCode, file.GetID())
|
||||
var ua string
|
||||
if args.Header != nil {
|
||||
ua = args.Header.Get("User-Agent")
|
||||
}
|
||||
downloadInfo, err := d.client.DownloadByShareCodeWithUA(ua, d.ShareCode, d.ReceiveCode, file.GetID())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &model.Link{URL: downloadInfo.URL.URL}, nil
|
||||
header := http.Header{}
|
||||
header.Set("User-Agent", ua)
|
||||
return &model.Link{
|
||||
URL: downloadInfo.URL.URL,
|
||||
Header: header,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *Pan115Share) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) error {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
driver115 "github.com/SheltonZhu/115driver/pkg/driver"
|
||||
@@ -20,6 +21,7 @@ type FileObj struct {
|
||||
FileName string
|
||||
isDir bool
|
||||
FileID string
|
||||
ThumbURL string
|
||||
}
|
||||
|
||||
func (f *FileObj) CreateTime() time.Time {
|
||||
@@ -54,6 +56,10 @@ func (f *FileObj) GetPath() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (f *FileObj) Thumb() string {
|
||||
return f.ThumbURL
|
||||
}
|
||||
|
||||
func transFunc(sf driver115.ShareFile) (model.Obj, error) {
|
||||
timeInt, err := strconv.ParseInt(sf.UpdateTime, 10, 64)
|
||||
if err != nil {
|
||||
@@ -74,15 +80,14 @@ func transFunc(sf driver115.ShareFile) (model.Obj, error) {
|
||||
FileName: string(sf.FileName),
|
||||
isDir: isDir,
|
||||
FileID: fileID,
|
||||
ThumbURL: sf.ThumbURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var UserAgent = driver115.UA115Browser
|
||||
|
||||
func (d *Pan115Share) login() error {
|
||||
var err error
|
||||
opts := []driver115.Option{
|
||||
driver115.UA(UserAgent),
|
||||
driver115.UA(base.UserAgentNT),
|
||||
}
|
||||
d.client = driver115.New(opts...)
|
||||
if _, err := d.client.GetShareSnap(d.ShareCode, d.ReceiveCode, ""); err != nil {
|
||||
|
||||
@@ -98,7 +98,7 @@ func (d *Pan123) Link(ctx context.Context, file model.Obj, args model.LinkArgs)
|
||||
}
|
||||
|
||||
log.Debug("download url: ", u_)
|
||||
res, err := base.NoRedirectClient.R().SetHeader("Referer", "https://www.123pan.com/").Get(u_)
|
||||
res, err := base.NoRedirectClient.R().SetHeader("Referer", "https://yun.123pan.com/").Get(u_)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+7
-7
@@ -24,9 +24,9 @@ import (
|
||||
// do others that not defined in Driver interface
|
||||
|
||||
const (
|
||||
Api = "https://www.123pan.com/api"
|
||||
AApi = "https://www.123pan.com/a/api"
|
||||
BApi = "https://www.123pan.com/b/api"
|
||||
Api = "https://yun.123pan.com/api"
|
||||
AApi = "https://yun.123pan.com/a/api"
|
||||
BApi = "https://yun.123pan.com/b/api"
|
||||
LoginApi = "https://login.123pan.com/api"
|
||||
MainApi = BApi
|
||||
SignIn = LoginApi + "/user/sign_in"
|
||||
@@ -169,8 +169,8 @@ func (d *Pan123) login() error {
|
||||
}
|
||||
res, err := base.RestyClient.R().
|
||||
SetHeaders(map[string]string{
|
||||
"origin": "https://www.123pan.com",
|
||||
"referer": "https://www.123pan.com/",
|
||||
"origin": "https://yun.123pan.com",
|
||||
"referer": "https://yun.123pan.com/",
|
||||
"user-agent": "Dart/2.19(dart:io)-openlist",
|
||||
"platform": "web",
|
||||
"app-version": "3",
|
||||
@@ -207,8 +207,8 @@ func (d *Pan123) Request(url string, method string, callback base.ReqCallback, r
|
||||
do:
|
||||
req := base.RestyClient.R()
|
||||
req.SetHeaders(map[string]string{
|
||||
"origin": "https://www.123pan.com",
|
||||
"referer": "https://www.123pan.com/",
|
||||
"origin": "https://yun.123pan.com",
|
||||
"referer": "https://yun.123pan.com/",
|
||||
"authorization": "Bearer " + d.AccessToken,
|
||||
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) openlist-client",
|
||||
"platform": d.Platform,
|
||||
|
||||
@@ -34,8 +34,8 @@ func (d *Open123) Init(ctx context.Context) error {
|
||||
d.UploadThread = 3
|
||||
}
|
||||
|
||||
if d.RefreshToken != "" {
|
||||
// refresh token 直接主动刷新
|
||||
if (d.UseOnlineAPI && d.RefreshToken != "" && len(d.APIAddress) > 0) || (d.ClientID != "" && d.ClientSecret != "") {
|
||||
// proactive refresh by renewapi or client credentials
|
||||
d.AccessToken = ""
|
||||
d.tm = &tokenManager{}
|
||||
} else {
|
||||
@@ -181,6 +181,22 @@ func (d *Open123) Put(ctx context.Context, dstDir model.Obj, file model.FileStre
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse parentFileID error: %v", err)
|
||||
}
|
||||
|
||||
// 尝试 SHA1 秒传
|
||||
sha1Hash := file.GetHash().GetHash(utils.SHA1)
|
||||
if len(sha1Hash) == utils.SHA1.Width {
|
||||
resp, err := d.sha1Reuse(parentFileId, file.GetName(), sha1Hash, file.GetSize(), 2)
|
||||
if err == nil && resp.Data.Reuse {
|
||||
return File{
|
||||
FileName: file.GetName(),
|
||||
Size: file.GetSize(),
|
||||
FileId: resp.Data.FileID,
|
||||
Type: 2,
|
||||
SHA1: sha1Hash,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// etag 文件md5
|
||||
etag := file.GetHash().GetHash(utils.MD5)
|
||||
if len(etag) < utils.MD5.Width {
|
||||
|
||||
@@ -6,9 +6,6 @@ import (
|
||||
)
|
||||
|
||||
type Addition struct {
|
||||
// refresh_token方式的AccessToken 【对个人开发者暂未开放】
|
||||
RefreshToken string `json:"RefreshToken" required:"false"`
|
||||
|
||||
// 通过 https://www.123pan.com/developer 申请
|
||||
ClientID string `json:"ClientID" required:"false"`
|
||||
ClientSecret string `json:"ClientSecret" required:"false"`
|
||||
@@ -16,6 +13,13 @@ type Addition struct {
|
||||
// 直接写入AccessToken, AccessToken有过期时间,不建议直接填写
|
||||
AccessToken string `json:"AccessToken" required:"false"`
|
||||
|
||||
// refresh_token方式的AccessToken 【对个人开发者暂未开放】
|
||||
RefreshToken string `json:"RefreshToken" required:"false"`
|
||||
|
||||
// 使用在线API
|
||||
UseOnlineAPI bool `json:"use_online_api" default:"true"`
|
||||
APIAddress string `json:"api_url_address" default:"https://api.oplist.org/123cloud/renewapi"`
|
||||
|
||||
// 用户名+密码方式登录的AccessToken可以兼容
|
||||
//Username string `json:"username" required:"false"`
|
||||
//Password string `json:"password" required:"false"`
|
||||
|
||||
+83
-69
@@ -1,7 +1,6 @@
|
||||
package _123_open
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -13,10 +12,16 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
AccessToken = "https://open-api.123pan.com/api/v1/access_token"
|
||||
RefreshToken = "https://open-api.123pan.com/api/v1/oauth2/access_token"
|
||||
AccessToken = "https://open-api.123pan.com/api/v1/access_token"
|
||||
)
|
||||
|
||||
func expiresInToExpiredAt(expiresIn int64) (time.Time, error) {
|
||||
if expiresIn <= 0 {
|
||||
return time.Time{}, errors.New("invalid expires_in from official API")
|
||||
}
|
||||
return time.Now().UTC().Add(time.Duration(expiresIn) * time.Second), nil
|
||||
}
|
||||
|
||||
type tokenManager struct {
|
||||
// accessToken string
|
||||
expiredAt time.Time
|
||||
@@ -43,73 +48,82 @@ func (d *Open123) getAccessToken(forceRefresh bool) (string, error) {
|
||||
}
|
||||
|
||||
func (d *Open123) flushAccessToken() error {
|
||||
// directly send request to avoid deadlock
|
||||
req := base.RestyClient.R()
|
||||
req.SetHeaders(map[string]string{
|
||||
"authorization": "Bearer " + d.AccessToken,
|
||||
"platform": "open_platform",
|
||||
"Content-Type": "application/json",
|
||||
})
|
||||
|
||||
if d.ClientID != "" {
|
||||
if d.RefreshToken != "" {
|
||||
var resp RefreshTokenResp
|
||||
req.SetQueryParam("client_id", d.ClientID)
|
||||
if d.ClientSecret != "" {
|
||||
req.SetQueryParam("client_secret", d.ClientSecret)
|
||||
}
|
||||
req.SetQueryParam("grant_type", "refresh_token")
|
||||
req.SetQueryParam("refresh_token", d.RefreshToken)
|
||||
req.SetResult(&resp)
|
||||
res, err := req.Execute(http.MethodPost, RefreshToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body := res.Body()
|
||||
var baseResp BaseResp
|
||||
if err = json.Unmarshal(body, &baseResp); err != nil {
|
||||
return err
|
||||
}
|
||||
if baseResp.Code != 0 {
|
||||
return fmt.Errorf("get access token failed: %s", baseResp.Message)
|
||||
}
|
||||
|
||||
d.AccessToken = resp.AccessToken
|
||||
// add token expire time
|
||||
d.tm.expiredAt = time.Now().Add(time.Duration(resp.ExpiresIn) * time.Second)
|
||||
d.RefreshToken = resp.RefreshToken
|
||||
op.MustSaveDriverStorage(d)
|
||||
d.tm.blockRefresh = false
|
||||
return nil
|
||||
} else if d.ClientSecret != "" {
|
||||
var resp AccessTokenResp
|
||||
req.SetBody(base.Json{
|
||||
"clientID": d.ClientID,
|
||||
"clientSecret": d.ClientSecret,
|
||||
})
|
||||
req.SetResult(&resp)
|
||||
res, err := req.Execute(http.MethodPost, AccessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
body := res.Body()
|
||||
var baseResp BaseResp
|
||||
if err = json.Unmarshal(body, &baseResp); err != nil {
|
||||
return err
|
||||
}
|
||||
if baseResp.Code != 0 {
|
||||
return fmt.Errorf("get access token failed: %s", baseResp.Message)
|
||||
}
|
||||
d.AccessToken = resp.Data.AccessToken
|
||||
// parse token expire time
|
||||
d.tm.expiredAt, err = time.Parse(time.RFC3339, resp.Data.ExpiredAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse expire time failed: %w", err)
|
||||
}
|
||||
op.MustSaveDriverStorage(d)
|
||||
d.tm.blockRefresh = false
|
||||
return nil
|
||||
// Official app renewapi response contains access_token, refresh_token and expires_in.
|
||||
if d.UseOnlineAPI && d.RefreshToken != "" && len(d.APIAddress) > 0 {
|
||||
var resp RefreshTokenResp
|
||||
_, err := base.RestyClient.R().
|
||||
SetResult(&resp).
|
||||
SetQueryParams(map[string]string{
|
||||
"refresh_ui": d.RefreshToken,
|
||||
"server_use": "true",
|
||||
"driver_txt": "123cloud_oa",
|
||||
}).
|
||||
Get(d.APIAddress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if resp.AccessToken == "" || resp.RefreshToken == "" {
|
||||
errMessage := resp.ErrorDescription
|
||||
if errMessage == "" {
|
||||
errMessage = resp.Text
|
||||
}
|
||||
if errMessage == "" {
|
||||
errMessage = resp.Message
|
||||
}
|
||||
if errMessage == "" {
|
||||
errMessage = resp.Error
|
||||
}
|
||||
if errMessage != "" {
|
||||
return fmt.Errorf("failed to refresh token: %s", errMessage)
|
||||
}
|
||||
return fmt.Errorf("empty access_token or refresh_token returned from official API")
|
||||
}
|
||||
expiredAt, err := expiresInToExpiredAt(resp.ExpiresIn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
d.AccessToken = resp.AccessToken
|
||||
d.RefreshToken = resp.RefreshToken
|
||||
d.tm.expiredAt = expiredAt
|
||||
op.MustSaveDriverStorage(d)
|
||||
d.tm.blockRefresh = false
|
||||
return nil
|
||||
}
|
||||
|
||||
// Developer API response contains code/message/data(accessToken, expiredAt).
|
||||
if d.ClientID != "" && d.ClientSecret != "" {
|
||||
req := base.RestyClient.R()
|
||||
req.SetHeaders(map[string]string{
|
||||
"platform": "open_platform",
|
||||
"Content-Type": "application/json",
|
||||
})
|
||||
var resp AccessTokenResp
|
||||
req.SetBody(base.Json{
|
||||
"clientID": d.ClientID,
|
||||
"clientSecret": d.ClientSecret,
|
||||
})
|
||||
req.SetResult(&resp)
|
||||
_, err := req.Execute(http.MethodPost, AccessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Code != 0 {
|
||||
return fmt.Errorf("get access token failed: %s", resp.Message)
|
||||
}
|
||||
if resp.Data.AccessToken == "" || resp.Data.ExpiredAt == "" {
|
||||
return errors.New("invalid token payload from developer API")
|
||||
}
|
||||
expiredAt, err := time.Parse(time.RFC3339, resp.Data.ExpiredAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse expire time failed: %w", err)
|
||||
}
|
||||
d.AccessToken = resp.Data.AccessToken
|
||||
d.tm.expiredAt = expiredAt.UTC()
|
||||
op.MustSaveDriverStorage(d)
|
||||
d.tm.blockRefresh = false
|
||||
return nil
|
||||
}
|
||||
return errors.New("no valid authentication method available")
|
||||
}
|
||||
|
||||
@@ -58,9 +58,13 @@ type File struct {
|
||||
Category int `json:"category"`
|
||||
Status int `json:"status"`
|
||||
Trashed int `json:"trashed"`
|
||||
SHA1 string
|
||||
}
|
||||
|
||||
func (f File) GetHash() utils.HashInfo {
|
||||
if len(f.SHA1) == utils.SHA1.Width && len(f.Etag) != utils.MD5.Width {
|
||||
return utils.NewHashInfo(utils.SHA1, f.SHA1)
|
||||
}
|
||||
return utils.NewHashInfo(utils.MD5, f.Etag)
|
||||
}
|
||||
|
||||
@@ -121,11 +125,14 @@ type AccessTokenResp struct {
|
||||
}
|
||||
|
||||
type RefreshTokenResp struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
Scope string `json:"scope"`
|
||||
TokenType string `json:"token_type"`
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
Error string `json:"error"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
type UserInfoResp struct {
|
||||
@@ -190,6 +197,14 @@ type UploadCompleteResp struct {
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type SHA1ReuseResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
FileID int64 `json:"fileID"`
|
||||
Reuse bool `json:"reuse"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type OfflineDownloadResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
|
||||
@@ -183,3 +183,21 @@ func (d *Open123) complete(preuploadID string) (*UploadCompleteResp, error) {
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// SHA1 秒传
|
||||
func (d *Open123) sha1Reuse(parentFileID int64, filename string, sha1Hash string, size int64, duplicate int) (*SHA1ReuseResp, error) {
|
||||
var resp SHA1ReuseResp
|
||||
_, err := d.Request(UploadSHA1Reuse, http.MethodPost, func(req *resty.Request) {
|
||||
req.SetBody(base.Json{
|
||||
"parentFileID": parentFileID,
|
||||
"filename": filename,
|
||||
"sha1": strings.ToLower(sha1Hash),
|
||||
"size": size,
|
||||
"duplicate": duplicate,
|
||||
})
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
+11
-10
@@ -21,16 +21,17 @@ import (
|
||||
var ( // 不同情况下获取的AccessTokenQPS限制不同 如下模块化易于拓展
|
||||
Api = "https://open-api.123pan.com"
|
||||
|
||||
UserInfo = InitApiInfo(Api+"/api/v1/user/info", 1)
|
||||
FileList = InitApiInfo(Api+"/api/v2/file/list", 3)
|
||||
DownloadInfo = InitApiInfo(Api+"/api/v1/file/download_info", 5)
|
||||
DirectLink = InitApiInfo(Api+"/api/v1/direct-link/url", 5)
|
||||
Mkdir = InitApiInfo(Api+"/upload/v1/file/mkdir", 2)
|
||||
Move = InitApiInfo(Api+"/api/v1/file/move", 1)
|
||||
Rename = InitApiInfo(Api+"/api/v1/file/name", 1)
|
||||
Trash = InitApiInfo(Api+"/api/v1/file/trash", 2)
|
||||
UploadCreate = InitApiInfo(Api+"/upload/v2/file/create", 2)
|
||||
UploadComplete = InitApiInfo(Api+"/upload/v2/file/upload_complete", 0)
|
||||
UserInfo = InitApiInfo(Api+"/api/v1/user/info", 1)
|
||||
FileList = InitApiInfo(Api+"/api/v2/file/list", 3)
|
||||
DownloadInfo = InitApiInfo(Api+"/api/v1/file/download_info", 5)
|
||||
DirectLink = InitApiInfo(Api+"/api/v1/direct-link/url", 5)
|
||||
Mkdir = InitApiInfo(Api+"/upload/v1/file/mkdir", 2)
|
||||
Move = InitApiInfo(Api+"/api/v1/file/move", 1)
|
||||
Rename = InitApiInfo(Api+"/api/v1/file/name", 1)
|
||||
Trash = InitApiInfo(Api+"/api/v1/file/trash", 2)
|
||||
UploadCreate = InitApiInfo(Api+"/upload/v2/file/create", 2)
|
||||
UploadComplete = InitApiInfo(Api+"/upload/v2/file/upload_complete", 0)
|
||||
UploadSHA1Reuse = InitApiInfo(Api+"/upload/v2/file/sha1_reuse", 2)
|
||||
|
||||
OfflineDownload = InitApiInfo(Api+"/api/v1/offline/download", 1)
|
||||
OfflineDownloadProcess = InitApiInfo(Api+"/api/v1/offline/download/process", 5)
|
||||
|
||||
@@ -101,7 +101,7 @@ func (d *Pan123Share) Link(ctx context.Context, file model.Obj, args model.LinkA
|
||||
}
|
||||
|
||||
log.Debug("download url: ", u_)
|
||||
res, err := base.NoRedirectClient.R().SetHeader("Referer", "https://www.123pan.com/").Get(u_)
|
||||
res, err := base.NoRedirectClient.R().SetHeader("Referer", "https://yun.123pan.com/").Get(u_)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -20,9 +20,9 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
Api = "https://www.123pan.com/api"
|
||||
AApi = "https://www.123pan.com/a/api"
|
||||
BApi = "https://www.123pan.com/b/api"
|
||||
Api = "https://yun.123pan.com/api"
|
||||
AApi = "https://yun.123pan.com/a/api"
|
||||
BApi = "https://yun.123pan.com/b/api"
|
||||
MainApi = BApi
|
||||
FileList = MainApi + "/share/get"
|
||||
DownloadInfo = MainApi + "/share/download/info"
|
||||
@@ -58,8 +58,8 @@ func (d *Pan123Share) request(url string, method string, callback base.ReqCallba
|
||||
}
|
||||
req := base.RestyClient.R()
|
||||
req.SetHeaders(map[string]string{
|
||||
"origin": "https://www.123pan.com",
|
||||
"referer": "https://www.123pan.com/",
|
||||
"origin": "https://yun.123pan.com",
|
||||
"referer": "https://yun.123pan.com/",
|
||||
"authorization": "Bearer " + d.AccessToken,
|
||||
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) openlist-client",
|
||||
"platform": "web",
|
||||
|
||||
+257
-138
@@ -19,6 +19,7 @@ import (
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/cron"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils/random"
|
||||
"github.com/avast/retry-go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
@@ -29,7 +30,9 @@ type Yun139 struct {
|
||||
Account string
|
||||
ref *Yun139
|
||||
PersonalCloudHost string
|
||||
RootPath string
|
||||
FamilyCloudHost string
|
||||
GroupCloudHost string
|
||||
ProviderRoot string
|
||||
}
|
||||
|
||||
func (d *Yun139) Config() driver.Config {
|
||||
@@ -42,53 +45,62 @@ func (d *Yun139) GetAddition() driver.Additional {
|
||||
|
||||
func (d *Yun139) Init(ctx context.Context) error {
|
||||
if d.ref == nil {
|
||||
if len(d.Authorization) == 0 {
|
||||
if d.Username != "" && d.Password != "" {
|
||||
log.Infof("139yun: authorization is empty, trying to login with password.")
|
||||
newAuth, err := d.loginWithPassword()
|
||||
log.Debugf("newAuth: Ok: %s", newAuth)
|
||||
if err != nil {
|
||||
return fmt.Errorf("login with password failed: %w", err)
|
||||
}
|
||||
} else {
|
||||
return fmt.Errorf("authorization is empty and username/password is not provided")
|
||||
// Share links may be browsed without account credentials. All other
|
||||
// storage types need an authorization or a supported login fallback.
|
||||
if !d.isShare() {
|
||||
if err := d.validateAndInitCredentials(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err := d.refreshToken()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Query Route Policy
|
||||
var resp QueryRoutePolicyResp
|
||||
_, err = d.requestRoute(base.Json{
|
||||
"userInfo": base.Json{
|
||||
"userType": 1,
|
||||
"accountType": 1,
|
||||
"accountName": d.Account,
|
||||
},
|
||||
"modAddrType": 1,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, policyItem := range resp.Data.RoutePolicyList {
|
||||
if policyItem.ModName == "personal" {
|
||||
d.PersonalCloudHost = policyItem.HttpsUrl
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(d.PersonalCloudHost) == 0 {
|
||||
return fmt.Errorf("PersonalCloudHost is empty")
|
||||
}
|
||||
|
||||
d.cron = cron.NewCron(time.Hour * 12)
|
||||
d.cron.Do(func() {
|
||||
if d.Authorization != "" {
|
||||
err := d.refreshToken()
|
||||
if err != nil {
|
||||
log.Errorf("%+v", err)
|
||||
return err
|
||||
}
|
||||
})
|
||||
|
||||
// Query Route Policy
|
||||
var resp QueryRoutePolicyResp
|
||||
_, err = d.requestRoute(base.Json{
|
||||
"userInfo": base.Json{
|
||||
"userType": 1,
|
||||
"accountType": 1,
|
||||
"accountName": d.Account,
|
||||
},
|
||||
"modAddrType": 1,
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, policyItem := range resp.Data.RoutePolicyList {
|
||||
switch policyItem.ModName {
|
||||
case "personal":
|
||||
d.PersonalCloudHost = policyItem.HttpsUrl
|
||||
case "group":
|
||||
d.GroupCloudHost = policyItem.HttpsUrl
|
||||
case "family":
|
||||
d.FamilyCloudHost = policyItem.HttpsUrl
|
||||
}
|
||||
}
|
||||
if len(d.PersonalCloudHost) == 0 {
|
||||
return fmt.Errorf("PersonalCloudHost is empty")
|
||||
}
|
||||
if d.isGroup() || d.isFamily() {
|
||||
if len(d.GroupCloudHost) == 0 {
|
||||
return fmt.Errorf("GroupCloudHost is empty")
|
||||
}
|
||||
if len(d.FamilyCloudHost) == 0 {
|
||||
return fmt.Errorf("FamilyCloudHost is empty")
|
||||
}
|
||||
}
|
||||
|
||||
d.cron = cron.NewCron(time.Hour * 12)
|
||||
d.cron.Do(func() {
|
||||
err := d.refreshToken()
|
||||
if err != nil {
|
||||
log.Errorf("%+v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
@@ -107,15 +119,25 @@ func (d *Yun139) Init(ctx context.Context) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case MetaFamily:
|
||||
case MetaShare:
|
||||
if len(d.Addition.RootFolderID) == 0 {
|
||||
// Attempt to obtain data.path as the root via a query and persist it.
|
||||
if root, err := d.getFamilyRootPath(d.CloudID); err == nil && root != "" {
|
||||
d.RootFolderID = root
|
||||
op.MustSaveDriverStorage(d)
|
||||
}
|
||||
d.RootFolderID = "root"
|
||||
}
|
||||
_, err := d.familyGetFiles(d.RootFolderID)
|
||||
if len(d.shareEntries()) == 0 {
|
||||
return fmt.Errorf("link_id is empty")
|
||||
}
|
||||
case MetaFamily:
|
||||
// Attempt to obtain data.path as the root via a query and persist it.
|
||||
root, err := d.getFamilyRootPath(d.CloudID)
|
||||
if err != nil || root == "" {
|
||||
return fmt.Errorf("failed to get family root path: %w", err)
|
||||
}
|
||||
d.ProviderRoot = root
|
||||
if len(d.Addition.RootFolderID) == 0 {
|
||||
d.RootFolderID = root
|
||||
op.MustSaveDriverStorage(d)
|
||||
}
|
||||
_, err = d.familyGetFiles(d.RootFolderID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -134,6 +156,19 @@ func (d *Yun139) InitReference(storage driver.Driver) error {
|
||||
return errs.NotSupport
|
||||
}
|
||||
|
||||
func (d *Yun139) Get(ctx context.Context, path string) (model.Obj, error) {
|
||||
if !d.isShare() {
|
||||
return nil, errs.NotImplement
|
||||
}
|
||||
if path == "/" {
|
||||
return &model.Object{ID: "root", Name: "root", IsFolder: true, Path: "/"}, nil
|
||||
}
|
||||
if obj, err := d.shareGetObj(path); err == nil {
|
||||
return obj, nil
|
||||
}
|
||||
return nil, errs.ObjectNotFound
|
||||
}
|
||||
|
||||
func (d *Yun139) Drop(ctx context.Context) error {
|
||||
if d.cron != nil {
|
||||
d.cron.Stop()
|
||||
@@ -152,12 +187,23 @@ func (d *Yun139) List(ctx context.Context, dir model.Obj, args model.ListArgs) (
|
||||
return d.familyGetFiles(dir.GetID())
|
||||
case MetaGroup:
|
||||
return d.groupGetFiles(dir.GetID())
|
||||
case MetaShare:
|
||||
if dir.GetID() == "root" {
|
||||
return d.shareGetMergedFiles(d.shareRootEntries())
|
||||
}
|
||||
if refs, ok := decodeShareRefs(dir.GetID()); ok {
|
||||
return d.shareGetMergedFiles(refs)
|
||||
}
|
||||
return d.shareGetFilesWithRef(shareRef{LinkID: d.LinkID, NodeID: dir.GetID()}, dir.GetID())
|
||||
default:
|
||||
return nil, errs.NotImplement
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Yun139) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (*model.Link, error) {
|
||||
if file.IsDir() {
|
||||
return nil, errs.NotFile
|
||||
}
|
||||
var url string
|
||||
var err error
|
||||
switch d.Addition.Type {
|
||||
@@ -169,6 +215,16 @@ func (d *Yun139) Link(ctx context.Context, file model.Obj, args model.LinkArgs)
|
||||
url, err = d.familyGetLink(file.GetID(), file.GetPath())
|
||||
case MetaGroup:
|
||||
url, err = d.groupGetLink(file.GetID(), file.GetPath())
|
||||
case MetaShare:
|
||||
if refs, ok := decodeShareRefs(file.GetID()); ok && len(refs) > 0 {
|
||||
return d.shareGetLinkWithRef(refs[0], refs[0].NodeID, args.Type)
|
||||
}
|
||||
fallbackRef := shareRef{LinkID: d.LinkID, NodeID: "root"}
|
||||
if entries := d.shareEntries(); len(entries) > 0 {
|
||||
fallbackRef.LinkID = entries[0].LinkID
|
||||
fallbackRef.Password = entries[0].Password
|
||||
}
|
||||
return d.shareGetLinkWithRef(fallbackRef, file.GetID(), args.Type)
|
||||
default:
|
||||
return nil, errs.NotImplement
|
||||
}
|
||||
@@ -179,6 +235,9 @@ func (d *Yun139) Link(ctx context.Context, file model.Obj, args model.LinkArgs)
|
||||
}
|
||||
|
||||
func (d *Yun139) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) error {
|
||||
if d.isShare() {
|
||||
return errs.NotImplement
|
||||
}
|
||||
var err error
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
@@ -212,7 +271,7 @@ func (d *Yun139) MakeDir(ctx context.Context, parentDir model.Obj, dirName strin
|
||||
"accountType": 1,
|
||||
},
|
||||
"docLibName": dirName,
|
||||
"path": path.Join(parentDir.GetPath(), parentDir.GetID()),
|
||||
"path": d.dirPath(parentDir),
|
||||
}
|
||||
pathname := "/orchestration/familyCloud-rebuild/cloudCatalog/v1.0/createCloudDoc"
|
||||
_, err = d.post(pathname, data, nil)
|
||||
@@ -225,7 +284,7 @@ func (d *Yun139) MakeDir(ctx context.Context, parentDir model.Obj, dirName strin
|
||||
},
|
||||
"groupID": d.CloudID,
|
||||
"parentFileId": parentDir.GetID(),
|
||||
"path": path.Join(parentDir.GetPath(), parentDir.GetID()),
|
||||
"path": d.dirPath(parentDir),
|
||||
}
|
||||
pathname := "/orchestration/group-rebuild/catalog/v1.0/createGroupCatalog"
|
||||
_, err = d.post(pathname, data, nil)
|
||||
@@ -236,6 +295,9 @@ func (d *Yun139) MakeDir(ctx context.Context, parentDir model.Obj, dirName strin
|
||||
}
|
||||
|
||||
func (d *Yun139) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj, error) {
|
||||
if d.isShare() {
|
||||
return nil, errs.NotImplement
|
||||
}
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
data := base.Json{
|
||||
@@ -310,9 +372,9 @@ func (d *Yun139) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj,
|
||||
var contentList []string
|
||||
var catalogList []string
|
||||
if srcObj.IsDir() {
|
||||
catalogList = append(catalogList, path.Join(srcObj.GetPath(), srcObj.GetID()))
|
||||
catalogList = append(catalogList, d.dirPath(srcObj))
|
||||
} else {
|
||||
contentList = append(contentList, path.Join(srcObj.GetPath(), srcObj.GetID()))
|
||||
contentList = append(contentList, d.dirPath(srcObj))
|
||||
}
|
||||
|
||||
body := base.Json{
|
||||
@@ -324,7 +386,7 @@ func (d *Yun139) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj,
|
||||
"contentList": contentList,
|
||||
"destCatalogID": dstDir.GetID(),
|
||||
"destGroupID": d.CloudID,
|
||||
"destPath": path.Join(dstDir.GetPath(), dstDir.GetID()),
|
||||
"destPath": d.dirPath(dstDir),
|
||||
"destType": 0,
|
||||
"srcGroupID": d.CloudID,
|
||||
"srcType": 0,
|
||||
@@ -347,6 +409,9 @@ func (d *Yun139) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj,
|
||||
}
|
||||
|
||||
func (d *Yun139) Rename(ctx context.Context, srcObj model.Obj, newName string) error {
|
||||
if d.isShare() {
|
||||
return errs.NotImplement
|
||||
}
|
||||
var err error
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
@@ -425,7 +490,7 @@ func (d *Yun139) Rename(ctx context.Context, srcObj model.Obj, newName string) e
|
||||
},
|
||||
"docLibName": newName,
|
||||
"docLibraryID": srcObj.GetID(),
|
||||
"path": path.Join(srcObj.GetPath(), srcObj.GetID()),
|
||||
"path": d.dirPath(srcObj),
|
||||
}
|
||||
var resp ModifyCloudDocV2Resp
|
||||
_, err = d.andAlbumRequest(pathname, data, &resp)
|
||||
@@ -456,6 +521,9 @@ func (d *Yun139) Rename(ctx context.Context, srcObj model.Obj, newName string) e
|
||||
}
|
||||
|
||||
func (d *Yun139) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
if d.isShare() {
|
||||
return errs.NotImplement
|
||||
}
|
||||
var err error
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
@@ -525,6 +593,9 @@ func (d *Yun139) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
}
|
||||
|
||||
func (d *Yun139) Remove(ctx context.Context, obj model.Obj) error {
|
||||
if d.isShare() {
|
||||
return errs.NotImplement
|
||||
}
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
data := base.Json{
|
||||
@@ -615,8 +686,25 @@ func (d *Yun139) getPartSize(size int64) int64 {
|
||||
}
|
||||
|
||||
func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStreamer, up driver.UpdateProgress) error {
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonalNew:
|
||||
if d.isShare() {
|
||||
return errs.NotImplement
|
||||
}
|
||||
// PersonalNew 以及 Group/Family 在非旧流模式时走新上传路径
|
||||
if d.Addition.Type == MetaPersonalNew ||
|
||||
((d.isGroup() || d.isFamily()) && !d.UseOldStreamUpload) {
|
||||
var createPath, getUploadUrlPath, completePath string
|
||||
if d.isGroup() || d.isFamily() {
|
||||
// 家庭云和共享群共用同一套新上传 API
|
||||
createPath = "/dynamic/file/create"
|
||||
getUploadUrlPath = "/dynamic/file/getUploadUrl"
|
||||
completePath = "/dynamic/file/complete"
|
||||
} else {
|
||||
// MetaPersonalNew
|
||||
createPath = "/file/create"
|
||||
getUploadUrlPath = "/file/getUploadUrl"
|
||||
completePath = "/file/complete"
|
||||
}
|
||||
|
||||
var err error
|
||||
fullHash := stream.GetHash().GetHash(utils.SHA256)
|
||||
if len(fullHash) != utils.SHA256.Width {
|
||||
@@ -671,9 +759,22 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
"type": "file",
|
||||
"fileRenameMode": "auto_rename",
|
||||
}
|
||||
pathname := "/file/create"
|
||||
// 家庭云和共享群需要额外的参数
|
||||
if d.isGroup() || d.isFamily() {
|
||||
if d.CloudID == "" {
|
||||
return fmt.Errorf("cloud_id is required for group/family upload")
|
||||
}
|
||||
data["groupId"] = d.CloudID
|
||||
if d.isGroup() {
|
||||
data["groupType"] = 2
|
||||
} else if d.isFamily() {
|
||||
data["groupType"] = 1
|
||||
}
|
||||
data["catalogType"] = 3
|
||||
data["seqNo"] = random.String(32)
|
||||
}
|
||||
var resp PersonalUploadResp
|
||||
_, err = d.personalPost(pathname, data, &resp)
|
||||
_, err = d.newPost(createPath, data, &resp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -690,10 +791,19 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
if resp.Data.PartInfos != nil {
|
||||
// Progress
|
||||
p := driver.NewProgress(size, up)
|
||||
|
||||
rateLimited := driver.NewLimitedUploadStream(ctx, stream)
|
||||
ss, err := streamPkg.NewStreamSectionReader(&streamPkg.FileStream{
|
||||
Ctx: ctx,
|
||||
Reader: rateLimited,
|
||||
Obj: &model.Object{Size: size},
|
||||
}, int(partSize), &up)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 先上传前100个分片
|
||||
err = d.uploadPersonalParts(ctx, partInfos, resp.Data.PartInfos, rateLimited, p)
|
||||
err = d.uploadPersonalParts(ctx, partInfos, resp.Data.PartInfos, ss, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -711,13 +821,12 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
"accountType": 1,
|
||||
},
|
||||
}
|
||||
pathname := "/file/getUploadUrl"
|
||||
var moreresp PersonalUploadUrlResp
|
||||
_, err = d.personalPost(pathname, moredata, &moreresp)
|
||||
_, err = d.newPost(getUploadUrlPath, moredata, &moreresp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = d.uploadPersonalParts(ctx, partInfos, moreresp.Data.PartInfos, rateLimited, p)
|
||||
err = d.uploadPersonalParts(ctx, partInfos, moreresp.Data.PartInfos, ss, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -730,7 +839,11 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
"fileId": resp.Data.FileId,
|
||||
"uploadId": resp.Data.UploadId,
|
||||
}
|
||||
_, err = d.personalPost("/file/complete", data, nil)
|
||||
// 家庭云和共享群需要额外的参数
|
||||
if d.isGroup() || d.isFamily() {
|
||||
data["groupId"] = d.CloudID
|
||||
}
|
||||
_, err = d.newPost(completePath, data, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -775,11 +888,11 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case MetaPersonal:
|
||||
fallthrough
|
||||
case MetaGroup:
|
||||
fallthrough
|
||||
case MetaFamily:
|
||||
}
|
||||
|
||||
// 旧上传路径
|
||||
switch d.Addition.Type {
|
||||
case MetaPersonal, MetaGroup, MetaFamily:
|
||||
// 处理冲突
|
||||
// 获取文件列表
|
||||
files, err := d.List(ctx, dstDir, model.ListArgs{})
|
||||
@@ -826,11 +939,11 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
},
|
||||
}
|
||||
pathname := "/orchestration/personalCloud/uploadAndDownload/v1.0/pcUploadFileRequest"
|
||||
if d.isFamily() || d.Addition.Type == MetaGroup {
|
||||
uploadPath := path.Join(dstDir.GetPath(), dstDir.GetID())
|
||||
// if dstDir is root folder
|
||||
if dstDir.GetID() == d.RootFolderID {
|
||||
uploadPath = d.RootPath
|
||||
if d.isFamily() || d.isGroup() {
|
||||
uploadPath := d.dirPath(dstDir)
|
||||
// 共享群的根目录上传路径为 0
|
||||
if d.isGroup() && dstDir.GetID() == d.RootFolderID {
|
||||
uploadPath = "0"
|
||||
}
|
||||
data = d.newJson(base.Json{
|
||||
"fileCount": 1,
|
||||
@@ -858,56 +971,86 @@ func (d *Yun139) Put(ctx context.Context, dstDir model.Obj, stream model.FileStr
|
||||
}
|
||||
|
||||
size := stream.GetSize()
|
||||
partSize := d.getPartSize(size)
|
||||
|
||||
// Progress
|
||||
p := driver.NewProgress(size, up)
|
||||
partSize := d.getPartSize(size)
|
||||
rateLimited := driver.NewLimitedUploadStream(ctx, stream)
|
||||
|
||||
// StreamSectionReader for per-chunk buffering and retry
|
||||
ss, err := streamPkg.NewStreamSectionReader(&streamPkg.FileStream{
|
||||
Ctx: ctx,
|
||||
Reader: rateLimited,
|
||||
Obj: &model.Object{Size: size},
|
||||
}, int(partSize), &up)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
part := int64(1)
|
||||
if size > partSize {
|
||||
part = (size + partSize - 1) / partSize
|
||||
}
|
||||
rateLimited := driver.NewLimitedUploadStream(ctx, stream)
|
||||
for i := int64(0); i < part; i++ {
|
||||
if utils.IsCanceled(ctx) {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
start := i * partSize
|
||||
byteSize := min(size-start, partSize)
|
||||
|
||||
limitReader := io.LimitReader(rateLimited, byteSize)
|
||||
// Update Progress
|
||||
r := io.TeeReader(limitReader, p)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, resp.Data.UploadResult.RedirectionURL, r)
|
||||
if err != nil {
|
||||
return err
|
||||
rd, getErr := ss.GetSectionReader(start, byteSize)
|
||||
if getErr != nil {
|
||||
return getErr
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain;name="+unicode(stream.GetName()))
|
||||
req.Header.Set("contentSize", strconv.FormatInt(size, 10))
|
||||
req.Header.Set("range", fmt.Sprintf("bytes=%d-%d", start, start+byteSize-1))
|
||||
req.Header.Set("uploadtaskID", resp.Data.UploadResult.UploadTaskID)
|
||||
req.Header.Set("rangeType", "0")
|
||||
req.ContentLength = byteSize
|
||||
|
||||
res, err := base.HttpClient.Do(req)
|
||||
err = retry.Do(
|
||||
func() error {
|
||||
if _, err := rd.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, resp.Data.UploadResult.RedirectionURL,
|
||||
io.TeeReader(rd, p))
|
||||
if reqErr != nil {
|
||||
return reqErr
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/plain;name="+unicode(stream.GetName()))
|
||||
req.Header.Set("contentSize", strconv.FormatInt(size, 10))
|
||||
req.Header.Set("range", fmt.Sprintf("bytes=%d-%d", start, start+byteSize-1))
|
||||
req.Header.Set("uploadtaskID", resp.Data.UploadResult.UploadTaskID)
|
||||
req.Header.Set("rangeType", "0")
|
||||
req.ContentLength = byteSize
|
||||
|
||||
res, doErr := base.HttpClient.Do(req)
|
||||
if doErr != nil {
|
||||
return doErr
|
||||
}
|
||||
defer res.Body.Close()
|
||||
bodyBytes, readErr := io.ReadAll(res.Body)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("error reading response body: %v", readErr)
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("unexpected status code: %d, body: %s", res.StatusCode, string(bodyBytes))
|
||||
}
|
||||
var result InterLayerUploadResult
|
||||
xmlErr := xml.Unmarshal(bodyBytes, &result)
|
||||
if xmlErr != nil {
|
||||
return fmt.Errorf("error parsing XML: %v", xmlErr)
|
||||
}
|
||||
if result.ResultCode != 0 {
|
||||
return fmt.Errorf("upload failed with result code: %d, message: %s", result.ResultCode, result.Msg)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
retry.Context(ctx),
|
||||
retry.Attempts(3),
|
||||
retry.DelayType(retry.BackOffDelay),
|
||||
retry.Delay(time.Second),
|
||||
)
|
||||
ss.FreeSectionReader(rd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
res.Body.Close()
|
||||
return fmt.Errorf("unexpected status code: %d", res.StatusCode)
|
||||
}
|
||||
bodyBytes, err := io.ReadAll(res.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error reading response body: %v", err)
|
||||
}
|
||||
var result InterLayerUploadResult
|
||||
err = xml.Unmarshal(bodyBytes, &result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error parsing XML: %v", err)
|
||||
}
|
||||
if result.ResultCode != 0 {
|
||||
return fmt.Errorf("upload failed with result code: %d, message: %s", result.ResultCode, result.Msg)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
@@ -944,38 +1087,14 @@ func (d *Yun139) GetDetails(ctx context.Context) (*model.StorageDetails, error)
|
||||
if d.UserDomainID == "" {
|
||||
return nil, errs.NotImplement
|
||||
}
|
||||
var total, used int64
|
||||
if d.isFamily() {
|
||||
diskInfo, err := d.getFamilyDiskInfo(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
totalMb, err := strconv.ParseInt(diskInfo.Data.DiskSize, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed convert disk size into integer: %+v", err)
|
||||
}
|
||||
usedMb, err := strconv.ParseInt(diskInfo.Data.UsedSize, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed convert used size into integer: %+v", err)
|
||||
}
|
||||
total = totalMb * 1024 * 1024
|
||||
used = usedMb * 1024 * 1024
|
||||
} else {
|
||||
diskInfo, err := d.getPersonalDiskInfo(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
totalMb, err := strconv.ParseInt(diskInfo.Data.DiskSize, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed convert disk size into integer: %+v", err)
|
||||
}
|
||||
freeMb, err := strconv.ParseInt(diskInfo.Data.FreeDiskSize, 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed convert free size into integer: %+v", err)
|
||||
}
|
||||
total = totalMb * 1024 * 1024
|
||||
used = total - (freeMb * 1024 * 1024)
|
||||
detail, err := d.getDiskQuotaDetail(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
total := detail.Data.DiskSize * utils.MB
|
||||
used := (detail.Data.DiskSize - detail.Data.FreeDiskSize) * utils.MB
|
||||
|
||||
return &model.StorageDetails{
|
||||
DiskUsage: model.DiskUsage{
|
||||
TotalSpace: total,
|
||||
|
||||
+8
-5
@@ -7,17 +7,20 @@ import (
|
||||
|
||||
type Addition struct {
|
||||
//Account string `json:"account" required:"true"`
|
||||
Authorization string `json:"authorization" type:"text" required:"true"`
|
||||
Username string `json:"username" required:"true"`
|
||||
Password string `json:"password" required:"true" secret:"true"`
|
||||
MailCookies string `json:"mail_cookies" required:"true" type:"text" help:"Cookies from mail.139.com used for login authentication."`
|
||||
Authorization string `json:"authorization" type:"text" help:"Authorization can be used alone. If empty, use username + password; mail_cookies is optional and will be established/updated automatically. Existing mail_cookies can also be used alone for fast login."`
|
||||
Username string `json:"username" help:"Use together with password when Authorization is empty. mail_cookies may be left empty on the first login."`
|
||||
Password string `json:"password" secret:"true" help:"Use together with username when Authorization is empty. mail_cookies may be left empty on the first login."`
|
||||
SmsCode string `json:"sms_code" secret:"true" help:"Fill this only after OpenList reports that a 139 Mail SMS verification code was sent, then save the storage again."`
|
||||
MailCookies string `json:"mail_cookies" type:"text" help:"Optional cookies from mail.10086.cn. Leave empty for a first username/password login; cookies created or updated by password/SMS login are persisted and reused as device context. Existing cookies may also be used alone for fast login."`
|
||||
driver.RootID
|
||||
Type string `json:"type" type:"select" options:"personal_new,family,group,personal" default:"personal_new"`
|
||||
Type string `json:"type" type:"select" options:"personal_new,family,group,personal,share" default:"personal_new"`
|
||||
LinkID string `json:"link_id" type:"text" help:"Multiple shares are separated by commas or new lines. Use link_id#password for password-protected shares."`
|
||||
CloudID string `json:"cloud_id"`
|
||||
UserDomainID string `json:"user_domain_id" help:"ud_id in Cookie, fill in to show disk usage"`
|
||||
CustomUploadPartSize int64 `json:"custom_upload_part_size" type:"number" default:"0" help:"0 for auto"`
|
||||
ReportRealSize bool `json:"report_real_size" type:"bool" default:"true" help:"Enable to report the real file size during upload"`
|
||||
UseLargeThumbnail bool `json:"use_large_thumbnail" type:"bool" default:"false" help:"Enable to use large thumbnail for images"`
|
||||
UseOldStreamUpload bool `json:"use_old_stream_upload" type:"bool" default:"false" help:"Enable to use old stream upload method (not support rapid upload)"`
|
||||
}
|
||||
|
||||
var config = driver.Config{
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package _139
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestShareEntriesAndRefEncoding(t *testing.T) {
|
||||
d := &Yun139{Addition: Addition{
|
||||
Type: MetaShare,
|
||||
LinkID: "share-a,share-b,share-c#pass",
|
||||
}}
|
||||
|
||||
entries := d.shareEntries()
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("expected 3 share entries, got %d", len(entries))
|
||||
}
|
||||
if entries[2].LinkID != "share-c" || entries[2].Password != "pass" {
|
||||
t.Fatalf("unexpected password share entry: %+v", entries[2])
|
||||
}
|
||||
|
||||
refs := []shareRef{
|
||||
{LinkID: entries[0].LinkID, Password: entries[0].Password, NodeID: "root-a"},
|
||||
{LinkID: entries[2].LinkID, Password: entries[2].Password, NodeID: "root-b"},
|
||||
}
|
||||
encoded := encodeShareRefs(refs)
|
||||
decoded, ok := decodeShareRefs(encoded)
|
||||
if !ok || len(decoded) != len(refs) {
|
||||
t.Fatalf("failed to decode merged share refs: %q", encoded)
|
||||
}
|
||||
for i := range refs {
|
||||
if decoded[i] != refs[i] {
|
||||
t.Fatalf("unexpected decoded ref at %d: %+v", i, decoded[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
-12
@@ -9,6 +9,7 @@ const (
|
||||
MetaFamily string = "family"
|
||||
MetaGroup string = "group"
|
||||
MetaPersonalNew string = "personal_new"
|
||||
MetaShare string = "share"
|
||||
)
|
||||
|
||||
type BaseResp struct {
|
||||
@@ -285,6 +286,56 @@ type PersonalUploadUrlResp struct {
|
||||
}
|
||||
}
|
||||
|
||||
type ShareCatalog struct {
|
||||
CaID string `json:"caId"`
|
||||
CaName string `json:"caName"`
|
||||
UdTime string `json:"udTime"`
|
||||
}
|
||||
|
||||
type ShareContent struct {
|
||||
CoID string `json:"coId"`
|
||||
CoName string `json:"coName"`
|
||||
CoSize int64 `json:"coSize"`
|
||||
CoType int `json:"coType"`
|
||||
UdTime string `json:"udTime"`
|
||||
CoPath string `json:"coPath"`
|
||||
PresentURL string `json:"presentURL"`
|
||||
DownloadURL string `json:"downloadURL"`
|
||||
}
|
||||
|
||||
type ShareListResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
LKName string `json:"lkName"`
|
||||
Passwd string `json:"password"`
|
||||
CaLst []ShareCatalog `json:"caLst"`
|
||||
CoLst []ShareContent `json:"coLst"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type ShareContentInfo struct {
|
||||
PresentURL string `json:"presentURL"`
|
||||
DownloadURL string `json:"cdnDownLoadUrl"`
|
||||
}
|
||||
|
||||
type ShareDownloadResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
DownloadURL string `json:"downloadURL"`
|
||||
RedrURL string `json:"redrUrl"`
|
||||
ExtInfo struct {
|
||||
CDNDownloadURL string `json:"cdnDownloadUrl"`
|
||||
} `json:"extInfo"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type ShareContentInfoResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
ContentInfo ShareContentInfo `json:"contentInfo"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type QueryRoutePolicyResp struct {
|
||||
Success bool `json:"success"`
|
||||
Code string `json:"code"`
|
||||
@@ -313,20 +364,16 @@ type RefreshTokenResp struct {
|
||||
Desc string `xml:"desc"`
|
||||
}
|
||||
|
||||
type PersonalDiskInfoResp struct {
|
||||
type DiskQuotaDetail struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
FreeDiskSize string `json:"freeDiskSize"`
|
||||
DiskSize string `json:"diskSize"`
|
||||
IsInfinitePicStorage *bool `json:"isInfinitePicStorage"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type FamilyDiskInfoResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
UsedSize string `json:"usedSize"`
|
||||
DiskSize string `json:"diskSize"`
|
||||
FreeDiskSize int64 `json:"freeDiskSize"`
|
||||
DiskSize int64 `json:"diskSize"`
|
||||
// QuotaList []struct {
|
||||
// DriveType int `json:"driveType"`
|
||||
// DriveName string `json:"driveName"`
|
||||
// UsedSize int64 `json:"usedSize"`
|
||||
// } `json:"quotaList"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
|
||||
+831
-141
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,474 @@
|
||||
package _139
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
func useRetryingTestClient(t *testing.T) {
|
||||
t.Helper()
|
||||
oldClient := base.RestyClient
|
||||
base.RestyClient = resty.New().SetRetryCount(3)
|
||||
t.Cleanup(func() {
|
||||
base.RestyClient = oldClient
|
||||
})
|
||||
}
|
||||
|
||||
func TestMergeMailCookiesPreservesExistingOrderAndAppendsNewNames(t *testing.T) {
|
||||
got := mergeMailCookieHeader("z=zv; behaviorid=b; Os_SSo_Sid=old", []*http.Cookie{
|
||||
{Name: "RMKEY", Value: "rm"},
|
||||
{Name: "Os_SSo_Sid", Value: "sid"},
|
||||
{Name: "a", Value: "av"},
|
||||
})
|
||||
want := "z=zv;behaviorid=b;Os_SSo_Sid=sid;RMKEY=rm;a=av"
|
||||
if got != want {
|
||||
t.Fatalf("mergeMailCookieHeader() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractFastLoginCookies(t *testing.T) {
|
||||
sid, rmkey := extractFastLoginCookies("RMKEY=rm; Os_SSo_Sid=sid")
|
||||
if sid != "sid" || rmkey != "rm" {
|
||||
t.Fatalf("extractFastLoginCookies() = %q, %q; want sid, rm", sid, rmkey)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialState(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
d Yun139
|
||||
want credentialState
|
||||
err bool
|
||||
}{
|
||||
{
|
||||
name: "authorization",
|
||||
d: Yun139{Addition: Addition{Authorization: " auth "}},
|
||||
want: credentialStateAuthorization,
|
||||
},
|
||||
{
|
||||
name: "full login",
|
||||
d: Yun139{Addition: Addition{
|
||||
MailCookies: "RMKEY=rm; Os_SSo_Sid=sid",
|
||||
Username: "user",
|
||||
Password: "password",
|
||||
}},
|
||||
want: credentialStateFullLogin,
|
||||
},
|
||||
{
|
||||
name: "full login without initial cookies",
|
||||
d: Yun139{Addition: Addition{
|
||||
Username: "user",
|
||||
Password: "password",
|
||||
}},
|
||||
want: credentialStateFullLogin,
|
||||
},
|
||||
{
|
||||
name: "cookies only",
|
||||
d: Yun139{Addition: Addition{MailCookies: "RMKEY=rm; Os_SSo_Sid=sid"}},
|
||||
want: credentialStateCookiesOnly,
|
||||
},
|
||||
{
|
||||
name: "partial password login",
|
||||
d: Yun139{Addition: Addition{Username: "user"}},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "missing credentials",
|
||||
d: Yun139{},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "invalid cookie",
|
||||
d: Yun139{Addition: Addition{MailCookies: "invalid-cookie"}},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "authorization with basic prefix",
|
||||
d: Yun139{Addition: Addition{Authorization: "Basic abc"}},
|
||||
err: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := tt.d.credentialState()
|
||||
if tt.err {
|
||||
if err == nil {
|
||||
t.Fatal("credentialState() expected error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("credentialState() unexpected error: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("credentialState() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationLoginObtainsAuthorization(t *testing.T) {
|
||||
if os.Getenv("OPENLIST_139_INTEGRATION") != "1" {
|
||||
t.Skip("set OPENLIST_139_INTEGRATION=1 to run live 139Yun login checks")
|
||||
}
|
||||
base.RestyClient = resty.New().
|
||||
SetHeader("user-agent", base.UserAgent).
|
||||
SetRetryCount(3).
|
||||
SetRetryResetReaders(true).
|
||||
SetTimeout(30 * time.Second)
|
||||
|
||||
username := os.Getenv("OPENLIST_139_USERNAME")
|
||||
password := os.Getenv("OPENLIST_139_PASSWORD")
|
||||
mailCookies := os.Getenv("OPENLIST_139_MAIL_COOKIES")
|
||||
authorization := strings.TrimSpace(os.Getenv("OPENLIST_139_AUTHORIZATION"))
|
||||
|
||||
if authorization != "" {
|
||||
t.Run("authorization", func(t *testing.T) {
|
||||
d := Yun139{Addition: Addition{Authorization: authorization}}
|
||||
state, err := d.credentialState()
|
||||
if err != nil {
|
||||
t.Fatalf("credentialState() unexpected error: %v", err)
|
||||
}
|
||||
if state != credentialStateAuthorization {
|
||||
t.Fatalf("credentialState() = %v, want authorization", state)
|
||||
}
|
||||
if d.Authorization == "" || strings.HasPrefix(strings.ToLower(d.Authorization), "basic ") {
|
||||
t.Fatal("authorization should be present without Basic prefix")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if mailCookies == "" {
|
||||
t.Fatal("OPENLIST_139_MAIL_COOKIES is required")
|
||||
}
|
||||
|
||||
runFastLogin := func(mailCookies string) error {
|
||||
d := Yun139{Addition: Addition{MailCookies: mailCookies}}
|
||||
state, err := d.credentialState()
|
||||
if err != nil {
|
||||
return fmt.Errorf("credentialState() error: %w", err)
|
||||
}
|
||||
if state != credentialStateCookiesOnly {
|
||||
return fmt.Errorf("credentialState() = %v, want cookies only", state)
|
||||
}
|
||||
sid, rmkey := extractFastLoginCookies(d.MailCookies)
|
||||
if sid == "" || rmkey == "" {
|
||||
return fmt.Errorf("mail cookies are missing Os_SSo_Sid or RMKEY")
|
||||
}
|
||||
token, err := d.step2_get_single_token(sid)
|
||||
if err != nil {
|
||||
return fmt.Errorf("step2_get_single_token() error: %w", err)
|
||||
}
|
||||
auth, err := d.step3_third_party_login(token)
|
||||
if err != nil {
|
||||
return fmt.Errorf("step3_third_party_login() error: %w", err)
|
||||
}
|
||||
if auth == "" {
|
||||
return fmt.Errorf("authorization is empty after fast login")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
if username == "" || password == "" {
|
||||
t.Fatal("OPENLIST_139_USERNAME and OPENLIST_139_PASSWORD are required for password fallback")
|
||||
}
|
||||
|
||||
var refreshedMailCookies string
|
||||
var generatedAuthorization string
|
||||
t.Run("password login fallback", func(t *testing.T) {
|
||||
d := Yun139{Addition: Addition{
|
||||
MailCookies: mailCookies,
|
||||
Username: username,
|
||||
Password: password,
|
||||
}}
|
||||
state, err := d.credentialState()
|
||||
if err != nil {
|
||||
t.Fatalf("credentialState() unexpected error: %v", err)
|
||||
}
|
||||
if state != credentialStateFullLogin {
|
||||
t.Fatalf("credentialState() = %v, want full login", state)
|
||||
}
|
||||
passId, err := d.step1_password_login()
|
||||
if err != nil {
|
||||
t.Fatalf("step1_password_login() error: %v", err)
|
||||
}
|
||||
token, err := d.step2_get_single_token(passId)
|
||||
if err != nil {
|
||||
t.Fatalf("step2_get_single_token() error: %v", err)
|
||||
}
|
||||
auth, err := d.step3_third_party_login(token)
|
||||
if err != nil {
|
||||
t.Fatalf("step3_third_party_login() error: %v", err)
|
||||
}
|
||||
d.Authorization = auth
|
||||
if auth == "" || d.Authorization == "" {
|
||||
t.Fatal("authorization is empty after password login")
|
||||
}
|
||||
generatedAuthorization = auth
|
||||
refreshedMailCookies = d.MailCookies
|
||||
})
|
||||
|
||||
t.Run("authorization generated by password login", func(t *testing.T) {
|
||||
if generatedAuthorization == "" {
|
||||
t.Fatal("password login did not generate authorization")
|
||||
}
|
||||
d := Yun139{Addition: Addition{Authorization: generatedAuthorization}}
|
||||
state, err := d.credentialState()
|
||||
if err != nil {
|
||||
t.Fatalf("credentialState() unexpected error: %v", err)
|
||||
}
|
||||
if state != credentialStateAuthorization {
|
||||
t.Fatalf("credentialState() = %v, want authorization", state)
|
||||
}
|
||||
if strings.HasPrefix(strings.ToLower(d.Authorization), "basic ") {
|
||||
t.Fatal("authorization should not include Basic prefix")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mail cookies fast login from input", func(t *testing.T) {
|
||||
sid, rmkey := extractFastLoginCookies(mailCookies)
|
||||
if sid == "" || rmkey == "" {
|
||||
t.Skip("input mail cookies are missing Os_SSo_Sid or RMKEY")
|
||||
}
|
||||
if err := runFastLogin(mailCookies); err != nil {
|
||||
t.Skipf("input mail cookies are stale or unusable: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("mail cookies fast login after password login", func(t *testing.T) {
|
||||
if refreshedMailCookies == "" {
|
||||
t.Fatal("password login did not refresh mail cookies")
|
||||
}
|
||||
if err := runFastLogin(refreshedMailCookies); err != nil {
|
||||
t.Fatalf("refreshed mail cookies fast login failed: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestInvalidAuthorizationDoesNotUseCookieFastLogin(t *testing.T) {
|
||||
d := Yun139{Addition: Addition{
|
||||
Authorization: "not-base64",
|
||||
MailCookies: "Os_SSo_Sid=sid; RMKEY=rmkey",
|
||||
}}
|
||||
|
||||
err := d.refreshToken()
|
||||
if err == nil || !strings.Contains(err.Error(), "password login failed") {
|
||||
t.Fatalf("refreshToken() error = %v, want password login fallback error", err)
|
||||
}
|
||||
if d.Authorization != "not-base64" {
|
||||
t.Fatalf("Authorization = %q, want original invalid value retained", d.Authorization)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSMSSceneForRisk(t *testing.T) {
|
||||
tests := map[string]int{
|
||||
"S025": 1,
|
||||
"S035": 1,
|
||||
"PML401010062": 2,
|
||||
"MW0016": 4,
|
||||
}
|
||||
for riskCode, want := range tests {
|
||||
got, ok := smsSceneForRisk(riskCode)
|
||||
if !ok || got != want {
|
||||
t.Fatalf("smsSceneForRisk(%q) = %d, %t; want %d, true", riskCode, got, ok, want)
|
||||
}
|
||||
}
|
||||
if _, ok := smsSceneForRisk("PICTURE_ONLY"); ok {
|
||||
t.Fatal("smsSceneForRisk() accepted unsupported risk code")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendSMSVerificationCode(t *testing.T) {
|
||||
useRetryingTestClient(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read request body: %v", err)
|
||||
}
|
||||
if r.URL.Query().Get("func") != "login:sendSmsCodeByScene" {
|
||||
t.Errorf("func = %q", r.URL.Query().Get("func"))
|
||||
}
|
||||
if !strings.Contains(string(body), `<string name="scene">1</string>`) {
|
||||
t.Errorf("request body = %s", body)
|
||||
}
|
||||
if !strings.Contains(r.Header.Get("Cookie"), "device=fingerprint") {
|
||||
t.Errorf("Cookie = %q", r.Header.Get("Cookie"))
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "challenge", Value: "sms"})
|
||||
_, _ = io.WriteString(w, `{"code":"S_OK"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := mailSMSURL
|
||||
mailSMSURL = server.URL
|
||||
defer func() { mailSMSURL = oldURL }()
|
||||
|
||||
d := Yun139{Addition: Addition{Username: "18800000000", MailCookies: "device=fingerprint"}}
|
||||
if err := d.sendSMSVerificationCode("S025"); err != nil {
|
||||
t.Fatalf("sendSMSVerificationCode() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(d.MailCookies, "challenge=sms") {
|
||||
t.Fatalf("MailCookies = %q", d.MailCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendSMSVerificationCodeStopsAtPictureChallenge(t *testing.T) {
|
||||
useRetryingTestClient(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"code":"PML401010021"}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := mailSMSURL
|
||||
mailSMSURL = server.URL
|
||||
defer func() { mailSMSURL = oldURL }()
|
||||
|
||||
d := Yun139{Addition: Addition{Username: "18800000000"}}
|
||||
err := d.sendSMSVerificationCode("S025")
|
||||
if err == nil || !strings.Contains(err.Error(), "requires picture verification") {
|
||||
t.Fatalf("sendSMSVerificationCode() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifySMSCode(t *testing.T) {
|
||||
useRetryingTestClient(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read request body: %v", err)
|
||||
}
|
||||
if r.URL.Query().Get("func") != "/login/inlogin.action" {
|
||||
t.Errorf("func = %q", r.URL.Query().Get("func"))
|
||||
}
|
||||
wantHash := sha1Hash("fetion.com.cn:123456")
|
||||
if !strings.Contains(string(body), `<string name="loginPassword">`+wantHash+`</string>`) {
|
||||
t.Errorf("request body does not contain SMS code hash: %s", body)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "RMKEY", Value: "new-rmkey"})
|
||||
_, _ = io.WriteString(w, `{"code":"S_OK","var":{"loginSuccessUrl":"https://mail.10086.cn/?sid=sms-sid"}}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := mailSMSURL
|
||||
mailSMSURL = server.URL
|
||||
defer func() { mailSMSURL = oldURL }()
|
||||
|
||||
d := Yun139{Addition: Addition{
|
||||
Username: "18800000000",
|
||||
SmsCode: "123456",
|
||||
MailCookies: "challenge=sms",
|
||||
}}
|
||||
sid, err := d.verifySMSCode("S025")
|
||||
if err != nil {
|
||||
t.Fatalf("verifySMSCode() error = %v", err)
|
||||
}
|
||||
if sid != "sms-sid" {
|
||||
t.Fatalf("sid = %q", sid)
|
||||
}
|
||||
if d.SmsCode != "" {
|
||||
t.Fatalf("SmsCode = %q, want cleared", d.SmsCode)
|
||||
}
|
||||
if !strings.Contains(d.MailCookies, "RMKEY=new-rmkey") {
|
||||
t.Fatalf("MailCookies = %q", d.MailCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordLoginWithoutInitialCookiesStopsAtRedirectAndPersistsCookies(t *testing.T) {
|
||||
useRetryingTestClient(t)
|
||||
|
||||
var loginRequests, redirectRequests int
|
||||
var server *httptest.Server
|
||||
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/Login/Login.ashx":
|
||||
loginRequests++
|
||||
http.SetCookie(w, &http.Cookie{Name: "RMKEY", Value: "new-rm"})
|
||||
http.SetCookie(w, &http.Cookie{Name: "Os_SSo_Sid", Value: "new-sid"})
|
||||
w.Header().Set("Location", server.URL+"/appmail?sid=single-sid")
|
||||
w.WriteHeader(http.StatusFound)
|
||||
case "/appmail":
|
||||
redirectRequests++
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := mailPasswordURL
|
||||
mailPasswordURL = server.URL + "/Login/Login.ashx"
|
||||
defer func() { mailPasswordURL = oldURL }()
|
||||
|
||||
d := Yun139{Addition: Addition{Username: "18800000000", Password: "password"}}
|
||||
sid, err := d.step1_password_login()
|
||||
if err != nil || sid != "single-sid" {
|
||||
t.Fatalf("sid=%q err=%v", sid, err)
|
||||
}
|
||||
if loginRequests != 1 || redirectRequests != 0 {
|
||||
t.Fatalf("login/redirect requests=%d/%d, want 1/0", loginRequests, redirectRequests)
|
||||
}
|
||||
if !strings.Contains(d.MailCookies, "RMKEY=new-rm") || !strings.Contains(d.MailCookies, "Os_SSo_Sid=new-sid") {
|
||||
t.Fatalf("response cookies were not persisted: %q", d.MailCookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPasswordLoginReusesRawRefreshedCookies(t *testing.T) {
|
||||
useRetryingTestClient(t)
|
||||
|
||||
var n int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
n++
|
||||
cookie := r.Header.Get("Cookie")
|
||||
if !strings.Contains(cookie, "JSESSIONID=stale") || !strings.Contains(cookie, "behaviorid=device") {
|
||||
t.Errorf("login %d lost raw cookie context: %q", n, cookie)
|
||||
}
|
||||
if n == 1 {
|
||||
http.SetCookie(w, &http.Cookie{Name: "RMKEY", Value: "rm-1"})
|
||||
http.SetCookie(w, &http.Cookie{Name: "Os_SSo_Sid", Value: "sid-1"})
|
||||
w.Header().Set("Location", "https://mail.10086.cn/?sid=first")
|
||||
} else {
|
||||
if !strings.Contains(cookie, "RMKEY=rm-1") || !strings.Contains(cookie, "Os_SSo_Sid=sid-1") {
|
||||
t.Errorf("second login did not reuse first refreshed cookies: %q", cookie)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "RMKEY", Value: "rm-2"})
|
||||
http.SetCookie(w, &http.Cookie{Name: "Os_SSo_Sid", Value: "sid-2"})
|
||||
w.Header().Set("Location", "https://mail.10086.cn/?sid=second")
|
||||
}
|
||||
w.WriteHeader(http.StatusFound)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
oldURL := mailPasswordURL
|
||||
mailPasswordURL = server.URL
|
||||
defer func() { mailPasswordURL = oldURL }()
|
||||
|
||||
d := Yun139{Addition: Addition{Username: "18800000000", Password: "password", MailCookies: "Os_SSo_Sid=old; RMKEY=old; JSESSIONID=stale; behaviorid=device"}}
|
||||
if sid, err := d.step1_password_login(); err != nil || sid != "first" {
|
||||
t.Fatalf("first login sid=%q err=%v", sid, err)
|
||||
}
|
||||
refreshed := d.MailCookies
|
||||
if !strings.Contains(refreshed, "RMKEY=rm-1") || !strings.Contains(refreshed, "Os_SSo_Sid=sid-1") {
|
||||
t.Fatalf("first login did not persist refreshed cookies: %q", refreshed)
|
||||
}
|
||||
d.Authorization = ""
|
||||
d.MailCookies = refreshed
|
||||
if sid, err := d.step1_password_login(); err != nil || sid != "second" {
|
||||
t.Fatalf("second login sid=%q err=%v", sid, err)
|
||||
}
|
||||
if n != 2 {
|
||||
t.Fatalf("login count=%d, want 2", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package _189
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/torrent"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
)
|
||||
|
||||
// GenerateTorrent 根据上传过程中收集的哈希信息生成包含 CAS 扩展的 torrent 文件
|
||||
func GenerateTorrent(fileName string, fileSize int64, fileMD5 string, sliceMD5s []string, sliceSize int64, pieceHashes []byte) ([]byte, error) {
|
||||
// 计算 sliceMD5
|
||||
sliceMD5 := fileMD5
|
||||
if len(sliceMD5s) > 1 {
|
||||
joined := strings.Join(sliceMD5s, "\n")
|
||||
sliceMD5 = strings.ToUpper(torrent.GetMD5Str(joined))
|
||||
}
|
||||
|
||||
t := torrent.NewTorrent(fileName, fileSize, fileMD5)
|
||||
t.Info.PieceLength = sliceSize
|
||||
t.SetPieces(pieceHashes)
|
||||
t.SetCASInfo(&torrent.CASInfo{
|
||||
FileMD5: fileMD5,
|
||||
SliceMD5: sliceMD5,
|
||||
SliceMD5s: sliceMD5s,
|
||||
SliceSize: sliceSize,
|
||||
Cloud: "189",
|
||||
})
|
||||
|
||||
return t.Encode()
|
||||
}
|
||||
|
||||
// RapidUploadFromTorrent 从 torrent 文件中提取 CAS 信息进行秒传
|
||||
func (d *Cloud189) RapidUploadFromTorrent(ctx context.Context, dstDir model.Obj, torrentData []byte) error {
|
||||
// 解析 torrent
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return fmt.Errorf("解析 torrent 失败: %w", err)
|
||||
}
|
||||
|
||||
// 检查是否包含 CAS 扩展信息
|
||||
if !t.HasCASInfo() {
|
||||
return fmt.Errorf("torrent 不包含 CAS 扩展信息,无法秒传")
|
||||
}
|
||||
|
||||
cas := t.CAS
|
||||
fileName := t.Info.Name
|
||||
fileSize := t.GetTotalSize()
|
||||
|
||||
// 获取 sessionKey
|
||||
sessionKey, err := d.getSessionKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.sessionKey = sessionKey
|
||||
|
||||
// 初始化上传
|
||||
res, err := d.uploadRequest("/person/initMultiUpload", map[string]string{
|
||||
"parentFolderId": dstDir.GetID(),
|
||||
"fileName": encode(fileName),
|
||||
"fileSize": fmt.Sprint(fileSize),
|
||||
"sliceSize": fmt.Sprint(cas.SliceSize),
|
||||
"lazyCheck": "1",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("初始化上传失败: %w", err)
|
||||
}
|
||||
|
||||
uploadFileId := utils.Json.Get(res, "data", "uploadFileId").ToString()
|
||||
|
||||
// 提交上传(使用 CAS 信息秒传)
|
||||
_, err = d.uploadRequest("/person/commitMultiUploadFile", map[string]string{
|
||||
"uploadFileId": uploadFileId,
|
||||
"fileMd5": cas.FileMD5,
|
||||
"sliceMd5": cas.SliceMD5,
|
||||
"lazyCheck": "1",
|
||||
"opertype": "3",
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("秒传提交失败: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ComputeTorrentFromReader 从 io.Reader 计算并生成 torrent 文件
|
||||
func ComputeTorrentFromReader(reader io.Reader, fileName string, fileSize int64, sliceSize int64) ([]byte, error) {
|
||||
if sliceSize <= 0 {
|
||||
sliceSize = torrent.DefaultPieceSize
|
||||
}
|
||||
|
||||
hw := torrent.NewHashWriter(sliceSize, sliceSize)
|
||||
|
||||
buf := make([]byte, 32*1024)
|
||||
for {
|
||||
n, err := reader.Read(buf)
|
||||
if n > 0 {
|
||||
hw.Write(buf[:n])
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
hw.Finish()
|
||||
|
||||
fileMD5 := hw.GetFileMD5()
|
||||
sliceMD5s := hw.GetSliceMD5s()
|
||||
pieceHashes := hw.GetPieceHashes()
|
||||
|
||||
return GenerateTorrent(fileName, fileSize, fileMD5, sliceMD5s, sliceSize, pieceHashes)
|
||||
}
|
||||
|
||||
// ComputePieceSHA1 计算单个分片的 SHA-1 哈希
|
||||
func ComputePieceSHA1(data []byte) []byte {
|
||||
h := sha1.Sum(data)
|
||||
return h[:]
|
||||
}
|
||||
|
||||
// ExtractCASFromTorrent 从 torrent 数据中提取 CAS 信息
|
||||
func ExtractCASFromTorrent(torrentData []byte) (*torrent.CASInfo, string, int64, error) {
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return nil, "", 0, fmt.Errorf("解析 torrent 失败: %w", err)
|
||||
}
|
||||
|
||||
if !t.HasCASInfo() {
|
||||
return nil, "", 0, fmt.Errorf("torrent 不包含 CAS 扩展信息")
|
||||
}
|
||||
|
||||
return t.CAS, t.Info.Name, t.GetTotalSize(), nil
|
||||
}
|
||||
|
||||
// GetInfoHashHex 获取 torrent 的 info_hash(十六进制字符串)
|
||||
func GetInfoHashHex(torrentData []byte) (string, error) {
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(t.InfoHash), nil
|
||||
}
|
||||
+173
-25
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
sha1Pkg "crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
@@ -18,6 +19,8 @@ import (
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/op"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/stream"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
myrand "github.com/OpenListTeam/OpenList/v4/pkg/utils/random"
|
||||
"github.com/go-resty/resty/v2"
|
||||
@@ -311,48 +314,107 @@ func (d *Cloud189) newUpload(ctx context.Context, dstDir model.Obj, file model.F
|
||||
}
|
||||
d.sessionKey = sessionKey
|
||||
const DEFAULT int64 = 10485760
|
||||
count := int64(math.Ceil(float64(file.GetSize()) / float64(DEFAULT)))
|
||||
fileSize := file.GetSize()
|
||||
count := int64(math.Ceil(float64(fileSize) / float64(DEFAULT)))
|
||||
|
||||
res, err := d.uploadRequest("/person/initMultiUpload", map[string]string{
|
||||
// 先计算文件完整MD5和分片MD5,用于秒传判断
|
||||
fileMd5Hex := file.GetHash().GetHash(utils.MD5)
|
||||
sliceMd5Hex := ""
|
||||
md5s := make([]string, 0)
|
||||
|
||||
if len(fileMd5Hex) < utils.MD5.Width {
|
||||
// 没有MD5,先缓存流并同时计算文件MD5和分片MD5
|
||||
fileMd5Hash := md5.New()
|
||||
sliceMd5Hash := md5.New()
|
||||
var finish int64
|
||||
cache, err := file.CacheFullAndWriter(nil, io.MultiWriter(fileMd5Hash, &sliceHashWriter{
|
||||
hash: sliceMd5Hash,
|
||||
md5s: &md5s,
|
||||
sliceSize: DEFAULT,
|
||||
finish: &finish,
|
||||
fileSize: fileSize,
|
||||
up: up,
|
||||
ctx: ctx,
|
||||
}))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 处理最后一个分片的MD5
|
||||
if finish%DEFAULT != 0 || finish == 0 {
|
||||
md5s = append(md5s, strings.ToUpper(hex.EncodeToString(sliceMd5Hash.Sum(nil))))
|
||||
}
|
||||
fileMd5Hex = hex.EncodeToString(fileMd5Hash.Sum(nil))
|
||||
|
||||
// seek回起始位置,供后续上传使用
|
||||
if _, err := cache.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 计算sliceMd5
|
||||
if fileSize > DEFAULT && len(md5s) > 0 {
|
||||
sliceMd5Hex = utils.GetMD5EncodeStr(strings.Join(md5s, "\n"))
|
||||
} else {
|
||||
sliceMd5Hex = fileMd5Hex
|
||||
}
|
||||
|
||||
// 带fileMd5调用initMultiUpload,支持秒传
|
||||
initParams := map[string]string{
|
||||
"parentFolderId": dstDir.GetID(),
|
||||
"fileName": encode(file.GetName()),
|
||||
"fileSize": strconv.FormatInt(file.GetSize(), 10),
|
||||
"fileSize": strconv.FormatInt(fileSize, 10),
|
||||
"sliceSize": strconv.FormatInt(DEFAULT, 10),
|
||||
"lazyCheck": "1",
|
||||
}, nil)
|
||||
"fileMd5": fileMd5Hex,
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
}
|
||||
|
||||
res, err := d.uploadRequest("/person/initMultiUpload", initParams, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
uploadFileId := jsoniter.Get(res, "data", "uploadFileId").ToString()
|
||||
//_, err = d.uploadRequest("/person/getUploadedPartsInfo", map[string]string{
|
||||
// "uploadFileId": uploadFileId,
|
||||
//}, nil)
|
||||
fileDataExists := jsoniter.Get(res, "data", "fileDataExists").ToInt()
|
||||
|
||||
// 秒传成功,直接提交
|
||||
if fileDataExists == 1 {
|
||||
_, err = d.uploadRequest("/person/commitMultiUploadFile", map[string]string{
|
||||
"uploadFileId": uploadFileId,
|
||||
"fileMd5": fileMd5Hex,
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
"lazyCheck": "1",
|
||||
"opertype": "3",
|
||||
}, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// 非秒传,需要上传分片
|
||||
var finish int64 = 0
|
||||
var i int64
|
||||
var byteSize int64
|
||||
md5s := make([]string, 0)
|
||||
md5Sum := md5.New()
|
||||
|
||||
// 额外计算 SHA-1 piece hash 用于生成 torrent
|
||||
pieceSHA1Hashes := make([]byte, 0, int(count)*20)
|
||||
|
||||
for i = 1; i <= count; i++ {
|
||||
if utils.IsCanceled(ctx) {
|
||||
return ctx.Err()
|
||||
}
|
||||
byteSize = file.GetSize() - finish
|
||||
byteSize = fileSize - finish
|
||||
if DEFAULT < byteSize {
|
||||
byteSize = DEFAULT
|
||||
}
|
||||
// log.Debugf("%d,%d", byteSize, finish)
|
||||
byteData := make([]byte, byteSize)
|
||||
n, err := io.ReadFull(file, byteData)
|
||||
// log.Debug(err, n)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
finish += int64(n)
|
||||
md5Bytes := getMd5(byteData)
|
||||
md5Hex := hex.EncodeToString(md5Bytes)
|
||||
md5Base64 := base64.StdEncoding.EncodeToString(md5Bytes)
|
||||
md5s = append(md5s, strings.ToUpper(md5Hex))
|
||||
md5Sum.Write(byteData)
|
||||
|
||||
// 计算 SHA-1 piece hash
|
||||
sha1Hash := sha1Pkg.Sum(byteData)
|
||||
pieceSHA1Hashes = append(pieceSHA1Hashes, sha1Hash[:]...)
|
||||
var resp UploadUrlsResp
|
||||
res, err = d.uploadRequest("/person/getMultiUploadUrls", map[string]string{
|
||||
"partInfo": fmt.Sprintf("%s-%s", strconv.FormatInt(i, 10), md5Base64),
|
||||
@@ -379,21 +441,58 @@ func (d *Cloud189) newUpload(ctx context.Context, dstDir model.Obj, file model.F
|
||||
}
|
||||
log.Debugf("%+v %+v", r, r.Request.Header)
|
||||
_ = r.Body.Close()
|
||||
up(float64(i) * 100 / float64(count))
|
||||
}
|
||||
fileMd5 := hex.EncodeToString(md5Sum.Sum(nil))
|
||||
sliceMd5 := fileMd5
|
||||
if file.GetSize() > DEFAULT {
|
||||
sliceMd5 = utils.GetMD5EncodeStr(strings.Join(md5s, "\n"))
|
||||
up(50 + float64(i)*50/float64(count))
|
||||
}
|
||||
res, err = d.uploadRequest("/person/commitMultiUploadFile", map[string]string{
|
||||
"uploadFileId": uploadFileId,
|
||||
"fileMd5": fileMd5,
|
||||
"sliceMd5": sliceMd5,
|
||||
"fileMd5": fileMd5Hex,
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
"lazyCheck": "1",
|
||||
"opertype": "3",
|
||||
}, nil)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 生成 torrent 文件(异步,不影响上传结果)
|
||||
capturedDstDir := dstDir
|
||||
capturedFileName := file.GetName()
|
||||
capturedFileSize := fileSize
|
||||
capturedFileMd5Hex := fileMd5Hex
|
||||
capturedMd5s := md5s
|
||||
go func() {
|
||||
fileMD5Upper := strings.ToUpper(capturedFileMd5Hex)
|
||||
torrentData, err := GenerateTorrent(capturedFileName, capturedFileSize, fileMD5Upper, capturedMd5s, DEFAULT, pieceSHA1Hashes)
|
||||
if err != nil {
|
||||
log.Warnf("生成 torrent 失败: %v", err)
|
||||
return
|
||||
}
|
||||
infoHash, _ := GetInfoHashHex(torrentData)
|
||||
torrentName := capturedFileName + ".cas.torrent"
|
||||
log.Infof("已生成 torrent: %s (info_hash: %s, size: %d bytes)",
|
||||
torrentName, infoHash, len(torrentData))
|
||||
|
||||
// 将 torrent 文件上传到同一目录
|
||||
torrentFileStream := &stream.FileStream{
|
||||
Ctx: context.Background(),
|
||||
Obj: &model.Object{
|
||||
Name: torrentName,
|
||||
Size: int64(len(torrentData)),
|
||||
IsFolder: false,
|
||||
},
|
||||
Reader: bytes.NewReader(torrentData),
|
||||
Mimetype: "application/x-bittorrent",
|
||||
}
|
||||
uploadErr := d.oldUpload(capturedDstDir, torrentFileStream)
|
||||
if uploadErr != nil {
|
||||
log.Warnf("上传 torrent 文件失败: %v", uploadErr)
|
||||
} else {
|
||||
log.Infof("torrent 文件已上传: %s", torrentName)
|
||||
op.Cache.DeleteDirectory(d, capturedDstDir.GetPath())
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *Cloud189) getCapacityInfo(ctx context.Context) (*CapacityResp, error) {
|
||||
@@ -406,3 +505,52 @@ func (d *Cloud189) getCapacityInfo(ctx context.Context) (*CapacityResp, error) {
|
||||
}
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// sliceHashWriter 在写入过程中按分片大小自动切分并计算每个分片的MD5,
|
||||
// 同时支持进度回调和取消检查。
|
||||
type sliceHashWriter struct {
|
||||
hash io.Writer // 当前分片的MD5 hash
|
||||
md5s *[]string // 收集每个分片的MD5十六进制字符串
|
||||
sliceSize int64 // 分片大小
|
||||
finish *int64 // 已写入的总字节数
|
||||
fileSize int64 // 文件总大小
|
||||
up driver.UpdateProgress
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (w *sliceHashWriter) Write(p []byte) (int, error) {
|
||||
if utils.IsCanceled(w.ctx) {
|
||||
return 0, w.ctx.Err()
|
||||
}
|
||||
total := len(p)
|
||||
written := 0
|
||||
for written < total {
|
||||
// 当前分片还能写入的字节数
|
||||
sliceRemain := w.sliceSize - (*w.finish % w.sliceSize)
|
||||
toWrite := int64(total - written)
|
||||
if toWrite > sliceRemain {
|
||||
toWrite = sliceRemain
|
||||
}
|
||||
n, err := w.hash.Write(p[written : written+int(toWrite)])
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
written += n
|
||||
*w.finish += int64(n)
|
||||
|
||||
// 当前分片写满,记录MD5并重置
|
||||
if *w.finish%w.sliceSize == 0 {
|
||||
if h, ok := w.hash.(interface{ Sum([]byte) []byte }); ok {
|
||||
*w.md5s = append(*w.md5s, strings.ToUpper(hex.EncodeToString(h.Sum(nil))))
|
||||
}
|
||||
if resetter, ok := w.hash.(interface{ Reset() }); ok {
|
||||
resetter.Reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
// 报告进度(缓存阶段占50%)
|
||||
if w.fileSize > 0 && w.up != nil {
|
||||
w.up(float64(*w.finish) / float64(w.fileSize) * 50)
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
|
||||
+21
-3
@@ -5,12 +5,15 @@ import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
)
|
||||
|
||||
func clientSuffix() map[string]string {
|
||||
@@ -57,7 +60,13 @@ func timestamp() int64 {
|
||||
|
||||
type Time time.Time
|
||||
|
||||
func (t *Time) UnmarshalJSON(b []byte) error { return t.Unmarshal(b) }
|
||||
func (t *Time) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
return t.Unmarshal([]byte(s))
|
||||
}
|
||||
func (t *Time) UnmarshalXML(e *xml.Decoder, ee xml.StartElement) error {
|
||||
b, err := e.Token()
|
||||
if err != nil {
|
||||
@@ -72,10 +81,19 @@ func (t *Time) UnmarshalXML(e *xml.Decoder, ee xml.StartElement) error {
|
||||
}
|
||||
func (t *Time) Unmarshal(b []byte) error {
|
||||
bs := strings.Trim(string(b), "\"")
|
||||
// 189 时间串里 AM/PM 前可能使用 U+202F 窄不换行空格或 U+00A0 不换行空格,统一替换为普通空格
|
||||
bs = strings.ReplaceAll(bs, "\u202f", " ")
|
||||
bs = strings.ReplaceAll(bs, "\u00a0", " ")
|
||||
var v time.Time
|
||||
var err error
|
||||
for _, f := range []string{"2006-01-02 15:04:05 -07", "Jan 2, 2006 15:04:05 PM -07"} {
|
||||
v, err = time.ParseInLocation(f, bs+" +08", time.Local)
|
||||
// 189 返回的时间可能自带时区(如 "Aug 11, 2026, 10:37:18 PM +08"),也可能不带,分别尝试
|
||||
for _, s := range []string{bs, bs + " +08"} {
|
||||
for _, f := range []string{"2006-01-02 15:04:05 -07", "Jan 2, 2006 3:04:05 PM -07", "Jan 2, 2006, 3:04:05 PM -07"} {
|
||||
v, err = time.ParseInLocation(f, s, utils.CNLoc)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package _189_tv
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTimeUnmarshal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want time.Time
|
||||
}{
|
||||
{"numeric date", `"2026-08-11 10:37:18"`, time.Date(2026, 8, 11, 10, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"legacy month date", `"Aug 11, 2026 10:37:18 PM"`, time.Date(2026, 8, 11, 22, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"new format with tz", `"Aug 11, 2026, 10:37:18 PM +08"`, time.Date(2026, 8, 11, 22, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"new format no tz", `"Aug 11, 2026, 10:37:18 PM"`, time.Date(2026, 8, 11, 22, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"narrow no-break space (U+202F)", "\"Aug 12, 2026, 12:35:41\u202fAM +08\"", time.Date(2026, 8, 12, 0, 35, 41, 0, time.FixedZone("", 8*3600))},
|
||||
{"no-break space (U+00A0)", "\"Aug 12, 2026, 12:35:41\u00a0AM +08\"", time.Date(2026, 8, 12, 0, 35, 41, 0, time.FixedZone("", 8*3600))},
|
||||
{"JSON escaped narrow space", `"Sep 4, 2026, 10:59:33\u202fPM +08"`, time.Date(2026, 9, 4, 22, 59, 33, 0, time.FixedZone("", 8*3600))},
|
||||
{"JSON escaped space without timezone", `"Sep 4, 2026, 12:59:33\u00a0AM"`, time.Date(2026, 9, 4, 0, 59, 33, 0, time.FixedZone("", 8*3600))},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var tm Time
|
||||
if err := json.Unmarshal([]byte(tt.input), &tm); err != nil {
|
||||
t.Fatalf("Unmarshal(%s) error: %v", tt.input, err)
|
||||
}
|
||||
if !tt.want.Equal(time.Time(tm)) {
|
||||
t.Fatalf("Unmarshal(%s) = %v, want %v", tt.input, time.Time(tm), tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalRejectsInvalid(t *testing.T) {
|
||||
var tm Time
|
||||
if err := tm.Unmarshal([]byte("Aug 12, 2026, 25:32:44 AM")); err == nil {
|
||||
t.Fatal("Unmarshal accepted an invalid time")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalJSONRejectsInvalid(t *testing.T) {
|
||||
for _, input := range []string{`"invalid"`, `123`, `null`, `"Sep 4, 2026, 10:59:33\uZZZZPM +08"`} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
var tm Time
|
||||
if err := tm.UnmarshalJSON([]byte(input)); err == nil {
|
||||
t.Fatalf("UnmarshalJSON(%s) accepted invalid input", input)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalXML(t *testing.T) {
|
||||
var tm Time
|
||||
if err := xml.Unmarshal([]byte(`<time>Sep 4, 2026, 10:59:33 PM +08</time>`), &tm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := time.Date(2026, 9, 4, 22, 59, 33, 0, time.FixedZone("", 8*3600))
|
||||
if !want.Equal(time.Time(tm)) {
|
||||
t.Fatalf("UnmarshalXML = %v, want %v", time.Time(tm), want)
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -184,6 +184,7 @@ func (y *Cloud189TV) getFiles(ctx context.Context, fileId string, isFamily bool)
|
||||
}
|
||||
fullUrl += "/listFiles.action"
|
||||
|
||||
pageSize := 130 // 每一页返回的文件数量
|
||||
res := make([]model.Obj, 0, 130)
|
||||
for pageNum := 1; ; pageNum++ {
|
||||
var resp Cloud189FilesResp
|
||||
@@ -195,7 +196,7 @@ func (y *Cloud189TV) getFiles(ctx context.Context, fileId string, isFamily bool)
|
||||
"mediaAttr": "0",
|
||||
"iconOption": "5",
|
||||
"pageNum": fmt.Sprint(pageNum),
|
||||
"pageSize": "130",
|
||||
"pageSize": fmt.Sprint(pageSize),
|
||||
})
|
||||
if isFamily {
|
||||
r.SetQueryParams(map[string]string{
|
||||
@@ -218,13 +219,22 @@ func (y *Cloud189TV) getFiles(ctx context.Context, fileId string, isFamily bool)
|
||||
if resp.FileListAO.Count == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
FolderCount := len(resp.FileListAO.FolderList) // 当前文件夹总数
|
||||
FileCount := len(resp.FileListAO.FileList) // 当前文件总数
|
||||
PageCount := FolderCount + FileCount // 当前页数总数
|
||||
|
||||
for i := 0; i < len(resp.FileListAO.FolderList); i++ {
|
||||
for i := 0; i < FolderCount; i++ {
|
||||
res = append(res, &resp.FileListAO.FolderList[i])
|
||||
}
|
||||
for i := 0; i < len(resp.FileListAO.FileList); i++ {
|
||||
for i := 0; i < FileCount; i++ {
|
||||
res = append(res, &resp.FileListAO.FileList[i])
|
||||
}
|
||||
|
||||
// 文件数量小于设定数量时跳出
|
||||
if PageCount < pageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
+55
-13
@@ -87,7 +87,12 @@ func (y *Cloud189PC) Init(ctx context.Context) (err error) {
|
||||
}
|
||||
|
||||
// 先尝试用Token刷新,之后尝试登陆
|
||||
if y.Addition.RefreshToken != "" {
|
||||
if y.Addition.AccessToken != "" {
|
||||
y.tokenInfo = &AppSessionResp{AccessToken: y.Addition.AccessToken, RefreshToken: y.Addition.RefreshToken}
|
||||
if err = y.refreshSession(); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if y.Addition.RefreshToken != "" {
|
||||
y.tokenInfo = &AppSessionResp{RefreshToken: y.Addition.RefreshToken}
|
||||
if err = y.refreshToken(); err != nil {
|
||||
return err
|
||||
@@ -257,6 +262,16 @@ func (y *Cloud189PC) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.
|
||||
if err = y.WaitBatchTask("MOVE", resp.TaskID, time.Millisecond*400); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 跟随移动 torrent 文件
|
||||
if !srcObj.IsDir() {
|
||||
var srcFolderId string
|
||||
if f, ok := srcObj.(*Cloud189File); ok {
|
||||
srcFolderId = f.ParentID
|
||||
}
|
||||
y.torrentFollowMove(srcFolderId, srcObj.GetName(), dstDir)
|
||||
}
|
||||
|
||||
return srcObj, nil
|
||||
}
|
||||
|
||||
@@ -271,29 +286,41 @@ func (y *Cloud189PC) Rename(ctx context.Context, srcObj model.Obj, newName strin
|
||||
queryParam["familyId"] = y.FamilyID
|
||||
}
|
||||
|
||||
var newObj model.Obj
|
||||
switch f := srcObj.(type) {
|
||||
switch srcObj.(type) {
|
||||
case *Cloud189File:
|
||||
fullUrl += "/renameFile.action"
|
||||
queryParam["fileId"] = srcObj.GetID()
|
||||
queryParam["destFileName"] = newName
|
||||
newObj = &Cloud189File{Icon: f.Icon} // 复用预览
|
||||
case *Cloud189Folder:
|
||||
fullUrl += "/renameFolder.action"
|
||||
queryParam["folderId"] = srcObj.GetID()
|
||||
queryParam["destFolderName"] = newName
|
||||
newObj = &Cloud189Folder{}
|
||||
default:
|
||||
return nil, errs.NotSupport
|
||||
}
|
||||
|
||||
var resp RenameResp
|
||||
_, err := y.request(fullUrl, method, func(req *resty.Request) {
|
||||
req.SetContext(ctx).SetQueryParams(queryParam)
|
||||
}, nil, newObj, isFamily)
|
||||
}, nil, &resp, isFamily)
|
||||
if err != nil {
|
||||
if code, ok := resp.ResCode.(string); ok && code == "FileAlreadyExists" {
|
||||
return nil, errs.ObjectAlreadyExists
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return newObj, nil
|
||||
|
||||
// 跟随重命名 torrent 文件
|
||||
if f, ok := srcObj.(*Cloud189File); ok {
|
||||
y.torrentFollowRename(f.ParentID, srcObj.GetName(), newName)
|
||||
}
|
||||
|
||||
switch f := srcObj.(type) {
|
||||
case *Cloud189File:
|
||||
return resp.toFile(f), nil
|
||||
case *Cloud189Folder:
|
||||
return resp.toFolder(), nil
|
||||
}
|
||||
return nil, errs.NotSupport
|
||||
}
|
||||
|
||||
func (y *Cloud189PC) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
@@ -308,7 +335,20 @@ func (y *Cloud189PC) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return y.WaitBatchTask("COPY", resp.TaskID, time.Second)
|
||||
if err = y.WaitBatchTask("COPY", resp.TaskID, time.Second); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 跟随复制 torrent 文件
|
||||
if !srcObj.IsDir() {
|
||||
var srcFolderId string
|
||||
if f, ok := srcObj.(*Cloud189File); ok {
|
||||
srcFolderId = f.ParentID
|
||||
}
|
||||
y.torrentFollowCopy(srcFolderId, srcObj.GetName(), dstDir)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (y *Cloud189PC) Remove(ctx context.Context, obj model.Obj) error {
|
||||
@@ -332,6 +372,7 @@ func (y *Cloud189PC) Put(ctx context.Context, dstDir model.Obj, stream model.Fil
|
||||
|
||||
// 响应时间长,按需启用
|
||||
if y.Addition.RapidUpload && !stream.IsForceStreamUpload() {
|
||||
// 尝试妙传
|
||||
if newObj, err := y.RapidUpload(ctx, dstDir, stream, isFamily, overwrite); err == nil {
|
||||
return newObj, nil
|
||||
}
|
||||
@@ -340,10 +381,11 @@ func (y *Cloud189PC) Put(ctx context.Context, dstDir model.Obj, stream model.Fil
|
||||
uploadMethod := y.UploadMethod
|
||||
if stream.IsForceStreamUpload() {
|
||||
uploadMethod = "stream"
|
||||
}
|
||||
|
||||
// 旧版上传家庭云也有限制
|
||||
if uploadMethod == "old" {
|
||||
} else if y.Addition.RapidUpload && stream.GetFile() != nil {
|
||||
// 文件流支持随机读取,走FastUpload计算MD5并尝试秒传
|
||||
uploadMethod = "rapid"
|
||||
} else if uploadMethod == "old" {
|
||||
// 旧版上传家庭云也有限制
|
||||
return y.OldUpload(ctx, dstDir, stream, up, isFamily, overwrite)
|
||||
}
|
||||
|
||||
|
||||
+20
-3
@@ -9,6 +9,7 @@ import (
|
||||
"crypto/sha1"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils/random"
|
||||
)
|
||||
|
||||
@@ -101,7 +103,13 @@ func MustParseTime(str string) *time.Time {
|
||||
|
||||
type Time time.Time
|
||||
|
||||
func (t *Time) UnmarshalJSON(b []byte) error { return t.Unmarshal(b) }
|
||||
func (t *Time) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
return t.Unmarshal([]byte(s))
|
||||
}
|
||||
func (t *Time) UnmarshalXML(e *xml.Decoder, ee xml.StartElement) error {
|
||||
b, err := e.Token()
|
||||
if err != nil {
|
||||
@@ -116,10 +124,19 @@ func (t *Time) UnmarshalXML(e *xml.Decoder, ee xml.StartElement) error {
|
||||
}
|
||||
func (t *Time) Unmarshal(b []byte) error {
|
||||
bs := strings.Trim(string(b), "\"")
|
||||
// 189 时间串里 AM/PM 前可能使用 U+202F 窄不换行空格或 U+00A0 不换行空格,统一替换为普通空格
|
||||
bs = strings.ReplaceAll(bs, "\u202f", " ")
|
||||
bs = strings.ReplaceAll(bs, "\u00a0", " ")
|
||||
var v time.Time
|
||||
var err error
|
||||
for _, f := range []string{"2006-01-02 15:04:05 -07", "Jan 2, 2006 15:04:05 PM -07"} {
|
||||
v, err = time.ParseInLocation(f, bs+" +08", time.Local)
|
||||
// 189 返回的时间可能自带时区(如 "Aug 11, 2026, 10:37:18 PM +08"),也可能不带,分别尝试
|
||||
for _, s := range []string{bs, bs + " +08"} {
|
||||
for _, f := range []string{"2006-01-02 15:04:05 -07", "Jan 2, 2006 3:04:05 PM -07", "Jan 2, 2006, 3:04:05 PM -07"} {
|
||||
v, err = time.ParseInLocation(f, s, utils.CNLoc)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package _189pc
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTimeUnmarshal(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want time.Time
|
||||
}{
|
||||
{"numeric date", `"2026-08-11 10:37:18"`, time.Date(2026, 8, 11, 10, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"legacy month date", `"Aug 11, 2026 10:37:18 PM"`, time.Date(2026, 8, 11, 22, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"new format with tz", `"Aug 11, 2026, 10:37:18 PM +08"`, time.Date(2026, 8, 11, 22, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"new format no tz", `"Aug 11, 2026, 10:37:18 PM"`, time.Date(2026, 8, 11, 22, 37, 18, 0, time.FixedZone("", 8*3600))},
|
||||
{"narrow no-break space (U+202F)", "\"Aug 12, 2026, 12:35:41\u202fAM +08\"", time.Date(2026, 8, 12, 0, 35, 41, 0, time.FixedZone("", 8*3600))},
|
||||
{"no-break space (U+00A0)", "\"Aug 12, 2026, 12:35:41\u00a0AM +08\"", time.Date(2026, 8, 12, 0, 35, 41, 0, time.FixedZone("", 8*3600))},
|
||||
{"JSON escaped narrow space", `"Sep 4, 2026, 10:59:33\u202fPM +08"`, time.Date(2026, 9, 4, 22, 59, 33, 0, time.FixedZone("", 8*3600))},
|
||||
{"JSON escaped space without timezone", `"Sep 4, 2026, 12:59:33\u00a0AM"`, time.Date(2026, 9, 4, 0, 59, 33, 0, time.FixedZone("", 8*3600))},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var tm Time
|
||||
if err := json.Unmarshal([]byte(tt.input), &tm); err != nil {
|
||||
t.Fatalf("Unmarshal(%s) error: %v", tt.input, err)
|
||||
}
|
||||
if !tt.want.Equal(time.Time(tm)) {
|
||||
t.Fatalf("Unmarshal(%s) = %v, want %v", tt.input, time.Time(tm), tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalRejectsInvalid(t *testing.T) {
|
||||
var tm Time
|
||||
if err := tm.Unmarshal([]byte("Aug 12, 2026, 25:32:44 AM")); err == nil {
|
||||
t.Fatal("Unmarshal accepted an invalid time")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalJSONRejectsInvalid(t *testing.T) {
|
||||
for _, input := range []string{`"invalid"`, `123`, `null`, `"Sep 4, 2026, 10:59:33\uZZZZPM +08"`} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
var tm Time
|
||||
if err := tm.UnmarshalJSON([]byte(input)); err == nil {
|
||||
t.Fatalf("UnmarshalJSON(%s) accepted invalid input", input)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeUnmarshalXML(t *testing.T) {
|
||||
var tm Time
|
||||
if err := xml.Unmarshal([]byte(`<time>Sep 4, 2026, 10:59:33 PM +08</time>`), &tm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := time.Date(2026, 9, 4, 22, 59, 33, 0, time.FixedZone("", 8*3600))
|
||||
if !want.Equal(time.Time(tm)) {
|
||||
t.Fatalf("UnmarshalXML = %v, want %v", time.Time(tm), want)
|
||||
}
|
||||
}
|
||||
+11
-9
@@ -10,17 +10,19 @@ type Addition struct {
|
||||
Username string `json:"username" required:"true"`
|
||||
Password string `json:"password" required:"true"`
|
||||
VCode string `json:"validate_code"`
|
||||
AccessToken string `json:"access_token" required:"false"`
|
||||
RefreshToken string `json:"refresh_token" help:"To switch accounts, please clear this field"`
|
||||
driver.RootID
|
||||
OrderBy string `json:"order_by" type:"select" options:"filename,filesize,lastOpTime" default:"filename"`
|
||||
OrderDirection string `json:"order_direction" type:"select" options:"asc,desc" default:"asc"`
|
||||
Type string `json:"type" type:"select" options:"personal,family" default:"personal"`
|
||||
FamilyID string `json:"family_id"`
|
||||
UploadMethod string `json:"upload_method" type:"select" options:"stream,rapid,old" default:"stream"`
|
||||
UploadThread string `json:"upload_thread" default:"3" help:"1<=thread<=32"`
|
||||
FamilyTransfer bool `json:"family_transfer"`
|
||||
RapidUpload bool `json:"rapid_upload"`
|
||||
NoUseOcr bool `json:"no_use_ocr"`
|
||||
OrderBy string `json:"order_by" type:"select" options:"filename,filesize,lastOpTime" default:"filename"`
|
||||
OrderDirection string `json:"order_direction" type:"select" options:"asc,desc" default:"asc"`
|
||||
Type string `json:"type" type:"select" options:"personal,family" default:"personal"`
|
||||
FamilyID string `json:"family_id"`
|
||||
UploadMethod string `json:"upload_method" type:"select" options:"stream,rapid,old" default:"stream"`
|
||||
UploadThread string `json:"upload_thread" default:"3" help:"1<=thread<=32"`
|
||||
FamilyTransfer bool `json:"family_transfer"`
|
||||
RapidUpload bool `json:"rapid_upload"`
|
||||
NoUseOcr bool `json:"no_use_ocr"`
|
||||
GenerateTorrent bool `json:"generate_torrent" help:"Generate torrent file with CAS extension after upload"`
|
||||
}
|
||||
|
||||
var config = driver.Config{
|
||||
|
||||
@@ -0,0 +1,449 @@
|
||||
package _189pc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/op"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/stream"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/torrent"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
)
|
||||
|
||||
// GenerateTorrent 根据上传过程中收集的哈希信息生成包含 CAS 扩展的 torrent 文件
|
||||
// fileMD5: 整文件 MD5(大写十六进制)
|
||||
// sliceMD5s: 每个分片的 MD5 列表(大写十六进制)
|
||||
// sliceSize: 分片大小
|
||||
// pieceHashes: SHA-1 piece hashes 拼接(每 20 字节一个)
|
||||
// fileName: 文件名
|
||||
// fileSize: 文件大小
|
||||
func GenerateTorrent(fileName string, fileSize int64, fileMD5 string, sliceMD5s []string, sliceSize int64, pieceHashes []byte) ([]byte, error) {
|
||||
// 计算 sliceMD5
|
||||
sliceMD5 := fileMD5
|
||||
if len(sliceMD5s) > 1 {
|
||||
joined := strings.Join(sliceMD5s, "\n")
|
||||
sliceMD5 = strings.ToUpper(torrent.GetMD5Str(joined))
|
||||
}
|
||||
|
||||
t := torrent.NewTorrent(fileName, fileSize, fileMD5)
|
||||
t.Info.PieceLength = sliceSize
|
||||
t.SetPieces(pieceHashes)
|
||||
t.SetCASInfo(&torrent.CASInfo{
|
||||
FileMD5: fileMD5,
|
||||
SliceMD5: sliceMD5,
|
||||
SliceMD5s: sliceMD5s,
|
||||
SliceSize: sliceSize,
|
||||
Cloud: "189",
|
||||
})
|
||||
|
||||
return t.Encode()
|
||||
}
|
||||
|
||||
// RapidUploadFromTorrent 从 torrent 文件中提取 CAS 信息进行秒传
|
||||
// 返回值:上传成功的文件对象、错误
|
||||
func (y *Cloud189PC) RapidUploadFromTorrent(ctx context.Context, dstDir model.Obj, torrentData []byte, overwrite bool) (model.Obj, error) {
|
||||
isFamily := y.isFamily()
|
||||
|
||||
// 解析 torrent
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 torrent 失败: %w", err)
|
||||
}
|
||||
|
||||
// 检查是否包含 CAS 扩展信息
|
||||
if !t.HasCASInfo() {
|
||||
return nil, fmt.Errorf("torrent 不包含 CAS 扩展信息,无法秒传")
|
||||
}
|
||||
|
||||
cas := t.CAS
|
||||
fileName := t.Info.Name
|
||||
fileSize := t.GetTotalSize()
|
||||
|
||||
// 统一 MD5 为大写(与正常上传保持一致,天翼云盘要求大写)
|
||||
fileMD5Upper := strings.ToUpper(cas.FileMD5)
|
||||
|
||||
// 优先使用 torrent 中嵌入的分片大小,与生成时保持一致
|
||||
sliceSize := cas.SliceSize
|
||||
if sliceSize <= 0 {
|
||||
sliceSize = partSize(fileSize)
|
||||
}
|
||||
|
||||
// 计算 sliceMd5(与上传时一致的算法)
|
||||
// 优先使用 torrent 中已有的 SliceMD5;仅当有多分片列表时才重新计算
|
||||
sliceMd5Hex := strings.ToUpper(cas.SliceMD5)
|
||||
if sliceMd5Hex == "" {
|
||||
sliceMd5Hex = fileMD5Upper
|
||||
}
|
||||
if len(cas.SliceMD5s) > 1 {
|
||||
// 分片 MD5 也需要统一大写后再拼接计算
|
||||
upperSliceMD5s := make([]string, len(cas.SliceMD5s))
|
||||
for i, s := range cas.SliceMD5s {
|
||||
upperSliceMD5s[i] = strings.ToUpper(s)
|
||||
}
|
||||
sliceMd5Hex = strings.ToUpper(utils.GetMD5EncodeStr(strings.Join(upperSliceMD5s, "\n")))
|
||||
}
|
||||
|
||||
// 使用与 Web 端一致的三步秒传流程
|
||||
fullUrl := "https://upload.cloud.189.cn"
|
||||
if isFamily {
|
||||
fullUrl += "/family"
|
||||
} else {
|
||||
fullUrl += "/person"
|
||||
}
|
||||
|
||||
// Step 1: initMultiUpload(不传 fileMd5/sliceMd5,只传 lazyCheck)
|
||||
initParams := Params{
|
||||
"parentFolderId": dstDir.GetID(),
|
||||
"fileName": url.QueryEscape(fileName),
|
||||
"fileSize": fmt.Sprint(fileSize),
|
||||
"sliceSize": fmt.Sprint(sliceSize),
|
||||
"lazyCheck": "1",
|
||||
}
|
||||
if isFamily {
|
||||
initParams.Set("familyId", y.FamilyID)
|
||||
}
|
||||
|
||||
var uploadInfo InitMultiUploadResp
|
||||
_, err = y.request(fullUrl+"/initMultiUpload", "GET", func(req *resty.Request) {
|
||||
req.SetContext(ctx)
|
||||
}, initParams, &uploadInfo, isFamily)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initMultiUpload 失败: %w", err)
|
||||
}
|
||||
|
||||
uploadFileId := uploadInfo.Data.UploadFileID
|
||||
|
||||
// Step 2: checkTransSecond(用 fileMd5 + sliceMd5 + uploadFileId 检查秒传)
|
||||
checkParams := Params{
|
||||
"fileMd5": fileMD5Upper,
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
"uploadFileId": uploadFileId,
|
||||
}
|
||||
|
||||
var checkResp struct {
|
||||
Data struct {
|
||||
FileDataExists int `json:"fileDataExists"`
|
||||
} `json:"data"`
|
||||
}
|
||||
_, err = y.request(fullUrl+"/checkTransSecond", "GET", func(req *resty.Request) {
|
||||
req.SetContext(ctx)
|
||||
}, checkParams, &checkResp, isFamily)
|
||||
if err != nil {
|
||||
utils.Log.Errorf("[RapidUpload] checkTransSecond 失败: uploadFileId=%s, err=%v", uploadFileId, err)
|
||||
return nil, fmt.Errorf("秒传检查失败: %w", err)
|
||||
}
|
||||
|
||||
if checkResp.Data.FileDataExists != 1 {
|
||||
return nil, fmt.Errorf("秒传失败:云端不存在该文件(fileMD5=%s, sliceMD5=%s, size=%d)", fileMD5Upper, sliceMd5Hex, fileSize)
|
||||
}
|
||||
|
||||
// Step 3: commitMultiUploadFile(传 fileMd5 + sliceMd5)
|
||||
|
||||
var resp CommitMultiUploadFileResp
|
||||
commitParams := Params{
|
||||
"uploadFileId": uploadFileId,
|
||||
"fileMd5": fileMD5Upper,
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
"lazyCheck": "1",
|
||||
"opertype": IF(overwrite, "3", "1"),
|
||||
}
|
||||
|
||||
_, err = y.request(fullUrl+"/commitMultiUploadFile", "GET", func(req *resty.Request) {
|
||||
req.SetContext(ctx)
|
||||
}, commitParams, &resp, isFamily)
|
||||
if err != nil {
|
||||
utils.Log.Errorf("[RapidUpload] commitMultiUploadFile 失败: uploadFileId=%s, err=%v", uploadFileId, err)
|
||||
return nil, fmt.Errorf("提交上传失败: %w", err)
|
||||
}
|
||||
|
||||
// 秒传成功后,将 torrent 文件上传到目标目录(异步,不影响秒传结果)
|
||||
if y.Addition.GenerateTorrent {
|
||||
capturedDstDir := dstDir
|
||||
capturedIsFamily := isFamily
|
||||
go func() {
|
||||
torrentName := fileName + ".cas.torrent"
|
||||
infoHash, _ := GetInfoHashHex(torrentData)
|
||||
utils.Log.Infof("秒传成功,上传 torrent: %s (info_hash: %s, size: %d bytes)",
|
||||
torrentName, infoHash, len(torrentData))
|
||||
|
||||
torrentFileStream := &stream.FileStream{
|
||||
Ctx: context.Background(),
|
||||
Obj: &model.Object{
|
||||
Name: torrentName,
|
||||
Size: int64(len(torrentData)),
|
||||
IsFolder: false,
|
||||
},
|
||||
Reader: bytes.NewReader(torrentData),
|
||||
Mimetype: "application/x-bittorrent",
|
||||
}
|
||||
_, uploadErr := y.fastUpload(context.Background(), capturedDstDir, torrentFileStream, func(p float64) {}, capturedIsFamily, false, false)
|
||||
if uploadErr != nil {
|
||||
utils.Log.Warnf("上传 torrent 文件失败: %v", uploadErr)
|
||||
} else {
|
||||
utils.Log.Infof("torrent 文件已上传: %s", torrentName)
|
||||
op.Cache.DeleteDirectory(y, capturedDstDir.GetPath())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return resp.toFile(), nil
|
||||
}
|
||||
|
||||
// ComputeTorrentFromReader 从 io.Reader 计算并生成 torrent 文件
|
||||
// 适用于:已有文件需要生成 torrent 的场景(如下载完成后生成)
|
||||
func ComputeTorrentFromReader(reader io.Reader, fileName string, fileSize int64, sliceSize int64) ([]byte, error) {
|
||||
if sliceSize <= 0 {
|
||||
sliceSize = torrent.DefaultPieceSize
|
||||
}
|
||||
|
||||
hw := torrent.NewHashWriter(sliceSize, sliceSize)
|
||||
|
||||
buf := make([]byte, 32*1024)
|
||||
for {
|
||||
n, err := reader.Read(buf)
|
||||
if n > 0 {
|
||||
hw.Write(buf[:n])
|
||||
}
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
hw.Finish()
|
||||
|
||||
fileMD5 := hw.GetFileMD5()
|
||||
sliceMD5s := hw.GetSliceMD5s()
|
||||
pieceHashes := hw.GetPieceHashes()
|
||||
|
||||
return GenerateTorrent(fileName, fileSize, fileMD5, sliceMD5s, sliceSize, pieceHashes)
|
||||
}
|
||||
|
||||
// ComputePieceSHA1 计算单个分片的 SHA-1 哈希
|
||||
func ComputePieceSHA1(data []byte) []byte {
|
||||
h := sha1.Sum(data)
|
||||
return h[:]
|
||||
}
|
||||
|
||||
// ExtractCASFromTorrent 从 torrent 数据中提取 CAS 信息
|
||||
// 返回:CAS 信息、文件名、文件大小、错误
|
||||
func ExtractCASFromTorrent(torrentData []byte) (*torrent.CASInfo, string, int64, error) {
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return nil, "", 0, fmt.Errorf("解析 torrent 失败: %w", err)
|
||||
}
|
||||
|
||||
if !t.HasCASInfo() {
|
||||
return nil, "", 0, fmt.Errorf("torrent 不包含 CAS 扩展信息")
|
||||
}
|
||||
|
||||
return t.CAS, t.Info.Name, t.GetTotalSize(), nil
|
||||
}
|
||||
|
||||
// InjectCASIntoTorrent 向已有的 torrent 文件注入 CAS 扩展信息
|
||||
// 用于:下载完成后,计算了 MD5 信息,写回到 torrent 中
|
||||
func InjectCASIntoTorrent(torrentData []byte, fileMD5 string, sliceMD5s []string, sliceSize int64) ([]byte, error) {
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 torrent 失败: %w", err)
|
||||
}
|
||||
|
||||
// 计算 sliceMD5
|
||||
sliceMD5 := fileMD5
|
||||
if len(sliceMD5s) > 1 {
|
||||
joined := strings.Join(sliceMD5s, "\n")
|
||||
sliceMD5 = strings.ToUpper(torrent.GetMD5Str(joined))
|
||||
}
|
||||
|
||||
// 注入 CAS 信息
|
||||
t.SetCASInfo(&torrent.CASInfo{
|
||||
FileMD5: fileMD5,
|
||||
SliceMD5: sliceMD5,
|
||||
SliceMD5s: sliceMD5s,
|
||||
SliceSize: sliceSize,
|
||||
Cloud: "189",
|
||||
})
|
||||
|
||||
// 同时更新 info 中的 md5sum 字段
|
||||
if t.Info.MD5Sum == "" {
|
||||
t.Info.MD5Sum = fileMD5
|
||||
}
|
||||
|
||||
return t.Encode()
|
||||
}
|
||||
|
||||
// GetInfoHashHex 获取 torrent 的 info_hash(十六进制字符串)
|
||||
func GetInfoHashHex(torrentData []byte) (string, error) {
|
||||
t, err := torrent.Decode(torrentData)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(t.InfoHash), nil
|
||||
}
|
||||
|
||||
func isCASTorrentFile(fileName string) bool {
|
||||
return strings.HasSuffix(fileName, ".cas.torrent")
|
||||
}
|
||||
|
||||
// ComputeSliceMD5sFromReader 从 reader 中计算每个 10MB 分片的 MD5
|
||||
// 返回:整文件 MD5、分片 MD5 列表
|
||||
func ComputeSliceMD5sFromReader(reader io.Reader, sliceSize int64) (string, []string, error) {
|
||||
if sliceSize <= 0 {
|
||||
sliceSize = torrent.DefaultPieceSize
|
||||
}
|
||||
|
||||
fileMD5Hash := utils.MD5.NewFunc()
|
||||
sliceMD5s := make([]string, 0)
|
||||
|
||||
buf := make([]byte, sliceSize)
|
||||
for {
|
||||
n, err := io.ReadFull(reader, buf)
|
||||
if n > 0 {
|
||||
chunk := buf[:n]
|
||||
fileMD5Hash.Write(chunk)
|
||||
// 计算该分片的 MD5
|
||||
sliceMD5 := strings.ToUpper(utils.HashData(utils.MD5, chunk))
|
||||
sliceMD5s = append(sliceMD5s, sliceMD5)
|
||||
}
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
}
|
||||
|
||||
fileMD5Hex := strings.ToUpper(hex.EncodeToString(fileMD5Hash.Sum(nil)))
|
||||
return fileMD5Hex, sliceMD5s, nil
|
||||
}
|
||||
|
||||
// torrentFollowCopy 跟随复制 torrent 文件(异步,不影响主操作)
|
||||
// srcFolderId: 源文件所在目录 ID
|
||||
// srcFileName: 源文件名
|
||||
// dstDir: 目标目录
|
||||
func (y *Cloud189PC) torrentFollowCopy(srcFolderId string, srcFileName string, dstDir model.Obj) {
|
||||
if !y.Addition.GenerateTorrent {
|
||||
return
|
||||
}
|
||||
if srcFolderId == "" {
|
||||
return
|
||||
}
|
||||
torrentName := srcFileName + ".cas.torrent"
|
||||
isFamily := y.isFamily()
|
||||
|
||||
go func() {
|
||||
torrentFile, err := y.findFileByName(context.Background(), torrentName, srcFolderId, isFamily)
|
||||
if err != nil {
|
||||
utils.Log.Debugf("查找 torrent 文件失败(跟随复制): %v", err)
|
||||
return
|
||||
}
|
||||
// 复制 torrent 文件到目标目录
|
||||
resp, copyErr := y.CreateBatchTask("COPY", IF(isFamily, y.FamilyID, ""), dstDir.GetID(),
|
||||
map[string]string{"targetFileName": dstDir.GetName()},
|
||||
BatchTaskInfo{
|
||||
FileId: torrentFile.GetID(),
|
||||
FileName: torrentFile.GetName(),
|
||||
IsFolder: 0,
|
||||
})
|
||||
if copyErr != nil {
|
||||
utils.Log.Warnf("跟随复制 torrent 文件失败: %v", copyErr)
|
||||
return
|
||||
}
|
||||
if err = y.WaitBatchTask("COPY", resp.TaskID, time.Second); err != nil {
|
||||
utils.Log.Warnf("等待跟随复制 torrent 文件失败: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// torrentFollowMove 跟随移动 torrent 文件(异步,不影响主操作)
|
||||
// srcFolderId: 源文件所在目录 ID
|
||||
// srcFileName: 源文件名
|
||||
// dstDir: 目标目录
|
||||
func (y *Cloud189PC) torrentFollowMove(srcFolderId string, srcFileName string, dstDir model.Obj) {
|
||||
if !y.Addition.GenerateTorrent {
|
||||
return
|
||||
}
|
||||
if srcFolderId == "" {
|
||||
return
|
||||
}
|
||||
torrentName := srcFileName + ".cas.torrent"
|
||||
isFamily := y.isFamily()
|
||||
|
||||
go func() {
|
||||
torrentFile, err := y.findFileByName(context.Background(), torrentName, srcFolderId, isFamily)
|
||||
if err != nil {
|
||||
utils.Log.Debugf("查找 torrent 文件失败(跟随移动): %v", err)
|
||||
return
|
||||
}
|
||||
// 移动 torrent 文件到目标目录
|
||||
resp, moveErr := y.CreateBatchTask("MOVE", IF(isFamily, y.FamilyID, ""), dstDir.GetID(),
|
||||
map[string]string{"targetFileName": dstDir.GetName()},
|
||||
BatchTaskInfo{
|
||||
FileId: torrentFile.GetID(),
|
||||
FileName: torrentFile.GetName(),
|
||||
IsFolder: 0,
|
||||
})
|
||||
if moveErr != nil {
|
||||
utils.Log.Warnf("跟随移动 torrent 文件失败: %v", moveErr)
|
||||
return
|
||||
}
|
||||
if err = y.WaitBatchTask("MOVE", resp.TaskID, time.Millisecond*400); err != nil {
|
||||
utils.Log.Warnf("等待跟随移动 torrent 文件失败: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// torrentFollowRename 跟随重命名 torrent 文件(异步,不影响主操作)
|
||||
// folderId: 文件所在目录 ID
|
||||
// oldFileName: 原文件名
|
||||
// newFileName: 新文件名
|
||||
func (y *Cloud189PC) torrentFollowRename(folderId string, oldFileName string, newFileName string) {
|
||||
if !y.Addition.GenerateTorrent {
|
||||
return
|
||||
}
|
||||
if folderId == "" {
|
||||
return
|
||||
}
|
||||
oldTorrentName := oldFileName + ".cas.torrent"
|
||||
newTorrentName := newFileName + ".cas.torrent"
|
||||
isFamily := y.isFamily()
|
||||
|
||||
go func() {
|
||||
torrentFile, err := y.findFileByName(context.Background(), oldTorrentName, folderId, isFamily)
|
||||
if err != nil {
|
||||
utils.Log.Debugf("查找 torrent 文件失败(跟随重命名): %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 重命名 torrent 文件
|
||||
queryParam := make(map[string]string)
|
||||
fullUrl := API_URL
|
||||
method := "POST"
|
||||
if isFamily {
|
||||
fullUrl += "/family/file"
|
||||
method = "GET"
|
||||
queryParam["familyId"] = y.FamilyID
|
||||
}
|
||||
fullUrl += "/renameFile.action"
|
||||
queryParam["fileId"] = torrentFile.GetID()
|
||||
queryParam["destFileName"] = newTorrentName
|
||||
|
||||
_, renameErr := y.request(fullUrl, method, func(req *resty.Request) {
|
||||
req.SetContext(context.Background()).SetQueryParams(queryParam)
|
||||
}, nil, &RenameResp{}, isFamily)
|
||||
if renameErr != nil {
|
||||
utils.Log.Warnf("跟随重命名 torrent 文件失败: %v", renameErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
+51
-4
@@ -166,10 +166,11 @@ type FamilyInfoResp struct {
|
||||
/*文件部分*/
|
||||
// 文件
|
||||
type Cloud189File struct {
|
||||
ID String `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Md5 string `json:"md5"`
|
||||
ID String `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Md5 string `json:"md5"`
|
||||
ParentID string `json:"-"` // 由 getFiles 设置,不从 JSON 解析
|
||||
|
||||
LastOpTime Time `json:"lastOpTime"`
|
||||
CreateDate Time `json:"createDate"`
|
||||
@@ -190,6 +191,10 @@ type Cloud189File struct {
|
||||
// StarLabel int64 `json:"starLabel"`
|
||||
}
|
||||
|
||||
func normalizeCloud189Name(name string) string {
|
||||
return strings.ReplaceAll(name, "\\'", "'")
|
||||
}
|
||||
|
||||
func (c *Cloud189File) CreateTime() time.Time {
|
||||
return time.Time(c.CreateDate)
|
||||
}
|
||||
@@ -206,6 +211,8 @@ func (c *Cloud189File) GetID() string { return string(c.ID) }
|
||||
func (c *Cloud189File) GetPath() string { return "" }
|
||||
func (c *Cloud189File) Thumb() string { return c.Icon.SmallUrl }
|
||||
|
||||
func (c *Cloud189File) GetDisplayName() string { return normalizeCloud189Name(c.Name) }
|
||||
|
||||
// 文件夹
|
||||
type Cloud189Folder struct {
|
||||
ID String `json:"id"`
|
||||
@@ -237,6 +244,8 @@ func (c *Cloud189Folder) IsDir() bool { return true }
|
||||
func (c *Cloud189Folder) GetID() string { return string(c.ID) }
|
||||
func (c *Cloud189Folder) GetPath() string { return "" }
|
||||
|
||||
func (c *Cloud189Folder) GetDisplayName() string { return normalizeCloud189Name(c.Name) }
|
||||
|
||||
type Cloud189FilesResp struct {
|
||||
//ResCode int `json:"res_code"`
|
||||
//ResMessage string `json:"res_message"`
|
||||
@@ -427,3 +436,41 @@ type CapacityResp struct {
|
||||
} `json:"familyCapacityInfo"`
|
||||
TotalSize uint64 `json:"totalSize"`
|
||||
}
|
||||
|
||||
type RenameResp struct {
|
||||
ResMsg string `json:"res_message"`
|
||||
CreateDate Time `json:"createDate"`
|
||||
FileCate int `json:"fileCata"`
|
||||
ID String `json:"id"`
|
||||
LastOpTime Time `json:"lastOpTime"`
|
||||
MD5 string `json:"md5"`
|
||||
MediaType int `json:"mediaType"`
|
||||
Name string `json:"name"`
|
||||
Oeientation int `json:"orientation"`
|
||||
ParentID int64 `json:"parentId"`
|
||||
Rev string `json:"rev"`
|
||||
Size int64 `json:"size"`
|
||||
ResCode any `json:"res_code"` // int or string
|
||||
}
|
||||
|
||||
func (r *RenameResp) toFile(f *Cloud189File) *Cloud189File {
|
||||
return &Cloud189File{
|
||||
ID: r.ID,
|
||||
Name: r.Name,
|
||||
Size: r.Size,
|
||||
Md5: r.MD5,
|
||||
LastOpTime: r.LastOpTime,
|
||||
CreateDate: r.CreateDate,
|
||||
Icon: f.Icon,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RenameResp) toFolder() *Cloud189Folder {
|
||||
return &Cloud189Folder{
|
||||
ID: r.ID,
|
||||
Name: r.Name,
|
||||
ParentID: r.ParentID,
|
||||
LastOpTime: r.LastOpTime,
|
||||
CreateDate: r.CreateDate,
|
||||
}
|
||||
}
|
||||
|
||||
+140
-5
@@ -3,6 +3,7 @@ package _189pc
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
sha1Pkg "crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
@@ -194,9 +195,10 @@ func (y *Cloud189PC) put(ctx context.Context, url string, headers map[string]str
|
||||
}
|
||||
|
||||
func (y *Cloud189PC) getFiles(ctx context.Context, fileId string, isFamily bool) ([]model.Obj, error) {
|
||||
pageSize := 1000 // 每一页返回的文件数量
|
||||
res := make([]model.Obj, 0, 100)
|
||||
for pageNum := 1; ; pageNum++ {
|
||||
resp, err := y.getFilesWithPage(ctx, fileId, isFamily, pageNum, 1000, y.OrderBy, y.OrderDirection)
|
||||
resp, err := y.getFilesWithPage(ctx, fileId, isFamily, pageNum, pageSize, y.OrderBy, y.OrderDirection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -204,13 +206,23 @@ func (y *Cloud189PC) getFiles(ctx context.Context, fileId string, isFamily bool)
|
||||
if resp.FileListAO.Count == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
FolderCount := len(resp.FileListAO.FolderList) // 当前文件夹总数
|
||||
FileCount := len(resp.FileListAO.FileList) // 当前文件总数
|
||||
PageCount := FolderCount + FileCount // 当前页数总数
|
||||
|
||||
for i := 0; i < len(resp.FileListAO.FolderList); i++ {
|
||||
for i := 0; i < FolderCount; i++ {
|
||||
res = append(res, &resp.FileListAO.FolderList[i])
|
||||
}
|
||||
for i := 0; i < len(resp.FileListAO.FileList); i++ {
|
||||
for i := 0; i < FileCount; i++ {
|
||||
resp.FileListAO.FileList[i].ParentID = fileId
|
||||
res = append(res, &resp.FileListAO.FileList[i])
|
||||
}
|
||||
|
||||
// 当前文件数量小于设定数量则跳出
|
||||
if PageCount < pageSize {
|
||||
break
|
||||
}
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
@@ -356,6 +368,7 @@ func (y *Cloud189PC) loginByPassword() (err error) {
|
||||
err = fmt.Errorf(tokenInfo.ResMessage)
|
||||
return err
|
||||
}
|
||||
y.Addition.AccessToken = tokenInfo.AccessToken
|
||||
y.Addition.RefreshToken = tokenInfo.RefreshToken
|
||||
y.tokenInfo = &tokenInfo
|
||||
op.MustSaveDriverStorage(y)
|
||||
@@ -414,6 +427,7 @@ func (y *Cloud189PC) loginByQRCode() error {
|
||||
if tokenInfo.ResCode != 0 {
|
||||
return fmt.Errorf(tokenInfo.ResMessage)
|
||||
}
|
||||
y.Addition.AccessToken = tokenInfo.AccessToken
|
||||
y.Addition.RefreshToken = tokenInfo.RefreshToken
|
||||
y.tokenInfo = &tokenInfo
|
||||
op.MustSaveDriverStorage(y)
|
||||
@@ -661,6 +675,7 @@ func (y *Cloud189PC) refreshTokenWithRetry(retryCount int) (err error) {
|
||||
return y.login()
|
||||
}
|
||||
|
||||
y.Addition.AccessToken = tokenInfo.AccessToken
|
||||
y.Addition.RefreshToken = tokenInfo.RefreshToken
|
||||
y.tokenInfo = &tokenInfo
|
||||
op.MustSaveDriverStorage(y)
|
||||
@@ -739,6 +754,10 @@ func (y *Cloud189PC) StreamUpload(ctx context.Context, dstDir model.Obj, file mo
|
||||
silceMd5 := utils.MD5.NewFunc()
|
||||
var writers io.Writer = silceMd5
|
||||
|
||||
// 如果启用了 torrent 生成,额外计算 SHA-1 piece hash
|
||||
generateTorrent := y.Addition.GenerateTorrent
|
||||
pieceSHA1Hashes := make([]byte, 0, count*20)
|
||||
|
||||
fileMd5Hex := file.GetHash().GetHash(utils.MD5)
|
||||
var fileMd5 hash.Hash
|
||||
if len(fileMd5Hex) != utils.MD5.Width {
|
||||
@@ -763,7 +782,18 @@ func (y *Cloud189PC) StreamUpload(ctx context.Context, dstDir model.Obj, file mo
|
||||
return err
|
||||
}
|
||||
silceMd5.Reset()
|
||||
w, err := utils.CopyWithBuffer(writers, reader)
|
||||
|
||||
// 如果需要生成 torrent,同时计算 SHA-1
|
||||
var sha1Writer hash.Hash
|
||||
var multiWriter io.Writer
|
||||
if generateTorrent {
|
||||
sha1Writer = sha1Pkg.New()
|
||||
multiWriter = io.MultiWriter(writers, sha1Writer)
|
||||
} else {
|
||||
multiWriter = writers
|
||||
}
|
||||
|
||||
w, err := utils.CopyWithBuffer(multiWriter, reader)
|
||||
if w != partSize {
|
||||
return fmt.Errorf("failed to read all data: (expect =%d, actual =%d) %w", partSize, w, err)
|
||||
}
|
||||
@@ -771,6 +801,11 @@ func (y *Cloud189PC) StreamUpload(ctx context.Context, dstDir model.Obj, file mo
|
||||
md5Bytes := silceMd5.Sum(nil)
|
||||
silceMd5Hexs = append(silceMd5Hexs, strings.ToUpper(hex.EncodeToString(md5Bytes)))
|
||||
partInfo = fmt.Sprintf("%d-%s", i, base64.StdEncoding.EncodeToString(md5Bytes))
|
||||
|
||||
// 收集 SHA-1 piece hash
|
||||
if generateTorrent && sha1Writer != nil {
|
||||
pieceSHA1Hashes = append(pieceSHA1Hashes, sha1Writer.Sum(nil)...)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Do: func(ctx context.Context) (err error) {
|
||||
@@ -824,6 +859,45 @@ func (y *Cloud189PC) StreamUpload(ctx context.Context, dstDir model.Obj, file mo
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 生成 torrent 文件(异步,不影响上传结果)
|
||||
if generateTorrent && len(pieceSHA1Hashes) > 0 {
|
||||
// 捕获必要的变量
|
||||
capturedDstDir := dstDir
|
||||
capturedIsFamily := isFamily
|
||||
capturedFileName := file.GetName()
|
||||
go func() {
|
||||
torrentData, err := GenerateTorrent(capturedFileName, fileSize, fileMd5Hex, silceMd5Hexs, sliceSize, pieceSHA1Hashes)
|
||||
if err != nil {
|
||||
utils.Log.Warnf("生成 torrent 失败: %v", err)
|
||||
return
|
||||
}
|
||||
infoHash, _ := GetInfoHashHex(torrentData)
|
||||
torrentName := capturedFileName + ".cas.torrent"
|
||||
utils.Log.Infof("已生成 torrent: %s (info_hash: %s, size: %d bytes)",
|
||||
torrentName, infoHash, len(torrentData))
|
||||
|
||||
// 将 torrent 文件上传到同一目录(使用 FastUpload,因为 torrent 文件很小)
|
||||
torrentFileStream := &stream.FileStream{
|
||||
Ctx: context.Background(),
|
||||
Obj: &model.Object{
|
||||
Name: torrentName,
|
||||
Size: int64(len(torrentData)),
|
||||
IsFolder: false,
|
||||
},
|
||||
Reader: bytes.NewReader(torrentData),
|
||||
Mimetype: "application/x-bittorrent",
|
||||
}
|
||||
_, uploadErr := y.FastUpload(context.Background(), capturedDstDir, torrentFileStream, func(p float64) {}, capturedIsFamily, false)
|
||||
if uploadErr != nil {
|
||||
utils.Log.Warnf("上传 torrent 文件失败: %v", uploadErr)
|
||||
} else {
|
||||
utils.Log.Infof("torrent 文件已上传: %s", torrentName)
|
||||
op.Cache.DeleteDirectory(y, capturedDstDir.GetPath())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return resp.toFile(), nil
|
||||
}
|
||||
|
||||
@@ -847,6 +921,11 @@ func (y *Cloud189PC) RapidUpload(ctx context.Context, dstDir model.Obj, stream m
|
||||
|
||||
// 快传
|
||||
func (y *Cloud189PC) FastUpload(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress, isFamily bool, overwrite bool) (model.Obj, error) {
|
||||
generateTorrent := y.Addition.GenerateTorrent && !isCASTorrentFile(file.GetName())
|
||||
return y.fastUpload(ctx, dstDir, file, up, isFamily, overwrite, generateTorrent)
|
||||
}
|
||||
|
||||
func (y *Cloud189PC) fastUpload(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress, isFamily bool, overwrite bool, generateTorrent bool) (model.Obj, error) {
|
||||
var (
|
||||
cache = file.GetFile()
|
||||
tmpF *os.File
|
||||
@@ -884,6 +963,9 @@ func (y *Cloud189PC) FastUpload(ctx context.Context, dstDir model.Obj, file mode
|
||||
if tmpF != nil {
|
||||
writers = append(writers, tmpF)
|
||||
}
|
||||
|
||||
pieceSHA1Hashes := make([]byte, 0, count*20)
|
||||
|
||||
written := int64(0)
|
||||
for i := 1; i <= count; i++ {
|
||||
if utils.IsCanceled(ctx) {
|
||||
@@ -894,7 +976,17 @@ func (y *Cloud189PC) FastUpload(ctx context.Context, dstDir model.Obj, file mode
|
||||
byteSize = lastSliceSize
|
||||
}
|
||||
|
||||
n, err := utils.CopyWithBufferN(io.MultiWriter(writers...), file, byteSize)
|
||||
// 如果需要生成 torrent,同时计算 SHA-1
|
||||
var sha1Writer hash.Hash
|
||||
var multiWriter io.Writer
|
||||
if generateTorrent {
|
||||
sha1Writer = sha1Pkg.New()
|
||||
multiWriter = io.MultiWriter(append(writers, sha1Writer)...)
|
||||
} else {
|
||||
multiWriter = io.MultiWriter(writers...)
|
||||
}
|
||||
|
||||
n, err := utils.CopyWithBufferN(multiWriter, file, byteSize)
|
||||
written += n
|
||||
if err != nil && err != io.EOF {
|
||||
return nil, err
|
||||
@@ -903,6 +995,11 @@ func (y *Cloud189PC) FastUpload(ctx context.Context, dstDir model.Obj, file mode
|
||||
sliceMd5Hexs = append(sliceMd5Hexs, strings.ToUpper(hex.EncodeToString(md5Byte)))
|
||||
partInfos = append(partInfos, fmt.Sprint(i, "-", base64.StdEncoding.EncodeToString(md5Byte)))
|
||||
sliceMd5.Reset()
|
||||
|
||||
// 收集 SHA-1 piece hash(仅在本次分片实际写入了数据时追加)
|
||||
if generateTorrent && n > 0 {
|
||||
pieceSHA1Hashes = append(pieceSHA1Hashes, sha1Writer.Sum(nil)...)
|
||||
}
|
||||
}
|
||||
|
||||
if tmpF != nil {
|
||||
@@ -1018,6 +1115,44 @@ func (y *Cloud189PC) FastUpload(ctx context.Context, dstDir model.Obj, file mode
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 生成 torrent 文件(异步,不影响上传结果)
|
||||
if generateTorrent && size > 0 && len(pieceSHA1Hashes) > 0 {
|
||||
capturedDstDir := dstDir
|
||||
capturedIsFamily := isFamily
|
||||
capturedFileName := file.GetName()
|
||||
go func() {
|
||||
torrentData, err := GenerateTorrent(capturedFileName, size, fileMd5Hex, sliceMd5Hexs, sliceSize, pieceSHA1Hashes)
|
||||
if err != nil {
|
||||
utils.Log.Warnf("生成 torrent 失败: %v", err)
|
||||
return
|
||||
}
|
||||
infoHash, _ := GetInfoHashHex(torrentData)
|
||||
torrentName := capturedFileName + ".cas.torrent"
|
||||
utils.Log.Infof("已生成 torrent: %s (info_hash: %s, size: %d bytes)",
|
||||
torrentName, infoHash, len(torrentData))
|
||||
|
||||
// 将 torrent 文件上传到同一目录
|
||||
torrentFileStream := &stream.FileStream{
|
||||
Ctx: context.Background(),
|
||||
Obj: &model.Object{
|
||||
Name: torrentName,
|
||||
Size: int64(len(torrentData)),
|
||||
IsFolder: false,
|
||||
},
|
||||
Reader: bytes.NewReader(torrentData),
|
||||
Mimetype: "application/x-bittorrent",
|
||||
}
|
||||
_, uploadErr := y.fastUpload(context.Background(), capturedDstDir, torrentFileStream, func(p float64) {}, capturedIsFamily, false, false)
|
||||
if uploadErr != nil {
|
||||
utils.Log.Warnf("上传 torrent 文件失败: %v", uploadErr)
|
||||
} else {
|
||||
utils.Log.Infof("torrent 文件已上传: %s", torrentName)
|
||||
op.Cache.DeleteDirectory(y, capturedDstDir.GetPath())
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return resp.toFile(), nil
|
||||
}
|
||||
|
||||
|
||||
+25
-16
@@ -249,6 +249,7 @@ func (d *Alias) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (
|
||||
}
|
||||
linkClosers := make([]io.Closer, 0, len(files))
|
||||
rrf := make([]model.RangeReaderIF, 0, len(files))
|
||||
requireReference := false
|
||||
for _, f := range files {
|
||||
link, fi, err := d.link(ctx, f.GetPath(), args)
|
||||
if err != nil {
|
||||
@@ -258,9 +259,13 @@ func (d *Alias) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (
|
||||
_ = link.Close()
|
||||
continue
|
||||
}
|
||||
l := *link // 复制一份,避免修改到原始link
|
||||
if l.ContentLength == 0 {
|
||||
l.ContentLength = fi.GetSize()
|
||||
l := &model.Link{
|
||||
URL: link.URL,
|
||||
Header: link.Header,
|
||||
RangeReader: link.RangeReader,
|
||||
Concurrency: link.Concurrency,
|
||||
PartSize: link.PartSize,
|
||||
ContentLength: link.ContentLength,
|
||||
}
|
||||
if d.DownloadConcurrency > 0 {
|
||||
l.Concurrency = d.DownloadConcurrency
|
||||
@@ -268,20 +273,27 @@ func (d *Alias) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (
|
||||
if d.DownloadPartSize > 0 {
|
||||
l.PartSize = d.DownloadPartSize * utils.KB
|
||||
}
|
||||
rr, err := stream.GetRangeReaderFromLink(l.ContentLength, &l)
|
||||
if l.ContentLength == 0 {
|
||||
l.ContentLength = fi.GetSize()
|
||||
}
|
||||
rr, err := stream.GetRangeReaderFromLink(l.ContentLength, l)
|
||||
if err != nil {
|
||||
_ = link.Close()
|
||||
continue
|
||||
}
|
||||
linkClosers = append(linkClosers, link)
|
||||
if link.RequireReference {
|
||||
requireReference = true
|
||||
}
|
||||
rrf = append(rrf, rr)
|
||||
}
|
||||
rr := func(ctx context.Context, httpRange http_range.Range) (io.ReadCloser, error) {
|
||||
return rrf[rand.Intn(len(rrf))].RangeRead(ctx, httpRange)
|
||||
}
|
||||
return &model.Link{
|
||||
RangeReader: stream.RangeReaderFunc(rr),
|
||||
SyncClosers: utils.NewSyncClosers(linkClosers...),
|
||||
RangeReader: stream.RangeReaderFunc(rr),
|
||||
SyncClosers: utils.NewSyncClosers(linkClosers...),
|
||||
RequireReference: requireReference,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -315,14 +327,10 @@ func (d *Alias) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resultLink := *link // 复制一份,避免修改到原始link
|
||||
resultLink := link.Clone() // 复制一份,避免修改到原始link
|
||||
resultLink.Expiration = nil
|
||||
resultLink.SyncClosers = utils.NewSyncClosers(link)
|
||||
if args.Redirect {
|
||||
return &resultLink, nil
|
||||
}
|
||||
if resultLink.ContentLength == 0 {
|
||||
resultLink.ContentLength = fi.GetSize()
|
||||
return resultLink, nil
|
||||
}
|
||||
if d.DownloadConcurrency > 0 {
|
||||
resultLink.Concurrency = d.DownloadConcurrency
|
||||
@@ -330,7 +338,10 @@ func (d *Alias) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (
|
||||
if d.DownloadPartSize > 0 {
|
||||
resultLink.PartSize = d.DownloadPartSize * utils.KB
|
||||
}
|
||||
return &resultLink, nil
|
||||
if resultLink.ContentLength == 0 {
|
||||
resultLink.ContentLength = fi.GetSize()
|
||||
}
|
||||
return resultLink, nil
|
||||
}
|
||||
|
||||
func (d *Alias) Other(ctx context.Context, args model.OtherArgs) (interface{}, error) {
|
||||
@@ -501,9 +512,7 @@ func (d *Alias) Extract(ctx context.Context, obj model.Obj, args model.ArchiveIn
|
||||
sign.SignArchive(reqPath)),
|
||||
}, nil
|
||||
}
|
||||
resultLink := *link
|
||||
resultLink.SyncClosers = utils.NewSyncClosers(link)
|
||||
return &resultLink, nil
|
||||
return link.Clone(), nil
|
||||
}
|
||||
|
||||
func (d *Alias) ArchiveDecompress(ctx context.Context, srcObj, dstDir model.Obj, args model.ArchiveDecompressArgs) error {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package alidoc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
type AliDoc struct {
|
||||
model.Storage
|
||||
Addition
|
||||
|
||||
client *resty.Client
|
||||
}
|
||||
|
||||
func (d *AliDoc) Config() driver.Config {
|
||||
return config
|
||||
}
|
||||
|
||||
func (d *AliDoc) GetAddition() driver.Additional {
|
||||
return &d.Addition
|
||||
}
|
||||
|
||||
func (d *AliDoc) Init(ctx context.Context) error {
|
||||
d.Cookie = strings.TrimSpace(d.Cookie)
|
||||
d.RootFolderID = strings.TrimSpace(d.RootFolderID)
|
||||
if d.Cookie == "" {
|
||||
return fmt.Errorf("cookie is empty")
|
||||
}
|
||||
if d.RootFolderID == "" {
|
||||
return fmt.Errorf("root folder id is empty")
|
||||
}
|
||||
d.client = newClient()
|
||||
if err := d.checkCookie(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) Drop(ctx context.Context) error {
|
||||
d.client = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) List(ctx context.Context, dir model.Obj, args model.ListArgs) ([]model.Obj, error) {
|
||||
items, err := d.list(ctx, dir.GetID())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
objs := make([]model.Obj, 0, len(items))
|
||||
for _, item := range items {
|
||||
if strings.TrimSpace(item.DentryUUID) == "" || strings.TrimSpace(item.Name) == "" {
|
||||
continue
|
||||
}
|
||||
objs = append(objs, toObj(item))
|
||||
}
|
||||
return objs, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (*model.Link, error) {
|
||||
if file.IsDir() {
|
||||
return nil, fmt.Errorf("alidoc does not support directory links")
|
||||
}
|
||||
resp, err := d.download(ctx, file.GetID())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
url, err := firstDownloadURL(resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &model.Link{
|
||||
URL: url,
|
||||
Header: http.Header{
|
||||
"User-Agent": []string{base.UserAgent},
|
||||
"Referer": []string{apiBase + "/"},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) (model.Obj, error) {
|
||||
err := d.post(ctx, "/box/api/v2/dentry/createfolder", map[string]string{
|
||||
"dentryType": "folder",
|
||||
"name": dirName,
|
||||
"parentDentryUuid": parentDir.GetID(),
|
||||
"conflictHandleStrategy": "auto_rename",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) Move(ctx context.Context, srcObj, dstDir model.Obj) (model.Obj, error) {
|
||||
err := d.post(ctx, "/box/api/v2/dentry/move", map[string]interface{}{
|
||||
"targetParentDentryUuid": dstDir.GetID(),
|
||||
"sourceDentryUuid": srcObj.GetID(),
|
||||
"operateFrom": 1,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return srcObj, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) Rename(ctx context.Context, srcObj model.Obj, newName string) (model.Obj, error) {
|
||||
err := d.post(ctx, "/box/api/v2/dentry/rename", map[string]string{
|
||||
"dentryUuid": srcObj.GetID(),
|
||||
"name": newName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
srcObj.(*model.Object).Name = newName
|
||||
return srcObj, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) Copy(ctx context.Context, srcObj, dstDir model.Obj) error {
|
||||
return d.post(ctx, "/box/api/v2/dentry/copy", map[string]interface{}{
|
||||
"sourceDentryUuid": srcObj.GetID(),
|
||||
"targetParentDentryUuid": dstDir.GetID(),
|
||||
"operateFrom": 1,
|
||||
"onlyCopyMeta": false,
|
||||
})
|
||||
}
|
||||
|
||||
func (d *AliDoc) Remove(ctx context.Context, obj model.Obj) error {
|
||||
return d.post(ctx, "/box/api/v1/dentry/recycle", map[string]string{
|
||||
"dentryUuid": obj.GetID(),
|
||||
})
|
||||
}
|
||||
|
||||
var (
|
||||
_ driver.Driver = (*AliDoc)(nil)
|
||||
_ driver.MkdirResult = (*AliDoc)(nil)
|
||||
_ driver.MoveResult = (*AliDoc)(nil)
|
||||
_ driver.RenameResult = (*AliDoc)(nil)
|
||||
_ driver.Copy = (*AliDoc)(nil)
|
||||
_ driver.Remove = (*AliDoc)(nil)
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package alidoc
|
||||
|
||||
import (
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/op"
|
||||
)
|
||||
|
||||
type Addition struct {
|
||||
driver.RootID
|
||||
Cookie string `json:"cookie" type:"text" required:"true" help:"钉钉文档网页 Cookie"`
|
||||
}
|
||||
|
||||
var config = driver.Config{
|
||||
Name: "AliDoc",
|
||||
LocalSort: true,
|
||||
DefaultRoot: "",
|
||||
}
|
||||
|
||||
func init() {
|
||||
op.RegisterDriver(func() driver.Driver {
|
||||
return &AliDoc{}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package alidoc
|
||||
|
||||
type apiResp struct {
|
||||
Status int `json:"status"`
|
||||
IsSuccess bool `json:"isSuccess"`
|
||||
Message string `json:"message"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
|
||||
func (r apiResp) ErrMessage() string {
|
||||
if r.Message != "" {
|
||||
return r.Message
|
||||
}
|
||||
if r.Msg != "" {
|
||||
return r.Msg
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type listResp struct {
|
||||
apiResp
|
||||
Data listData `json:"data"`
|
||||
}
|
||||
|
||||
type listData struct {
|
||||
Children []dentry `json:"children"`
|
||||
}
|
||||
|
||||
type dentry struct {
|
||||
DentryType string `json:"dentryType"`
|
||||
DentryUUID string `json:"dentryUuid"`
|
||||
ParentDentryUUID string `json:"parentDentryUuid"`
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
FileSize int64 `json:"fileSize"`
|
||||
CreatedTime int64 `json:"createdTime"`
|
||||
UpdatedTime int64 `json:"updatedTime"`
|
||||
ContentType string `json:"contentType"`
|
||||
Extension string `json:"extension"`
|
||||
DentryStatistic struct {
|
||||
ChildrenCount int `json:"childrenCount"`
|
||||
} `json:"dentryStatistic"`
|
||||
URL struct {
|
||||
PCChildAppPreviewURL string `json:"pcChildAppPreviewUrl"`
|
||||
PCChildAppURL string `json:"pcChildAppUrl"`
|
||||
} `json:"url"`
|
||||
}
|
||||
|
||||
type downloadResp struct {
|
||||
apiResp
|
||||
Data downloadData `json:"data"`
|
||||
}
|
||||
|
||||
type downloadData struct {
|
||||
OSSURLPreSignatureInfo struct {
|
||||
PreSignURLs []string `json:"preSignUrls"`
|
||||
} `json:"ossUrlPreSignatureInfo"`
|
||||
}
|
||||
|
||||
type uploadInfoResp struct {
|
||||
apiResp
|
||||
Data uploadInfoData `json:"data"`
|
||||
}
|
||||
|
||||
type uploadInfoData struct {
|
||||
CurrentTimestamp int64 `json:"currentTimestamp"`
|
||||
FileUploadProtocolConfig uploadProtocolConfig `json:"fileUploadProtocolConfig"`
|
||||
STSSignatureInfo uploadSTSSignatureInfo `json:"stsSignatureInfo"`
|
||||
UploadKey string `json:"uploadKey"`
|
||||
UploadType string `json:"uploadType"`
|
||||
}
|
||||
|
||||
type uploadProtocolConfig struct {
|
||||
MinPartSize int64 `json:"minPartSize"`
|
||||
}
|
||||
|
||||
type uploadSTSSignatureInfo struct {
|
||||
AccelerateCname string `json:"accelerateCname"`
|
||||
AccessKeyID string `json:"accessKeyId"`
|
||||
AccessKeySecret string `json:"accessKeySecret"`
|
||||
AccessToken string `json:"accessToken"`
|
||||
AccessTokenExpiration int64 `json:"accessTokenExpiration"`
|
||||
Bucket string `json:"bucket"`
|
||||
Cname string `json:"cname"`
|
||||
EndPoint string `json:"endPoint"`
|
||||
ObjectKey string `json:"objectKey"`
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package alidoc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
netutil "github.com/OpenListTeam/OpenList/v4/internal/net"
|
||||
streamPkg "github.com/OpenListTeam/OpenList/v4/internal/stream"
|
||||
"github.com/aliyun/aliyun-oss-go-sdk/oss"
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultAliDocMultipartThreshold = 16 * 1024 * 1024
|
||||
defaultAliDocPartSize = 100 * 1024
|
||||
maxAliDocMultipartParts = 10000
|
||||
)
|
||||
|
||||
func (d *AliDoc) Put(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress) error {
|
||||
size := file.GetSize()
|
||||
useMultipart := size > defaultAliDocMultipartThreshold
|
||||
info, err := d.getUploadInfo(ctx, dstDir.GetID(), file.GetName(), size, useMultipart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size > 0 {
|
||||
partSize := calcAliDocPartSize(size, info.Data.FileUploadProtocolConfig.MinPartSize)
|
||||
if size > partSize && !useMultipart {
|
||||
useMultipart = true
|
||||
info, err = d.getUploadInfo(ctx, dstDir.GetID(), file.GetName(), size, true)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if useMultipart {
|
||||
err = d.multipartUpload(ctx, file, size, info, up)
|
||||
} else {
|
||||
err = d.singleUpload(ctx, file, size, info, up)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.commitUpload(ctx, dstDir.GetID(), file.GetName(), size, info.Data.UploadKey); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) getUploadInfo(ctx context.Context, parentDentryUUID, name string, fileSize int64, multipart bool) (uploadInfoResp, error) {
|
||||
var result uploadInfoResp
|
||||
body := map[string]interface{}{
|
||||
"uploadType": "STS_SIGNATURE",
|
||||
"supportUploadTypes": []string{"STS_SIGNATURE", "HTTP_TO_CENTER"},
|
||||
"parentDentryUuid": parentDentryUUID,
|
||||
"fileSize": fileSize,
|
||||
"name": name,
|
||||
"multipart": multipart,
|
||||
}
|
||||
resp, err := d.request(ctx).
|
||||
SetBody(body).
|
||||
SetResult(&result).
|
||||
SetError(&result).
|
||||
Post(apiBase + "/box/api/v2/file/uploadinfo")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := checkResp(resp, result.apiResp); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if strings.TrimSpace(result.Data.STSSignatureInfo.Bucket) == "" {
|
||||
return result, fmt.Errorf("empty upload bucket")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) commitUpload(ctx context.Context, parentDentryUUID, name string, fileSize int64, uploadKey string) error {
|
||||
uploadKey = strings.TrimSpace(uploadKey)
|
||||
if uploadKey == "" {
|
||||
return fmt.Errorf("empty upload key")
|
||||
}
|
||||
|
||||
var result apiResp
|
||||
body := map[string]interface{}{
|
||||
"parentDentryUuid": parentDentryUUID,
|
||||
"uploadKey": uploadKey,
|
||||
"fileSize": fileSize,
|
||||
"name": name,
|
||||
"toPrevDentryUuid": nil,
|
||||
"toNextDentryUuid": nil,
|
||||
"batchId": uuid.NewString(),
|
||||
"batchUploadType": 1,
|
||||
"batchParentDentryUuid": parentDentryUUID,
|
||||
}
|
||||
resp, err := d.request(ctx).
|
||||
SetBody(body).
|
||||
SetResult(&result).
|
||||
SetError(&result).
|
||||
Post(apiBase + "/box/api/v2/file/commit")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkResp(resp, result)
|
||||
}
|
||||
|
||||
func calcAliDocPartSize(fileSize, minPartSize int64) int64 {
|
||||
partSize := minPartSize
|
||||
if partSize <= 0 {
|
||||
partSize = defaultAliDocPartSize
|
||||
}
|
||||
if fileSize <= 0 {
|
||||
return partSize
|
||||
}
|
||||
minRequired := int64(math.Ceil(float64(fileSize) / maxAliDocMultipartParts))
|
||||
if minRequired > partSize {
|
||||
partSize = minRequired
|
||||
}
|
||||
return partSize
|
||||
}
|
||||
|
||||
func (d *AliDoc) singleUpload(ctx context.Context, src model.FileStreamer, size int64, info uploadInfoResp, up driver.UpdateProgress) error {
|
||||
bucket, objectKey, err := d.newOSSBucket(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = bucket.PutObject(
|
||||
objectKey,
|
||||
driver.NewLimitedUploadStream(ctx, io.TeeReader(src, driver.NewProgress(size, up))),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
up(100)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) multipartUpload(ctx context.Context, src model.FileStreamer, size int64, info uploadInfoResp, up driver.UpdateProgress) error {
|
||||
bucket, objectKey, err := d.newOSSBucket(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
imur, err := bucket.InitiateMultipartUpload(objectKey, oss.Sequential())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
partSize := calcAliDocPartSize(size, info.Data.FileUploadProtocolConfig.MinPartSize)
|
||||
partNum := int((size + partSize - 1) / partSize)
|
||||
parts := make([]oss.UploadPart, 0, partNum)
|
||||
ss, err := streamPkg.NewStreamSectionReader(src, int(partSize), &up)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var offset int64
|
||||
for partNumber := 1; partNumber <= partNum; partNumber++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
length := partSize
|
||||
if remain := size - offset; remain < length {
|
||||
length = remain
|
||||
}
|
||||
|
||||
reader, err := ss.GetSectionReader(offset, length)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var part oss.UploadPart
|
||||
var uploadErr error
|
||||
err = retry.Do(func() error {
|
||||
if _, err := reader.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
part, uploadErr = bucket.UploadPart(
|
||||
imur,
|
||||
driver.NewLimitedUploadStream(ctx, reader),
|
||||
length,
|
||||
partNumber,
|
||||
)
|
||||
return uploadErr
|
||||
},
|
||||
retry.Context(ctx),
|
||||
retry.Attempts(3),
|
||||
retry.DelayType(retry.BackOffDelay),
|
||||
retry.Delay(time.Second),
|
||||
)
|
||||
ss.FreeSectionReader(reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parts = append(parts, part)
|
||||
up(100 * float64(len(parts)) / float64(partNum+1))
|
||||
offset += length
|
||||
}
|
||||
|
||||
_, err = bucket.CompleteMultipartUpload(imur, parts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
up(100)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) newOSSBucket(info uploadInfoResp) (*oss.Bucket, string, error) {
|
||||
sts := info.Data.STSSignatureInfo
|
||||
objectKey := strings.TrimSpace(sts.ObjectKey)
|
||||
if objectKey == "" {
|
||||
objectKey = strings.TrimSpace(info.Data.UploadKey)
|
||||
}
|
||||
if objectKey == "" {
|
||||
return nil, "", fmt.Errorf("empty upload object key")
|
||||
}
|
||||
|
||||
endpoint, useCname := pickAliDocOSSEndpoint(sts)
|
||||
if endpoint == "" {
|
||||
return nil, "", fmt.Errorf("empty upload endpoint")
|
||||
}
|
||||
if !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "https://") {
|
||||
endpoint = "https://" + endpoint
|
||||
}
|
||||
|
||||
options := []oss.ClientOption{oss.SecurityToken(sts.AccessToken)}
|
||||
if useCname {
|
||||
options = append(options, oss.UseCname(true))
|
||||
}
|
||||
client, err := netutil.NewOSSClient(
|
||||
endpoint,
|
||||
sts.AccessKeyID,
|
||||
sts.AccessKeySecret,
|
||||
options...,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
bucket, err := client.Bucket(sts.Bucket)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return bucket, objectKey, nil
|
||||
}
|
||||
|
||||
func pickAliDocOSSEndpoint(sts uploadSTSSignatureInfo) (endpoint string, useCname bool) {
|
||||
if endpoint = strings.TrimSpace(sts.EndPoint); endpoint != "" {
|
||||
return endpoint, false
|
||||
}
|
||||
if endpoint = strings.TrimSpace(sts.Cname); endpoint != "" {
|
||||
return endpoint, true
|
||||
}
|
||||
if endpoint = strings.TrimSpace(sts.AccelerateCname); endpoint != "" {
|
||||
return endpoint, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package alidoc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
const apiBase = "https://alidocs.dingtalk.com"
|
||||
|
||||
func (d *AliDoc) request(ctx context.Context) *resty.Request {
|
||||
return d.client.R().
|
||||
SetContext(ctx).
|
||||
SetHeader("Cookie", d.Cookie).
|
||||
SetHeader("Accept", "application/json, text/plain, */*").
|
||||
SetHeader("Referer", apiBase+"/").
|
||||
SetHeader("Origin", apiBase)
|
||||
}
|
||||
|
||||
func msToTime(v int64) time.Time {
|
||||
if v <= 0 {
|
||||
return time.Time{}
|
||||
}
|
||||
return time.UnixMilli(v)
|
||||
}
|
||||
|
||||
func checkResp(resp *resty.Response, result apiResp) error {
|
||||
if resp != nil && resp.IsError() {
|
||||
if msg := result.ErrMessage(); msg != "" {
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
return fmt.Errorf("http error: %d", resp.StatusCode())
|
||||
}
|
||||
if !result.IsSuccess || result.Status != 200 {
|
||||
msg := result.ErrMessage()
|
||||
if msg == "" {
|
||||
msg = "request failed"
|
||||
}
|
||||
return fmt.Errorf("%s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toObj(item dentry) model.Obj {
|
||||
return &model.Object{
|
||||
ID: item.DentryUUID,
|
||||
Name: item.Name,
|
||||
Size: item.FileSize,
|
||||
Modified: msToTime(item.UpdatedTime),
|
||||
Ctime: msToTime(item.CreatedTime),
|
||||
IsFolder: item.DentryType == "folder",
|
||||
}
|
||||
}
|
||||
|
||||
func firstDownloadURL(resp downloadResp) (string, error) {
|
||||
if len(resp.Data.OSSURLPreSignatureInfo.PreSignURLs) == 0 {
|
||||
return "", fmt.Errorf("empty download url")
|
||||
}
|
||||
return resp.Data.OSSURLPreSignatureInfo.PreSignURLs[0], nil
|
||||
}
|
||||
|
||||
func newClient() *resty.Client {
|
||||
client := base.NewRestyClient()
|
||||
client.SetHeader("User-Agent", base.UserAgent)
|
||||
return client
|
||||
}
|
||||
|
||||
func (d *AliDoc) post(ctx context.Context, path string, body interface{}) error {
|
||||
var result apiResp
|
||||
resp, err := d.request(ctx).
|
||||
SetBody(body).
|
||||
SetResult(&result).
|
||||
SetError(&result).
|
||||
Post(apiBase + path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkResp(resp, result)
|
||||
}
|
||||
|
||||
func (d *AliDoc) checkCookie(ctx context.Context) error {
|
||||
var result apiResp
|
||||
resp, err := d.request(ctx).
|
||||
SetResult(&result).
|
||||
SetError(&result).
|
||||
Get(apiBase + "/portal/api/v1/mine/info")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return checkResp(resp, result)
|
||||
}
|
||||
|
||||
func (d *AliDoc) list(ctx context.Context, dentryUUID string) ([]dentry, error) {
|
||||
var result listResp
|
||||
resp, err := d.request(ctx).
|
||||
SetQueryParam("dentryUuid", dentryUUID).
|
||||
SetQueryParam("withParentAncestors", "true").
|
||||
SetQueryParam("orderType", "SORT_KEY").
|
||||
SetQueryParam("sortType", "desc").
|
||||
SetQueryParam("listDentrySource", "2").
|
||||
SetQueryParam("pageSize", "1000").
|
||||
SetResult(&result).
|
||||
SetError(&result).
|
||||
Get(apiBase + "/box/api/v2/dentry/list")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := checkResp(resp, result.apiResp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return result.Data.Children, nil
|
||||
}
|
||||
|
||||
func (d *AliDoc) download(ctx context.Context, dentryUUID string) (downloadResp, error) {
|
||||
var result downloadResp
|
||||
resp, err := d.request(ctx).
|
||||
SetQueryParam("dentryUuid", dentryUUID).
|
||||
SetQueryParam("version", "1").
|
||||
SetQueryParam("supportDownloadTypes", "URL_PRE_SIGNATURE,HTTP_TO_CENTER").
|
||||
SetQueryParam("downloadType", "URL_PRE_SIGNATURE").
|
||||
SetResult(&result).
|
||||
SetError(&result).
|
||||
Get(apiBase + "/box/api/v2/file/download")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := checkResp(resp, result.apiResp); err != nil {
|
||||
return result, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/189_tv"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/189pc"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/alias"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/alidoc"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/alist_v3"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/aliyundrive"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/aliyundrive_open"
|
||||
@@ -21,22 +22,27 @@ import (
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/azure_blob"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/baidu_netdisk"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/baidu_photo"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/bunny_storage"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/chaoxing"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/chunk"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/cloudflare_imgbed"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/cloudreve"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/cloudreve_v4"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/cnb_releases"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/crypt"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/degoo"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/doubao"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/doubao_new"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/doubao_share"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/dropbox"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/emby"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/febbox"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/ftp"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/github"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/github_releases"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/google_drive"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/google_photo"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/guangyapan"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/halalcloud"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/halalcloud_open"
|
||||
_ "github.com/OpenListTeam/OpenList/v4/drivers/ilanzou"
|
||||
|
||||
@@ -2,6 +2,7 @@ package azure_blob
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
@@ -12,10 +13,13 @@ import (
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
|
||||
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Azure Blob Storage based on the blob APIs
|
||||
@@ -85,6 +89,9 @@ func (d *AzureBlob) Drop(ctx context.Context) error {
|
||||
// List retrieves blobs and directories under the specified path.
|
||||
func (d *AzureBlob) List(ctx context.Context, dir model.Obj, args model.ListArgs) ([]model.Obj, error) {
|
||||
prefix := ensureTrailingSlash(dir.GetPath())
|
||||
if prefix == "/" {
|
||||
prefix = ""
|
||||
}
|
||||
|
||||
pager := d.containerClient.NewListBlobsHierarchyPager("/", &container.ListBlobsHierarchyOptions{
|
||||
Prefix: &prefix,
|
||||
@@ -100,10 +107,11 @@ func (d *AzureBlob) List(ctx context.Context, dir model.Obj, args model.ListArgs
|
||||
// Process directories
|
||||
for _, blobPrefix := range page.Segment.BlobPrefixes {
|
||||
objs = append(objs, &model.Object{
|
||||
Name: path.Base(strings.TrimSuffix(*blobPrefix.Name, "/")),
|
||||
Path: *blobPrefix.Name,
|
||||
Modified: *blobPrefix.Properties.LastModified,
|
||||
Ctime: *blobPrefix.Properties.CreationTime,
|
||||
Name: path.Base(strings.TrimSuffix(*blobPrefix.Name, "/")),
|
||||
Path: *blobPrefix.Name,
|
||||
// Azure does not support properties now.
|
||||
//Modified: *blobPrefix.Properties.LastModified,
|
||||
//Ctime: *blobPrefix.Properties.CreationTime,
|
||||
IsFolder: true,
|
||||
})
|
||||
}
|
||||
@@ -279,6 +287,26 @@ func (d *AzureBlob) Put(ctx context.Context, dstDir model.Obj, stream model.File
|
||||
// Determine optimal upload options based on file size
|
||||
options := optimizedUploadOptions(stream.GetSize())
|
||||
|
||||
// Preserve the file content type for direct Azure Blob downloads.
|
||||
contentType := stream.GetMimetype()
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
options.HTTPHeaders = &blob.HTTPHeaders{
|
||||
BlobContentType: &contentType,
|
||||
}
|
||||
|
||||
// Preserve the MD5 checksum when it is available.
|
||||
md5Hex := stream.GetHash().GetHash(utils.MD5)
|
||||
if md5Hex != "" {
|
||||
md5, err := hex.DecodeString(md5Hex)
|
||||
if err == nil && len(md5) == 16 {
|
||||
options.HTTPHeaders.BlobContentMD5 = md5
|
||||
} else {
|
||||
log.Warnf("Invalid MD5 hash: %s, error: %v", md5Hex, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Track upload progress
|
||||
progressTracker := &progressTracker{
|
||||
total: stream.GetSize(),
|
||||
|
||||
@@ -215,11 +215,13 @@ func (d *BaiduNetdisk) linkOfficial(file model.Obj, _ model.LinkArgs) (*model.Li
|
||||
u = res.Header().Get("location")
|
||||
//}
|
||||
|
||||
exp := time.Hour
|
||||
return &model.Link{
|
||||
URL: u,
|
||||
Header: http.Header{
|
||||
"User-Agent": []string{"pan.baidu.com"},
|
||||
},
|
||||
Expiration: &exp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ func (c *File) Thumb() string {
|
||||
}
|
||||
|
||||
func (c *File) GetHash() utils.HashInfo {
|
||||
return utils.NewHashInfo(utils.MD5, DecryptMd5(c.Md5))
|
||||
return utils.HashInfo{}
|
||||
}
|
||||
|
||||
/*相册部分*/
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
@@ -411,12 +412,14 @@ func (d *BaiduPhoto) linkFile(ctx context.Context, file *File, args model.LinkAr
|
||||
// }
|
||||
|
||||
// location := resp.Header().Get("Location")
|
||||
exp := time.Hour
|
||||
link := &model.Link{
|
||||
URL: downloadUrl.Dlink,
|
||||
Header: http.Header{
|
||||
"User-Agent": []string{headers["User-Agent"]},
|
||||
"Referer": []string{"https://photo.baidu.com/"},
|
||||
},
|
||||
Expiration: &exp,
|
||||
}
|
||||
return link, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package bunny_storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
stdpath "path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/errs"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
type BunnyStorage struct {
|
||||
model.Storage
|
||||
Addition
|
||||
client *resty.Client
|
||||
endpoint *url.URL
|
||||
cdnBase *url.URL
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Config() driver.Config {
|
||||
cfg := config
|
||||
if d.StorageZoneName != "" && d.CDNBaseURL == "" {
|
||||
cfg.OnlyProxy = true
|
||||
cfg.PreferProxy = true
|
||||
}
|
||||
if d.CDNTokenKey != "" && d.CDNTokenIncludeIP {
|
||||
cfg.LinkCacheMode = driver.LinkCacheIP
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) GetAddition() driver.Additional {
|
||||
return &d.Addition
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Init(ctx context.Context) error {
|
||||
if d.RootFolderPath == "" {
|
||||
d.RootFolderPath = "/"
|
||||
}
|
||||
if d.Endpoint == "" {
|
||||
d.Endpoint = defaultEndpoint
|
||||
}
|
||||
if d.SignURLExpire <= 0 {
|
||||
d.SignURLExpire = 4
|
||||
}
|
||||
if d.CDNTokenMethod == "" {
|
||||
d.CDNTokenMethod = cdnTokenMethodSHA256
|
||||
}
|
||||
endpoint, err := normalizeBaseURL(d.Endpoint, defaultEndpoint)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid endpoint: %w", err)
|
||||
}
|
||||
d.endpoint = endpoint
|
||||
if d.CDNBaseURL != "" {
|
||||
cdnBase, err := normalizeBaseURL(d.CDNBaseURL, "")
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid cdn_base_url: %w", err)
|
||||
}
|
||||
d.cdnBase = cdnBase
|
||||
}
|
||||
d.client = base.RestyClient
|
||||
if d.client == nil {
|
||||
d.client = base.NewRestyClient()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Drop(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) List(ctx context.Context, dir model.Obj, args model.ListArgs) ([]model.Obj, error) {
|
||||
var items []bunnyObject
|
||||
resp, err := d.authRequest().
|
||||
SetContext(ctx).
|
||||
SetResult(&items).
|
||||
Get(d.storageURL(dir.GetPath(), true))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := d.handleResponseError(resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]model.Obj, 0, len(items))
|
||||
placeholder := d.placeholderName()
|
||||
for _, item := range items {
|
||||
if item.ObjectName == "" {
|
||||
continue
|
||||
}
|
||||
if !args.S3ShowPlaceholder && !item.IsDirectory && item.ObjectName == placeholder {
|
||||
continue
|
||||
}
|
||||
result = append(result, d.toObj(dir.GetPath(), item))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (*model.Link, error) {
|
||||
if file.IsDir() {
|
||||
return nil, errs.NotFile
|
||||
}
|
||||
cacheTTL := time.Duration(0)
|
||||
if d.cdnBase != nil {
|
||||
linkURL := d.cdnURL(d.cdnObjectPath(file.GetPath()))
|
||||
link := &model.Link{
|
||||
URL: linkURL,
|
||||
ContentLength: file.GetSize(),
|
||||
Expiration: &cacheTTL,
|
||||
}
|
||||
if d.CDNTokenKey != "" {
|
||||
signedURL, _, err := d.signCDNURL(linkURL, args.IP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
link.URL = signedURL
|
||||
}
|
||||
return link, nil
|
||||
}
|
||||
return &model.Link{
|
||||
URL: d.storageURL(file.GetPath(), false),
|
||||
Header: http.Header{"AccessKey": []string{d.AccessKey}},
|
||||
ContentLength: file.GetSize(),
|
||||
Expiration: &cacheTTL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) (model.Obj, error) {
|
||||
dirPath := stdpath.Join(parentDir.GetPath(), dirName)
|
||||
placeholderPath := stdpath.Join(dirPath, d.placeholderName())
|
||||
if err := d.putReader(ctx, placeholderPath, bytes.NewReader(nil), 0, "application/octet-stream", nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
return &model.Object{
|
||||
Path: dirPath,
|
||||
Name: dirName,
|
||||
Modified: now,
|
||||
Ctime: now,
|
||||
IsFolder: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Remove(ctx context.Context, obj model.Obj) error {
|
||||
resp, err := d.authRequest().
|
||||
SetContext(ctx).
|
||||
Delete(d.storageURL(obj.GetPath(), obj.IsDir()))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.handleResponseError(resp)
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Put(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress) (model.Obj, error) {
|
||||
if up == nil {
|
||||
up = func(float64) {}
|
||||
}
|
||||
dstPath := stdpath.Join(dstDir.GetPath(), file.GetName())
|
||||
err := d.putReader(ctx, dstPath, driver.NewLimitedUploadStream(ctx, &driver.ReaderUpdatingProgress{
|
||||
Reader: file,
|
||||
UpdateProgress: up,
|
||||
}), file.GetSize(), file.GetMimetype(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
now := time.Now()
|
||||
return &model.Object{
|
||||
Path: dstPath,
|
||||
Name: file.GetName(),
|
||||
Size: file.GetSize(),
|
||||
Modified: now,
|
||||
Ctime: now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) putReader(ctx context.Context, path string, body any, size int64, contentType string, extraHeaders http.Header) error {
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
req := d.authRequest().
|
||||
SetContext(ctx).
|
||||
SetBody(body).
|
||||
SetHeader("Content-Type", contentType)
|
||||
if size >= 0 {
|
||||
req.SetHeader("Content-Length", fmt.Sprint(size))
|
||||
}
|
||||
for key, values := range extraHeaders {
|
||||
for _, value := range values {
|
||||
req.SetHeader(key, value)
|
||||
}
|
||||
}
|
||||
resp, err := req.Put(d.storageURL(path, false))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.handleResponseError(resp)
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) Get(ctx context.Context, path string) (model.Obj, error) {
|
||||
fullPath := stdpath.Join(d.GetRootPath(), path)
|
||||
parentPath, name := stdpath.Split(fullPath)
|
||||
parentPath = strings.TrimSuffix(parentPath, "/")
|
||||
if parentPath == "" {
|
||||
parentPath = "/"
|
||||
}
|
||||
objs, err := d.List(ctx, &model.Object{Path: parentPath, IsFolder: true}, model.ListArgs{S3ShowPlaceholder: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, obj := range objs {
|
||||
if obj.GetName() == name {
|
||||
return obj, nil
|
||||
}
|
||||
}
|
||||
return nil, errs.ObjectNotFound
|
||||
}
|
||||
|
||||
var _ driver.Driver = (*BunnyStorage)(nil)
|
||||
var _ driver.Getter = (*BunnyStorage)(nil)
|
||||
@@ -0,0 +1,32 @@
|
||||
package bunny_storage
|
||||
|
||||
import (
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/op"
|
||||
)
|
||||
|
||||
type Addition struct {
|
||||
driver.RootPath
|
||||
StorageZoneName string `json:"storage_zone_name" required:"true"`
|
||||
AccessKey string `json:"access_key" required:"true"`
|
||||
Endpoint string `json:"endpoint" required:"true" default:"storage.bunnycdn.com"`
|
||||
CDNBaseURL string `json:"cdn_base_url"`
|
||||
CDNTokenKey string `json:"cdn_token_key"`
|
||||
CDNTokenMethod string `json:"cdn_token_method" type:"select" options:"sha256,hmac_sha256" default:"sha256"`
|
||||
CDNTokenIncludeIP bool `json:"cdn_token_include_ip" default:"false"`
|
||||
SignURLExpire int `json:"sign_url_expire" type:"number" default:"4"`
|
||||
Placeholder string `json:"placeholder" default:".openlist"`
|
||||
}
|
||||
|
||||
var config = driver.Config{
|
||||
Name: "Bunny Storage",
|
||||
LocalSort: true,
|
||||
DefaultRoot: "/",
|
||||
CheckStatus: true,
|
||||
}
|
||||
|
||||
func init() {
|
||||
op.RegisterDriver(func() driver.Driver {
|
||||
return &BunnyStorage{}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package bunny_storage
|
||||
|
||||
import "time"
|
||||
|
||||
type bunnyObject struct {
|
||||
Guid string `json:"Guid"`
|
||||
StorageZoneName string `json:"StorageZoneName"`
|
||||
Path string `json:"Path"`
|
||||
ObjectName string `json:"ObjectName"`
|
||||
Length int64 `json:"Length"`
|
||||
LastChanged string `json:"LastChanged"`
|
||||
IsDirectory bool `json:"IsDirectory"`
|
||||
ServerID int `json:"ServerId"`
|
||||
UserID string `json:"UserId"`
|
||||
DateCreated string `json:"DateCreated"`
|
||||
StorageZoneID int64 `json:"StorageZoneId"`
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
HttpCode int `json:"HttpCode"`
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
|
||||
type parsedTimes struct {
|
||||
modified time.Time
|
||||
created time.Time
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
package bunny_storage
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
stdpath "path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/errs"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "storage.bunnycdn.com"
|
||||
defaultPlaceholder = ".openlist"
|
||||
|
||||
cdnTokenMethodSHA256 = "sha256"
|
||||
cdnTokenMethodHMACSHA256 = "hmac_sha256"
|
||||
)
|
||||
|
||||
func normalizeBaseURL(raw string, fallback string) (*url.URL, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
raw = fallback
|
||||
}
|
||||
if raw == "" {
|
||||
return nil, fmt.Errorf("empty url")
|
||||
}
|
||||
if !strings.Contains(raw, "://") {
|
||||
raw = "https://" + raw
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if u.Host == "" {
|
||||
return nil, fmt.Errorf("invalid url: %s", raw)
|
||||
}
|
||||
u.Path = strings.TrimRight(u.Path, "/")
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func cleanObjectPath(path string) string {
|
||||
if path == "" {
|
||||
return "/"
|
||||
}
|
||||
return stdpath.Clean("/" + strings.TrimPrefix(path, "/"))
|
||||
}
|
||||
|
||||
func stripObjectPathPrefix(path string, prefix string) (string, bool) {
|
||||
path = cleanObjectPath(path)
|
||||
prefix = cleanObjectPath(prefix)
|
||||
if prefix == "/" {
|
||||
return path, false
|
||||
}
|
||||
if path == prefix {
|
||||
return "/", true
|
||||
}
|
||||
if strings.HasPrefix(path, prefix+"/") {
|
||||
return cleanObjectPath(strings.TrimPrefix(path, prefix)), true
|
||||
}
|
||||
return path, false
|
||||
}
|
||||
|
||||
func isObjectPathOrChild(path string, parent string) bool {
|
||||
path = cleanObjectPath(path)
|
||||
parent = cleanObjectPath(parent)
|
||||
return path == parent || strings.HasPrefix(path, parent+"/")
|
||||
}
|
||||
|
||||
func trimCDNBasePath(path string, mountPath string) string {
|
||||
path = cleanObjectPath(path)
|
||||
if path == "/" {
|
||||
return ""
|
||||
}
|
||||
if stripped, ok := stripObjectPathPrefix(path, mountPath); ok {
|
||||
path = stripped
|
||||
}
|
||||
if path == "/" {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimRight(path, "/")
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) cdnObjectPath(path string) string {
|
||||
objectPath := cleanObjectPath(path)
|
||||
if stripped, ok := stripObjectPathPrefix(objectPath, d.GetStorage().MountPath); ok {
|
||||
objectPath = stripped
|
||||
}
|
||||
rootPath := cleanObjectPath(d.GetRootPath())
|
||||
if rootPath != "/" && !isObjectPathOrChild(objectPath, rootPath) {
|
||||
objectPath = cleanObjectPath(stdpath.Join(rootPath, objectPath))
|
||||
}
|
||||
return objectPath
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) placeholderName() string {
|
||||
if d.Placeholder == "" {
|
||||
return defaultPlaceholder
|
||||
}
|
||||
return d.Placeholder
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) storageURL(path string, dir bool) string {
|
||||
u := *d.endpoint
|
||||
cleanPath := cleanObjectPath(path)
|
||||
zone := strings.Trim(d.StorageZoneName, "/")
|
||||
if cleanPath == "/" {
|
||||
u.Path = "/" + zone + "/"
|
||||
return u.String()
|
||||
}
|
||||
u.Path = "/" + zone + "/" + strings.TrimPrefix(cleanPath, "/")
|
||||
if dir && !strings.HasSuffix(u.Path, "/") {
|
||||
u.Path += "/"
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) cdnURL(path string) string {
|
||||
u := *d.cdnBase
|
||||
cleanPath := cleanObjectPath(path)
|
||||
basePath := trimCDNBasePath(u.Path, d.GetStorage().MountPath)
|
||||
if cleanPath == "/" {
|
||||
if basePath == "" {
|
||||
u.Path = "/"
|
||||
} else {
|
||||
u.Path = basePath + "/"
|
||||
}
|
||||
return u.String()
|
||||
}
|
||||
u.Path = basePath + "/" + strings.TrimPrefix(cleanPath, "/")
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) authRequest() *resty.Request {
|
||||
return d.client.R().SetHeader("AccessKey", d.AccessKey)
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) handleResponseError(resp *resty.Response) error {
|
||||
if resp == nil {
|
||||
return fmt.Errorf("empty response")
|
||||
}
|
||||
if resp.StatusCode() >= http.StatusOK && resp.StatusCode() < http.StatusMultipleChoices {
|
||||
return nil
|
||||
}
|
||||
message := strings.TrimSpace(resp.String())
|
||||
var apiErrors []apiError
|
||||
if err := json.Unmarshal(resp.Body(), &apiErrors); err == nil && len(apiErrors) > 0 && apiErrors[0].Message != "" {
|
||||
message = apiErrors[0].Message
|
||||
}
|
||||
switch resp.StatusCode() {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return errs.NewErr(errs.PermissionDenied, "bunny storage request failed: %s", message)
|
||||
case http.StatusNotFound:
|
||||
return errs.NewErr(errs.ObjectNotFound, "bunny storage request failed: %s", message)
|
||||
default:
|
||||
return fmt.Errorf("bunny storage request failed: %s: %s", resp.Status(), message)
|
||||
}
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) parseTimes(item bunnyObject) parsedTimes {
|
||||
return parsedTimes{
|
||||
modified: parseBunnyTime(item.LastChanged, d.Modified),
|
||||
created: parseBunnyTime(item.DateCreated, time.Time{}),
|
||||
}
|
||||
}
|
||||
|
||||
func parseBunnyTime(value string, fallback time.Time) time.Time {
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
if t, err := time.Parse(time.RFC3339Nano, value); err == nil {
|
||||
return t
|
||||
}
|
||||
if t, err := time.Parse("2006-01-02T15:04:05.999999999", value); err == nil {
|
||||
return t
|
||||
}
|
||||
if t, err := time.Parse("2006-01-02T15:04:05", value); err == nil {
|
||||
return t
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) toObj(parentPath string, item bunnyObject) model.Obj {
|
||||
times := d.parseTimes(item)
|
||||
return &model.Object{
|
||||
ID: item.Guid,
|
||||
Path: stdpath.Join(parentPath, item.ObjectName),
|
||||
Name: item.ObjectName,
|
||||
Size: item.Length,
|
||||
Modified: times.modified,
|
||||
Ctime: times.created,
|
||||
IsFolder: item.IsDirectory,
|
||||
}
|
||||
}
|
||||
|
||||
func canonicalQuery(values url.Values) (string, error) {
|
||||
keys := make([]string, 0, len(values))
|
||||
for key := range values {
|
||||
if key == "token" || key == "expires" {
|
||||
continue
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
vals := values[key]
|
||||
if len(vals) > 1 {
|
||||
return "", fmt.Errorf("duplicate query parameter %q is not supported", key)
|
||||
}
|
||||
value := ""
|
||||
if len(vals) == 1 {
|
||||
value = vals[0]
|
||||
}
|
||||
parts = append(parts, key+"="+value)
|
||||
}
|
||||
return strings.Join(parts, "&"), nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) signCDNURL(rawURL string, clientIP string) (string, time.Duration, error) {
|
||||
return d.signCDNURLAt(rawURL, clientIP, time.Now())
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) signCDNURLAt(rawURL string, clientIP string, now time.Time) (string, time.Duration, error) {
|
||||
expire := time.Hour * time.Duration(d.SignURLExpire)
|
||||
if expire <= 0 {
|
||||
expire = 4 * time.Hour
|
||||
}
|
||||
expires := now.Add(expire).Unix()
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
query := u.Query()
|
||||
parameterData, err := canonicalQuery(query)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
signaturePath, err := url.PathUnescape(u.EscapedPath())
|
||||
if err != nil {
|
||||
signaturePath = u.Path
|
||||
}
|
||||
if !d.CDNTokenIncludeIP {
|
||||
clientIP = ""
|
||||
}
|
||||
token := d.signCDNToken(signaturePath, strconv.FormatInt(expires, 10), parameterData, clientIP)
|
||||
query.Set("token", token)
|
||||
query.Set("expires", strconv.FormatInt(expires, 10))
|
||||
u.RawQuery = query.Encode()
|
||||
return u.String(), expire, nil
|
||||
}
|
||||
|
||||
func (d *BunnyStorage) signCDNToken(signaturePath string, expires string, parameterData string, clientIP string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(d.CDNTokenMethod)) {
|
||||
case cdnTokenMethodHMACSHA256:
|
||||
message := signaturePath + expires + parameterData + clientIP
|
||||
mac := hmac.New(sha256.New, []byte(d.CDNTokenKey))
|
||||
_, _ = mac.Write([]byte(message))
|
||||
return "HS256-" + base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
|
||||
default:
|
||||
hashableBase := d.CDNTokenKey + signaturePath + expires + parameterData + clientIP
|
||||
sum := sha256.Sum256([]byte(hashableBase))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
package bunny_storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
)
|
||||
|
||||
func TestStorageURL(t *testing.T) {
|
||||
endpoint, err := normalizeBaseURL("ny.storage.bunnycdn.com", defaultEndpoint)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
driver := &BunnyStorage{
|
||||
Addition: Addition{
|
||||
StorageZoneName: "my-zone",
|
||||
},
|
||||
endpoint: endpoint,
|
||||
}
|
||||
if got, want := driver.storageURL("/", true), "https://ny.storage.bunnycdn.com/my-zone/"; got != want {
|
||||
t.Fatalf("root list url = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := driver.storageURL("/dir/a file.txt", false), "https://ny.storage.bunnycdn.com/my-zone/dir/a%20file.txt"; got != want {
|
||||
t.Fatalf("file url = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := driver.storageURL("/dir", true), "https://ny.storage.bunnycdn.com/my-zone/dir/"; got != want {
|
||||
t.Fatalf("dir url = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCDNURLWithBasePath(t *testing.T) {
|
||||
cdnBase, err := normalizeBaseURL("https://cdn.example.com/prefix/", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
driver := &BunnyStorage{cdnBase: cdnBase}
|
||||
if got, want := driver.cdnURL("/dir/a file.txt"), "https://cdn.example.com/prefix/dir/a%20file.txt"; got != want {
|
||||
t.Fatalf("cdn url = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCDNURLUsesObjectPathWithoutMountPath(t *testing.T) {
|
||||
cdnBase, err := normalizeBaseURL("https://cdn.firmant.me", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
driver := &BunnyStorage{
|
||||
Storage: model.Storage{MountPath: "/BS"},
|
||||
cdnBase: cdnBase,
|
||||
}
|
||||
if got, want := driver.cdnURL(driver.cdnObjectPath("/BS/Video")), "https://cdn.firmant.me/Video"; got != want {
|
||||
t.Fatalf("cdn url = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCDNURLDropsMountPathFromBaseURL(t *testing.T) {
|
||||
cdnBase, err := normalizeBaseURL("https://cdn.firmant.me/BS/", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
driver := &BunnyStorage{
|
||||
Storage: model.Storage{MountPath: "/BS"},
|
||||
cdnBase: cdnBase,
|
||||
}
|
||||
if got, want := driver.cdnURL(driver.cdnObjectPath("/Video")), "https://cdn.firmant.me/Video"; got != want {
|
||||
t.Fatalf("cdn url = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCDNObjectPathKeepsRootFolderPath(t *testing.T) {
|
||||
driver := &BunnyStorage{}
|
||||
driver.MountPath = "/BS"
|
||||
driver.RootFolderPath = "/library"
|
||||
if got, want := driver.cdnObjectPath("/BS/Video"), "/library/Video"; got != want {
|
||||
t.Fatalf("cdn object path = %q, want %q", got, want)
|
||||
}
|
||||
if got, want := driver.cdnObjectPath("/library/Video"), "/library/Video"; got != want {
|
||||
t.Fatalf("cdn object path = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLinkDisablesLongLivedCache(t *testing.T) {
|
||||
cdnBase, err := normalizeBaseURL("https://cdn.example.com", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
driver := &BunnyStorage{cdnBase: cdnBase}
|
||||
link, err := driver.Link(context.Background(), &model.Object{
|
||||
Path: "/video.mp4",
|
||||
Name: "video.mp4",
|
||||
Size: 123,
|
||||
}, model.LinkArgs{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if link.Expiration == nil || *link.Expiration != 0 {
|
||||
t.Fatalf("link expiration = %v, want immediate cache expiration", link.Expiration)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignCDNURL(t *testing.T) {
|
||||
driver := &BunnyStorage{
|
||||
Addition: Addition{
|
||||
CDNTokenKey: "secret",
|
||||
CDNTokenIncludeIP: true,
|
||||
SignURLExpire: 1,
|
||||
},
|
||||
}
|
||||
signed, expire, err := driver.signCDNURLAt("https://zone.b-cdn.net/video.mp4?quality=high", "192.0.2.1", time.Unix(1700000000, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if expire <= 0 {
|
||||
t.Fatal("expected positive expiration")
|
||||
}
|
||||
parsed, err := url.Parse(signed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token := parsed.Query().Get("token")
|
||||
if want := "FxSpFem88zFo6uHFziwTuoMQTgDaD2PEn5n1zTMBUBI"; token != want {
|
||||
t.Fatalf("token = %q, want %q", token, want)
|
||||
}
|
||||
if parsed.Query().Get("expires") != "1700003600" {
|
||||
t.Fatalf("expires = %q, want 1700003600", parsed.Query().Get("expires"))
|
||||
}
|
||||
if parsed.Query().Get("quality") != "high" {
|
||||
t.Fatal("expected existing query parameters to be preserved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignCDNURLSupportsHMACSHA256(t *testing.T) {
|
||||
driver := &BunnyStorage{
|
||||
Addition: Addition{
|
||||
CDNTokenKey: "secret",
|
||||
CDNTokenMethod: cdnTokenMethodHMACSHA256,
|
||||
CDNTokenIncludeIP: true,
|
||||
SignURLExpire: 1,
|
||||
},
|
||||
}
|
||||
signed, _, err := driver.signCDNURLAt("https://zone.b-cdn.net/video.mp4?quality=high", "192.0.2.1", time.Unix(1700000000, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, err := url.Parse(signed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := parsed.Query().Get("token"), "HS256-sdrSSJE2JVwhSk2AoDUrmTV1muH6R5UHpZVcVfHeNxg"; got != want {
|
||||
t.Fatalf("token = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignCDNURLUsesDecodedPathForSHA256(t *testing.T) {
|
||||
driver := &BunnyStorage{
|
||||
Addition: Addition{
|
||||
CDNTokenKey: "secret",
|
||||
SignURLExpire: 1,
|
||||
},
|
||||
}
|
||||
signed, _, err := driver.signCDNURLAt("https://zone.b-cdn.net/%E8%A7%86%E9%A2%91/%5Ba%20b%5D.mp4", "", time.Unix(1700000000, 0))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parsed, err := url.Parse(signed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := parsed.Query().Get("token"), "yq1evD7klw0e3DjCbv8dJptbW4S4JwVW3GKLnxfeKGM"; got != want {
|
||||
t.Fatalf("token = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignCDNURLTreatsPlusAsLiteralPathCharacter(t *testing.T) {
|
||||
driver := &BunnyStorage{
|
||||
Addition: Addition{
|
||||
CDNTokenKey: "secret",
|
||||
SignURLExpire: 1,
|
||||
},
|
||||
}
|
||||
now := time.Unix(1700000000, 0)
|
||||
literal, _, err := driver.signCDNURLAt("https://zone.b-cdn.net/a+b.mp4", "", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, _, err := driver.signCDNURLAt("https://zone.b-cdn.net/a%2Bb.mp4", "", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
space, _, err := driver.signCDNURLAt("https://zone.b-cdn.net/a%20b.mp4", "", now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
literalURL, err := url.Parse(literal)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encodedURL, err := url.Parse(encoded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spaceURL, err := url.Parse(space)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, want := literalURL.Query().Get("token"), encodedURL.Query().Get("token"); got != want {
|
||||
t.Fatalf("literal plus token = %q, encoded plus token = %q", got, want)
|
||||
}
|
||||
if got, notWant := literalURL.Query().Get("token"), spaceURL.Query().Get("token"); got == notWant {
|
||||
t.Fatalf("literal plus token = %q, space token should differ", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignCDNURLRejectsDuplicateQueryParameters(t *testing.T) {
|
||||
driver := &BunnyStorage{
|
||||
Addition: Addition{
|
||||
CDNTokenKey: "secret",
|
||||
SignURLExpire: 1,
|
||||
},
|
||||
}
|
||||
_, _, err := driver.signCDNURLAt("https://zone.b-cdn.net/video.mp4?quality=high&quality=low", "", time.Unix(1700000000, 0))
|
||||
if err == nil {
|
||||
t.Fatal("expected duplicate query parameters to be rejected")
|
||||
}
|
||||
if got, want := err.Error(), `duplicate query parameter "quality" is not supported`; got != want {
|
||||
t.Fatalf("error = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseBunnyTimeSupportsFractionalSecondsWithoutTimezone(t *testing.T) {
|
||||
fallback := time.Unix(1, 0)
|
||||
got := parseBunnyTime("2023-03-21T13:38:31.693", fallback)
|
||||
want := time.Date(2023, 3, 21, 13, 38, 31, 693000000, time.UTC)
|
||||
if !got.Equal(want) {
|
||||
t.Fatalf("parsed time = %s, want %s", got.Format(time.RFC3339Nano), want.Format(time.RFC3339Nano))
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigProxyMode(t *testing.T) {
|
||||
registeredConfig := (&BunnyStorage{}).Config()
|
||||
if registeredConfig.OnlyProxy {
|
||||
t.Fatal("driver registration config should allow users to choose proxy policy")
|
||||
}
|
||||
withoutCDN := (&BunnyStorage{Addition: Addition{StorageZoneName: "my-zone"}}).Config()
|
||||
if !withoutCDN.OnlyProxy {
|
||||
t.Fatal("storage API links require AccessKey headers and should be proxied without CDN")
|
||||
}
|
||||
withCDN := (&BunnyStorage{Addition: Addition{StorageZoneName: "my-zone", CDNBaseURL: "https://zone.b-cdn.net"}}).Config()
|
||||
if withCDN.OnlyProxy {
|
||||
t.Fatal("CDN links should be allowed to redirect directly")
|
||||
}
|
||||
}
|
||||
+73
-35
@@ -105,44 +105,82 @@ func (ios *int_str) UnmarshalJSON(data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 时间戳同样存在字符串/数字两种形式,且毫秒级时间戳会超出 int32 范围,需用 int64 解析
|
||||
// 超星 API 返回的 uploadDate 有三种格式:
|
||||
// 1. 数字时间戳:1780191356415
|
||||
// 2. 字符串时间戳:"1780191356415"
|
||||
// 3. 日期字符串:"2024-11-06 07:49"
|
||||
type int64_str int64
|
||||
|
||||
func (ios *int64_str) UnmarshalJSON(data []byte) error {
|
||||
// 去除引号
|
||||
str := string(bytes.Trim(data, "\""))
|
||||
|
||||
// 尝试直接解析为数字(处理格式 1 和 2)
|
||||
intValue, err := strconv.ParseInt(str, 10, 64)
|
||||
if err == nil {
|
||||
*ios = int64_str(intValue)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 尝试解析日期字符串(处理格式 3)
|
||||
// 支持格式:"2024-11-06 07:49" 或 "2024-11-06 07:49:30"
|
||||
layouts := []string{
|
||||
"2006-01-02 15:04",
|
||||
"2006-01-02 15:04:05",
|
||||
}
|
||||
|
||||
for _, layout := range layouts {
|
||||
if t, err := time.Parse(layout, str); err == nil {
|
||||
// 转换为毫秒时间戳
|
||||
*ios = int64_str(t.UnixMilli())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// 所有格式都失败,返回 0(避免因时间格式问题导致整个解析失败)
|
||||
*ios = 0
|
||||
return nil
|
||||
}
|
||||
|
||||
type File struct {
|
||||
Cataid int `json:"cataid"`
|
||||
Cfid int `json:"cfid"`
|
||||
Content struct {
|
||||
Cfid int `json:"cfid"`
|
||||
Pid int `json:"pid"`
|
||||
FolderName string `json:"folderName"`
|
||||
ShareType int `json:"shareType"`
|
||||
Preview string `json:"preview"`
|
||||
Filetype string `json:"filetype"`
|
||||
PreviewURL string `json:"previewUrl"`
|
||||
IsImg bool `json:"isImg"`
|
||||
ParentPath string `json:"parentPath"`
|
||||
Icon string `json:"icon"`
|
||||
Suffix string `json:"suffix"`
|
||||
Duration int `json:"duration"`
|
||||
Pantype string `json:"pantype"`
|
||||
Puid int_str `json:"puid"`
|
||||
Filepath string `json:"filepath"`
|
||||
Crc string `json:"crc"`
|
||||
Isfile bool `json:"isfile"`
|
||||
Residstr string `json:"residstr"`
|
||||
ObjectID string `json:"objectId"`
|
||||
Extinfo string `json:"extinfo"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Creator int `json:"creator"`
|
||||
ResTypeValue int `json:"resTypeValue"`
|
||||
UploadDateFormat string `json:"uploadDateFormat"`
|
||||
DisableOpt bool `json:"disableOpt"`
|
||||
DownPath string `json:"downPath"`
|
||||
Sort int `json:"sort"`
|
||||
Topsort int `json:"topsort"`
|
||||
Restype string `json:"restype"`
|
||||
Size int_str `json:"size"`
|
||||
UploadDate int64 `json:"uploadDate"`
|
||||
FileSize string `json:"fileSize"`
|
||||
Name string `json:"name"`
|
||||
FileID string `json:"fileId"`
|
||||
Cfid int `json:"cfid"`
|
||||
Pid int `json:"pid"`
|
||||
FolderName string `json:"folderName"`
|
||||
ShareType int `json:"shareType"`
|
||||
Preview string `json:"preview"`
|
||||
Filetype string `json:"filetype"`
|
||||
PreviewURL string `json:"previewUrl"`
|
||||
IsImg bool `json:"isImg"`
|
||||
ParentPath string `json:"parentPath"`
|
||||
Icon string `json:"icon"`
|
||||
Suffix string `json:"suffix"`
|
||||
Duration int `json:"duration"`
|
||||
Pantype string `json:"pantype"`
|
||||
Puid int_str `json:"puid"`
|
||||
Filepath string `json:"filepath"`
|
||||
Crc string `json:"crc"`
|
||||
Isfile bool `json:"isfile"`
|
||||
Residstr string `json:"residstr"`
|
||||
ObjectID string `json:"objectId"`
|
||||
Extinfo string `json:"extinfo"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Creator int `json:"creator"`
|
||||
ResTypeValue int `json:"resTypeValue"`
|
||||
UploadDateFormat string `json:"uploadDateFormat"`
|
||||
DisableOpt bool `json:"disableOpt"`
|
||||
DownPath string `json:"downPath"`
|
||||
Sort int `json:"sort"`
|
||||
Topsort int `json:"topsort"`
|
||||
Restype string `json:"restype"`
|
||||
Size int_str `json:"size"`
|
||||
UploadDate int64_str `json:"uploadDate"`
|
||||
FileSize string `json:"fileSize"`
|
||||
Name string `json:"name"`
|
||||
FileID string `json:"fileId"`
|
||||
} `json:"content"`
|
||||
CreatorID int `json:"creatorId"`
|
||||
DesID string `json:"des_id"`
|
||||
@@ -265,7 +303,7 @@ func fileToObj(f File) *model.Object {
|
||||
IsFolder: true,
|
||||
}
|
||||
}
|
||||
paserTime := time.UnixMilli(f.Content.UploadDate)
|
||||
paserTime := time.UnixMilli(int64(f.Content.UploadDate))
|
||||
return &model.Object{
|
||||
ID: fmt.Sprintf("%d$%s", f.ID, f.Content.FileID),
|
||||
Name: f.Content.Name,
|
||||
|
||||
+64
-15
@@ -53,8 +53,8 @@ func (d *Chunk) Drop(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (Addition) GetRootPath() string {
|
||||
return "/"
|
||||
func (*Chunk) GetRootPath() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func (d *Chunk) Get(ctx context.Context, path string) (model.Obj, error) {
|
||||
@@ -80,7 +80,7 @@ func (d *Chunk) Get(ctx context.Context, path string) (model.Obj, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var totalSize int64 = 0
|
||||
var totalSize int64
|
||||
// 0号块默认为-1 以支持空文件
|
||||
chunkSizes := []int64{-1}
|
||||
h := make(map[*utils.HashType]string)
|
||||
@@ -119,6 +119,25 @@ func (d *Chunk) Get(ctx context.Context, path string) (model.Obj, error) {
|
||||
}
|
||||
}
|
||||
reqDir, _ := stdpath.Split(path)
|
||||
// 文件块不完整时,返回文件夹对象
|
||||
if chunkSizes[0] == -1 {
|
||||
return &model.Object{
|
||||
Path: stdpath.Join(reqDir, chunkName),
|
||||
Name: chunkName,
|
||||
IsFolder: true,
|
||||
Modified: d.Modified,
|
||||
}, nil
|
||||
}
|
||||
for i, l := 1, len(chunkSizes)-1; i < l; i++ {
|
||||
if chunkSizes[i] == 0 {
|
||||
return &model.Object{
|
||||
Path: stdpath.Join(reqDir, chunkName),
|
||||
Name: chunkName,
|
||||
IsFolder: true,
|
||||
Modified: d.Modified,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
objRes := chunkObject{
|
||||
Object: model.Object{
|
||||
Path: stdpath.Join(reqDir, chunkName),
|
||||
@@ -161,37 +180,69 @@ func (d *Chunk) List(ctx context.Context, dir model.Obj, args model.ListArgs) ([
|
||||
result = append(result, nil)
|
||||
listG.Go(func(ctx context.Context) error {
|
||||
chunkObjs, err := op.List(ctx, remoteStorage, stdpath.Join(remoteActualDir, rawName), model.ListArgs{
|
||||
ReqPath: stdpath.Join(args.ReqPath, rawName),
|
||||
Refresh: args.Refresh,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
totalSize := int64(0)
|
||||
var totalSize int64
|
||||
// 0号块默认为-1 以支持空文件
|
||||
chunkSizes := []int64{-1}
|
||||
h := make(map[*utils.HashType]string)
|
||||
first := obj
|
||||
var first model.Obj
|
||||
for _, o := range chunkObjs {
|
||||
if o.IsDir() {
|
||||
continue
|
||||
}
|
||||
if after, ok := strings.CutPrefix(strings.TrimSuffix(o.GetName(), d.CustomExt), "hash_"); ok {
|
||||
hn, value, ok := strings.Cut(after, "_")
|
||||
if after, ok := strings.CutPrefix(o.GetName(), "hash_"); ok {
|
||||
hn, value, ok := strings.Cut(strings.TrimSuffix(after, d.CustomExt), "_")
|
||||
if ok {
|
||||
ht, ok := utils.GetHashByName(hn)
|
||||
if ok {
|
||||
h[ht] = value
|
||||
}
|
||||
continue
|
||||
}
|
||||
continue
|
||||
}
|
||||
idx, err := strconv.Atoi(strings.TrimSuffix(o.GetName(), d.CustomExt))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if idx == 0 {
|
||||
first = o
|
||||
}
|
||||
totalSize += o.GetSize()
|
||||
if len(chunkSizes) > idx {
|
||||
if idx == 0 {
|
||||
first = o
|
||||
}
|
||||
chunkSizes[idx] = o.GetSize()
|
||||
} else if len(chunkSizes) == idx {
|
||||
chunkSizes = append(chunkSizes, o.GetSize())
|
||||
} else {
|
||||
newChunkSizes := make([]int64, idx+1)
|
||||
copy(newChunkSizes, chunkSizes)
|
||||
chunkSizes = newChunkSizes
|
||||
chunkSizes[idx] = o.GetSize()
|
||||
}
|
||||
}
|
||||
// 文件块不完整时,返回文件夹对象
|
||||
if chunkSizes[0] == -1 {
|
||||
result[resultIdx] = &model.Object{
|
||||
Name: rawName,
|
||||
Size: obj.GetSize(),
|
||||
Modified: obj.ModTime(),
|
||||
IsFolder: true,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for i, l := 1, len(chunkSizes)-1; i < l; i++ {
|
||||
if chunkSizes[i] == 0 {
|
||||
result[resultIdx] = &model.Object{
|
||||
Name: rawName,
|
||||
Size: obj.GetSize(),
|
||||
Modified: obj.ModTime(),
|
||||
IsFolder: true,
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
objRes := model.Object{
|
||||
Name: name,
|
||||
@@ -263,9 +314,7 @@ func (d *Chunk) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resultLink := *l
|
||||
resultLink.SyncClosers = utils.NewSyncClosers(l)
|
||||
return &resultLink, nil
|
||||
return l.Clone(), nil
|
||||
}
|
||||
// 检查0号块不等于-1 以支持空文件
|
||||
// 如果块数量大于1 最后一块不可能为0
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package cloudflare_imgbed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/cache"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/errs"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
type CFImgBed struct {
|
||||
model.Storage
|
||||
Addition
|
||||
client *resty.Client
|
||||
virtualDir *cache.WeakCacheMap[string, model.Object]
|
||||
publicUrlPrefix string
|
||||
}
|
||||
|
||||
func (d *CFImgBed) Config() driver.Config { return config }
|
||||
func (d *CFImgBed) GetAddition() driver.Additional { return &d.Addition }
|
||||
|
||||
func (d *CFImgBed) Init(ctx context.Context) error {
|
||||
d.UploadThread = min(d.UploadThread, 32)
|
||||
if d.UploadThread < 1 {
|
||||
d.UploadThread = 3
|
||||
}
|
||||
d.Address = strings.TrimRight(d.Address, "/")
|
||||
|
||||
d.client = base.NewRestyClient().
|
||||
SetBaseURL(d.Address).
|
||||
SetHeader("Authorization", "Bearer "+d.Token).
|
||||
SetDebug(false)
|
||||
|
||||
// 连通性测试:尝试获取根目录单条数据
|
||||
_, err := d.doRequest(ctx, http.MethodGet, listApi, func(req *resty.Request) {
|
||||
req.SetQueryParams(map[string]string{
|
||||
"start": "0",
|
||||
"count": "1",
|
||||
"dir": "/",
|
||||
})
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("init verification failed: %w", err)
|
||||
}
|
||||
d.virtualDir = cache.NewWeakCacheMap[string, model.Object]()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *CFImgBed) Drop(ctx context.Context) error {
|
||||
if d.virtualDir != nil {
|
||||
d.virtualDir.Clear()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *CFImgBed) List(ctx context.Context, dir model.Obj, args model.ListArgs) ([]model.Obj, error) {
|
||||
// if !args.Refresh && model.ObjHasMask(dir, model.Virtual) {
|
||||
// if _, ok := d.virtualDir.Load(dir.GetPath()); ok {
|
||||
// return nil, nil
|
||||
// }
|
||||
// }
|
||||
|
||||
var dirSeen map[string]bool
|
||||
var fileSeen map[string]bool
|
||||
var objs []model.Obj
|
||||
|
||||
start := 0
|
||||
for {
|
||||
var resp ListResponse
|
||||
_, err := d.doRequest(ctx, http.MethodGet, listApi, func(req *resty.Request) {
|
||||
req.SetQueryParams(map[string]string{
|
||||
"dir": dir.GetPath(),
|
||||
"start": fmt.Sprintf("%d", start),
|
||||
"count": fmt.Sprintf("%d", listPageSize),
|
||||
})
|
||||
}, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(resp.Files) == 0 && len(resp.Directories) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
if start == 0 {
|
||||
dirSeen = make(map[string]bool, len(resp.Directories))
|
||||
fileSeen = make(map[string]bool, len(resp.Files))
|
||||
objs = make([]model.Obj, 0, len(resp.Directories)+len(resp.Files))
|
||||
}
|
||||
|
||||
for _, rawDir := range resp.Directories {
|
||||
rawDir = "/" + strings.TrimRight(rawDir, "/")
|
||||
if !dirSeen[rawDir] {
|
||||
dirSeen[rawDir] = true
|
||||
objs = append(objs, &model.Object{
|
||||
Path: rawDir,
|
||||
Name: path.Base(rawDir),
|
||||
Modified: d.Modified,
|
||||
IsFolder: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
for _, item := range resp.Files {
|
||||
if !fileSeen[item.Name] {
|
||||
fileSeen[item.Name] = true
|
||||
objs = append(objs, parseFile(item))
|
||||
}
|
||||
}
|
||||
|
||||
// 如果当前获取的数量少于分页大小,说明已加载完毕
|
||||
if len(resp.Files)+len(resp.Directories) < listPageSize {
|
||||
break
|
||||
}
|
||||
start += listPageSize
|
||||
}
|
||||
return objs, nil
|
||||
}
|
||||
|
||||
func (d *CFImgBed) Link(ctx context.Context, file model.Obj, args model.LinkArgs) (*model.Link, error) {
|
||||
if d.publicUrlPrefix != "" {
|
||||
return &model.Link{URL: d.publicUrlPrefix + utils.EncodePath(file.GetPath())}, nil
|
||||
}
|
||||
return &model.Link{URL: d.Address + "/file" + utils.EncodePath(file.GetPath())}, nil
|
||||
}
|
||||
|
||||
func (d *CFImgBed) Get(ctx context.Context, pathStr string) (model.Obj, error) {
|
||||
fullPath := path.Join(d.RootFolderPath, pathStr)
|
||||
if obj, found := d.virtualDir.Load(fullPath); found {
|
||||
return obj, nil
|
||||
}
|
||||
return nil, errs.NotSupport
|
||||
}
|
||||
|
||||
// MakeDir 在图床中通常是虚拟的,此处返回虚拟目录对象以支持上传时的路径展示
|
||||
func (d *CFImgBed) MakeDir(ctx context.Context, parentDir model.Obj, dirName string) (model.Obj, error) {
|
||||
fullPath := path.Join(parentDir.GetPath(), dirName)
|
||||
temp := &model.Object{
|
||||
Path: fullPath,
|
||||
Name: dirName,
|
||||
IsFolder: true,
|
||||
Modified: d.Modified,
|
||||
Mask: model.Virtual,
|
||||
}
|
||||
d.virtualDir.Store(fullPath, temp)
|
||||
return temp, nil
|
||||
}
|
||||
|
||||
func (d *CFImgBed) Remove(ctx context.Context, obj model.Obj) error {
|
||||
reqPath := obj.GetPath()
|
||||
if model.ObjHasMask(obj, model.Virtual) {
|
||||
d.virtualDir.Delete(reqPath)
|
||||
return nil
|
||||
}
|
||||
_, err := d.doRequest(ctx, http.MethodPost, deleteApi+utils.EncodePath(reqPath), func(req *resty.Request) {
|
||||
req.SetQueryParam("folder", fmt.Sprintf("%t", obj.IsDir()))
|
||||
}, nil)
|
||||
return err
|
||||
}
|
||||
|
||||
var _ driver.Driver = (*CFImgBed)(nil)
|
||||
@@ -0,0 +1,27 @@
|
||||
package cloudflare_imgbed
|
||||
|
||||
import (
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/op"
|
||||
)
|
||||
|
||||
type Addition struct {
|
||||
driver.RootPath
|
||||
Address string `json:"address" required:"true" help:"Backend API address of the image hosting service, e.g., https://img.example.com"`
|
||||
Token string `json:"token" required:"true" help:"Authentication Token"`
|
||||
SmallChannelName string `json:"smallChannelName" help:"Channel name for regular files (typically <20MB)"`
|
||||
LargeChannelName string `json:"largeChannelName" help:"Channel name for large files"`
|
||||
LargeChannelType string `json:"largeChannelType" type:"select" options:",huggingface,telegram,cfr2,s3,discord" help:"Large File Channel Type: Hugging Face (Direct Upload)、telegram/cfr2/s3/discord(Multipart Upload)"`
|
||||
UploadThread int `json:"uploadThread" type:"number" default:"3" help:"Concurrent thread count for HuggingFace chunked direct upload"`
|
||||
}
|
||||
|
||||
var config = driver.Config{
|
||||
Name: "cloudflare_imgbed",
|
||||
LocalSort: true,
|
||||
NoUpload: false,
|
||||
DefaultRoot: "/",
|
||||
}
|
||||
|
||||
func init() {
|
||||
op.RegisterDriver(func() driver.Driver { return &CFImgBed{} })
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package cloudflare_imgbed
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
)
|
||||
|
||||
const listPageSize = 1000
|
||||
|
||||
// ListResponse 列表接口响应
|
||||
type ListResponse struct {
|
||||
Files []FileItem `json:"files"`
|
||||
Directories []string `json:"directories"`
|
||||
}
|
||||
|
||||
type FileItem struct {
|
||||
Name string `json:"name"`
|
||||
Metadata map[string]interface{} `json:"metadata"` // 存储文件大小、哈希、时间戳等
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// standardUploadResp 标准上传成功返回的数组
|
||||
type standardUploadResp []struct {
|
||||
Src string `json:"src"`
|
||||
PublicUrl string `json:"publicUrl"`
|
||||
}
|
||||
|
||||
// hfGetUrlResp 获取 HF 直传授权地址的响应
|
||||
type hfGetUrlResp struct {
|
||||
Success bool `json:"success"`
|
||||
FullID string `json:"fullId"`
|
||||
FilePath string `json:"filePath"`
|
||||
ChannelName string `json:"channelName"`
|
||||
Repo string `json:"repo"`
|
||||
NeedsLfs bool `json:"needsLfs"` // 是否需要进行 LFS 物理上传
|
||||
AlreadyExists bool `json:"alreadyExists"` // 是否秒传成功
|
||||
Oid string `json:"oid"` // Git LFS 对象 ID (SHA256)
|
||||
UploadAction *UploadAction `json:"uploadAction"`
|
||||
}
|
||||
|
||||
type UploadAction struct {
|
||||
Href string `json:"href"`
|
||||
Header map[string]string `json:"header"`
|
||||
}
|
||||
|
||||
type hfCommitResp struct {
|
||||
Success bool `json:"success"`
|
||||
Src string `json:"src"`
|
||||
PublicUrl string `json:"publicUrl"`
|
||||
FileUrl string `json:"fileUrl"`
|
||||
FullID string `json:"fullId"`
|
||||
}
|
||||
|
||||
// 辅助函数:从 map 中安全提取字符串/数值
|
||||
func getString(m map[string]interface{}, keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
return val
|
||||
case float64:
|
||||
return strconv.FormatInt(int64(val), 10)
|
||||
default:
|
||||
return fmt.Sprintf("%v", val)
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func getInt64(m map[string]interface{}, keys ...string) int64 {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok {
|
||||
switch val := v.(type) {
|
||||
case string:
|
||||
n, _ := strconv.ParseInt(val, 10, 64)
|
||||
return n
|
||||
case float64:
|
||||
return int64(val)
|
||||
case int64:
|
||||
return val
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func parseFile(item FileItem) *model.Object {
|
||||
name := path.Base(item.Name)
|
||||
var size int64
|
||||
var modTime time.Time
|
||||
|
||||
if item.Metadata != nil {
|
||||
size = getInt64(item.Metadata, "FileSizeBytes", "File-Size")
|
||||
ts := getInt64(item.Metadata, "TimeStamp")
|
||||
if ts > 0 {
|
||||
modTime = time.UnixMilli(ts)
|
||||
}
|
||||
}
|
||||
|
||||
return &model.Object{
|
||||
Path: "/" + strings.TrimRight(item.Name, "/"),
|
||||
Name: name,
|
||||
Size: size,
|
||||
Modified: modTime,
|
||||
IsFolder: false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,560 @@
|
||||
package cloudflare_imgbed
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/driver"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/model"
|
||||
"github.com/OpenListTeam/OpenList/v4/internal/stream"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/errgroup"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/http_range"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/utils"
|
||||
"github.com/avast/retry-go"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (d *CFImgBed) Put(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress) (newObj model.Obj, err error) {
|
||||
if file.GetSize() < hfDirectThreshold {
|
||||
newObj, err = d.standardUpload(ctx, dstDir, file, up)
|
||||
} else {
|
||||
switch d.LargeChannelType {
|
||||
case "huggingface":
|
||||
newObj, err = d.hfDirectUpload(ctx, dstDir, file, up)
|
||||
case "telegram", "cfr2", "s3", "discord":
|
||||
newObj, err = d.chunkedUpload(ctx, dstDir, file, up, d.LargeChannelType, d.LargeChannelName)
|
||||
default:
|
||||
newObj, err = d.standardUpload(ctx, dstDir, file, up)
|
||||
}
|
||||
}
|
||||
if newObj != nil && model.ObjHasMask(dstDir, model.Virtual) {
|
||||
key := dstDir.GetPath()
|
||||
for d.virtualDir.Delete(key) {
|
||||
key = path.Dir(key)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// standardUpload 通过普通 multipart 表单上传。
|
||||
// 使用 io.MultiReader 实现虚拟拼接,避免将整个大文件读入内存构建表单。
|
||||
func (d *CFImgBed) standardUpload(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress) (model.Obj, error) {
|
||||
|
||||
channelName := d.SmallChannelName
|
||||
if file.GetSize() >= hfDirectThreshold {
|
||||
channelName = d.LargeChannelName
|
||||
log.WithField("size", file.GetSize()).Warn("large file falls back to standard upload, consider configuring LargeChannelType")
|
||||
}
|
||||
if channelName == "" {
|
||||
return nil, fmt.Errorf("channel name not configured")
|
||||
}
|
||||
|
||||
// 1. 将参数放入 Query String
|
||||
reqUrl, err := url.Parse(d.Address + uploadApi)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := reqUrl.Query()
|
||||
q.Set("returnFormat", "default")
|
||||
q.Set("channelName", channelName)
|
||||
q.Set("uploadFolder", dstDir.GetPath())
|
||||
q.Set("autoRetry", "true")
|
||||
reqUrl.RawQuery = q.Encode()
|
||||
|
||||
// 2. 构建 multipart 表单的头部
|
||||
b := bytes.NewBuffer(make([]byte, 0, 164+len(file.GetName()))) // 预估头部大小,避免频繁扩容
|
||||
w := multipart.NewWriter(b)
|
||||
_, err = w.CreateFormFile("file", file.GetName())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
headSize := b.Len()
|
||||
err = w.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
head := bytes.NewReader(b.Bytes()[:headSize])
|
||||
tail := bytes.NewReader(b.Bytes()[headSize:])
|
||||
|
||||
// 3. 将 [表单头 + 文件流 + 表单尾] 组合成单一 Reader
|
||||
rateLimitedReader := driver.NewLimitedUploadStream(ctx, &driver.ReaderUpdatingProgress{
|
||||
Reader: &driver.SimpleReaderWithSize{
|
||||
Reader: io.MultiReader(head, file, tail),
|
||||
Size: int64(b.Len()) + file.GetSize(),
|
||||
},
|
||||
UpdateProgress: up,
|
||||
})
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqUrl.String(), rateLimitedReader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
req.Header.Set("Authorization", "Bearer "+d.Token)
|
||||
req.ContentLength = int64(b.Len()) + file.GetSize()
|
||||
res, err := base.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
b.Reset()
|
||||
_, err = b.ReadFrom(res.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("upload failed %d: %s", res.StatusCode, b.String())
|
||||
}
|
||||
|
||||
var resp standardUploadResp
|
||||
if err := json.Unmarshal(b.Bytes(), &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(resp) == 0 || resp[0].Src == "" {
|
||||
return nil, fmt.Errorf("no src returned")
|
||||
}
|
||||
|
||||
srcPath := strings.TrimPrefix(resp[0].Src, "/file/")
|
||||
srcPath = strings.TrimPrefix(srcPath, "/")
|
||||
|
||||
if resp[0].PublicUrl != "" {
|
||||
if u, err := url.Parse(resp[0].PublicUrl); err == nil {
|
||||
d.publicUrlPrefix = u.Scheme + "://" + u.Host
|
||||
}
|
||||
}
|
||||
|
||||
return &model.Object{
|
||||
Path: srcPath,
|
||||
Name: file.GetName(),
|
||||
Size: file.GetSize(),
|
||||
Modified: file.ModTime(),
|
||||
IsFolder: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *CFImgBed) chunkedUpload(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress, channelType, channelName string) (model.Obj, error) {
|
||||
if channelName == "" {
|
||||
return nil, fmt.Errorf("channel name not configured for chunked upload")
|
||||
}
|
||||
|
||||
fileSize := file.GetSize()
|
||||
fileMime := file.GetMimetype()
|
||||
fileName := file.GetName()
|
||||
|
||||
var chunkSizeMap = map[string]int64{
|
||||
|
||||
}
|
||||
chunkSize := chunkSizeMap[channelType]
|
||||
if chunkSize == 0 {
|
||||
chunkSize = 5 * 1024 * 1024
|
||||
}
|
||||
totalChunks := int((fileSize + chunkSize - 1) / chunkSize)
|
||||
|
||||
// 第一步:initChunked
|
||||
var initResp struct {
|
||||
Success bool `json:"success"`
|
||||
UploadId string `json:"uploadId"`
|
||||
}
|
||||
_, err := d.doRequest(ctx, http.MethodPost, uploadApi, func(req *resty.Request) {
|
||||
req.SetQueryParams(map[string]string{
|
||||
"initChunked": "true",
|
||||
"uploadChannel": channelType,
|
||||
"channelName": channelName,
|
||||
})
|
||||
req.SetFormData(map[string]string{
|
||||
"originalFileName": fileName,
|
||||
"originalFileType": fileMime,
|
||||
"totalChunks": strconv.Itoa(totalChunks),
|
||||
})
|
||||
}, &initResp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("initChunked failed: %w", err)
|
||||
}
|
||||
if !initResp.Success || initResp.UploadId == "" {
|
||||
return nil, fmt.Errorf("initChunked returned no uploadId")
|
||||
}
|
||||
uploadId := initResp.UploadId
|
||||
|
||||
// 第二步:逐块上传
|
||||
ss, err := stream.NewStreamSectionReader(file, int(chunkSize), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reqUrl := d.Address + uploadApi + "?chunked=true&uploadChannel=" + channelType + "&channelName=" + channelName
|
||||
b := bytes.NewBuffer(make([]byte, 0, 2048))
|
||||
|
||||
g, uploadCtx := errgroup.NewOrderedGroupWithContext(ctx, min(d.UploadThread, totalChunks),
|
||||
retry.Attempts(3),
|
||||
retry.Delay(time.Second),
|
||||
retry.DelayType(retry.BackOffDelay))
|
||||
|
||||
for i := 0; i < totalChunks; i++ {
|
||||
if utils.IsCanceled(uploadCtx) {
|
||||
break
|
||||
}
|
||||
chunkIndex := i
|
||||
offset := int64(chunkIndex) * chunkSize
|
||||
sizeToRead := chunkSize
|
||||
if offset+sizeToRead > fileSize {
|
||||
sizeToRead = fileSize - offset
|
||||
}
|
||||
|
||||
var reader io.ReadSeeker
|
||||
g.GoWithLifecycle(errgroup.Lifecycle{
|
||||
Before: func(ctx context.Context) (err error) {
|
||||
reader, err = ss.GetSectionReader(offset, sizeToRead)
|
||||
return
|
||||
},
|
||||
After: func(err error) {
|
||||
ss.FreeSectionReader(reader)
|
||||
},
|
||||
Do: func(ctx context.Context) (err error) {
|
||||
_, err = reader.Seek(0, io.SeekStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
b.Reset()
|
||||
w := multipart.NewWriter(b)
|
||||
_ = w.WriteField("uploadId", uploadId)
|
||||
_ = w.WriteField("chunkIndex", strconv.Itoa(chunkIndex))
|
||||
_ = w.WriteField("totalChunks", strconv.Itoa(totalChunks))
|
||||
_ = w.WriteField("originalFileName", fileName)
|
||||
_ = w.WriteField("originalFileType", fileMime)
|
||||
_, _ = w.CreateFormFile("file", fileName)
|
||||
headSize := b.Len()
|
||||
_ = w.Close()
|
||||
head := bytes.NewReader(b.Bytes()[:headSize])
|
||||
tail := bytes.NewReader(b.Bytes()[headSize:])
|
||||
|
||||
rateLimitedRd := driver.NewLimitedUploadStream(ctx, io.MultiReader(head, reader, tail))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqUrl, rateLimitedRd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
req.Header.Set("Authorization", "Bearer "+d.Token)
|
||||
req.ContentLength = int64(headSize) + sizeToRead + int64(b.Len()-headSize)
|
||||
|
||||
res, err := base.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("chunk %d upload failed: %d", chunkIndex, res.StatusCode)
|
||||
}
|
||||
|
||||
up(90 * float64(chunkIndex+1) / float64(totalChunks))
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if err := g.Wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 第三步:merge
|
||||
var mergeResp standardUploadResp
|
||||
_, err = d.doRequest(ctx, http.MethodPost, uploadApi, func(req *resty.Request) {
|
||||
req.SetQueryParams(map[string]string{
|
||||
"chunked": "true",
|
||||
"merge": "true",
|
||||
"uploadChannel": channelType,
|
||||
"channelName": channelName,
|
||||
"returnFormat": "default",
|
||||
"uploadFolder": dstDir.GetPath(),
|
||||
})
|
||||
req.SetFormData(map[string]string{
|
||||
"uploadId": uploadId,
|
||||
"totalChunks": strconv.Itoa(totalChunks),
|
||||
"originalFileName": fileName,
|
||||
"originalFileType": fileMime,
|
||||
})
|
||||
}, &mergeResp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("merge failed: %w", err)
|
||||
}
|
||||
if len(mergeResp) == 0 || mergeResp[0].Src == "" {
|
||||
return nil, fmt.Errorf("merge returned no src")
|
||||
}
|
||||
|
||||
up(95)
|
||||
|
||||
srcPath := strings.TrimPrefix(mergeResp[0].Src, "/file/")
|
||||
srcPath = strings.TrimPrefix(srcPath, "/")
|
||||
|
||||
if mergeResp[0].PublicUrl != "" {
|
||||
if u, err := url.Parse(mergeResp[0].PublicUrl); err == nil {
|
||||
d.publicUrlPrefix = u.Scheme + "://" + u.Host
|
||||
}
|
||||
}
|
||||
|
||||
return &model.Object{
|
||||
Path: srcPath,
|
||||
Name: fileName,
|
||||
Size: fileSize,
|
||||
Modified: file.ModTime(),
|
||||
IsFolder: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// hfDirectUpload 处理 HuggingFace 的 LFS 直传逻辑(申请授权 -> 物理上传 -> 后端 Commit)
|
||||
func (d *CFImgBed) hfDirectUpload(ctx context.Context, dstDir model.Obj, file model.FileStreamer, up driver.UpdateProgress) (model.Obj, error) {
|
||||
channelName := d.LargeChannelName
|
||||
if channelName == "" {
|
||||
return nil, errors.New("LargeChannelName not configured")
|
||||
}
|
||||
|
||||
sha256Hash := file.GetHash().GetHash(utils.SHA256)
|
||||
if len(sha256Hash) != utils.SHA256.Width {
|
||||
var err error
|
||||
_, sha256Hash, err = stream.CacheFullAndHash(file, &up, utils.SHA256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
fileSize := file.GetSize()
|
||||
sampleSize := min(fileSize, fileSampleSize)
|
||||
sampleRd, err := file.RangeRead(http_range.Range{Start: 0, Length: sampleSize})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sampleBuf := make([]byte, sampleSize)
|
||||
_, err = io.ReadFull(sampleRd, sampleBuf)
|
||||
if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return nil, err
|
||||
}
|
||||
fileSample := base64.StdEncoding.EncodeToString(sampleBuf)
|
||||
|
||||
fileMime := file.GetMimetype()
|
||||
// 1. 请求图床后端获取 HF 授权地址
|
||||
reqBody := map[string]interface{}{
|
||||
"fileName": file.GetName(),
|
||||
"fileType": fileMime,
|
||||
"fileSize": fileSize,
|
||||
"sha256": sha256Hash,
|
||||
"fileSample": fileSample,
|
||||
"channelName": channelName,
|
||||
"uploadFolder": dstDir.GetPath(),
|
||||
}
|
||||
|
||||
var getUrlResp hfGetUrlResp
|
||||
_, err = d.doRequest(ctx, http.MethodPost, hfGetUrlApi, func(req *resty.Request) {
|
||||
req.SetBody(reqBody)
|
||||
req.SetHeader("Content-Type", "application/json")
|
||||
}, &getUrlResp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 秒传逻辑
|
||||
if getUrlResp.AlreadyExists || !getUrlResp.NeedsLfs {
|
||||
up(100)
|
||||
return d.hfCommit(ctx, getUrlResp, file.GetName(), fileSize, fileMime, file.ModTime())
|
||||
}
|
||||
|
||||
if getUrlResp.UploadAction == nil {
|
||||
return nil, fmt.Errorf("HF upload action is nil")
|
||||
}
|
||||
|
||||
headers := getUrlResp.UploadAction.Header
|
||||
href := getUrlResp.UploadAction.Href
|
||||
|
||||
// 2. 根据响应判断是执行分片上传还是单文件上传
|
||||
chunkSizeStr, needChunk := headers["chunk_size"]
|
||||
if needChunk {
|
||||
// 分片直传 (AWS S3 Multipart 风格)
|
||||
chunkSize, _ := strconv.ParseInt(chunkSizeStr, 10, 64)
|
||||
if chunkSize <= 0 {
|
||||
chunkSize = 20 * 1024 * 1024
|
||||
}
|
||||
|
||||
partUrls := make(map[int]string)
|
||||
for k, v := range headers {
|
||||
if k != "chunk_size" {
|
||||
if idx, err := strconv.Atoi(k); err == nil {
|
||||
partUrls[idx] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
totalParts := len(partUrls)
|
||||
|
||||
ss, err := stream.NewStreamSectionReader(file, int(chunkSize), &up)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
g, uploadCtx := errgroup.NewOrderedGroupWithContext(ctx, min(d.UploadThread, totalParts),
|
||||
retry.Attempts(3),
|
||||
retry.Delay(time.Second),
|
||||
retry.DelayType(retry.BackOffDelay))
|
||||
|
||||
parts := make([]map[string]any, totalParts)
|
||||
|
||||
for partNumber := range partUrls {
|
||||
if utils.IsCanceled(uploadCtx) {
|
||||
break
|
||||
}
|
||||
partUrl := partUrls[partNumber]
|
||||
offset := int64(partNumber-1) * chunkSize
|
||||
sizeToRead := chunkSize
|
||||
if offset+sizeToRead > fileSize {
|
||||
sizeToRead = fileSize - offset
|
||||
}
|
||||
|
||||
var reader io.ReadSeeker
|
||||
g.GoWithLifecycle(errgroup.Lifecycle{
|
||||
Before: func(ctx context.Context) (err error) {
|
||||
reader, err = ss.GetSectionReader(offset, sizeToRead)
|
||||
return
|
||||
},
|
||||
After: func(err error) {
|
||||
ss.FreeSectionReader(reader)
|
||||
},
|
||||
Do: func(ctx context.Context) (err error) {
|
||||
_, err = reader.Seek(0, io.SeekStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
limitedReader := driver.NewLimitedUploadStream(ctx, reader)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, partUrl, limitedReader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.ContentLength = sizeToRead
|
||||
|
||||
res, err := base.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("chunk %d failed: %d", partNumber, res.StatusCode)
|
||||
}
|
||||
|
||||
etag := res.Header.Get("ETag")
|
||||
parts[partNumber-1] = map[string]any{"partNumber": partNumber, "etag": etag}
|
||||
|
||||
up(95 * float64(g.Success()+1) / float64(totalParts))
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if err := g.Wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 合并分片
|
||||
// sort.Slice(parts, func(i, j int) bool { return parts[i]["partNumber"].(int) < parts[j]["partNumber"].(int) })
|
||||
mergeBody, _ := json.Marshal(map[string]any{"oid": getUrlResp.Oid, "parts": parts})
|
||||
mergeReq, err := http.NewRequestWithContext(ctx, http.MethodPost, href, bytes.NewReader(mergeBody))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mergeReq.Header.Set("Content-Type", "application/vnd.git-lfs+json")
|
||||
if d.Token != "" {
|
||||
mergeReq.Header.Set("Authorization", "Bearer "+d.Token)
|
||||
}
|
||||
|
||||
res, err := base.HttpClient.Do(mergeReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, _ := io.ReadAll(res.Body) // 读取 HF 返回的错误详情
|
||||
if res.StatusCode != http.StatusOK {
|
||||
log.WithField("status", res.StatusCode).WithField("response", string(body)).Error("HF merge chunks failed")
|
||||
return nil, fmt.Errorf("merge chunks failed: %s", string(body))
|
||||
}
|
||||
up(97)
|
||||
|
||||
} else {
|
||||
// 单文件直传 (PUT)
|
||||
limitedReader := driver.NewLimitedUploadStream(ctx, &driver.ReaderUpdatingProgress{
|
||||
Reader: file,
|
||||
UpdateProgress: model.UpdateProgressWithRange(up, 0, 97),
|
||||
})
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPut, href, limitedReader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.ContentLength = fileSize
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := base.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("direct upload failed")
|
||||
}
|
||||
}
|
||||
|
||||
defer up(100)
|
||||
|
||||
// 3. 通知图床后端完成文件登记
|
||||
return d.hfCommit(ctx, getUrlResp, file.GetName(), fileSize, fileMime, file.ModTime())
|
||||
}
|
||||
|
||||
func (d *CFImgBed) hfCommit(ctx context.Context, getUrlResp hfGetUrlResp, fileName string, fileSize int64, fileMime string, modTime time.Time) (model.Obj, error) {
|
||||
commitBody := map[string]interface{}{
|
||||
"fullId": getUrlResp.FullID,
|
||||
"filePath": getUrlResp.FilePath,
|
||||
"sha256": getUrlResp.Oid,
|
||||
"fileSize": fileSize,
|
||||
"fileName": fileName,
|
||||
"fileType": fileMime,
|
||||
"channelName": getUrlResp.ChannelName,
|
||||
}
|
||||
var commitResp hfCommitResp
|
||||
_, err := d.doRequest(ctx, http.MethodPost, hfCommitApi, func(req *resty.Request) {
|
||||
req.SetBody(commitBody)
|
||||
}, &commitResp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("HF commit request failed: %w", err)
|
||||
}
|
||||
if !commitResp.Success {
|
||||
return nil, fmt.Errorf("HF commit failed: success=false")
|
||||
}
|
||||
|
||||
srcPath := strings.TrimPrefix(commitResp.Src, "/file/")
|
||||
srcPath = strings.TrimPrefix(srcPath, "/")
|
||||
|
||||
if commitResp.PublicUrl != "" {
|
||||
if u, err := url.Parse(commitResp.PublicUrl); err == nil {
|
||||
d.publicUrlPrefix = u.Scheme + "://" + u.Host
|
||||
}
|
||||
}
|
||||
|
||||
return &model.Object{
|
||||
Path: srcPath,
|
||||
Name: fileName,
|
||||
Size: fileSize,
|
||||
Modified: modTime,
|
||||
IsFolder: false,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package cloudflare_imgbed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
listApi = "/api/manage/list"
|
||||
deleteApi = "/api/manage/delete"
|
||||
uploadApi = "/upload"
|
||||
hfGetUrlApi = "/upload/huggingface/getUploadUrl"
|
||||
hfCommitApi = "/upload/huggingface/commitUpload"
|
||||
hfDirectThreshold int64 = 20 * 1024 * 1024
|
||||
fileSampleSize = 512 // HF 申请上传地址时需提供文件前 512 字节的 Sample
|
||||
)
|
||||
|
||||
// doRequest 通用请求封装,包含重试和 API 错误解析
|
||||
func (d *CFImgBed) doRequest(ctx context.Context, method, urlPath string, callback func(*resty.Request), resp interface{}) ([]byte, error) {
|
||||
maxRetries := 3
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
req := d.client.R()
|
||||
req.SetContext(ctx)
|
||||
if callback != nil {
|
||||
callback(req)
|
||||
}
|
||||
if resp != nil {
|
||||
req.SetResult(resp)
|
||||
}
|
||||
|
||||
res, err := req.Execute(method, urlPath)
|
||||
if err != nil {
|
||||
log.WithError(err).Warnf("request %s %s failed, attempt %d/%d", method, urlPath, i+1, maxRetries)
|
||||
if i < maxRetries-1 {
|
||||
time.Sleep(time.Duration(i+1) * time.Second)
|
||||
continue
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Retry on rate limit before attempting to interpret the body as an API error.
|
||||
if res.StatusCode() == 429 {
|
||||
time.Sleep(time.Duration(i+1) * 2 * time.Second)
|
||||
continue
|
||||
}
|
||||
|
||||
body := res.Body()
|
||||
var apiErr apiError
|
||||
if err := json.Unmarshal(body, &apiErr); err == nil {
|
||||
if apiErr.Error != "" || apiErr.Message != "" {
|
||||
msg := apiErr.Error
|
||||
if msg == "" {
|
||||
msg = apiErr.Message
|
||||
}
|
||||
return nil, fmt.Errorf("API error: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
if res.IsError() {
|
||||
return nil, fmt.Errorf("HTTP %d", res.StatusCode())
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
return nil, fmt.Errorf("max retries exceeded")
|
||||
}
|
||||
@@ -89,6 +89,10 @@ func (d *Cloudreve) Link(ctx context.Context, file model.Obj, args model.LinkArg
|
||||
}
|
||||
return &model.Link{
|
||||
URL: dUrl,
|
||||
Header: http.Header{
|
||||
"Referer": {d.Address},
|
||||
"User-Agent": {d.getUA()},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,9 @@ func (d *CloudreveV4) Init(ctx context.Context) error {
|
||||
if d.ref != nil {
|
||||
return nil
|
||||
}
|
||||
if d.isShare() {
|
||||
return nil
|
||||
}
|
||||
if d.canLogin() {
|
||||
return d.login()
|
||||
}
|
||||
@@ -164,6 +167,10 @@ func (d *CloudreveV4) Link(ctx context.Context, file model.Obj, args model.LinkA
|
||||
return &model.Link{
|
||||
URL: url.Urls[0].URL,
|
||||
Expiration: &exp,
|
||||
Header: http.Header{
|
||||
"Referer": {d.Address},
|
||||
"User-Agent": {d.getUA()},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ const (
|
||||
CodeLoginRequired = http.StatusUnauthorized
|
||||
CodePathNotExist = 40016 // Path not exist
|
||||
CodeCredentialInvalid = 40020 // Failed to issue token
|
||||
CodeObjectExisted = 40004 // Object existed
|
||||
// IncorrectSharePassword = 40069 // Incorrect share password
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -106,6 +108,9 @@ func (d *CloudreveV4) _request(method string, path string, callback base.ReqCall
|
||||
if r.Code == CodePathNotExist {
|
||||
return errs.ObjectNotFound
|
||||
}
|
||||
if r.Code == CodeObjectExisted {
|
||||
return errs.ObjectAlreadyExists
|
||||
}
|
||||
return fmt.Errorf("%d: %s", r.Code, r.Msg)
|
||||
}
|
||||
|
||||
@@ -277,9 +282,16 @@ func (d *CloudreveV4) parseJWT(token string, jwt any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *CloudreveV4) isShare() bool {
|
||||
return strings.HasSuffix(d.GetRootPath(), "@share")
|
||||
}
|
||||
|
||||
// check if token is expired
|
||||
// https://github.com/cloudreve/frontend/blob/ddfacc1c31c49be03beb71de4cc114c8811038d6/src/session/index.ts#L177-L200
|
||||
func (d *CloudreveV4) isTokenExpired() bool {
|
||||
if d.isShare() {
|
||||
return false
|
||||
}
|
||||
if d.RefreshToken == "" {
|
||||
// login again if username and password is set
|
||||
if d.canLogin() {
|
||||
|
||||
@@ -251,7 +251,7 @@ func (d *Crypt) Link(ctx context.Context, file model.Obj, _ model.LinkArgs) (*mo
|
||||
rrf, err := stream.GetRangeReaderFromLink(remoteSize, remoteLink)
|
||||
if err != nil {
|
||||
_ = remoteLink.Close()
|
||||
return nil, fmt.Errorf("the remote storage driver need to be enhanced to support encrytion")
|
||||
return nil, fmt.Errorf("the remote storage driver need to be enhanced to support encryption")
|
||||
}
|
||||
|
||||
mu := &sync.Mutex{}
|
||||
|
||||
@@ -0,0 +1,597 @@
|
||||
package doubao_new
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/OpenListTeam/OpenList/v4/drivers/base"
|
||||
"github.com/OpenListTeam/OpenList/v4/pkg/cookie"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultAuthRefreshAheadSeconds = int64(120)
|
||||
defaultDpopRefreshAheadSeconds = int64(5)
|
||||
)
|
||||
|
||||
type Clock interface {
|
||||
Now() (int64, error)
|
||||
}
|
||||
|
||||
type SystemClock struct{}
|
||||
|
||||
func (SystemClock) Now() (int64, error) { return time.Now().Unix(), nil }
|
||||
|
||||
type DPoPTokenInput struct {
|
||||
KeyPair *ecdsa.PrivateKey
|
||||
ExpiresIn int64 // 默认 15
|
||||
|
||||
JTI string
|
||||
HTM string
|
||||
HTU string
|
||||
IAT int64
|
||||
Nonce string
|
||||
Clock Clock
|
||||
}
|
||||
|
||||
type DPoPTokenOutput struct {
|
||||
DPoPToken string `json:"dpopToken"`
|
||||
ExpiredTime int64 `json:"expiredTime"`
|
||||
ExpiresIn int64 `json:"expiresIn"`
|
||||
}
|
||||
|
||||
type JWTPayload struct {
|
||||
Exp int64 `json:"exp,omitempty"`
|
||||
Iat int64 `json:"iat,omitempty"`
|
||||
Nbf int64 `json:"nbf,omitempty"`
|
||||
Jti string `json:"jti,omitempty"`
|
||||
Htm string `json:"htm,omitempty"`
|
||||
Htu string `json:"htu,omitempty"`
|
||||
Nonce string `json:"nonce,omitempty"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
}
|
||||
|
||||
type jwkECPrivateKey struct {
|
||||
Kty string `json:"kty"`
|
||||
Crv string `json:"crv"`
|
||||
X string `json:"x"`
|
||||
Y string `json:"y"`
|
||||
D string `json:"d"`
|
||||
}
|
||||
|
||||
type dpopKeyPairEnvelope struct {
|
||||
PrivateKey *jwkECPrivateKey `json:"privateKey"`
|
||||
KeyPair *jwkECPrivateKey `json:"keyPair"`
|
||||
JWK *jwkECPrivateKey `json:"jwk"`
|
||||
}
|
||||
|
||||
type encryptedDpopKeyPair struct {
|
||||
Data string `json:"data"`
|
||||
Ciphertext string `json:"ciphertext"`
|
||||
Encrypted string `json:"encrypted"`
|
||||
Secret string `json:"secret"`
|
||||
Password string `json:"password"`
|
||||
Passphrase string `json:"passphrase"`
|
||||
}
|
||||
|
||||
func GenerateDPoPToken(in DPoPTokenInput) (*DPoPTokenOutput, error) {
|
||||
if in.KeyPair == nil {
|
||||
return nil, errors.New("keyPair required")
|
||||
}
|
||||
if in.KeyPair.Curve != elliptic.P256() {
|
||||
return nil, errors.New("ES256 requires P-256 key")
|
||||
}
|
||||
if in.Clock == nil {
|
||||
in.Clock = SystemClock{}
|
||||
}
|
||||
if in.ExpiresIn <= 0 {
|
||||
in.ExpiresIn = 15
|
||||
}
|
||||
|
||||
now, err := in.Clock.Now()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payload := map[string]any{
|
||||
"jti": pickStr(in.JTI, uuid.NewString()),
|
||||
"htm": pickStr(in.HTM, ""),
|
||||
"htu": pickStr(in.HTU, ""),
|
||||
"iat": pickI64(in.IAT, now),
|
||||
"nonce": pickStr(in.Nonce, uuid.NewString()),
|
||||
}
|
||||
if in.ExpiresIn > 0 {
|
||||
payload["exp"] = payload["iat"].(int64) + in.ExpiresIn
|
||||
}
|
||||
|
||||
pub := in.KeyPair.PublicKey
|
||||
header := map[string]any{
|
||||
"typ": "dpop+jwt",
|
||||
"alg": "ES256",
|
||||
"jwk": map[string]string{
|
||||
"kty": "EC",
|
||||
"crv": "P-256",
|
||||
"x": b64url(pad32(pub.X.Bytes())),
|
||||
"y": b64url(pad32(pub.Y.Bytes())),
|
||||
},
|
||||
}
|
||||
|
||||
hb, err := json.Marshal(header)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pb, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
hEnc := b64url(hb)
|
||||
pEnc := b64url(pb)
|
||||
signingInput := hEnc + "." + pEnc
|
||||
|
||||
sum := sha256.Sum256([]byte(signingInput))
|
||||
r, s, err := ecdsa.Sign(rand.Reader, in.KeyPair, sum[:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
sig := append(pad32(r.Bytes()), pad32(s.Bytes())...)
|
||||
token := signingInput + "." + b64url(sig)
|
||||
|
||||
iat := payload["iat"].(int64)
|
||||
return &DPoPTokenOutput{
|
||||
DPoPToken: token,
|
||||
ExpiredTime: iat + in.ExpiresIn,
|
||||
ExpiresIn: in.ExpiresIn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func GenerateDPoPKeyPair() (*ecdsa.PrivateKey, error) {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return validateP256Key(key)
|
||||
}
|
||||
|
||||
func ParseJWTPayload(token string, out any) error {
|
||||
token = strings.TrimSpace(trimTokenScheme(token))
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) < 2 {
|
||||
return fmt.Errorf("invalid JWT format")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to decode JWT payload: %w", err)
|
||||
}
|
||||
if err := json.Unmarshal(payload, out); err != nil {
|
||||
return fmt.Errorf("failed to parse JWT payload: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseECPrivateKeyJWK(raw string) (*ecdsa.PrivateKey, error) {
|
||||
var jwk jwkECPrivateKey
|
||||
if err := json.Unmarshal([]byte(raw), &jwk); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if jwk.D == "" || jwk.X == "" || jwk.Y == "" {
|
||||
var env dpopKeyPairEnvelope
|
||||
if err := json.Unmarshal([]byte(raw), &env); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case env.PrivateKey != nil:
|
||||
jwk = *env.PrivateKey
|
||||
case env.KeyPair != nil:
|
||||
jwk = *env.KeyPair
|
||||
case env.JWK != nil:
|
||||
jwk = *env.JWK
|
||||
default:
|
||||
return nil, errors.New("missing private key JWK")
|
||||
}
|
||||
}
|
||||
|
||||
if jwk.Kty != "" && jwk.Kty != "EC" {
|
||||
return nil, errors.New("unsupported JWK kty")
|
||||
}
|
||||
if jwk.Crv != "" && jwk.Crv != "P-256" {
|
||||
return nil, errors.New("unsupported JWK curve")
|
||||
}
|
||||
if jwk.D == "" || jwk.X == "" || jwk.Y == "" {
|
||||
return nil, errors.New("incomplete JWK")
|
||||
}
|
||||
|
||||
xBytes, err := base64.RawURLEncoding.DecodeString(jwk.X)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid jwk x: %w", err)
|
||||
}
|
||||
yBytes, err := base64.RawURLEncoding.DecodeString(jwk.Y)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid jwk y: %w", err)
|
||||
}
|
||||
dBytes, err := base64.RawURLEncoding.DecodeString(jwk.D)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid jwk d: %w", err)
|
||||
}
|
||||
|
||||
key := &ecdsa.PrivateKey{
|
||||
PublicKey: ecdsa.PublicKey{
|
||||
Curve: elliptic.P256(),
|
||||
X: new(big.Int).SetBytes(xBytes),
|
||||
Y: new(big.Int).SetBytes(yBytes),
|
||||
},
|
||||
D: new(big.Int).SetBytes(dBytes),
|
||||
}
|
||||
return validateP256Key(key)
|
||||
}
|
||||
|
||||
func parseEncryptedDPoPKeyPair(raw, secret string) (*ecdsa.PrivateKey, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, errors.New("empty encrypted key pair")
|
||||
}
|
||||
|
||||
var payload encryptedDpopKeyPair
|
||||
ciphertext := raw
|
||||
if strings.HasPrefix(raw, "{") {
|
||||
if err := json.Unmarshal([]byte(raw), &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case strings.TrimSpace(payload.Data) != "":
|
||||
ciphertext = strings.TrimSpace(payload.Data)
|
||||
case strings.TrimSpace(payload.Ciphertext) != "":
|
||||
ciphertext = strings.TrimSpace(payload.Ciphertext)
|
||||
case strings.TrimSpace(payload.Encrypted) != "":
|
||||
ciphertext = strings.TrimSpace(payload.Encrypted)
|
||||
default:
|
||||
return nil, errors.New("missing encrypted dpop payload")
|
||||
}
|
||||
}
|
||||
|
||||
decoded, err := decodeBase64Loose(ciphertext)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(decoded) <= 12 {
|
||||
return nil, errors.New("encrypted dpop payload too short")
|
||||
}
|
||||
|
||||
plain, err := decryptDoubaoKeyPair(decoded, secret)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to decrypt with secret: %w", err)
|
||||
}
|
||||
return parseECPrivateKeyJWK(string(plain))
|
||||
}
|
||||
|
||||
func decryptDoubaoKeyPair(ciphertext []byte, secret string) ([]byte, error) {
|
||||
key := pbkdf2.Key([]byte(secret), []byte("fixed-salt"), 100000, 32, sha256.New)
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nonceSize := aead.NonceSize()
|
||||
if len(ciphertext) <= nonceSize {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
nonce := ciphertext[:nonceSize]
|
||||
enc := ciphertext[nonceSize:]
|
||||
return aead.Open(nil, nonce, enc, nil)
|
||||
}
|
||||
|
||||
func decodeBase64Loose(raw string) ([]byte, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.ReplaceAll(raw, "\n", "")
|
||||
raw = strings.ReplaceAll(raw, "\r", "")
|
||||
raw = strings.ReplaceAll(raw, "\t", "")
|
||||
raw = strings.ReplaceAll(raw, " ", "")
|
||||
|
||||
encodings := []*base64.Encoding{
|
||||
base64.StdEncoding,
|
||||
base64.RawStdEncoding,
|
||||
base64.URLEncoding,
|
||||
base64.RawURLEncoding,
|
||||
}
|
||||
var lastErr error
|
||||
for _, enc := range encodings {
|
||||
decoded, err := enc.DecodeString(raw)
|
||||
if err == nil {
|
||||
return decoded, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = errors.New("invalid base64")
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func validateP256Key(key *ecdsa.PrivateKey) (*ecdsa.PrivateKey, error) {
|
||||
if key == nil {
|
||||
return nil, errors.New("nil private key")
|
||||
}
|
||||
if key.Curve != elliptic.P256() {
|
||||
return nil, errors.New("ES256 requires P-256 key")
|
||||
}
|
||||
if key.PublicKey.X == nil || key.PublicKey.Y == nil || key.D == nil {
|
||||
return nil, errors.New("invalid private key")
|
||||
}
|
||||
if !key.Curve.IsOnCurve(key.PublicKey.X, key.PublicKey.Y) {
|
||||
return nil, errors.New("public key is not on P-256 curve")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
func trimTokenScheme(token string) string {
|
||||
token = strings.TrimSpace(token)
|
||||
if i := strings.IndexByte(token, ' '); i > 0 {
|
||||
scheme := strings.ToLower(strings.TrimSpace(token[:i]))
|
||||
if scheme == "bearer" || scheme == "dpop" {
|
||||
return strings.TrimSpace(token[i+1:])
|
||||
}
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
func b64url(b []byte) string {
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func pad32(b []byte) []byte {
|
||||
if len(b) >= 32 {
|
||||
return b[len(b)-32:]
|
||||
}
|
||||
out := make([]byte, 32)
|
||||
copy(out[32-len(b):], b)
|
||||
return out
|
||||
}
|
||||
|
||||
func pickStr(v, def string) string {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func pickI64(v, def int64) int64 {
|
||||
if v != 0 {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) resolveAuthorization() string {
|
||||
auth := trimTokenScheme(d.Authorization)
|
||||
if auth == "" {
|
||||
return ""
|
||||
}
|
||||
return "DPoP " + auth
|
||||
}
|
||||
|
||||
func shouldRefreshJWT(token string) bool {
|
||||
if token == "" {
|
||||
return true
|
||||
}
|
||||
var payload JWTPayload
|
||||
if err := ParseJWTPayload(token, &payload); err != nil {
|
||||
return true
|
||||
}
|
||||
if payload.Exp <= 0 {
|
||||
return false
|
||||
}
|
||||
return payload.Exp <= time.Now().Unix()+defaultAuthRefreshAheadSeconds
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) fetchBizAuth(dpop string, public bool) (string, error) {
|
||||
var reqUrl string
|
||||
client := base.RestyClient.Clone()
|
||||
req := client.R()
|
||||
req.SetHeader("accept", "application/json, text/javascript")
|
||||
req.SetHeader("origin", DoubaoURL)
|
||||
req.SetHeader("referer", DoubaoURL+"/")
|
||||
req.SetHeader("content-type", "application/x-www-form-urlencoded")
|
||||
if public {
|
||||
reqUrl = DoubaoURL + "/passport/anonymity_user/biz_auth/"
|
||||
} else {
|
||||
reqUrl = DoubaoURL + "/passport/user/biz_auth/"
|
||||
if d.Cookie != "" {
|
||||
req.SetHeader("cookie", d.Cookie)
|
||||
if csrf := strings.TrimSpace(cookie.GetStr(d.Cookie, "passport_csrf_token")); csrf != "" {
|
||||
req.SetHeader("x-tt-passport-csrf-token", csrf)
|
||||
}
|
||||
}
|
||||
if oldAuth := d.resolveAuthorization(); oldAuth != "" {
|
||||
req.SetHeader("authorization", oldAuth)
|
||||
}
|
||||
}
|
||||
if dpop != "" {
|
||||
req.SetHeader("dpop", dpop)
|
||||
}
|
||||
values := url.Values{}
|
||||
values.Set("client_id", d.AuthClientID)
|
||||
values.Set("client_type", d.AuthClientType)
|
||||
values.Set("scope", d.AuthScope)
|
||||
values.Set("d_pop", dpop)
|
||||
req.SetBody(values.Encode())
|
||||
req.SetQueryParam("aid", d.AppID)
|
||||
req.SetQueryParam("account_sdk_source", d.AuthSDKSource)
|
||||
req.SetQueryParam("sdk_version", d.AuthSDKVersion)
|
||||
|
||||
res, err := req.Post(reqUrl)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var resp bizAuthResp
|
||||
if err = json.Unmarshal(res.Body(), &resp); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resp.Message != "success" || resp.Data.AccessToken == "" {
|
||||
return "", fmt.Errorf("[doubao_new] %s: %s", resp.Message, resp.Data.Description)
|
||||
}
|
||||
return resp.Data.AccessToken, nil
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) refreshAuthorizationWithDPoP(dpop string) (string, error) {
|
||||
token, err := d.fetchBizAuth(dpop, false)
|
||||
if err == nil && token != "" {
|
||||
return token, nil
|
||||
}
|
||||
if err == nil {
|
||||
err = errors.New("biz auth refresh failed")
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) resolveDpopForRequest(method, rawURL string) (string, error) {
|
||||
if d.DPoPKeyPair != nil {
|
||||
proof, err := GenerateDPoPToken(DPoPTokenInput{
|
||||
KeyPair: d.DPoPKeyPair,
|
||||
HTM: strings.ToUpper(strings.TrimSpace(method)),
|
||||
HTU: normalizeDPoPURL(rawURL),
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return proof.DPoPToken, nil
|
||||
}
|
||||
|
||||
static := d.DPoP
|
||||
if static == "" {
|
||||
return "", nil
|
||||
}
|
||||
if !d.IgnoreJWTCheck {
|
||||
if payload, err := parseDPoPPayload(static); err == nil && payload.Exp > 0 {
|
||||
now := time.Now().Unix()
|
||||
if payload.Exp <= now+defaultDpopRefreshAheadSeconds {
|
||||
return "", errors.New("static dpop token expired or near expiry; configure dpop_key_pair for automatic refresh")
|
||||
}
|
||||
}
|
||||
}
|
||||
return static, nil
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) ensureAuthAdditons() bool {
|
||||
return d.DPoPKeySecret != "" && d.AuthClientID != "" && d.AuthClientType != "" &&
|
||||
d.AuthScope != "" && d.AuthSDKSource != "" && d.AuthSDKVersion != ""
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) resolveAuthorizationForRequest(method, rawURL string) (string, error) {
|
||||
if !shouldRefreshJWT(d.Authorization) {
|
||||
return d.resolveAuthorization(), nil
|
||||
}
|
||||
|
||||
if d.DPoPKeyPair == nil || strings.TrimSpace(d.Cookie) == "" || !d.ensureAuthAdditons() {
|
||||
return d.resolveAuthorization(), nil
|
||||
}
|
||||
|
||||
d.authRefreshMu.Lock()
|
||||
defer d.authRefreshMu.Unlock()
|
||||
|
||||
if !shouldRefreshJWT(d.Authorization) {
|
||||
return d.resolveAuthorization(), nil
|
||||
}
|
||||
|
||||
refreshDpop, err := d.resolveDpopForRequest(method, rawURL)
|
||||
if err != nil || refreshDpop == "" {
|
||||
return "", err
|
||||
}
|
||||
|
||||
newToken, err := d.refreshAuthorizationWithDPoP(refreshDpop)
|
||||
if err != nil {
|
||||
if auth := d.resolveAuthorization(); auth != "" {
|
||||
return auth, nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
d.Authorization = trimTokenScheme(newToken)
|
||||
return d.resolveAuthorization(), nil
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) resolveAuthorizationForPublic() (dpop string, auth string, err error) {
|
||||
if d.DPoPPublic != "" && !shouldRefreshJWT(d.AuthorizationPublic) {
|
||||
return d.DPoPPublic, "DPoP " + d.AuthorizationPublic, nil
|
||||
}
|
||||
|
||||
if !d.ensureAuthAdditons() {
|
||||
return "", "", fmt.Errorf("[doubao_new] missing auth additions, please fill them all")
|
||||
}
|
||||
|
||||
d.authRefreshPublicMu.Lock()
|
||||
defer d.authRefreshPublicMu.Unlock()
|
||||
|
||||
if d.DPoPPublic != "" && !shouldRefreshJWT(d.AuthorizationPublic) {
|
||||
return d.DPoPPublic, "DPoP " + d.AuthorizationPublic, nil
|
||||
}
|
||||
|
||||
// generate new public dpop
|
||||
keypair, err := GenerateDPoPKeyPair()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
proof, err := GenerateDPoPToken(DPoPTokenInput{
|
||||
KeyPair: keypair,
|
||||
})
|
||||
d.DPoPPublic = proof.DPoPToken
|
||||
|
||||
// get authorization token
|
||||
d.AuthorizationPublic, err = d.fetchBizAuth(proof.DPoPToken, true)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return d.DPoPPublic, "DPoP " + d.AuthorizationPublic, nil
|
||||
}
|
||||
|
||||
func (d *DoubaoNew) applyAuthHeaders(req *resty.Request, method, rawURL string) error {
|
||||
auth, err := d.resolveAuthorizationForRequest(method, rawURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if auth != "" {
|
||||
req.SetHeader("authorization", auth)
|
||||
}
|
||||
dpop, err := d.resolveDpopForRequest(method, rawURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dpop != "" {
|
||||
req.SetHeader("dpop", dpop)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func normalizeDPoPURL(rawURL string) string {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil {
|
||||
return rawURL
|
||||
}
|
||||
u.Fragment = ""
|
||||
return u.String()
|
||||
}
|
||||
|
||||
func parseDPoPPayload(token string) (*JWTPayload, error) {
|
||||
var payload JWTPayload
|
||||
if err := ParseJWTPayload(token, &payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &payload, nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user