Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d315f01289 | ||
|
|
bb17c7d48a | ||
|
|
75ffe70a4d | ||
|
|
36f9f65384 | ||
|
|
5f89ae3516 | ||
|
|
0cc2b690f8 | ||
|
|
a45b6455be | ||
|
|
b991482617 | ||
|
|
f0aa44455c | ||
|
|
99ed770017 | ||
|
|
1f8906f952 | ||
|
|
0efc85d3c0 | ||
|
|
481675107f | ||
|
|
6568498850 | ||
|
|
67814348dc | ||
|
|
53d13dfe28 | ||
|
|
d511e66d56 | ||
|
|
16f2d30476 | ||
|
|
aafd039205 | ||
|
|
647e161431 | ||
|
|
8f3cf35162 | ||
|
|
f2145de571 | ||
|
|
39cd9034cd | ||
|
|
177c225f16 | ||
|
|
3be8db664c | ||
|
|
9b704f6f14 | ||
|
|
f49e2510f5 | ||
|
|
c5c8bb2bf5 | ||
|
|
962ff4dc98 | ||
|
|
59f3aa7028 | ||
|
|
cfdf87c3b8 | ||
|
|
99924296ef | ||
|
|
9d3221ebbb | ||
|
|
7b7327ffb3 | ||
|
|
fdfc6902a7 | ||
|
|
9fb3758203 | ||
|
|
e2ac8ce64b | ||
|
|
c01d11305c | ||
|
|
def54f8998 | ||
|
|
a205c0b8d7 | ||
|
|
ae70dc240c | ||
|
|
d7f6c3b206 | ||
|
|
a83e38dac4 | ||
|
|
d46c06f08d | ||
|
|
a61cdbed67 | ||
|
|
daa8c39dad | ||
|
|
a5cd53f94c | ||
|
|
847e88881d | ||
|
|
3d20e818e5 | ||
|
|
09f7c88ed3 | ||
|
|
f7b26753c1 | ||
|
|
9704d4af27 | ||
|
|
1907f404ac | ||
|
|
72c5ba7d20 | ||
|
|
5b0254f7c0 | ||
|
|
d36b345f92 | ||
|
|
bc5c818eae | ||
|
|
98bd3305b7 | ||
|
|
3f38848051 | ||
|
|
82d7f8ec81 | ||
|
|
a6981d58e9 | ||
|
|
1b1631b41a | ||
|
|
3eb6df55df | ||
|
|
6de63c3f63 | ||
|
|
969615f353 | ||
|
|
5a88b98314 | ||
|
|
2674b1c39e | ||
|
|
4c90b38247 | ||
|
|
93088b22f1 | ||
|
|
fe90c1d261 | ||
|
|
640e798d70 | ||
|
|
ba2df0ecff | ||
|
|
d61da67456 | ||
|
|
7c696ee6e0 | ||
|
|
7b840b4261 | ||
|
|
a3c1f84c2c | ||
|
|
8d33e1a5b3 | ||
|
|
bad7f1d06c | ||
|
|
af1c8b2719 | ||
|
|
d90af0b9d1 | ||
|
|
6016ee1d24 | ||
|
|
e275fd58bd | ||
|
|
c9626cb389 | ||
|
|
f86a379f93 | ||
|
|
a9eee26be7 | ||
|
|
abd16d5326 | ||
|
|
6756d82ffa | ||
|
|
71c9e6947a | ||
|
|
24db9bb58b | ||
|
|
de0afb1481 | ||
|
|
cb6331c20d | ||
|
|
b0e133b554 | ||
|
|
dbe37befa3 | ||
|
|
0d5c4e8e7f | ||
|
|
5515a1c48c | ||
|
|
3abf6ed933 | ||
|
|
af40e8aa63 | ||
|
|
64c5ece02c | ||
|
|
4ccbc3ebc5 | ||
|
|
14d9642d3c | ||
|
|
2f5fbfb17c | ||
|
|
49b4d99b5e | ||
|
|
9d9f1caaaa | ||
|
|
5bb8541385 | ||
|
|
f7189668fd | ||
|
|
1b36ed1807 | ||
|
|
07dc196c3c | ||
|
|
76bec67ab2 | ||
|
|
a2a9e3dc2a | ||
|
|
9a5680fb45 | ||
|
|
75a8a3a9ac | ||
|
|
3e8c85b945 | ||
|
|
90f70d1bf6 | ||
|
|
20a70d7f91 | ||
|
|
d33546a4b5 | ||
|
|
93614d46a8 | ||
|
|
04b0e691eb | ||
|
|
7f08fa0b23 | ||
|
|
df6a51d23c | ||
|
|
46c379d556 | ||
|
|
46cd9f7a3e | ||
|
|
5c2f66f4b6 | ||
|
|
cfdcb586ee | ||
|
|
55e6bdc4f7 | ||
|
|
b31b42301e | ||
|
|
7ce0d876b0 | ||
|
|
2fd2596aa0 | ||
|
|
e0973e4a34 | ||
|
|
4f7b8a05ad | ||
|
|
2927d1ef2b | ||
|
|
3451f577ab | ||
|
|
06671be0d8 | ||
|
|
8ae9363f0f | ||
|
|
5d84445f8f | ||
|
|
7c541e4047 | ||
|
|
3262e5a11b | ||
|
|
ff43a373cd | ||
|
|
7394d948e4 | ||
|
|
5afb3aa43b | ||
|
|
7705af6e68 | ||
|
|
684e060ef3 | ||
|
|
0c67792441 | ||
|
|
b0ef2c2a87 | ||
|
|
1977c2a0fc | ||
|
|
d289708f9e | ||
|
|
cd5fd45667 | ||
|
|
50bc9ab129 | ||
|
|
bfad91dcab | ||
|
|
61a959adda | ||
|
|
f4b839fd11 | ||
|
|
969aeb5e0a | ||
|
|
68d42eb397 | ||
|
|
08603f9510 | ||
|
|
b450bf67bd | ||
|
|
03e26dbea8 | ||
|
|
046a3ac9f9 | ||
|
|
9c5aebaf36 | ||
|
|
a094715d69 | ||
|
|
69bb875172 | ||
|
|
589f10c7ef | ||
|
|
654e57e946 | ||
|
|
b94b99ae09 | ||
|
|
fba990a056 | ||
|
|
cb07ce58bc | ||
|
|
50beef7b08 | ||
|
|
bd39e4110f | ||
|
|
86efcb98c5 | ||
|
|
f3d9873395 | ||
|
|
ef228c1722 | ||
|
|
6863317e9d | ||
|
|
2b83a735cb | ||
|
|
447f599783 | ||
|
|
f986f6253d | ||
|
|
2e1b621250 | ||
|
|
d50947b2e6 | ||
|
|
520a72415c | ||
|
|
a372b67edb | ||
|
|
2d86b5c132 | ||
|
|
63b3144633 | ||
|
|
1b0178fed9 | ||
|
|
83febe0a00 | ||
|
|
987580d400 | ||
|
|
0919936050 | ||
|
|
acc7ed8f6b | ||
|
|
ccb3267fba | ||
|
|
1249493a8a | ||
|
|
107141bbe7 | ||
|
|
b329fee107 | ||
|
|
3ce95f21fd | ||
|
|
f54ed5df5a | ||
|
|
727b7edb84 | ||
|
|
f5891ee03d | ||
|
|
724276ac69 | ||
|
|
a3f559c8e5 | ||
|
|
edd189a8a8 | ||
|
|
c970378fd7 | ||
|
|
8b61343aef | ||
|
|
2cb93a03e2 | ||
|
|
81dfc073a6 | ||
|
|
427921ccab | ||
|
|
f4876c8a0e | ||
|
|
35a3625b11 | ||
|
|
dc9b501e35 | ||
|
|
85fe92a378 | ||
|
|
983d9ad09e | ||
|
|
d9f757aaf0 | ||
|
|
cd409fcfb9 | ||
|
|
366244fa5d | ||
|
|
7a2e9b4fd1 | ||
|
|
203385d3f8 | ||
|
|
aaf73dec24 | ||
|
|
2523282a89 | ||
|
|
3384f5197a | ||
|
|
cd77665f02 | ||
|
|
a22b431150 | ||
|
|
eb7c9ad7f2 | ||
|
|
ea11fc38f1 | ||
|
|
1be16e9f2c | ||
|
|
1d86d14a20 | ||
|
|
5ad15cc4ac | ||
|
|
49604966fd | ||
|
|
bdb8ed177f | ||
|
|
2dc7048cba | ||
|
|
d3750464aa | ||
|
|
5c9bcd3731 | ||
|
|
bdda550b2c | ||
|
|
3308d966f0 | ||
|
|
18041ed9ec | ||
|
|
56b85e545e | ||
|
|
c5af916952 | ||
|
|
a1981328aa | ||
|
|
51244133e0 | ||
|
|
0c17093b1a | ||
|
|
6538b29b62 | ||
|
|
81e90e6b89 | ||
|
|
4f39296664 | ||
|
|
ece5b91dc2 | ||
|
|
d9f04ae928 | ||
|
|
e3ccecbd9c | ||
|
|
fb1c2cb060 | ||
|
|
9bff75464d | ||
|
|
863f759248 | ||
|
|
f89fb5e438 | ||
|
|
7ca1cc8c64 | ||
|
|
1f791c66e6 | ||
|
|
4d60c47d39 | ||
|
|
3fd3dd49d2 | ||
|
|
d119de7b98 | ||
|
|
69b359a9c9 | ||
|
|
4fbe13a1f0 | ||
|
|
3b50465708 | ||
|
|
473c58796c | ||
|
|
fab8f135f3 | ||
|
|
0fca7b6bc7 | ||
|
|
4700d0ba28 | ||
|
|
6e31ea089f | ||
|
|
4a2088f6fb | ||
|
|
17c8fb7e4d | ||
|
|
8c99bbc847 | ||
|
|
06c7fe7a22 | ||
|
|
8b3b5d4394 | ||
|
|
2ee73ab619 | ||
|
|
15413dbc95 | ||
|
|
c7c43fac80 | ||
|
|
4283bdfa5a | ||
|
|
328ba8592c | ||
|
|
a191a4140d | ||
|
|
3521837964 | ||
|
|
b30cd78f86 | ||
|
|
0583e4aaa6 | ||
|
|
a89c55b5c4 | ||
|
|
68c40d7f3f | ||
|
|
42a0b89d95 | ||
|
|
1860f534cd | ||
|
|
5c2d2ad7b4 | ||
|
|
db6352ada8 | ||
|
|
d1a5ed8b3d | ||
|
|
be9583be0f | ||
|
|
d2c70b077b | ||
|
|
53b3eea4fc | ||
|
|
54347f41b6 | ||
|
|
cea454b015 | ||
|
|
070db64ca9 | ||
|
|
6a8956b04d | ||
|
|
057504bb81 | ||
|
|
470b488824 | ||
|
|
c8c9df1ae8 | ||
|
|
33d787c74e | ||
|
|
67338a5e83 | ||
|
|
723697192d | ||
|
|
4294d07d6a | ||
|
|
3936fd786f | ||
|
|
45197e9a3b | ||
|
|
c9692e76e5 | ||
|
|
0a9e39ed75 | ||
|
|
1971f582b5 | ||
|
|
c62d6be3da | ||
|
|
7d5e503894 | ||
|
|
6c4066fde4 | ||
|
|
ffdf3e717f | ||
|
|
f66814b4ae | ||
|
|
0c3e201a51 | ||
|
|
c32a5d750f | ||
|
|
207c287c97 | ||
|
|
56ef25065e | ||
|
|
bd6d6be71f | ||
|
|
1d3a028bae | ||
|
|
27011fb96b | ||
|
|
c696b59c4b | ||
|
|
78b5b8a78b | ||
|
|
c81ca7f5cd | ||
|
|
e39d50fe09 | ||
|
|
086269f8bd | ||
|
|
00d2183961 | ||
|
|
5f914dc4c4 | ||
|
|
9bf204cf04 | ||
|
|
a816b9ccc8 | ||
|
|
d60d370463 | ||
|
|
84d054b494 | ||
|
|
1aa96e147f | ||
|
|
8c01e45780 | ||
|
|
8ad571aa08 | ||
|
|
39316e9b8e | ||
|
|
f778596390 | ||
|
|
c2cbc14492 | ||
|
|
62c22bc6b4 | ||
|
|
b89c7bc608 | ||
|
|
f2cd686563 | ||
|
|
ef5ee99f04 | ||
|
|
6d136604db | ||
|
|
38ff711ea9 | ||
|
|
a1a8abc25f | ||
|
|
abccbabc78 | ||
|
|
c26eb26b8f | ||
|
|
74beea6044 | ||
|
|
e548d7e0c9 | ||
|
|
a996d57914 | ||
|
|
f7dc60ad50 | ||
|
|
8425a96ac9 | ||
|
|
99f4e8c895 | ||
|
|
cc0f61b527 | ||
|
|
922ef969a6 | ||
|
|
3a542054fc | ||
|
|
895a8d2ee4 | ||
|
|
29d0f5ebcf | ||
|
|
31228e3edf | ||
|
|
31a32d7e14 | ||
|
|
65fd6fb489 | ||
|
|
953b878a89 | ||
|
|
ae4ca3da58 | ||
|
|
d09bd180af | ||
|
|
3d24e353c5 | ||
|
|
ce7489b0c0 | ||
|
|
2b5091ba21 | ||
|
|
ff32971aca | ||
|
|
f2af61f9aa | ||
|
|
d935b9d631 | ||
|
|
ae66d1d83d | ||
|
|
aa91ca1d50 | ||
|
|
2d4bdea5cb | ||
|
|
2f2393ac20 | ||
|
|
5a761e244a | ||
|
|
6538766780 | ||
|
|
16b7a3d5b3 | ||
|
|
ef97528114 | ||
|
|
b58669bb46 | ||
|
|
51d28c5e53 | ||
|
|
db15650664 | ||
|
|
ee7da179c1 | ||
|
|
6bb32372ab | ||
|
|
7d6428c967 | ||
|
|
bba5107dd5 | ||
|
|
ddfe76b635 | ||
|
|
aad7395dde | ||
|
|
6f541715df | ||
|
|
848797b2fd | ||
|
|
0a05bf41e7 | ||
|
|
485656d1d4 | ||
|
|
c074e0c2bc | ||
|
|
0db0a2c987 | ||
|
|
b06a79b5c7 | ||
|
|
4840c4b8a4 | ||
|
|
e72b097aa2 | ||
|
|
af52c4ce7e | ||
|
|
aae79c2449 | ||
|
|
83838afce9 | ||
|
|
4690107e32 | ||
|
|
74b08b3631 | ||
|
|
953d348c0c | ||
|
|
00cea68b6e | ||
|
|
daa9d4c707 | ||
|
|
6bc587752a | ||
|
|
11befc09bd | ||
|
|
ff6c0da262 | ||
|
|
aab4a37a7e | ||
|
|
74c9491893 | ||
|
|
256faf2cbd | ||
|
|
32e3620f5e | ||
|
|
39202b44a1 | ||
|
|
457d9e85d6 | ||
|
|
858ad74339 | ||
|
|
755d7ce814 | ||
|
|
854f600d3f | ||
|
|
28da89f08c | ||
|
|
dddefb68a2 | ||
|
|
e882b663a8 | ||
|
|
6f8e9fc68f | ||
|
|
7799a4032c | ||
|
|
6316e9986a | ||
|
|
39d1028ee9 | ||
|
|
107f90649b | ||
|
|
c8b66501b7 | ||
|
|
398e3f7adc | ||
|
|
158018c248 | ||
|
|
c56447ad5f | ||
|
|
c073fc0a67 | ||
|
|
82d316af83 | ||
|
|
150953a033 | ||
|
|
f30ad6641f | ||
|
|
7019f18635 | ||
|
|
c0338c3d8e | ||
|
|
fe55f1bd54 | ||
|
|
48f8c60672 | ||
|
|
cc97cedf0f |
No files matched your search
@@ -0,0 +1,3 @@
|
|||||||
|
.venv/
|
||||||
|
.build/
|
||||||
|
__pycache__/
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
---
|
||||||
|
name: gopeed-file-category-icons
|
||||||
|
description: Design or revise Gopeed file-classification icons as one cohesive SVG-to-Flutter icon font. Use for file types, generic and protocol-marked folders, unknown files, and extension-to-icon taxonomy; do not use for launcher, navigation, action, or status icons.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Gopeed File Category Icons
|
||||||
|
|
||||||
|
Maintain Gopeed's file-classification visual language and its deterministic SVG → TTF → Flutter `IconData` pipeline.
|
||||||
|
|
||||||
|
The canonical editable materials live in `design/file-category-icons/`, outside the Flutter project. Read its `README.md` before changing any source. Do not add that directory to Flutter assets.
|
||||||
|
|
||||||
|
## Classification grammar
|
||||||
|
|
||||||
|
- A directory is always a folder outline. Add a classification or protocol mark only when one is known; otherwise leave the folder empty.
|
||||||
|
- A non-directory is always a file outline plus its classification mark.
|
||||||
|
- An unknown file is an empty file outline. Do not invent a generic interior mark.
|
||||||
|
- Transfer state is separate from classification. Never replace a file glyph with paused, failed, completed, or downloading artwork.
|
||||||
|
- Keep this skill scoped to file browsing, task assets, extension classification, and the font that renders those categories.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
1. Read `design/file-category-icons/README.md`, then inspect its manifest, the classification mapping, real task-card size, and file-tree size. Read [references/style-guide.md](references/style-guide.md) for every visual revision.
|
||||||
|
2. Preserve the shared file or folder shell. Redraw only the classification mark unless the task explicitly revises the complete system.
|
||||||
|
3. Create 24×24 SVG sources containing only closed, filled `<path>` geometry. Convert strokes and lettering to paths; never leave `<text>`, live strokes, masks, clipping, filters, or external references.
|
||||||
|
4. Keep every decorated mark inside the documented safe area. Reject any mark that touches or visually merges with the shell at 16 or 20 px.
|
||||||
|
5. Preserve existing names and codepoints. Omit the codepoint only for a new category, then allocate it with the builder. Bump the font version for a visual revision.
|
||||||
|
6. Rebuild the complete TTF and generated Dart class, then generate the multi-size contact sheet.
|
||||||
|
7. Inspect 16, 20, 24, and 32 px in light and dark swatches. Check the actual Flutter task card and task-detail file tree when their sizes differ from the sheet.
|
||||||
|
8. Run the relevant classification tests, `flutter analyze`, and `flutter test` after integration changes.
|
||||||
|
|
||||||
|
## Tool setup
|
||||||
|
|
||||||
|
The scripts require the pinned packages in `scripts/requirements.txt`. Keep the environment local and untracked:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .agent/skills/gopeed-file-category-icons/.venv
|
||||||
|
.agent/skills/gopeed-file-category-icons/.venv/bin/pip install -r .agent/skills/gopeed-file-category-icons/scripts/requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
Build and preview a manifest:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.agent/skills/gopeed-file-category-icons/.venv/bin/python .agent/skills/gopeed-file-category-icons/scripts/build_icon_font.py --manifest design/file-category-icons/manifest.json --allocate-codepoints
|
||||||
|
.agent/skills/gopeed-file-category-icons/.venv/bin/python .agent/skills/gopeed-file-category-icons/scripts/preview_icon_font.py --manifest design/file-category-icons/manifest.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Use [assets/manifest.example.json](assets/manifest.example.json) and [assets/folder-symbol-template.svg](assets/folder-symbol-template.svg) only as structural starting points.
|
||||||
|
|
||||||
|
## Invariants
|
||||||
|
|
||||||
|
- Existing codepoints are API: never renumber or reuse one unless the user explicitly approves a breaking migration.
|
||||||
|
- `design/file-category-icons/` is the sole editable source of truth. Flutter keeps only the generated runtime TTF and Dart constants.
|
||||||
|
- Never add the design-material directory to `pubspec.yaml`; it must remain outside the packaged Flutter asset graph.
|
||||||
|
- The manifest is the source of truth. Do not hand-edit generated Dart constants or patch the binary font.
|
||||||
|
- Keep icon names lowercase `snake_case`; the generator emits lowerCamelCase Dart fields.
|
||||||
|
- File and folder shells in the same revision must share outline weight, baseline, fold/tab geometry, and optical scale.
|
||||||
|
- Prefer a recognizable classification symbol over lettering. If lettering is necessary, convert it to geometry and prove it remains legible at 16 px; PDF-like multi-letter marks need deliberate spacing rather than scaling text into the available area.
|
||||||
|
- New classification groups require both an extension/domain mapping and a glyph. Do not add a glyph that no classifier can reach.
|
||||||
|
- Rebuild the complete font after every source change so all platforms consume the same binary.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
interface:
|
||||||
|
display_name: "Gopeed File Category Icons"
|
||||||
|
short_description: "Design cohesive Gopeed file-classification icons"
|
||||||
|
default_prompt: "Use $gopeed-file-category-icons to update the source materials and regenerate a consistent Gopeed file-category icon."
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M2 4C2 3.17 2.67 2.5 3.5 2.5H9.25L11.25 4.5H20.5C21.33 4.5 22 5.17 22 6V7.5H2V4ZM2 5.5H4V20H2V5.5ZM20 5.5H22V20H20V5.5ZM2 19.5H22V20C22 20.83 21.33 21.5 20.5 21.5H3.5C2.67 21.5 2 20.83 2 20V19.5Z"/>
|
||||||
|
<path d="M12 9.25C13.1 9.25 14 10.15 14 11.25C14 12.35 13.1 13.25 12 13.25C10.9 13.25 10 12.35 10 11.25C10 10.15 10.9 9.25 12 9.25ZM7.25 14.25C8.35 14.25 9.25 15.15 9.25 16.25C9.25 17.35 8.35 18.25 7.25 18.25C6.15 18.25 5.25 17.35 5.25 16.25C5.25 15.15 6.15 14.25 7.25 14.25ZM16.75 14.25C17.85 14.25 18.75 15.15 18.75 16.25C18.75 17.35 17.85 18.25 16.75 18.25C15.65 18.25 14.75 17.35 14.75 16.25C14.75 15.15 15.65 14.25 16.75 14.25ZM10.35 12L11.35 13.4L8.9 15.15L7.9 13.75L10.35 12ZM13.65 12L16.1 13.75L15.1 15.15L12.65 13.4L13.65 12Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 818 B |
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"fontFamily": "GopeedIcons",
|
||||||
|
"fontOutput": "../.build/GopeedIcons.ttf",
|
||||||
|
"dartOutput": "../.build/gopeed_icons.dart",
|
||||||
|
"previewOutput": "../.build/gopeed_icons_preview.png",
|
||||||
|
"dartClass": "GopeedIcons",
|
||||||
|
"codepointStart": "0xE900",
|
||||||
|
"unitsPerEm": 1024,
|
||||||
|
"ascent": 896,
|
||||||
|
"descent": -128,
|
||||||
|
"padding": 0,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"name": "file_category_template",
|
||||||
|
"source": "folder-symbol-template.svg",
|
||||||
|
"codepoint": "0xE900"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Gopeed file-category icon style
|
||||||
|
|
||||||
|
## Composition
|
||||||
|
|
||||||
|
- Unknown file: empty file shell.
|
||||||
|
- Known file: file shell plus one classification mark.
|
||||||
|
- Generic folder: empty folder shell.
|
||||||
|
- Known or protocol folder: folder shell plus one classification mark.
|
||||||
|
- Status and actions never belong inside a classification glyph.
|
||||||
|
|
||||||
|
## Geometry
|
||||||
|
|
||||||
|
- Use a `0 0 24 24` viewBox and keep the optical drawing inside `2…22` on both axes.
|
||||||
|
- Use the current shared shell as the source of truth. The established file shell spans roughly `x=3…21` with a 1.5-unit outline; do not silently introduce a heavier one-off border.
|
||||||
|
- Keep decorated marks approximately inside `x=6.2…17.8` and `y=9.2…19`. Preserve at least 1.5 units of visible separation from the shell wherever its interior edge is closer.
|
||||||
|
- Prefer radii around 1.5–2 units, consistent terminal shapes, and simple silhouettes. Avoid details or gaps below 1.25 units.
|
||||||
|
- Center by optical mass rather than bounding-box arithmetic when the shape has a tab, arrow, or asymmetric label.
|
||||||
|
- Use non-zero winding for counters and holes; reverse inner-contour direction where a cutout is required.
|
||||||
|
|
||||||
|
## Classification marks
|
||||||
|
|
||||||
|
- Use one dominant mark, not several miniature objects.
|
||||||
|
- Prefer semantic geometry: play for video, note for audio, image silhouette for images, grid for spreadsheets, a zipper for archive/compressed files, and a cylinder for databases.
|
||||||
|
- Avoid lettering when a semantic mark is clearer. When a conventional label such as PDF is retained, build each letter as filled geometry with at least 1.25-unit stems and explicit inter-letter gaps.
|
||||||
|
- Keep an empty file truly empty. A question mark, star, or extension text changes its meaning.
|
||||||
|
|
||||||
|
## Protocol-marked folders
|
||||||
|
|
||||||
|
- Keep the folder silhouette recognizable before adding the protocol symbol.
|
||||||
|
- Place a simple filled protocol symbol in the lower folder body with clear space from every edge.
|
||||||
|
- Prefer semantic marks such as a magnet/swarm for BitTorrent or a donkey/server-network mark for ED2K. Do not default to acronym lettering.
|
||||||
|
- Let the visible folder occupy about 80–85% of the 24-unit canvas. Avoid adding generator padding on top of the SVG optical margin; double padding makes Flutter icons look undersized.
|
||||||
|
- Compare optical center and occupied area against Flutter's `folder_outlined` at the actual widget size, not only in an enlarged preview.
|
||||||
|
|
||||||
|
## Consistency checks
|
||||||
|
|
||||||
|
- Compare new icons beside at least one existing folder icon and one file-type icon.
|
||||||
|
- Inspect the generated contact sheet at 16, 20, 24, and 32 px on light and dark swatches.
|
||||||
|
- Reject icons that depend on color, contain live text/strokes, have inconsistent baseline/weight, drift off center, become ambiguous at 16 px, or leave less than the shared safe-area separation from the shell.
|
||||||
|
- Compare decorated icons against both empty shells. Interior marks must not make the shell look heavier by merging into its border.
|
||||||
|
|
||||||
|
## Flutter usage
|
||||||
|
|
||||||
|
Register the generated TTF under `flutter.fonts` using the exact `fontFamily` from the manifest. Use the generated Dart constants rather than raw codepoints. Render icon-font glyphs with `Icon`; do not use `Text` because icon sizing and semantics should follow Flutter's icon pipeline.
|
||||||
@@ -0,0 +1,298 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build a deterministic Gopeed file-category font and Flutter IconData class from SVG paths."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import xml.etree.ElementTree as ET
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
try:
|
||||||
|
from fontTools.fontBuilder import FontBuilder
|
||||||
|
from fontTools.pens.boundsPen import BoundsPen
|
||||||
|
from fontTools.pens.cu2quPen import Cu2QuPen
|
||||||
|
from fontTools.pens.transformPen import TransformPen
|
||||||
|
from fontTools.pens.ttGlyphPen import TTGlyphPen
|
||||||
|
from fontTools.svgLib.path import SVGPath
|
||||||
|
except ImportError as error:
|
||||||
|
raise SystemExit("Missing fonttools; install scripts/requirements.txt in the skill's .venv") from error
|
||||||
|
|
||||||
|
|
||||||
|
NAME_PATTERN = re.compile(r"^[a-z][a-z0-9_]*$")
|
||||||
|
DART_NAME_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
|
||||||
|
PRIVATE_USE_START = 0xE000
|
||||||
|
PRIVATE_USE_END = 0xF8FF
|
||||||
|
ALLOWED_SVG_TAGS = {"svg", "g", "path"}
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--manifest", required=True, type=Path)
|
||||||
|
parser.add_argument("--allocate-codepoints", action="store_true")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def local_name(tag: str) -> str:
|
||||||
|
return tag.rsplit("}", 1)[-1]
|
||||||
|
|
||||||
|
|
||||||
|
def parse_number(value: object, field: str) -> int:
|
||||||
|
if isinstance(value, int):
|
||||||
|
return value
|
||||||
|
if isinstance(value, str):
|
||||||
|
try:
|
||||||
|
return int(value, 0)
|
||||||
|
except ValueError as error:
|
||||||
|
raise ValueError(f"{field} must be an integer or 0x-prefixed integer") from error
|
||||||
|
raise ValueError(f"{field} must be an integer or string")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_view_box(svg_text: str, source: Path) -> tuple[float, float, float, float]:
|
||||||
|
try:
|
||||||
|
root = ET.fromstring(svg_text)
|
||||||
|
except ET.ParseError as error:
|
||||||
|
raise ValueError(f"{source}: invalid XML: {error}") from error
|
||||||
|
if local_name(root.tag) != "svg":
|
||||||
|
raise ValueError(f"{source}: root element must be <svg>")
|
||||||
|
values = re.split(r"[\s,]+", root.attrib.get("viewBox", "").strip())
|
||||||
|
if len(values) != 4:
|
||||||
|
raise ValueError(f"{source}: viewBox must contain four numbers")
|
||||||
|
try:
|
||||||
|
min_x, min_y, width, height = (float(value) for value in values)
|
||||||
|
except ValueError as error:
|
||||||
|
raise ValueError(f"{source}: viewBox contains a non-numeric value") from error
|
||||||
|
if width <= 0 or height <= 0:
|
||||||
|
raise ValueError(f"{source}: viewBox dimensions must be positive")
|
||||||
|
if abs(width - height) > 1e-6:
|
||||||
|
raise ValueError(f"{source}: icon viewBox must be square")
|
||||||
|
|
||||||
|
path_count = 0
|
||||||
|
for element in root.iter():
|
||||||
|
tag = local_name(element.tag)
|
||||||
|
if tag not in ALLOWED_SVG_TAGS:
|
||||||
|
raise ValueError(f"{source}: unsupported <{tag}>; convert everything to filled paths")
|
||||||
|
style = element.attrib.get("style", "").replace(" ", "").lower()
|
||||||
|
stroke = element.attrib.get("stroke", "none").lower()
|
||||||
|
if stroke != "none" or ("stroke:" in style and "stroke:none" not in style):
|
||||||
|
raise ValueError(f"{source}: live strokes are not allowed; expand strokes to paths")
|
||||||
|
if tag == "path":
|
||||||
|
if not element.attrib.get("d", "").strip():
|
||||||
|
raise ValueError(f"{source}: every <path> needs path data")
|
||||||
|
if element.attrib.get("fill", "").lower() == "none" or "fill:none" in style:
|
||||||
|
raise ValueError(f"{source}: paths must be filled outlines")
|
||||||
|
path_count += 1
|
||||||
|
if path_count == 0:
|
||||||
|
raise ValueError(f"{source}: no paths found")
|
||||||
|
return min_x, min_y, width, height
|
||||||
|
|
||||||
|
|
||||||
|
def dart_name(icon: dict[str, object]) -> str:
|
||||||
|
explicit = icon.get("dartName")
|
||||||
|
if explicit is not None:
|
||||||
|
value = str(explicit)
|
||||||
|
else:
|
||||||
|
parts = str(icon["name"]).split("_")
|
||||||
|
value = parts[0] + "".join(part.capitalize() for part in parts[1:])
|
||||||
|
if not DART_NAME_PATTERN.fullmatch(value):
|
||||||
|
raise ValueError(f"invalid Dart field name: {value}")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def allocate_codepoints(manifest: dict[str, object], allow_allocation: bool) -> bool:
|
||||||
|
icons = manifest.get("icons")
|
||||||
|
if not isinstance(icons, list) or not icons:
|
||||||
|
raise ValueError("manifest.icons must be a non-empty list")
|
||||||
|
used = {
|
||||||
|
parse_number(icon["codepoint"], f"icons[{index}].codepoint")
|
||||||
|
for index, icon in enumerate(icons)
|
||||||
|
if isinstance(icon, dict) and icon.get("codepoint") is not None
|
||||||
|
}
|
||||||
|
next_codepoint = parse_number(manifest.get("codepointStart", "0xE900"), "codepointStart")
|
||||||
|
changed = False
|
||||||
|
for index, icon in enumerate(icons):
|
||||||
|
if not isinstance(icon, dict):
|
||||||
|
raise ValueError(f"icons[{index}] must be an object")
|
||||||
|
if icon.get("codepoint") is not None:
|
||||||
|
continue
|
||||||
|
if not allow_allocation:
|
||||||
|
raise ValueError(f"icons[{index}] has no codepoint; rerun with --allocate-codepoints")
|
||||||
|
while next_codepoint in used:
|
||||||
|
next_codepoint += 1
|
||||||
|
if next_codepoint > PRIVATE_USE_END:
|
||||||
|
raise ValueError("no codepoints remain in the BMP private-use area")
|
||||||
|
icon["codepoint"] = f"0x{next_codepoint:04X}"
|
||||||
|
used.add(next_codepoint)
|
||||||
|
next_codepoint += 1
|
||||||
|
changed = True
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def validate_icons(manifest: dict[str, object], manifest_dir: Path) -> list[dict[str, object]]:
|
||||||
|
icons = manifest["icons"]
|
||||||
|
assert isinstance(icons, list)
|
||||||
|
names: set[str] = set()
|
||||||
|
dart_names: set[str] = set()
|
||||||
|
codepoints: set[int] = set()
|
||||||
|
validated: list[dict[str, object]] = []
|
||||||
|
for index, raw_icon in enumerate(icons):
|
||||||
|
assert isinstance(raw_icon, dict)
|
||||||
|
name = str(raw_icon.get("name", ""))
|
||||||
|
if not NAME_PATTERN.fullmatch(name):
|
||||||
|
raise ValueError(f"icons[{index}].name must be lowercase snake_case")
|
||||||
|
field_name = dart_name(raw_icon)
|
||||||
|
codepoint = parse_number(raw_icon.get("codepoint"), f"icons[{index}].codepoint")
|
||||||
|
if not PRIVATE_USE_START <= codepoint <= PRIVATE_USE_END:
|
||||||
|
raise ValueError(f"{name}: codepoint must be in U+E000…U+F8FF")
|
||||||
|
source_value = raw_icon.get("source")
|
||||||
|
if not isinstance(source_value, str) or not source_value:
|
||||||
|
raise ValueError(f"{name}: source must be a relative SVG path")
|
||||||
|
source = (manifest_dir / source_value).resolve()
|
||||||
|
if source.suffix.lower() != ".svg" or not source.is_file():
|
||||||
|
raise ValueError(f"{name}: SVG source does not exist: {source}")
|
||||||
|
if name in names or field_name in dart_names or codepoint in codepoints:
|
||||||
|
raise ValueError(f"{name}: duplicate name, Dart field, or codepoint")
|
||||||
|
names.add(name)
|
||||||
|
dart_names.add(field_name)
|
||||||
|
codepoints.add(codepoint)
|
||||||
|
validated.append(
|
||||||
|
{
|
||||||
|
**raw_icon,
|
||||||
|
"name": name,
|
||||||
|
"glyphName": f"icon_{name}",
|
||||||
|
"dartName": field_name,
|
||||||
|
"codepoint": codepoint,
|
||||||
|
"sourcePath": source,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return sorted(validated, key=lambda icon: int(icon["codepoint"]))
|
||||||
|
|
||||||
|
|
||||||
|
def build_font(manifest: dict[str, object], manifest_dir: Path, icons: list[dict[str, object]]) -> Path:
|
||||||
|
family = str(manifest.get("fontFamily", "GopeedIcons"))
|
||||||
|
units_per_em = parse_number(manifest.get("unitsPerEm", 1024), "unitsPerEm")
|
||||||
|
ascent = parse_number(manifest.get("ascent", 896), "ascent")
|
||||||
|
descent = parse_number(manifest.get("descent", -128), "descent")
|
||||||
|
padding = parse_number(manifest.get("padding", 96), "padding")
|
||||||
|
if ascent <= 0 or descent >= 0 or ascent - descent != units_per_em:
|
||||||
|
raise ValueError("ascent must be positive, descent negative, and their span must equal unitsPerEm")
|
||||||
|
if padding < 0 or padding * 2 >= units_per_em:
|
||||||
|
raise ValueError("padding must leave positive drawing space")
|
||||||
|
|
||||||
|
glyph_order = [".notdef", *(str(icon["glyphName"]) for icon in icons)]
|
||||||
|
glyphs = {}
|
||||||
|
metrics = {".notdef": (units_per_em, 0)}
|
||||||
|
empty_pen = TTGlyphPen(None)
|
||||||
|
glyphs[".notdef"] = empty_pen.glyph()
|
||||||
|
|
||||||
|
for icon in icons:
|
||||||
|
source = icon["sourcePath"]
|
||||||
|
assert isinstance(source, Path)
|
||||||
|
svg_text = source.read_text(encoding="utf-8")
|
||||||
|
min_x, min_y, width, height = parse_view_box(svg_text, source)
|
||||||
|
available = units_per_em - padding * 2
|
||||||
|
scale = min(available / width, available / height)
|
||||||
|
glyph_width = width * scale
|
||||||
|
glyph_height = height * scale
|
||||||
|
left = (units_per_em - glyph_width) / 2
|
||||||
|
bottom = descent + (units_per_em - glyph_height) / 2
|
||||||
|
transform = (scale, 0, 0, -scale, left - scale * min_x, bottom + glyph_height + scale * min_y)
|
||||||
|
glyph_pen = TTGlyphPen(None)
|
||||||
|
quadratic_pen = Cu2QuPen(glyph_pen, max_err=1.0, reverse_direction=False)
|
||||||
|
transformed_pen = TransformPen(quadratic_pen, transform)
|
||||||
|
SVGPath.fromstring(svg_text).draw(transformed_pen)
|
||||||
|
glyphs[str(icon["glyphName"])] = glyph_pen.glyph()
|
||||||
|
|
||||||
|
bounds_pen = BoundsPen(None)
|
||||||
|
SVGPath.fromstring(svg_text).draw(TransformPen(bounds_pen, transform))
|
||||||
|
if bounds_pen.bounds is None:
|
||||||
|
raise ValueError(f"{source}: icon produced no drawable bounds")
|
||||||
|
metrics[str(icon["glyphName"])] = (units_per_em, round(bounds_pen.bounds[0]))
|
||||||
|
|
||||||
|
builder = FontBuilder(units_per_em, isTTF=True)
|
||||||
|
builder.setupGlyphOrder(glyph_order)
|
||||||
|
builder.setupCharacterMap({int(icon["codepoint"]): str(icon["glyphName"]) for icon in icons})
|
||||||
|
builder.setupGlyf(glyphs)
|
||||||
|
builder.setupHorizontalMetrics(metrics)
|
||||||
|
builder.setupHorizontalHeader(ascent=ascent, descent=descent)
|
||||||
|
version = str(manifest.get("version", "1.0.0"))
|
||||||
|
postscript_name = re.sub(r"[^A-Za-z0-9-]", "", family.replace(" ", "-")) or "GopeedIcons"
|
||||||
|
builder.setupNameTable(
|
||||||
|
{
|
||||||
|
"familyName": family,
|
||||||
|
"styleName": "Regular",
|
||||||
|
"uniqueFontIdentifier": f"{family};{version}",
|
||||||
|
"fullName": family,
|
||||||
|
"psName": postscript_name,
|
||||||
|
"version": f"Version {version}",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
builder.setupOS2(
|
||||||
|
sTypoAscender=ascent,
|
||||||
|
sTypoDescender=descent,
|
||||||
|
usWinAscent=ascent,
|
||||||
|
usWinDescent=-descent,
|
||||||
|
usWeightClass=400,
|
||||||
|
usWidthClass=5,
|
||||||
|
)
|
||||||
|
builder.setupPost()
|
||||||
|
builder.setupMaxp()
|
||||||
|
|
||||||
|
output = (manifest_dir / str(manifest["fontOutput"])).resolve()
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
builder.save(output)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def write_dart(manifest: dict[str, object], manifest_dir: Path, icons: list[dict[str, object]]) -> Path:
|
||||||
|
family = str(manifest.get("fontFamily", "GopeedIcons"))
|
||||||
|
class_name = str(manifest.get("dartClass", "GopeedIcons"))
|
||||||
|
if not DART_NAME_PATTERN.fullmatch(class_name):
|
||||||
|
raise ValueError("dartClass must be a valid Dart class name")
|
||||||
|
package = manifest.get("fontPackage")
|
||||||
|
package_argument = "" if package in (None, "") else f", fontPackage: '{package}'"
|
||||||
|
lines = [
|
||||||
|
"// Generated by gopeed-file-category-icons. Do not edit by hand.",
|
||||||
|
"import 'package:flutter/widgets.dart';",
|
||||||
|
"",
|
||||||
|
f"abstract final class {class_name} {{",
|
||||||
|
f" static const String _fontFamily = '{family}';",
|
||||||
|
]
|
||||||
|
for icon in icons:
|
||||||
|
lines.append(
|
||||||
|
f" static const IconData {icon['dartName']} = IconData(0x{int(icon['codepoint']):04x}, fontFamily: _fontFamily{package_argument});"
|
||||||
|
)
|
||||||
|
lines.extend(["}", ""])
|
||||||
|
output = (manifest_dir / str(manifest["dartOutput"])).resolve()
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output.write_text("\n".join(lines), encoding="utf-8")
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
manifest_path = args.manifest.resolve()
|
||||||
|
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||||
|
if allocate_codepoints(manifest, args.allocate_codepoints):
|
||||||
|
manifest_path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||||
|
manifest_dir = manifest_path.parent
|
||||||
|
icons = validate_icons(manifest, manifest_dir)
|
||||||
|
for required in ("fontOutput", "dartOutput"):
|
||||||
|
if not isinstance(manifest.get(required), str) or not manifest[required]:
|
||||||
|
raise ValueError(f"manifest.{required} must be a path")
|
||||||
|
font_output = build_font(manifest, manifest_dir, icons)
|
||||||
|
dart_output = write_dart(manifest, manifest_dir, icons)
|
||||||
|
print(f"Built {len(icons)} icons")
|
||||||
|
print(f"Font: {font_output}")
|
||||||
|
print(f"Dart: {dart_output}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
raise SystemExit(main())
|
||||||
|
except (KeyError, OSError, ValueError, json.JSONDecodeError) as error:
|
||||||
|
print(f"error: {error}", file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Render a light/dark multi-size contact sheet for a generated file-category font."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
try:
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
except ImportError as error:
|
||||||
|
raise SystemExit("Missing Pillow; install scripts/requirements.txt in the skill's .venv") from error
|
||||||
|
|
||||||
|
|
||||||
|
def parse_number(value: object) -> int:
|
||||||
|
return value if isinstance(value, int) else int(str(value), 0)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args() -> argparse.Namespace:
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--manifest", required=True, type=Path)
|
||||||
|
parser.add_argument("--sizes", default="16,20,24,32")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def draw_centered(
|
||||||
|
draw: ImageDraw.ImageDraw,
|
||||||
|
center: tuple[float, float],
|
||||||
|
char: str,
|
||||||
|
font: ImageFont.FreeTypeFont,
|
||||||
|
fill: str,
|
||||||
|
) -> None:
|
||||||
|
bounds = draw.textbbox((0, 0), char, font=font)
|
||||||
|
height = bounds[3] - bounds[1]
|
||||||
|
advance = draw.textlength(char, font=font)
|
||||||
|
draw.text(
|
||||||
|
(center[0] - advance / 2, center[1] - height / 2 - bounds[1]),
|
||||||
|
char,
|
||||||
|
font=font,
|
||||||
|
fill=fill,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
args = parse_args()
|
||||||
|
manifest_path = args.manifest.resolve()
|
||||||
|
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||||
|
manifest_dir = manifest_path.parent
|
||||||
|
font_path = (manifest_dir / str(manifest["fontOutput"])).resolve()
|
||||||
|
if not font_path.is_file():
|
||||||
|
raise ValueError(f"font does not exist; run the builder first: {font_path}")
|
||||||
|
sizes = [int(value) for value in args.sizes.split(",") if value.strip()]
|
||||||
|
if not sizes or any(size <= 0 for size in sizes):
|
||||||
|
raise ValueError("sizes must contain positive integers")
|
||||||
|
icons = sorted(manifest["icons"], key=lambda icon: parse_number(icon["codepoint"]))
|
||||||
|
|
||||||
|
label_width = 210
|
||||||
|
cell_width = 112
|
||||||
|
header_height = 44
|
||||||
|
row_height = 78
|
||||||
|
image = Image.new(
|
||||||
|
"RGB",
|
||||||
|
(label_width + cell_width * len(sizes), header_height + row_height * len(icons)),
|
||||||
|
"#F8FAFC",
|
||||||
|
)
|
||||||
|
draw = ImageDraw.Draw(image)
|
||||||
|
label_font = ImageFont.load_default()
|
||||||
|
draw.text((12, 15), "icon / codepoint", font=label_font, fill="#111827")
|
||||||
|
for column, size in enumerate(sizes):
|
||||||
|
x = label_width + column * cell_width
|
||||||
|
draw.text((x + 42, 15), f"{size}px", font=label_font, fill="#111827")
|
||||||
|
|
||||||
|
for row, icon in enumerate(icons):
|
||||||
|
y = header_height + row * row_height
|
||||||
|
codepoint = parse_number(icon["codepoint"])
|
||||||
|
draw.text(
|
||||||
|
(12, y + 29),
|
||||||
|
f"{icon['name']} U+{codepoint:04X}",
|
||||||
|
font=label_font,
|
||||||
|
fill="#111827",
|
||||||
|
)
|
||||||
|
for column, size in enumerate(sizes):
|
||||||
|
x = label_width + column * cell_width
|
||||||
|
midpoint = x + cell_width // 2
|
||||||
|
draw.rectangle((x, y, midpoint, y + row_height), fill="#FFFFFF")
|
||||||
|
draw.rectangle((midpoint, y, x + cell_width, y + row_height), fill="#111827")
|
||||||
|
font = ImageFont.truetype(str(font_path), size=size)
|
||||||
|
draw_centered(draw, (x + cell_width * 0.25, y + row_height / 2), chr(codepoint), font, "#111827")
|
||||||
|
draw_centered(draw, (x + cell_width * 0.75, y + row_height / 2), chr(codepoint), font, "#F8FAFC")
|
||||||
|
|
||||||
|
output_value = manifest.get("previewOutput", "file-category-icons-preview.png")
|
||||||
|
output = (manifest_dir / str(output_value)).resolve()
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
image.save(output)
|
||||||
|
print(f"Preview: {output}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
raise SystemExit(main())
|
||||||
|
except (KeyError, OSError, ValueError, json.JSONDecodeError) as error:
|
||||||
|
print(f"error: {error}", file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
fonttools==4.59.2
|
||||||
|
Pillow==11.3.0
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
.git
|
||||||
|
|
||||||
|
*.data
|
||||||
|
*.log
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
**/node_modules
|
||||||
|
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
|
||||||
|
.github
|
||||||
|
_docs
|
||||||
|
_examples
|
||||||
|
bin
|
||||||
|
ui
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
## Donate
|
|
||||||
|
|
||||||
🙏 Thank you for considering a donation to Gopeed project! Your support helps us continue to develop and maintain our software.
|
|
||||||
|
|
||||||
<div style="text-align: center;">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<th>微信</th>
|
|
||||||
<th>支付宝</th>
|
|
||||||
<th>Ko-fi</th>
|
|
||||||
<th>PayPal</th>
|
|
||||||
</tr>
|
|
||||||
<tr>
|
|
||||||
<td><img src="/.donate/qr/wechatpay.jpg" alt="wechatpay" width="300" /></td>
|
|
||||||
<td><img src="/.donate/qr/alipay.jpg" alt="alipay" width="300" /></td>
|
|
||||||
<td><a href="https://ko-fi.com/gopeed" target="_blank">Click Me</a></td>
|
|
||||||
<td><a href="https://paypal.me/monkeyWie" target="_blank">Click Me</a></td>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
### Crypto
|
|
||||||
|
|
||||||
- **BTC**: 35jYkPN8bgkh7AWjt3B1VgMQHqtGYcvF6p
|
|
||||||
- **ETH:** 0x928a7fd2398c941Ac6713704e606Fa414595e3A0
|
|
||||||
- **Matic:** 0x928a7fd2398c941Ac6713704e606Fa414595e3A0
|
|
||||||
- **BNB:** 0x928a7fd2398c941Ac6713704e606Fa414595e3A0
|
|
||||||
- **USDT(ERC20)**: 0x928a7fd2398c941Ac6713704e606Fa414595e3A0
|
|
||||||
|
Before Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 76 KiB |
@@ -0,0 +1 @@
|
|||||||
|
* @monkeyWie
|
||||||
@@ -12,4 +12,4 @@
|
|||||||
#custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
#custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||||
# github: monkeyWie
|
# github: monkeyWie
|
||||||
ko_fi: gopeed
|
ko_fi: gopeed
|
||||||
custom: https://github.com/GopeedLab/gopeed/blob/main/.donate/index.md#donate
|
custom: https://gopeed.com/docs/donate
|
||||||
@@ -1,35 +1,189 @@
|
|||||||
name-template: 'v$NEXT_PATCH_VERSION 🌈'
|
name-template: "v$NEXT_PATCH_VERSION 🌈"
|
||||||
tag-template: 'v$NEXT_PATCH_VERSION'
|
tag-template: "v$NEXT_PATCH_VERSION"
|
||||||
categories:
|
categories:
|
||||||
- title: '🆕 Features'
|
- title: "🆕 Features"
|
||||||
labels:
|
labels:
|
||||||
- 'feat'
|
- "feat"
|
||||||
- 'feature'
|
- "feature"
|
||||||
- 'enhancement'
|
- "enhancement"
|
||||||
- title: '🐛 Bug Fixes'
|
- title: "🐛 Bug Fixes"
|
||||||
labels:
|
labels:
|
||||||
- 'fix'
|
- "fix"
|
||||||
- 'bugfix'
|
- "bugfix"
|
||||||
- 'bug'
|
- "bug"
|
||||||
- title: '🧰 Maintenance'
|
- title: "🔧 Performance Improvements"
|
||||||
label: 'chore'
|
labels:
|
||||||
- title: '📖 Document'
|
- "perf"
|
||||||
label: 'doc'
|
- title: "🧪 Tests"
|
||||||
- title: '🚀 CI/CD'
|
label: "test"
|
||||||
label: 'ci'
|
- title: "🧰 Maintenance"
|
||||||
change-template: '- $TITLE @$AUTHOR (#$NUMBER)'
|
label: "chore"
|
||||||
|
- title: "📖 Document"
|
||||||
|
label: "docs"
|
||||||
|
- title: "🚀 CI/CD"
|
||||||
|
label: "ci"
|
||||||
|
- title: "🌎 Internationalization"
|
||||||
|
label: "translation"
|
||||||
|
change-template: "- $TITLE @$AUTHOR (#$NUMBER)"
|
||||||
version-resolver:
|
version-resolver:
|
||||||
major:
|
major:
|
||||||
labels:
|
labels:
|
||||||
- 'major'
|
- "major"
|
||||||
minor:
|
minor:
|
||||||
labels:
|
labels:
|
||||||
- 'minor'
|
- "minor"
|
||||||
patch:
|
patch:
|
||||||
labels:
|
labels:
|
||||||
- 'patch'
|
- "patch"
|
||||||
default: patch
|
default: patch
|
||||||
template: |
|
template: |
|
||||||
## Changes
|
<table>
|
||||||
|
<tbody>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="4">🪟 Windows</td>
|
||||||
|
<td rowspan="2"><code>EXE</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-windows-amd64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-windows-arm64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="2"><code>Portable</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-windows-amd64-portable.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-windows-arm64-portable.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="3">🍎 MacOS</td>
|
||||||
|
<td rowspan="3"><code>DMG</code></td>
|
||||||
|
<td>universal</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-macos.dmg">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-macos-amd64.dmg">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-macos-arm64.dmg">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="6">🐧 Linux</td>
|
||||||
|
<td><code>Flathub</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://flathub.org/apps/com.gopeed.Gopeed">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td><code>SNAP</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://snapcraft.io/gopeed">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="2"><code>DEB</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-linux-amd64.deb">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-linux-arm64.deb">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="2"><code>AppImage</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-linux-amd64.AppImage">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-linux-arm64.AppImage">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="4">🤖 Android</td>
|
||||||
|
<td rowspan="4"><code>APK</code></td>
|
||||||
|
<td>universal</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-android.apk">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>armeabi-v7a</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-android-armeabi-v7a.apk">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64-v8a</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-android-arm64-v8a.apk">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>x86_64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-android-x86_64.apk">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>📱 iOS</td>
|
||||||
|
<td><code>IPA</code></td>
|
||||||
|
<td>universal</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-v$NEXT_PATCH_VERSION-ios.ipa">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>🐳 Docker</td>
|
||||||
|
<td>-</td>
|
||||||
|
<td>universal</td>
|
||||||
|
<td><a href="https://hub.docker.com/r/liwei2633/gopeed">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="2">💾 Qnap</td>
|
||||||
|
<td rowspan="2"><code>QPKG</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-v$NEXT_PATCH_VERSION-qnap-amd64.qpkg">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-v$NEXT_PATCH_VERSION-qnap-arm64.qpkg">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="8">🌐 Web</td>
|
||||||
|
<td rowspan="3"><code>Windows</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-windows-amd64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-windows-arm64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>386</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-windows-386.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="2"><code>MacOS</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-macos-amd64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-macos-arm64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td rowspan="3"><code>Linux</code></td>
|
||||||
|
<td>amd64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-linux-amd64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>arm64</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-linux-arm64.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>386</td>
|
||||||
|
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-v$NEXT_PATCH_VERSION-linux-386.zip">📥</a></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
|
||||||
$CHANGES
|
# Release notes
|
||||||
|
|
||||||
|
$CHANGES
|
||||||
|
|
||||||
|
# 更新日志
|
||||||
|
|
||||||
|
$CHANGES
|
||||||
@@ -2,10 +2,21 @@ name: build
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
platform:
|
||||||
|
description: "Build platform"
|
||||||
|
required: true
|
||||||
|
default: "all"
|
||||||
|
test:
|
||||||
|
description: "Test mode"
|
||||||
|
required: true
|
||||||
|
default: "false"
|
||||||
|
|
||||||
env:
|
env:
|
||||||
GO_VERSION: 1.19
|
GO_VERSION: "1.25.4"
|
||||||
FLUTTER_VERSION: 3.10.6
|
FLUTTER_VERSION: "3.41.6"
|
||||||
|
GA4_MEASUREMENT_ID: ${{ secrets.GA4_MEASUREMENT_ID }}
|
||||||
|
GA4_API_SECRET: ${{ secrets.GA4_API_SECRET }}
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -14,56 +25,113 @@ jobs:
|
|||||||
get-release:
|
get-release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
outputs:
|
outputs:
|
||||||
tag_name: ${{ steps.get-release.outputs.tag_name }}
|
version: ${{ steps.get-release.outputs.version }}
|
||||||
upload_url: ${{ steps.get-release.outputs.upload_url }}
|
upload_url: ${{ steps.get-release.outputs.upload_url }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: monkeyWie/get-latest-release@v1
|
- uses: monkeyWie/get-latest-release@v2.1
|
||||||
id: get-release
|
id: get-release
|
||||||
with:
|
with:
|
||||||
myToken: ${{ github.token }}
|
myToken: ${{ github.token }}
|
||||||
|
|
||||||
build-windows:
|
build-windows:
|
||||||
runs-on: windows-latest
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'windows' }}
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- arch: arm64
|
||||||
|
os: windows-11-arm
|
||||||
|
llvm_ver: "20251202" # Only ARM64
|
||||||
|
flutter_channel: "main"
|
||||||
|
flutter_version: "7e1c8868"
|
||||||
|
- arch: amd64
|
||||||
|
os: windows-2022
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- name: Enable long paths for flutter main branch checks
|
||||||
|
run: |
|
||||||
|
git config --global core.longpaths true
|
||||||
|
|
||||||
|
# Install LLVM environment only on ARM64
|
||||||
|
- name: Install llvm-mingw-ucrt-aarch64 (ARM64 only)
|
||||||
|
if: matrix.arch == 'arm64'
|
||||||
|
run: |
|
||||||
|
$ver = "${{ matrix.llvm_ver }}"
|
||||||
|
$url = "https://github.com/mstorsjo/llvm-mingw/releases/download/$ver/llvm-mingw-$ver-ucrt-aarch64.zip"
|
||||||
|
$zip = "$env:RUNNER_TEMP\\llvm.zip"
|
||||||
|
$extract = "$env:RUNNER_TEMP\\extract"
|
||||||
|
$target = "C:\\clangarm64"
|
||||||
|
|
||||||
|
curl -L $url -o $zip
|
||||||
|
rm -r -fo $extract,$target -ea Ignore
|
||||||
|
mkdir $extract | Out-Null
|
||||||
|
|
||||||
|
tar -xf $zip -C $extract
|
||||||
|
mv (Get-ChildItem $extract)[0].FullName $target
|
||||||
|
|
||||||
|
$b = "$target\\bin"
|
||||||
|
"CC=$b\\clang.exe" >> $env:GITHUB_ENV
|
||||||
|
"CXX=$b\\clang++.exe" >> $env:GITHUB_ENV
|
||||||
|
"CLANGARM64_BIN=$b" >> $env:GITHUB_ENV
|
||||||
|
"CGO_ENABLED=1" >> $env:GITHUB_ENV
|
||||||
|
"CLANGARM64_ROOT=$target" >> $env:GITHUB_ENV
|
||||||
|
$b >> $env:GITHUB_PATH
|
||||||
|
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
channel: ${{ matrix.flutter_channel || 'stable' }}
|
||||||
|
flutter-version: ${{ matrix.flutter_version || env.FLUTTER_VERSION }}
|
||||||
- name: Build
|
- name: Build
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
|
GOARCH: ${{ matrix.arch }}
|
||||||
run: |
|
run: |
|
||||||
Invoke-WebRequest -Uri "https://github.com/jrsoftware/issrc/raw/main/Files/Languages/Unofficial/ChineseSimplified.isl" -OutFile "ChineseSimplified.isl"
|
Invoke-WebRequest -Uri "https://github.com/jrsoftware/issrc/raw/main/Files/Languages/ChineseSimplified.isl" -OutFile "ChineseSimplified.isl"
|
||||||
mv ChineseSimplified.isl "C:\Program Files (x86)\Inno Setup 6\Languages\"
|
mv ChineseSimplified.isl "C:\Program Files (x86)\Inno Setup 6\Languages\"
|
||||||
|
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
go build -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$env:VERSION" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/host.exe github.com/GopeedLab/gopeed/cmd/host
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/updater.exe github.com/GopeedLab/gopeed/cmd/updater
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build windows
|
$TAG = "v$env:VERSION"
|
||||||
$mingw = "C:\ProgramData\Chocolatey\lib\mingw\tools\install\mingw64\bin"
|
flutter build windows --dart-define="UPDATE_CHANNEL=windowsPortable" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
$system = "C:\Windows\System32"
|
$system = "C:\Windows\System32"
|
||||||
$release = "build\windows\runner\Release\"
|
if ("${{ matrix.arch }}" -eq "amd64") {
|
||||||
cp $mingw\libstdc++-6.dll $release
|
# for amd64
|
||||||
cp $mingw\libgcc_s_seh-1.dll $release
|
$release = "build\windows\x64\runner\Release\"
|
||||||
|
$mingw = "C:\Program Files\Git\mingw64\bin"
|
||||||
|
cp $mingw\libstdc++-6.dll $release
|
||||||
|
cp $mingw\libgcc_s_seh-1.dll $release
|
||||||
|
} else {
|
||||||
|
# for ARM64
|
||||||
|
$release = "build\windows\arm64\runner\Release\"
|
||||||
|
$mingw = "$env:CLANGARM64_ROOT\aarch64-w64-mingw32\bin"
|
||||||
|
cp $mingw\libc++.dll $release
|
||||||
|
cp $mingw\libunwind.dll $release
|
||||||
|
}
|
||||||
cp $mingw\libwinpthread-1.dll $release
|
cp $mingw\libwinpthread-1.dll $release
|
||||||
cp $system\msvcp140.dll $release
|
cp $system\msvcp140.dll $release
|
||||||
cp $system\vcruntime140.dll $release
|
cp $system\vcruntime140.dll $release
|
||||||
cp $system\vcruntime140_1.dll $release
|
cp $system\vcruntime140_1.dll $release
|
||||||
|
|
||||||
New-Item -Path build\windows\Output -ItemType Directory
|
New-Item -Path build\windows\Output -ItemType Directory
|
||||||
Compress-Archive -Path "$release*" -DestinationPath "build\windows\Output\Gopeed-$env:VERSION-windows-amd64-portable.zip"
|
Compress-Archive -Path "$release*" -DestinationPath "build\windows\Output\Gopeed-$TAG-windows-${{ matrix.arch }}-portable.zip"
|
||||||
|
|
||||||
|
flutter build windows --dart-define="UPDATE_CHANNEL=windowsInstaller" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
cd build/windows
|
cd build/windows
|
||||||
echo @"
|
echo @"
|
||||||
; Script generated by the Inno Setup Script Wizard.
|
; Script generated by the Inno Setup Script Wizard.
|
||||||
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
|
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
|
||||||
|
|
||||||
#define MyAppName "Gopeed"
|
#define MyAppName "Gopeed"
|
||||||
#define MyAppVersion "$($env:VERSION.substring(1))"
|
#define MyAppVersion "$env:VERSION"
|
||||||
#define MyAppPublisher "monkeyWie"
|
#define MyAppPublisher "monkeyWie"
|
||||||
#define MyAppURL "https://gopeed.com"
|
#define MyAppURL "https://gopeed.com"
|
||||||
#define MyAppExeName "gopeed.exe"
|
#define MyAppExeName "gopeed.exe"
|
||||||
@@ -86,11 +154,13 @@ jobs:
|
|||||||
PrivilegesRequired=lowest
|
PrivilegesRequired=lowest
|
||||||
OutputBaseFilename=gopeed
|
OutputBaseFilename=gopeed
|
||||||
SetupIconFile=..\..\assets\icon\icon.ico
|
SetupIconFile=..\..\assets\icon\icon.ico
|
||||||
|
UninstallDisplayIcon={app}\{#MyAppExeName}
|
||||||
Compression=lzma
|
Compression=lzma
|
||||||
SolidCompression=yes
|
SolidCompression=yes
|
||||||
WizardStyle=modern
|
WizardStyle=modern
|
||||||
LanguageDetectionMethod=uilanguage
|
LanguageDetectionMethod=uilanguage
|
||||||
ShowLanguageDialog=yes
|
ShowLanguageDialog=yes
|
||||||
|
CloseApplications=force
|
||||||
|
|
||||||
[Languages]
|
[Languages]
|
||||||
Name: "english"; MessagesFile: "compiler:Default.isl"
|
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||||
@@ -100,7 +170,7 @@ jobs:
|
|||||||
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
|
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
|
||||||
|
|
||||||
[Files]
|
[Files]
|
||||||
Source: ".\runner\Release\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs
|
Source: ".\${{ matrix.arch == 'amd64' && 'x64' || 'arm64' }}\runner\Release\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs;
|
||||||
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
|
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
|
||||||
|
|
||||||
[UninstallDelete]
|
[UninstallDelete]
|
||||||
@@ -114,39 +184,47 @@ jobs:
|
|||||||
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
|
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent
|
||||||
"@ > setup.iss
|
"@ > setup.iss
|
||||||
iscc.exe setup.iss
|
iscc.exe setup.iss
|
||||||
mv "Output\gopeed.exe" "Output\Gopeed-$env:VERSION-windows-amd64.exe"
|
mv "Output\gopeed.exe" "Output\Gopeed-$TAG-windows-${{ matrix.arch }}.exe"
|
||||||
Compress-Archive -Path "Output\Gopeed-$env:VERSION-windows-amd64.exe" -DestinationPath "Output\Gopeed-$env:VERSION-windows-amd64.zip"
|
Compress-Archive -Path "Output\Gopeed-$TAG-windows-${{ matrix.arch }}.exe" -DestinationPath "Output\Gopeed-$TAG-windows-${{ matrix.arch }}.zip"
|
||||||
Remove-Item -Path "Output\Gopeed-$env:VERSION-windows-amd64.exe"
|
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: shogo82148/actions-upload-release-asset@v1
|
uses: shogo82148/actions-upload-release-asset@v1.9.2
|
||||||
with:
|
with:
|
||||||
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
||||||
asset_path: ui/flutter/build/windows/Output/*
|
asset_path: ui/flutter/build/windows/Output/*
|
||||||
overwrite: true
|
overwrite: true
|
||||||
build-macos-arm64-lib:
|
build-macos-amd64-lib:
|
||||||
runs-on: ubuntu-latest
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'macos' }}
|
||||||
|
runs-on: macos-15-intel
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- name: Build
|
- name: Build
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
docker pull techknowlogick/xgo:go-1.19.x
|
go build -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -buildmode=c-shared -o libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
go install src.techknowlogick.com/xgo@latest
|
go build -ldflags="-w -s" github.com/GopeedLab/gopeed/cmd/host
|
||||||
xgo --targets=darwin/arm64 -tags="nosqlite" -ldflags="-w -s" -buildmode=c-shared -pkg=bind/desktop -out=libgopeed .
|
go build -ldflags="-w -s" github.com/GopeedLab/gopeed/cmd/updater
|
||||||
mv libgopeed-*.dylib libgopeed.dylib
|
- uses: actions/upload-artifact@v4
|
||||||
- uses: actions/upload-artifact@v3
|
|
||||||
with:
|
with:
|
||||||
name: macos-arm64-lib
|
name: macos-amd64-lib
|
||||||
path: libgopeed.dylib
|
path: |
|
||||||
|
libgopeed.dylib
|
||||||
|
host
|
||||||
|
updater
|
||||||
build-macos:
|
build-macos:
|
||||||
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'macos' }}
|
||||||
runs-on: macos-latest
|
runs-on: macos-latest
|
||||||
needs: [get-release, build-macos-arm64-lib]
|
strategy:
|
||||||
|
matrix:
|
||||||
|
channel: [arm64, amd64, universal]
|
||||||
|
needs: [get-release, build-macos-amd64-lib]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: actions/setup-node@v3
|
- uses: actions/setup-node@v3
|
||||||
@@ -156,28 +234,52 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- name: Install appdmg
|
- name: Install appdmg
|
||||||
run: npm install -g appdmg
|
|
||||||
- uses: actions/download-artifact@v3
|
|
||||||
with:
|
|
||||||
name: macos-arm64-lib
|
|
||||||
path: ui/flutter/lib-arm64
|
|
||||||
- name: Build
|
|
||||||
env:
|
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
|
||||||
run: |
|
run: |
|
||||||
PROJECT_DIR=$(pwd)
|
python3 -m pip install setuptools --break-system-packages
|
||||||
|
npm install -g appdmg
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: macos-amd64-lib
|
||||||
|
path: ui/flutter/lib-amd64
|
||||||
|
- if: ${{ matrix.channel == 'arm64' }}
|
||||||
|
name: Build Arm64 Libraries
|
||||||
|
run: |
|
||||||
|
go build -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/host github.com/GopeedLab/gopeed/cmd/host
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/updater github.com/GopeedLab/gopeed/cmd/updater
|
||||||
|
- if: ${{ matrix.channel == 'amd64' }}
|
||||||
|
name: Build Amd64 Libraries
|
||||||
|
run: |
|
||||||
|
mkdir -p ui/flutter/macos/Frameworks
|
||||||
|
|
||||||
|
cp ui/flutter/lib-amd64/libgopeed.dylib ui/flutter/macos/Frameworks/libgopeed.dylib
|
||||||
|
cp ui/flutter/lib-amd64/host ui/flutter/assets/exec/host
|
||||||
|
cp ui/flutter/lib-amd64/updater ui/flutter/assets/exec/updater
|
||||||
|
- if: ${{ matrix.channel == 'universal' }}
|
||||||
|
name: Build Universal Libraries
|
||||||
|
run: |
|
||||||
|
mkdir -p ui/flutter/macos/Frameworks
|
||||||
|
|
||||||
|
# arm64 lib
|
||||||
|
go build -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -buildmode=c-shared -o ui/flutter/.temp/libgopeed.dylib.arm64 github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/.temp/host.arm64 github.com/GopeedLab/gopeed/cmd/host
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/.temp/updater.arm64 github.com/GopeedLab/gopeed/cmd/updater
|
||||||
|
|
||||||
# amd64 lib
|
# amd64 lib
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/lib-amd64/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
cp ui/flutter/lib-amd64/libgopeed.dylib ui/flutter/.temp/libgopeed.dylib.amd64
|
||||||
# universal binary
|
cp ui/flutter/lib-amd64/host ui/flutter/.temp/host.amd64
|
||||||
mkdir -p ui/flutter/macos/Frameworks
|
cp ui/flutter/lib-amd64/updater ui/flutter/.temp/updater.amd64
|
||||||
cp ui/flutter/lib-amd64/libgopeed.dylib ui/flutter/macos/Frameworks/amd64-lib
|
|
||||||
cp ui/flutter/lib-arm64/libgopeed.dylib ui/flutter/macos/Frameworks/arm64-lib
|
|
||||||
cd ui/flutter/macos/Frameworks
|
|
||||||
lipo -create -output libgopeed.dylib amd64-lib arm64-lib
|
|
||||||
|
|
||||||
cd $PROJECT_DIR/ui/flutter
|
# universal lib
|
||||||
flutter build macos
|
lipo -create -output ui/flutter/macos/Frameworks/libgopeed.dylib ui/flutter/.temp/libgopeed.dylib.arm64 ui/flutter/.temp/libgopeed.dylib.amd64
|
||||||
|
lipo -create -output ui/flutter/assets/exec/host ui/flutter/.temp/host.arm64 ui/flutter/.temp/host.amd64
|
||||||
|
lipo -create -output ui/flutter/assets/exec/updater ui/flutter/.temp/updater.arm64 ui/flutter/.temp/updater.amd64
|
||||||
|
- name: Build
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
|
run: |
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build macos --dart-define="UPDATE_CHANNEL=macosDmg" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
cd build/macos/Build/Products/Release
|
cd build/macos/Build/Products/Release
|
||||||
cat>appdmg.json<<EOF
|
cat>appdmg.json<<EOF
|
||||||
{
|
{
|
||||||
@@ -190,7 +292,14 @@ jobs:
|
|||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
mkdir dist
|
mkdir dist
|
||||||
appdmg appdmg.json dist/Gopeed-$VERSION-macos.dmg
|
appdmg appdmg.json dist/Gopeed-v$VERSION-macos.dmg
|
||||||
|
|
||||||
|
if [[ "${{ matrix.channel }}" == "arm64" ]]; then
|
||||||
|
mv dist/Gopeed-v$VERSION-macos.dmg dist/Gopeed-v$VERSION-macos-arm64.dmg
|
||||||
|
fi
|
||||||
|
if [[ "${{ matrix.channel }}" == "amd64" ]]; then
|
||||||
|
mv dist/Gopeed-v$VERSION-macos.dmg dist/Gopeed-v$VERSION-macos-amd64.dmg
|
||||||
|
fi
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: shogo82148/actions-upload-release-asset@v1
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
with:
|
with:
|
||||||
@@ -198,96 +307,285 @@ jobs:
|
|||||||
asset_path: ui/flutter/build/macos/Build/Products/Release/dist/*
|
asset_path: ui/flutter/build/macos/Build/Products/Release/dist/*
|
||||||
overwrite: true
|
overwrite: true
|
||||||
build-linux:
|
build-linux:
|
||||||
runs-on: ubuntu-latest
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'linux' }}
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ubuntu-22.04, ubuntu-22.04-arm]
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
|
channel: master
|
||||||
- run: |
|
- run: |
|
||||||
sudo apt-get update -y
|
sudo apt update -y
|
||||||
sudo apt-get install -y ninja-build libgtk-3-dev libayatana-appindicator3-dev
|
sudo apt install -y ninja-build libgtk-3-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-1 libayatana-appindicator3-dev rpm patchelf libfuse2 locate libkeybinder-3.0-dev
|
||||||
|
arch=$(uname -m)
|
||||||
|
wget -O appimagetool "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-${arch}.AppImage"
|
||||||
|
chmod +x appimagetool
|
||||||
|
sudo mv appimagetool /usr/local/bin/
|
||||||
- name: Build
|
- name: Build
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
go build -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/host github.com/GopeedLab/gopeed/cmd/host
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/updater github.com/GopeedLab/gopeed/cmd/updater
|
||||||
|
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build linux
|
|
||||||
mkdir -p debian/gui
|
RPM_ARCH=$(uname -m)
|
||||||
cp assets/icon/icon_1024.png debian/gui/gopeed.png
|
mkdir -p linux/packaging/rpm
|
||||||
cat>debian/debian.yaml<<EOF
|
cat << EOF > linux/packaging/rpm/make_config.yaml
|
||||||
flutter_app:
|
display_name: Gopeed
|
||||||
command: gopeed
|
icon: assets/icon/icon.svg
|
||||||
arch: x64
|
summary: High speed downloader.
|
||||||
parent: /usr/local/lib
|
description: A high speed downloader that supports all platforms.
|
||||||
control:
|
group: Applications/Internet
|
||||||
Package: gopeed
|
license: GPL-3.0
|
||||||
Version: ${VERSION:1}
|
url: https://github.com/GopeedLab/gopeed
|
||||||
Architecture: amd64
|
vendor: GopeedLab
|
||||||
Essential: no
|
maintainer: GopeedLab <[email protected]>
|
||||||
Priority: optional
|
build_arch: $RPM_ARCH
|
||||||
Depends:
|
|
||||||
Maintainer: monkeyWie
|
|
||||||
Description: High speed downloader that supports all platforms.
|
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
cat>debian/gui/gopeed.desktop<<EOF
|
cat << EOF > distribute_options.yaml
|
||||||
[Desktop Entry]
|
output: dist/
|
||||||
Version=${VERSION:1}
|
releases:
|
||||||
Name=Gopeed
|
- name: linux
|
||||||
GenericName=Gopeed
|
jobs:
|
||||||
Comment=High speed downloader that supports all platforms.
|
- name: appimage
|
||||||
Terminal=false
|
package:
|
||||||
Type=Application
|
platform: linux
|
||||||
Categories=Utility
|
target: appimage
|
||||||
Keywords=Flutter;Downloader;
|
build_args:
|
||||||
|
dart-define:
|
||||||
|
UPDATE_CHANNEL: linuxAppImage
|
||||||
|
GA4_MEASUREMENT_ID: ${{ env.GA4_MEASUREMENT_ID }}
|
||||||
|
GA4_API_SECRET: ${{ env.GA4_API_SECRET }}
|
||||||
|
- name: deb
|
||||||
|
package:
|
||||||
|
platform: linux
|
||||||
|
target: deb
|
||||||
|
build_args:
|
||||||
|
dart-define:
|
||||||
|
UPDATE_CHANNEL: linuxDeb
|
||||||
|
GA4_MEASUREMENT_ID: ${{ env.GA4_MEASUREMENT_ID }}
|
||||||
|
GA4_API_SECRET: ${{ env.GA4_API_SECRET }}
|
||||||
|
- name: rpm
|
||||||
|
package:
|
||||||
|
platform: linux
|
||||||
|
target: rpm
|
||||||
|
build_args:
|
||||||
|
dart-define:
|
||||||
|
UPDATE_CHANNEL: linuxRpm
|
||||||
|
GA4_MEASUREMENT_ID: ${{ env.GA4_MEASUREMENT_ID }}
|
||||||
|
GA4_API_SECRET: ${{ env.GA4_API_SECRET }}
|
||||||
EOF
|
EOF
|
||||||
|
dart pub global activate -sgit https://github.com/GopeedLab/flutter_distributor.git --git-path packages/flutter_distributor
|
||||||
|
flutter_distributor release --name linux
|
||||||
|
cd dist/*
|
||||||
|
|
||||||
dart pub global activate flutter_to_debian
|
ARCH="amd64"
|
||||||
flutter_to_debian
|
if [[ "${{ matrix.os }}" == *-arm ]]; then
|
||||||
mv debian/packages/gopeed*.deb debian/packages/Gopeed-$VERSION-linux-amd64.deb
|
ARCH="arm64"
|
||||||
|
fi
|
||||||
|
|
||||||
|
mv gopeed-*-linux.AppImage Gopeed-v${VERSION}-linux-${ARCH}.AppImage
|
||||||
|
mv gopeed-*-linux.deb Gopeed-v${VERSION}-linux-${ARCH}.deb
|
||||||
|
mv gopeed-*-linux.rpm Gopeed-v${VERSION}-linux-${ARCH}.rpm
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: shogo82148/actions-upload-release-asset@v1
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
with:
|
with:
|
||||||
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
||||||
asset_path: ui/flutter/debian/packages/*
|
asset_path: ui/flutter/dist/*/*
|
||||||
overwrite: true
|
overwrite: true
|
||||||
|
build-snap:
|
||||||
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'snap' }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
needs: [get-release]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ${{ env.GO_VERSION }}
|
||||||
|
- name: Install Snap host build dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y --no-install-recommends pkg-config libgtk-3-dev libwebkit2gtk-4.1-dev
|
||||||
|
- name: Setup LXD
|
||||||
|
uses: canonical/[email protected]
|
||||||
|
with:
|
||||||
|
channel: latest/stable
|
||||||
|
- name: Build
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
|
run: |
|
||||||
|
go build -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/host github.com/GopeedLab/gopeed/cmd/host
|
||||||
|
go build -ldflags="-w -s" -o ui/flutter/assets/exec/updater github.com/GopeedLab/gopeed/cmd/updater
|
||||||
|
cd ui/flutter
|
||||||
|
|
||||||
|
sudo snap install snapcraft --classic
|
||||||
|
mkdir -p snap/gui
|
||||||
|
cp assets/icon/icon.svg snap/gui/gopeed.svg
|
||||||
|
|
||||||
|
cat>snap/snapcraft.yaml<<EOF
|
||||||
|
name: gopeed
|
||||||
|
version: $VERSION
|
||||||
|
summary: A modern download manager
|
||||||
|
description: High speed downloader that supports all platforms.
|
||||||
|
|
||||||
|
confinement: strict
|
||||||
|
base: core24
|
||||||
|
grade: stable
|
||||||
|
|
||||||
|
platforms:
|
||||||
|
amd64:
|
||||||
|
build-on: amd64
|
||||||
|
build-for: amd64
|
||||||
|
|
||||||
|
slots:
|
||||||
|
dbus-gopeed:
|
||||||
|
interface: dbus
|
||||||
|
bus: session
|
||||||
|
name: com.gopeed.gopeed
|
||||||
|
|
||||||
|
apps:
|
||||||
|
gopeed:
|
||||||
|
command-chain:
|
||||||
|
- bin/gpu-2404-wrapper
|
||||||
|
command: bin/gopeed
|
||||||
|
extensions: [gnome]
|
||||||
|
common-id: com.gopeed.Gopeed
|
||||||
|
plugs:
|
||||||
|
- network
|
||||||
|
- home
|
||||||
|
parts:
|
||||||
|
flutter-git:
|
||||||
|
source: https://github.com/flutter/flutter.git
|
||||||
|
source-tag: $FLUTTER_VERSION
|
||||||
|
source-depth: 1
|
||||||
|
plugin: nil
|
||||||
|
override-build: |
|
||||||
|
mkdir -p \$CRAFT_PART_INSTALL/usr/bin
|
||||||
|
mkdir -p \$CRAFT_PART_INSTALL/usr/libexec
|
||||||
|
cp -r \$CRAFT_PART_SRC \$CRAFT_PART_INSTALL/usr/libexec/flutter
|
||||||
|
ln -s \$CRAFT_PART_INSTALL/usr/libexec/flutter/bin/flutter \$CRAFT_PART_INSTALL/usr/bin/flutter
|
||||||
|
ln -s \$SNAPCRAFT_PART_INSTALL/usr/libexec/flutter/bin/dart \$SNAPCRAFT_PART_INSTALL/usr/bin/dart
|
||||||
|
\$CRAFT_PART_INSTALL/usr/bin/flutter doctor
|
||||||
|
build-packages:
|
||||||
|
- clang
|
||||||
|
- llvm-18
|
||||||
|
- lld
|
||||||
|
- cmake
|
||||||
|
- curl
|
||||||
|
- libgtk-3-dev
|
||||||
|
- libwebkit2gtk-4.1-dev
|
||||||
|
- libkeybinder-3.0-dev
|
||||||
|
- ninja-build
|
||||||
|
- unzip
|
||||||
|
- xz-utils
|
||||||
|
- zip
|
||||||
|
override-prime: ''
|
||||||
|
zenity:
|
||||||
|
plugin: nil
|
||||||
|
stage-packages:
|
||||||
|
- zenity
|
||||||
|
gopeed:
|
||||||
|
after: [flutter-git,zenity]
|
||||||
|
source: .
|
||||||
|
plugin: nil
|
||||||
|
stage-packages:
|
||||||
|
- libwebkit2gtk-4.1-0
|
||||||
|
- libgtk-3-dev
|
||||||
|
- libkeybinder-3.0-dev
|
||||||
|
- libappindicator3-dev
|
||||||
|
override-build: |
|
||||||
|
# work around pub get stack overflow # https://github.com/dart-lang/sdk/issues/51068#issuecomment-1396588253
|
||||||
|
set +e
|
||||||
|
dart pub get
|
||||||
|
set -eux
|
||||||
|
llvm_bin_dir="\$(dirname "\$(readlink -f "\$(command -v clang)")")"
|
||||||
|
test -x "\$llvm_bin_dir/llvm-ar"
|
||||||
|
test -x "\$llvm_bin_dir/ld.lld"
|
||||||
|
flutter build linux --dart-define="UPDATE_CHANNEL=linuxSnap" --dart-define="GA4_MEASUREMENT_ID=$GA4_MEASUREMENT_ID" --dart-define="GA4_API_SECRET=$GA4_API_SECRET"
|
||||||
|
mkdir -p \$CRAFT_PART_INSTALL/bin/
|
||||||
|
cp -r build/linux/*/release/bundle/* \$CRAFT_PART_INSTALL/bin/
|
||||||
|
gpu-2404:
|
||||||
|
after: [gopeed]
|
||||||
|
source: https://github.com/canonical/gpu-snap.git
|
||||||
|
plugin: dump
|
||||||
|
override-prime: |
|
||||||
|
craftctl default
|
||||||
|
\${CRAFT_PART_SRC}/bin/gpu-2404-cleanup mesa-2404
|
||||||
|
prime:
|
||||||
|
- bin/gpu-2404-wrapper
|
||||||
|
|
||||||
|
plugs:
|
||||||
|
gpu-2404:
|
||||||
|
interface: content
|
||||||
|
target: \$SNAP/gpu-2404
|
||||||
|
default-provider: mesa-2404
|
||||||
|
|
||||||
|
layout:
|
||||||
|
/usr/share/libdrm:
|
||||||
|
bind: \$SNAP/gpu-2404/libdrm
|
||||||
|
/usr/share/drirc.d:
|
||||||
|
symlink: \$SNAP/gpu-2404/drirc.d
|
||||||
|
/usr/share/X11/XErrorDB:
|
||||||
|
symlink: \$SNAP/gpu-2404/X11/XErrorDB
|
||||||
|
EOF
|
||||||
|
|
||||||
|
cp linux/assets/com.gopeed.Gopeed.desktop snap/gui/gopeed.desktop
|
||||||
|
sed -i 's/Icon=com.gopeed.Gopeed/Icon=\${SNAP}\/meta\/gui\/gopeed.svg/g' snap/gui/gopeed.desktop
|
||||||
|
|
||||||
|
snapcraft --use-lxd
|
||||||
|
|
||||||
|
# Snapcraft login
|
||||||
|
export SNAPCRAFT_STORE_CREDENTIALS=${{ secrets.SNAP_STORE_LOGIN }}
|
||||||
|
snapcraft upload --release=${{ github.event.inputs.test == 'true' && 'edge' || 'stable' }} gopeed_${VERSION}_amd64.snap
|
||||||
build-android:
|
build-android:
|
||||||
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'android' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: actions/setup-java@v3
|
- uses: actions/setup-java@v3
|
||||||
with:
|
with:
|
||||||
distribution: "zulu"
|
distribution: "zulu"
|
||||||
java-version: "11"
|
java-version: "17"
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- name: Build
|
- name: Build
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
APK_KEYSTORE : ${{ secrets.APK_KEYSTORE }}
|
APK_KEYSTORE: ${{ secrets.APK_KEYSTORE }}
|
||||||
APK_KEY_PASSWORD : ${{ secrets.APK_KEY_PASSWORD }}
|
APK_KEY_PASSWORD: ${{ secrets.APK_KEY_PASSWORD }}
|
||||||
APK_STORE_PASSWORD : ${{ secrets.APK_STORE_PASSWORD }}
|
APK_STORE_PASSWORD: ${{ secrets.APK_STORE_PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
go install golang.org/x/mobile/cmd/gomobile@latest
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
go get golang.org/x/mobile/bind
|
go get golang.org/x/mobile/bind
|
||||||
gomobile init
|
gomobile init
|
||||||
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 19 -javapkg=com.gopeed github.com/GopeedLab/gopeed/bind/mobile
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0 -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg=com.gopeed github.com/GopeedLab/gopeed/bind/mobile
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
echo $APK_KEYSTORE | base64 -di > android/app/upload-keystore.jks
|
echo $APK_KEYSTORE | base64 -di > android/app/upload-keystore.jks
|
||||||
flutter build apk
|
flutter build apk --dart-define="UPDATE_CHANNEL=androidApk" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
|
flutter build apk --split-per-abi --dart-define="UPDATE_CHANNEL=androidApk" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
mkdir dist
|
mkdir dist
|
||||||
cp build/app/outputs/flutter-apk/app-release.apk dist/Gopeed-$VERSION-android.apk
|
cp build/app/outputs/flutter-apk/app-release.apk dist/Gopeed-v$VERSION-android.apk
|
||||||
|
cp build/app/outputs/flutter-apk/app-armeabi-v7a-release.apk dist/Gopeed-v$VERSION-android-armeabi-v7a.apk
|
||||||
|
cp build/app/outputs/flutter-apk/app-arm64-v8a-release.apk dist/Gopeed-v$VERSION-android-arm64-v8a.apk
|
||||||
|
cp build/app/outputs/flutter-apk/app-x86_64-release.apk dist/Gopeed-v$VERSION-android-x86_64.apk
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: shogo82148/actions-upload-release-asset@v1
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
with:
|
with:
|
||||||
@@ -295,11 +593,12 @@ jobs:
|
|||||||
asset_path: ui/flutter/dist/*
|
asset_path: ui/flutter/dist/*
|
||||||
overwrite: true
|
overwrite: true
|
||||||
build-ios:
|
build-ios:
|
||||||
runs-on: macos-latest
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'ios' }}
|
||||||
|
runs-on: macos-26
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
@@ -307,19 +606,19 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- name: Build
|
- name: Build
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
go install golang.org/x/mobile/cmd/gomobile@latest
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
go get golang.org/x/mobile/bind
|
go get golang.org/x/mobile/bind
|
||||||
gomobile init
|
gomobile init
|
||||||
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
gomobile bind -tags nosqlite -ldflags="-w -s -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build ios --no-codesign
|
flutter build ios --no-codesign --dart-define="UPDATE_CHANNEL=iosIpa" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
mkdir Payload
|
mkdir Payload
|
||||||
cp -r build/ios/iphoneos/Runner.app Payload
|
cp -r build/ios/iphoneos/Runner.app Payload
|
||||||
zip -r -y Payload.zip Payload/Runner.app
|
zip -r -y Payload.zip Payload/Runner.app
|
||||||
mkdir dist
|
mkdir dist
|
||||||
mv Payload.zip dist/Gopeed-$VERSION-ios.ipa
|
mv Payload.zip dist/Gopeed-v$VERSION-ios.ipa
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: shogo82148/actions-upload-release-asset@v1
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
with:
|
with:
|
||||||
@@ -327,11 +626,12 @@ jobs:
|
|||||||
asset_path: ui/flutter/dist/*
|
asset_path: ui/flutter/dist/*
|
||||||
overwrite: true
|
overwrite: true
|
||||||
build-web:
|
build-web:
|
||||||
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'web' || github.event.inputs.platform == 'qnap' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
@@ -339,13 +639,15 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- name: Build
|
- name: Build
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
run: |
|
run: |
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build web --web-renderer html
|
flutter build web --no-web-resources-cdn --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
|
dart ../../.github/workflows/scripts/flutter_local_font.dart
|
||||||
cd ../../
|
cd ../../
|
||||||
cp -r ui/flutter/build/web cmd/web/dist
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
mkdir -p dist/zip
|
mkdir -p dist/zip
|
||||||
|
|
||||||
goos_arr=(windows darwin linux)
|
goos_arr=(windows darwin linux)
|
||||||
goarch_arr=(386 amd64 arm64)
|
goarch_arr=(386 amd64 arm64)
|
||||||
export CGO_ENABLED=0
|
export CGO_ENABLED=0
|
||||||
@@ -355,9 +657,9 @@ jobs:
|
|||||||
if [ $goos = "darwin" ]; then
|
if [ $goos = "darwin" ]; then
|
||||||
goos_name="macos"
|
goos_name="macos"
|
||||||
fi
|
fi
|
||||||
name=gopeed-web-$VERSION-$goos_name-$goarch
|
name=gopeed-web-v$VERSION-$goos_name-$goarch
|
||||||
dir="dist/$name/"
|
dir="dist/$name/"
|
||||||
(GOOS=$goos GOARCH=$goarch go build -tags nosqlite,web -ldflags="-s -w" -o $dir github.com/GopeedLab/gopeed/cmd/web \
|
(GOOS=$goos GOARCH=$goarch go build -tags nosqlite,web -ldflags="-s -w -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION" -o $dir github.com/GopeedLab/gopeed/cmd/web \
|
||||||
&& cd $dir \
|
&& cd $dir \
|
||||||
&& file=$(ls -AU | head -1) \
|
&& file=$(ls -AU | head -1) \
|
||||||
&& mkdir $name \
|
&& mkdir $name \
|
||||||
@@ -367,16 +669,86 @@ jobs:
|
|||||||
|| true
|
|| true
|
||||||
done
|
done
|
||||||
done
|
done
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: web-dist
|
||||||
|
path: dist/zip/
|
||||||
- name: Upload
|
- name: Upload
|
||||||
uses: shogo82148/actions-upload-release-asset@v1
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
with:
|
with:
|
||||||
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
||||||
asset_path: dist/zip/*
|
asset_path: dist/zip/*
|
||||||
overwrite: true
|
overwrite: true
|
||||||
|
build-qnap:
|
||||||
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'qnap' }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [get-release, build-web]
|
||||||
|
steps:
|
||||||
|
- uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: "3.8.18"
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: web-dist
|
||||||
|
path: dist/zip/
|
||||||
|
- name: Build
|
||||||
|
env:
|
||||||
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
|
run: |
|
||||||
|
sudo apt update -y
|
||||||
|
qdk_version=2.5.3
|
||||||
|
qdk_package="qdk_${qdk_version}_amd64.deb"
|
||||||
|
curl --fail --location --retry 3 --retry-all-errors \
|
||||||
|
--output "${qdk_package}" \
|
||||||
|
"https://github.com/qnap-dev/QDK/releases/download/v${qdk_version}/${qdk_package}"
|
||||||
|
echo "17b3841b7d4590a4ee025844ba583304b5e3c497d9fa8934d5175131d3908022 ${qdk_package}" | sha256sum --check --strict
|
||||||
|
sudo apt-get install -y "./${qdk_package}"
|
||||||
|
command -v qbuild
|
||||||
|
|
||||||
|
wget -O Gopeed.template.tar.gz "https://github.com/GopeedLab/QpkgBuild/raw/refs/heads/master/template/Gopeed.template.tar.gz"
|
||||||
|
tar -zxf Gopeed.template.tar.gz
|
||||||
|
[[ -d Gopeed ]] || exit 1
|
||||||
|
|
||||||
|
goos=linux
|
||||||
|
goarch_arr=(amd64 arm64)
|
||||||
|
for goarch in "${goarch_arr[@]}"; do
|
||||||
|
qarch=x86_64
|
||||||
|
[[ "${goarch}" == "arm64" ]] && qarch=arm_64
|
||||||
|
name=gopeed-web-v${VERSION}-${goos}-${goarch}
|
||||||
|
unzip dist/zip/${name}.zip -d dist/${name}
|
||||||
|
cp dist/${name}/${name}/* Gopeed/${qarch}/
|
||||||
|
done
|
||||||
|
cd Gopeed
|
||||||
|
sed -i -e 's/__QPKG_VER__/${VERSION}/g' qpkg.cfg
|
||||||
|
qbuild || exit 1
|
||||||
|
|
||||||
|
mkdir -p ../dist/qnap
|
||||||
|
goos=qnap
|
||||||
|
for goarch in "${goarch_arr[@]}"; do
|
||||||
|
qarch=x86_64
|
||||||
|
[[ "${goarch}" == "arm64" ]] && qarch=arm_64
|
||||||
|
sname=Gopeed_${VERSION}_${qarch}.qpkg
|
||||||
|
dname=gopeed-v${VERSION}-${goos}-${goarch}.qpkg
|
||||||
|
[[ -f build/${sname} ]] && cp -ra build/${sname} ../dist/qnap/${dname}
|
||||||
|
done
|
||||||
|
- name: Upload
|
||||||
|
uses: shogo82148/actions-upload-release-asset@v1
|
||||||
|
with:
|
||||||
|
upload_url: ${{ needs.get-release.outputs.upload_url }}
|
||||||
|
asset_path: dist/qnap/*
|
||||||
|
overwrite: true
|
||||||
build-docker:
|
build-docker:
|
||||||
|
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'docker' }}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [get-release]
|
needs: [get-release]
|
||||||
steps:
|
steps:
|
||||||
|
- name: Remove unnecessary files
|
||||||
|
run: |
|
||||||
|
sudo rm -rf /usr/share/dotnet
|
||||||
|
sudo rm -rf "$AGENT_TOOLSDIRECTORY"
|
||||||
|
- uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- name: Set up QEMU
|
- name: Set up QEMU
|
||||||
uses: docker/setup-qemu-action@v2
|
uses: docker/setup-qemu-action@v2
|
||||||
@@ -387,16 +759,29 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
username: liwei2633
|
username: liwei2633
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
|
- name: Build flutter web
|
||||||
|
run: |
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build web --no-web-resources-cdn --dart-define="UPDATE_CHANNEL=docker" --dart-define="GA4_MEASUREMENT_ID=${{ env.GA4_MEASUREMENT_ID }}" --dart-define="GA4_API_SECRET=${{ env.GA4_API_SECRET }}"
|
||||||
|
dart ../../.github/workflows/scripts/flutter_local_font.dart
|
||||||
|
cd ../../
|
||||||
|
rm -rf cmd/web/dist
|
||||||
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v2
|
uses: docker/build-push-action@v2
|
||||||
env:
|
env:
|
||||||
VERSION: ${{ needs.get-release.outputs.tag_name }}
|
VERSION: ${{ needs.get-release.outputs.version }}
|
||||||
with:
|
with:
|
||||||
push: true
|
context: .
|
||||||
|
push: ${{ github.event.inputs.test == 'true' && 'false' || 'true' }}
|
||||||
|
build-args: |
|
||||||
|
VERSION=${{ env.VERSION }}
|
||||||
|
IN_DOCKER=true
|
||||||
platforms: |
|
platforms: |
|
||||||
linux/386
|
linux/386
|
||||||
linux/amd64
|
linux/amd64
|
||||||
linux/arm64
|
linux/arm64
|
||||||
|
linux/arm/v7
|
||||||
tags: |
|
tags: |
|
||||||
liwei2633/gopeed:latest
|
liwei2633/gopeed:latest
|
||||||
liwei2633/gopeed:${{ env.VERSION }}
|
liwei2633/gopeed:v${{ env.VERSION }}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
name: l10n
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- "ui/flutter/lib/l10n/**"
|
||||||
|
- "ui/flutter/l10n.yaml"
|
||||||
|
- ".github/workflows/scripts/check_l10n.dart"
|
||||||
|
- ".github/workflows/l10n.yml"
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- main
|
||||||
|
paths:
|
||||||
|
- "ui/flutter/lib/l10n/**"
|
||||||
|
- "ui/flutter/l10n.yaml"
|
||||||
|
- ".github/workflows/scripts/check_l10n.dart"
|
||||||
|
- ".github/workflows/l10n.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: l10n-${{ github.event.pull_request.number || github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
env:
|
||||||
|
FLUTTER_VERSION: "3.41.6"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
validate:
|
||||||
|
name: Validate Flutter translations
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
defaults:
|
||||||
|
run:
|
||||||
|
working-directory: ui/flutter
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
|
- run: flutter pub get
|
||||||
|
- name: Validate ARB catalogs
|
||||||
|
run: dart run ../../.github/workflows/scripts/check_l10n.dart
|
||||||
|
- name: Generate localizations
|
||||||
|
run: flutter gen-l10n
|
||||||
|
- name: Analyze generated localization integration
|
||||||
|
run: flutter analyze
|
||||||
@@ -17,7 +17,7 @@ on:
|
|||||||
- "Dockerfile"
|
- "Dockerfile"
|
||||||
|
|
||||||
env:
|
env:
|
||||||
GO_VERSION: 1.19
|
GO_VERSION: "1.25.4"
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
@@ -31,7 +31,7 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: release-drafter/release-drafter@v5
|
- uses: release-drafter/release-drafter@v5
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// Validate Flutter ARB translation catalogs before localization code generation.
|
||||||
|
//
|
||||||
|
// Usage (from ui/flutter):
|
||||||
|
// dart run ../../.github/workflows/scripts/check_l10n.dart
|
||||||
|
//
|
||||||
|
// What it checks:
|
||||||
|
// - Every ARB file uses the repository's canonical two-space JSON formatting.
|
||||||
|
// - Every app_<locale>.arb file declares the matching @@locale value.
|
||||||
|
// - Message values are not empty (warning only).
|
||||||
|
// - Every locale has the same message keys as app_en.arb (warning only).
|
||||||
|
// - Every translation preserves the placeholder variables used by app_en.arb
|
||||||
|
// (warning only).
|
||||||
|
//
|
||||||
|
// Notes:
|
||||||
|
// - This script does not judge translation quality.
|
||||||
|
// - It does not generate localization code or fully parse ICU MessageFormat.
|
||||||
|
// `flutter gen-l10n` runs immediately afterwards in CI to validate ICU syntax
|
||||||
|
// and generate app_localizations*.dart.
|
||||||
|
// - The script exits with a failure only for malformed JSON, invalid ARB
|
||||||
|
// formatting, or a mismatched @@locale value. Translation completeness is
|
||||||
|
// reported as warnings; generation and analysis remain the compile-time gate.
|
||||||
|
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// Runs repository-specific checks that `flutter gen-l10n` does not enforce.
|
||||||
|
void main() {
|
||||||
|
final directory = Directory('lib/l10n');
|
||||||
|
final templateFile = File('${directory.path}/app_en.arb');
|
||||||
|
final template = _readArb(templateFile);
|
||||||
|
final templateKeys = _messageKeys(template);
|
||||||
|
var failed = false;
|
||||||
|
|
||||||
|
for (final file in directory.listSync().whereType<File>().where(
|
||||||
|
(file) => file.path.endsWith('.arb'),
|
||||||
|
)) {
|
||||||
|
final messages = _readArb(file);
|
||||||
|
if (!_hasCanonicalFormat(file, messages)) {
|
||||||
|
stderr.writeln(
|
||||||
|
'${file.path}: ARB formatting is not canonical (use two-space JSON indentation and a trailing newline)',
|
||||||
|
);
|
||||||
|
failed = true;
|
||||||
|
}
|
||||||
|
final expectedLocale = file.uri.pathSegments.last
|
||||||
|
.replaceFirst('app_', '')
|
||||||
|
.replaceFirst('.arb', '');
|
||||||
|
if (messages['@@locale'] != expectedLocale) {
|
||||||
|
stderr.writeln('${file.path}: @@locale must be $expectedLocale');
|
||||||
|
failed = true;
|
||||||
|
}
|
||||||
|
final keys = _messageKeys(messages);
|
||||||
|
final empty =
|
||||||
|
keys.where((key) => (messages[key] as String).trim().isEmpty).toList()
|
||||||
|
..sort();
|
||||||
|
if (empty.isNotEmpty) {
|
||||||
|
_warning('${file.path}: empty messages $empty');
|
||||||
|
}
|
||||||
|
if (file.path == templateFile.path) continue;
|
||||||
|
final missing = templateKeys.difference(keys);
|
||||||
|
final extra = keys.difference(templateKeys);
|
||||||
|
if (missing.isNotEmpty || extra.isNotEmpty) {
|
||||||
|
_warning(
|
||||||
|
'${file.path}: missing ${missing.toList()..sort()}, extra ${extra.toList()..sort()}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (final key in templateKeys.intersection(keys)) {
|
||||||
|
final expected = _placeholders(template[key] as String);
|
||||||
|
final actual = _placeholders(messages[key] as String);
|
||||||
|
if (!_sameSet(expected, actual)) {
|
||||||
|
_warning(
|
||||||
|
'${file.path}: $key placeholders $actual do not match $expected',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (failed) exitCode = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads one ARB file as its top-level JSON object.
|
||||||
|
Map<String, Object?> _readArb(File file) =>
|
||||||
|
jsonDecode(file.readAsStringSync()) as Map<String, Object?>;
|
||||||
|
|
||||||
|
/// Checks the exact JSON layout so whitespace-only formatting drift fails CI.
|
||||||
|
bool _hasCanonicalFormat(File file, Map<String, Object?> arb) {
|
||||||
|
const encoder = JsonEncoder.withIndent(' ');
|
||||||
|
return file.readAsStringSync() == '${encoder.convert(arb)}\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns user-facing message keys and excludes ARB metadata keys (`@`/`@@`).
|
||||||
|
Set<String> _messageKeys(Map<String, Object?> arb) =>
|
||||||
|
arb.keys.where((key) => !key.startsWith('@')).toSet();
|
||||||
|
|
||||||
|
/// Extracts both simple placeholders (`{name}`) and ICU selector variables.
|
||||||
|
///
|
||||||
|
/// For example, this returns `count` from
|
||||||
|
/// `{count, plural, =1{1 file} other{{count} files}}`.
|
||||||
|
Set<String> _placeholders(String message) => RegExp(
|
||||||
|
r'\{([A-Za-z_][A-Za-z0-9_]*)(?=\s*(?:\}|,\s*(?:plural|select|selectordinal)\s*,))',
|
||||||
|
).allMatches(message).map((match) => match.group(1)!).toSet();
|
||||||
|
|
||||||
|
/// Compares sets without depending on iteration order.
|
||||||
|
bool _sameSet(Set<String> left, Set<String> right) =>
|
||||||
|
left.length == right.length && left.containsAll(right);
|
||||||
|
|
||||||
|
void _warning(String message) => stderr.writeln('warning: $message');
|
||||||
@@ -0,0 +1,413 @@
|
|||||||
|
// Localize external Google Fonts (fonts.gstatic.com) references in Flutter Web build output.
|
||||||
|
//
|
||||||
|
// Usage (post-build):
|
||||||
|
// # Run AFTER: flutter build web --no-web-resources-cdn
|
||||||
|
// dart ../../.github/workflows/scripts/flutter_local_font.dart
|
||||||
|
//
|
||||||
|
// What it does:
|
||||||
|
// In main.dart.js:
|
||||||
|
// - Find any referenced resources under: https://fonts.gstatic.com/s/
|
||||||
|
// (including the common pattern where Flutter concatenates the base URL with a relative path)
|
||||||
|
// - Download them into: build/web/assets/gstatic/<path>
|
||||||
|
// - Rewrite "https://fonts.gstatic.com/s/" -> "assets/gstatic/" so runtime loads locally
|
||||||
|
// - Only download font subsets needed by supported locales (parsed from lib/l10n/*.arb)
|
||||||
|
//
|
||||||
|
// Notes:
|
||||||
|
// - This script DOES NOT call `flutter build web`. It only patches the output.
|
||||||
|
// - This is a best-effort post-process. Always verify in browser devtools.
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
/// Get font families required for a specific locale based on language/script.
|
||||||
|
/// Uses language code prefix to automatically detect the script system.
|
||||||
|
/// Returns empty set if base fonts (Latin/Cyrillic/Greek) are sufficient.
|
||||||
|
Set<String> _getFontFamiliesForLocale(String locale) {
|
||||||
|
final normalizedLocale = locale.toLowerCase().replaceAll('-', '_');
|
||||||
|
final lang = normalizedLocale.split('_').first;
|
||||||
|
|
||||||
|
// CJK languages - need specific large font files
|
||||||
|
if (lang == 'zh') {
|
||||||
|
// Simplified vs Traditional Chinese
|
||||||
|
if (normalizedLocale.contains('_tw') ||
|
||||||
|
normalizedLocale.contains('_hk') ||
|
||||||
|
normalizedLocale.contains('_mo')) {
|
||||||
|
return {'notosanstc', 'notosanshk'}; // Traditional Chinese (TW, HK, MO)
|
||||||
|
}
|
||||||
|
return {'notosanssc'}; // Simplified Chinese, including generic zh
|
||||||
|
}
|
||||||
|
if (lang == 'ja') return {'notosansjp'}; // Japanese
|
||||||
|
if (lang == 'ko') return {'notosanskr'}; // Korean
|
||||||
|
|
||||||
|
// Arabic script languages
|
||||||
|
if (lang == 'ar') return {'notosansarabic'}; // Arabic
|
||||||
|
if (lang == 'fa') return {'notosansarabic'}; // Persian/Farsi
|
||||||
|
if (lang == 'ur') return {'notosansarabic'}; // Urdu
|
||||||
|
if (lang == 'ps') return {'notosansarabic'}; // Pashto
|
||||||
|
if (lang == 'ku') return {'notosansarabic'}; // Kurdish (Arabic script)
|
||||||
|
|
||||||
|
// Hebrew script
|
||||||
|
if (lang == 'he' || lang == 'yi') return {'notosanshebrew'};
|
||||||
|
|
||||||
|
// South Asian scripts
|
||||||
|
if (lang == 'hi' || lang == 'mr' || lang == 'ne' || lang == 'sa') {
|
||||||
|
return {'notosansdevanagari'}; // Hindi, Marathi, Nepali, Sanskrit
|
||||||
|
}
|
||||||
|
if (lang == 'bn' || lang == 'as')
|
||||||
|
return {'notosansbengali'}; // Bengali, Assamese
|
||||||
|
if (lang == 'ta')
|
||||||
|
return {'notosanstamil', 'notosanstamilsupplement'}; // Tamil
|
||||||
|
if (lang == 'te') return {'notosanstelugu'}; // Telugu
|
||||||
|
if (lang == 'kn') return {'notosanskannada'}; // Kannada
|
||||||
|
if (lang == 'ml') return {'notosansmalayalam'}; // Malayalam
|
||||||
|
if (lang == 'gu') return {'notosansgujarati'}; // Gujarati
|
||||||
|
if (lang == 'pa') return {'notosansgurmukhi'}; // Punjabi (Gurmukhi)
|
||||||
|
if (lang == 'or') return {'notosansoriya'}; // Odia/Oriya
|
||||||
|
if (lang == 'si') return {'notosanssinhala'}; // Sinhala
|
||||||
|
|
||||||
|
// Southeast Asian scripts
|
||||||
|
if (lang == 'th') return {'notosansthai'}; // Thai
|
||||||
|
if (lang == 'lo') return {'notosanslao'}; // Lao
|
||||||
|
if (lang == 'my') return {'notosansmyanmar'}; // Myanmar/Burmese
|
||||||
|
if (lang == 'km') return {'notosanskhmer'}; // Khmer/Cambodian
|
||||||
|
if (lang == 'jv') return {'notosansjavanese'}; // Javanese
|
||||||
|
|
||||||
|
// Other scripts
|
||||||
|
if (lang == 'ka') return {'notosansgeorgian'}; // Georgian
|
||||||
|
if (lang == 'hy') return {'notosansarmenian'}; // Armenian
|
||||||
|
if (lang == 'am' || lang == 'ti')
|
||||||
|
return {'notosansethiopic'}; // Amharic, Tigrinya
|
||||||
|
if (lang == 'mn') return {'notosansmongolian'}; // Mongolian
|
||||||
|
|
||||||
|
// Latin/Cyrillic/Greek based languages - base notosans is sufficient
|
||||||
|
// Includes: English, German, French, Spanish, Italian, Portuguese,
|
||||||
|
// Russian, Ukrainian, Polish, Turkish, Vietnamese, Greek, etc.
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Base font families that are always included regardless of locale.
|
||||||
|
/// These provide core functionality and are relatively small.
|
||||||
|
const _baseFontFamilies = <String>{
|
||||||
|
'notosans', // Base Latin/Cyrillic/Greek/Vietnamese
|
||||||
|
'roboto', // Material Design default font
|
||||||
|
'notosanssymbols', // Common symbols
|
||||||
|
'notosanssymbols2', // Additional symbols
|
||||||
|
'notosansmath', // Math symbols
|
||||||
|
'notomusic', // Music notation symbols
|
||||||
|
// Note: notocoloremoji (~24MB) and notoemoji (~860KB) are excluded
|
||||||
|
// to reduce bundle size. Add them back if emoji support is needed.
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Parse supported locales from Flutter gen-l10n ARB filenames.
|
||||||
|
/// Filenames follow app_<locale>.arb, for example app_zh_CN.arb or app_en.arb.
|
||||||
|
Set<String> _parseSupportedLocales(Directory l10nDirectory) {
|
||||||
|
final locales = <String>{};
|
||||||
|
|
||||||
|
if (!l10nDirectory.existsSync()) {
|
||||||
|
_fail('Localization directory not found: ${l10nDirectory.path}');
|
||||||
|
}
|
||||||
|
|
||||||
|
final arbName = RegExp(r'^app_(.+)\.arb$');
|
||||||
|
for (final entity in l10nDirectory.listSync()) {
|
||||||
|
if (entity is! File) continue;
|
||||||
|
final filename = entity.uri.pathSegments.last;
|
||||||
|
final locale = arbName.firstMatch(filename)?.group(1);
|
||||||
|
if (locale != null && locale.isNotEmpty) locales.add(locale);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (locales.isEmpty) {
|
||||||
|
_fail('No app_<locale>.arb files found in ${l10nDirectory.path}');
|
||||||
|
}
|
||||||
|
|
||||||
|
return locales;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get required font families for the given locales.
|
||||||
|
/// Returns a set of font family names that should be included.
|
||||||
|
/// Automatically detects required fonts based on language code prefix.
|
||||||
|
Set<String> _getRequiredFontFamilies(Set<String> locales) {
|
||||||
|
final families = <String>{..._baseFontFamilies};
|
||||||
|
for (final locale in locales) {
|
||||||
|
final localeFamilies = _getFontFamiliesForLocale(locale);
|
||||||
|
families.addAll(localeFamilies);
|
||||||
|
}
|
||||||
|
return families;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if a font file path should be included based on required font families.
|
||||||
|
/// Font paths have the format: "fontfamily/version/filename.ext"
|
||||||
|
/// Example: "notosanssc/v36/xxx.ttf" -> font family is "notosanssc"
|
||||||
|
bool _fontMatchesRequiredFamilies(
|
||||||
|
String fontPath,
|
||||||
|
Set<String> requiredFamilies,
|
||||||
|
) {
|
||||||
|
// Extract font family from path (first segment before '/')
|
||||||
|
final slashIndex = fontPath.indexOf('/');
|
||||||
|
if (slashIndex == -1) {
|
||||||
|
// No slash found, include by default (unusual path format)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
final fontFamily = fontPath.substring(0, slashIndex).toLowerCase();
|
||||||
|
return requiredFamilies.contains(fontFamily);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> main(List<String> args) async {
|
||||||
|
try {
|
||||||
|
// This script is intentionally argument-free for CI convenience.
|
||||||
|
// It assumes it is executed from the Flutter project directory (ui/flutter),
|
||||||
|
// but will also try to locate pubspec.yaml by walking up.
|
||||||
|
final flutterDir = _findFlutterProjectRoot(Directory.current);
|
||||||
|
|
||||||
|
// Parse supported locales from Flutter gen-l10n ARB files.
|
||||||
|
final l10nDirectory = Directory(_join(flutterDir.path, 'lib', 'l10n'));
|
||||||
|
final supportedLocales = _parseSupportedLocales(l10nDirectory);
|
||||||
|
stdout.writeln('Supported locales: ${supportedLocales.join(', ')}');
|
||||||
|
|
||||||
|
// Get required font families based on supported locales
|
||||||
|
final requiredFamilies = _getRequiredFontFamilies(supportedLocales);
|
||||||
|
stdout.writeln('Required font families: ${requiredFamilies.join(', ')}');
|
||||||
|
|
||||||
|
final webDir = Directory(_join(flutterDir.path, 'build', 'web'));
|
||||||
|
if (!webDir.existsSync()) {
|
||||||
|
_fail(
|
||||||
|
'Web build directory not found: ${webDir.path}\n'
|
||||||
|
'Did you run: flutter build web --no-web-resources-cdn ?',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final mainJs = File(_join(webDir.path, 'main.dart.js'));
|
||||||
|
if (!mainJs.existsSync()) {
|
||||||
|
_fail('main.dart.js not found at: ${mainJs.path}');
|
||||||
|
}
|
||||||
|
|
||||||
|
final gstaticRoot = Directory(_join(webDir.path, 'assets', 'gstatic'));
|
||||||
|
if (!gstaticRoot.existsSync()) gstaticRoot.createSync(recursive: true);
|
||||||
|
|
||||||
|
const gstaticSPrefix = 'https://fonts.gstatic.com/s/';
|
||||||
|
final original = mainJs.readAsStringSync();
|
||||||
|
|
||||||
|
// Relative font asset paths which Flutter's loader typically concatenates with:
|
||||||
|
// https://fonts.gstatic.com/s/
|
||||||
|
// Keep this as a best-effort heuristic to cover the common concatenation pattern.
|
||||||
|
// Some gstatic assets include extra dot segments like: notocoloremoji/v32/Yq6P-KqIXTD0t4D9z1ESnKM3-HpFabsE4tq3luCC7p-aXxcn.0.woff2
|
||||||
|
// Allow dots in the path, while still restricting to font-like extensions.
|
||||||
|
final relAssetRegex = RegExp(
|
||||||
|
r"""["']([a-zA-Z0-9/_\.-]+\.(?:woff2|woff|ttf|otf|eot|svg))["']""",
|
||||||
|
caseSensitive: false,
|
||||||
|
);
|
||||||
|
final relAssetsUnderS = <String>{};
|
||||||
|
for (final m in relAssetRegex.allMatches(original)) {
|
||||||
|
final p = m.group(1);
|
||||||
|
if (p == null || p.isEmpty) continue;
|
||||||
|
if (p.contains('://') || p.startsWith('data:')) continue;
|
||||||
|
if (p.startsWith('/') ||
|
||||||
|
p.startsWith('assets/') ||
|
||||||
|
p.startsWith('packages/'))
|
||||||
|
continue;
|
||||||
|
if (p.contains('..')) continue;
|
||||||
|
relAssetsUnderS.add(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (relAssetsUnderS.isEmpty) {
|
||||||
|
_fail('No fonts.gstatic.com assets found in main.dart.js.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build a download plan: dest relative path (under assets/gstatic/) -> URL.
|
||||||
|
// Filter fonts based on required font families to reduce package size.
|
||||||
|
final downloads = <String, Uri>{};
|
||||||
|
final skippedFonts = <String, Set<String>>{};
|
||||||
|
|
||||||
|
for (final rel in relAssetsUnderS) {
|
||||||
|
if (_fontMatchesRequiredFamilies(rel, requiredFamilies)) {
|
||||||
|
downloads[rel] = Uri.parse('$gstaticSPrefix$rel');
|
||||||
|
} else {
|
||||||
|
// Track skipped fonts and their paths for fallback generation
|
||||||
|
final slashIndex = rel.indexOf('/');
|
||||||
|
final family = slashIndex > 0 ? rel.substring(0, slashIndex) : rel;
|
||||||
|
skippedFonts.putIfAbsent(family, () => <String>{}).add(rel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (skippedFonts.isNotEmpty) {
|
||||||
|
stdout.writeln(
|
||||||
|
'Skipped ${skippedFonts.length} font families not required by supported locales:',
|
||||||
|
);
|
||||||
|
stdout.writeln(' ${skippedFonts.keys.join(', ')}');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (downloads.isNotEmpty) {
|
||||||
|
stdout.writeln(
|
||||||
|
'Found ${downloads.length} fonts.gstatic.com assets to download...',
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reuse a single HttpClient to avoid creating hundreds of short-lived
|
||||||
|
// connections (can be flaky on some environments).
|
||||||
|
final httpClient = HttpClient()
|
||||||
|
..connectionTimeout = const Duration(seconds: 30)
|
||||||
|
..idleTimeout = const Duration(seconds: 30)
|
||||||
|
..maxConnectionsPerHost = 6;
|
||||||
|
try {
|
||||||
|
for (final entry in downloads.entries) {
|
||||||
|
final relPath = entry.key;
|
||||||
|
final url = entry.value;
|
||||||
|
final destPath = relPath.replaceAll('/', Platform.pathSeparator);
|
||||||
|
final dest = File(_join(gstaticRoot.path, destPath));
|
||||||
|
await _downloadIfMissing(httpClient, url, dest);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
httpClient.close(force: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate empty fallback font files for skipped fonts to prevent infinite loading
|
||||||
|
// Empty files will cause browsers to fail fast instead of retrying indefinitely
|
||||||
|
if (skippedFonts.isNotEmpty) {
|
||||||
|
var fallbackCount = 0;
|
||||||
|
for (final entry in skippedFonts.entries) {
|
||||||
|
for (final relPath in entry.value) {
|
||||||
|
final destPath = relPath.replaceAll('/', Platform.pathSeparator);
|
||||||
|
final dest = File(_join(gstaticRoot.path, destPath));
|
||||||
|
if (!dest.existsSync()) {
|
||||||
|
dest.parent.createSync(recursive: true);
|
||||||
|
// Create an empty file - browsers will recognize it as invalid and skip
|
||||||
|
dest.writeAsBytesSync([]);
|
||||||
|
fallbackCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (fallbackCount > 0) {
|
||||||
|
stdout.writeln(
|
||||||
|
'Generated $fallbackCount empty fallback font files to prevent infinite loading',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rewrite remote prefix so requests become:
|
||||||
|
// <origin>/assets/gstatic/<...>.woff2
|
||||||
|
final replacedGstatic = original.replaceAll(
|
||||||
|
gstaticSPrefix,
|
||||||
|
'assets/gstatic/',
|
||||||
|
);
|
||||||
|
|
||||||
|
if (replacedGstatic == original && downloads.isEmpty) {
|
||||||
|
stdout.writeln(
|
||||||
|
'No changes applied (no fonts.gstatic.com references found).',
|
||||||
|
);
|
||||||
|
exitCode = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
mainJs.writeAsStringSync(replacedGstatic);
|
||||||
|
|
||||||
|
stdout.writeln('Patched: ${mainJs.path}');
|
||||||
|
if (downloads.isNotEmpty) {
|
||||||
|
stdout.writeln(
|
||||||
|
' - downloaded ${downloads.length} files into: ${gstaticRoot.path}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
stdout.writeln(' - fonts.gstatic.com rewritten -> assets/gstatic/');
|
||||||
|
} catch (e, st) {
|
||||||
|
stderr.writeln('ERROR: $e');
|
||||||
|
stderr.writeln(st);
|
||||||
|
exitCode = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _downloadIfMissing(HttpClient client, Uri url, File dest) async {
|
||||||
|
if (dest.existsSync() && dest.lengthSync() > 0) return;
|
||||||
|
|
||||||
|
dest.parent.createSync(recursive: true);
|
||||||
|
|
||||||
|
// Network can be flaky in CI. Retry a few times on transient errors.
|
||||||
|
const maxAttempts = 4;
|
||||||
|
|
||||||
|
for (var attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||||
|
final tmp = File('${dest.path}.tmp');
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
final req = await client.getUrl(url);
|
||||||
|
|
||||||
|
final resp = await req.close().timeout(const Duration(seconds: 60));
|
||||||
|
if (resp.statusCode != 200) {
|
||||||
|
// 404 is not transient in practice - fail fast with a clear message.
|
||||||
|
if (resp.statusCode == 404) {
|
||||||
|
_fail('Missing gstatic asset (404): $url');
|
||||||
|
}
|
||||||
|
throw HttpException('HTTP ${resp.statusCode}', uri: url);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stream to temp file first, then rename to avoid leaving partial files.
|
||||||
|
if (tmp.existsSync()) tmp.deleteSync();
|
||||||
|
final sink = tmp.openWrite();
|
||||||
|
await resp.pipe(sink).timeout(const Duration(seconds: 120));
|
||||||
|
|
||||||
|
if (!tmp.existsSync() || tmp.lengthSync() == 0) {
|
||||||
|
throw const FormatException('Downloaded asset is empty');
|
||||||
|
}
|
||||||
|
if (dest.existsSync()) dest.deleteSync();
|
||||||
|
tmp.renameSync(dest.path);
|
||||||
|
return;
|
||||||
|
} finally {
|
||||||
|
// no-op: HttpClient lifecycle managed by the caller
|
||||||
|
}
|
||||||
|
} on TimeoutException {
|
||||||
|
if (tmp.existsSync()) tmp.deleteSync();
|
||||||
|
if (attempt == maxAttempts) {
|
||||||
|
_fail('Timeout downloading asset: $url');
|
||||||
|
}
|
||||||
|
} on SocketException catch (e) {
|
||||||
|
if (tmp.existsSync()) tmp.deleteSync();
|
||||||
|
if (attempt == maxAttempts) {
|
||||||
|
_fail('Socket error downloading asset: $url ($e)');
|
||||||
|
}
|
||||||
|
} on HttpException catch (e) {
|
||||||
|
if (tmp.existsSync()) tmp.deleteSync();
|
||||||
|
if (attempt == maxAttempts) {
|
||||||
|
_fail('HTTP error downloading asset: $url ($e)');
|
||||||
|
}
|
||||||
|
} on FileSystemException catch (e) {
|
||||||
|
if (tmp.existsSync()) tmp.deleteSync();
|
||||||
|
_fail('File write error downloading asset: $url ($e)');
|
||||||
|
} catch (e) {
|
||||||
|
if (tmp.existsSync()) tmp.deleteSync();
|
||||||
|
if (attempt == maxAttempts) {
|
||||||
|
_fail('Unexpected error downloading asset: $url ($e)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backoff before retrying.
|
||||||
|
final backoffSeconds = 1 << (attempt - 1);
|
||||||
|
stdout.writeln(
|
||||||
|
'Retrying (${attempt + 1}/$maxAttempts) for: $url (wait ${backoffSeconds}s)',
|
||||||
|
);
|
||||||
|
await Future.delayed(Duration(seconds: backoffSeconds));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Directory _findFlutterProjectRoot(Directory start) {
|
||||||
|
var dir = start;
|
||||||
|
for (var i = 0; i < 10; i++) {
|
||||||
|
final pubspec = File(_join(dir.path, 'pubspec.yaml'));
|
||||||
|
if (pubspec.existsSync()) return dir;
|
||||||
|
final parent = dir.parent;
|
||||||
|
if (parent.path == dir.path) break;
|
||||||
|
dir = parent;
|
||||||
|
}
|
||||||
|
// Fallback: use current directory, error messages will explain what is missing.
|
||||||
|
return start;
|
||||||
|
}
|
||||||
|
|
||||||
|
Never _fail(String msg) {
|
||||||
|
throw FormatException(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _join(String a, [String? b, String? c, String? d]) {
|
||||||
|
final parts = <String>[
|
||||||
|
a,
|
||||||
|
if (b != null) b,
|
||||||
|
if (c != null) c,
|
||||||
|
if (d != null) d,
|
||||||
|
];
|
||||||
|
return parts.join(Platform.pathSeparator);
|
||||||
|
}
|
||||||
@@ -25,10 +25,11 @@ on:
|
|||||||
- ".github/workflows/test.yml"
|
- ".github/workflows/test.yml"
|
||||||
- "go.mod"
|
- "go.mod"
|
||||||
- "go.sum"
|
- "go.sum"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
GO_VERSION: 1.19
|
GO_VERSION: "1.25.4"
|
||||||
FLUTTER_VERSION: 3.10.6
|
FLUTTER_VERSION: "3.41.6"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
# lint:
|
# lint:
|
||||||
@@ -49,32 +50,237 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
|
- name: Install webview dependencies
|
||||||
|
run: |
|
||||||
|
sudo apt-get update -y
|
||||||
|
sudo apt-get install -y libgtk-3-dev libwebkit2gtk-4.1-dev xvfb
|
||||||
- name: Run Unit tests.
|
- name: Run Unit tests.
|
||||||
run: go test $(go list ./... | grep -v /cmd/ | grep -v /bind/ ) -v -covermode=count -coverprofile=coverage.txt
|
run: |
|
||||||
- uses: codecov/codecov-action@v3
|
# Get packages for testing and coverage (including cmd/web for flags_test.go)
|
||||||
|
PACKAGES=$(go list ./... | awk '!/\/bind\// && (!/\/cmd\// || /\/cmd\/web$/)')
|
||||||
|
env CGO_ENABLED=1 xvfb-run -a go test -tags webview -v -coverpkg=$(echo "$PACKAGES" | paste -sd "," -) -covermode=count -coverprofile=coverage.txt $PACKAGES
|
||||||
|
# Filter out main.go from coverage report to avoid lowering coverage percentage
|
||||||
|
grep -v "main.go" coverage.txt > coverage_filtered.txt || true
|
||||||
|
mv coverage_filtered.txt coverage.txt
|
||||||
|
- uses: codecov/codecov-action@v4
|
||||||
with:
|
with:
|
||||||
files: ./coverage.txt
|
files: ./coverage.txt
|
||||||
build:
|
token: ${{ secrets.CODECOV_UPLOAD_TOKEN }}
|
||||||
name: Build check
|
test-webview-integration:
|
||||||
runs-on: ubuntu-latest
|
name: Test webview integration (${{ matrix.name }})
|
||||||
# needs: [lint, test]
|
strategy:
|
||||||
needs: [test]
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- name: Windows
|
||||||
|
os: windows-latest
|
||||||
|
- name: macOS
|
||||||
|
os: macos-latest
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
- uses: actions/setup-go@v4
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ${{ env.GO_VERSION }}
|
||||||
|
- uses: subosito/flutter-action@v2
|
||||||
|
if: runner.os == 'macOS'
|
||||||
|
with:
|
||||||
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
|
- name: Test webview
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
run: go test -tags webview -v -count=1 -timeout 300s ./internal/webview/goprovider/
|
||||||
|
env:
|
||||||
|
CGO_ENABLED: 1
|
||||||
|
- name: Test webview
|
||||||
|
if: runner.os == 'macOS'
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
SOCKET_PATH="$HOME/Library/Application Support/com.gopeed.gopeed/gopeed_webview.sock"
|
||||||
|
LOG_PATH="$RUNNER_TEMP/gopeed-webview-rpc.log"
|
||||||
|
rm -f "$SOCKET_PATH"
|
||||||
|
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
|
||||||
|
cd ui/flutter
|
||||||
|
flutter pub get
|
||||||
|
flutter run --machine -d macos >"$LOG_PATH" 2>&1 &
|
||||||
|
FLUTTER_PID=$!
|
||||||
|
cd ../..
|
||||||
|
|
||||||
|
cleanup() {
|
||||||
|
kill "$FLUTTER_PID" >/dev/null 2>&1 || true
|
||||||
|
}
|
||||||
|
trap cleanup EXIT
|
||||||
|
|
||||||
|
FLUTTER_STARTED=false
|
||||||
|
for _ in $(seq 1 600); do
|
||||||
|
if grep -Eq '"event"[[:space:]]*:[[:space:]]*"app\.started"' "$LOG_PATH"; then
|
||||||
|
FLUTTER_STARTED=true
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
if ! kill -0 "$FLUTTER_PID" >/dev/null 2>&1; then
|
||||||
|
echo "Flutter exited before reporting app.started"
|
||||||
|
cat "$LOG_PATH"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
if [[ "$FLUTTER_STARTED" != true ]]; then
|
||||||
|
echo "Timed out waiting for Flutter to report app.started"
|
||||||
|
cat "$LOG_PATH"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! go test -tags webview -v -count=1 -timeout 600s ./internal/webview/rpcprovider/ -args -webview-rpc-network unix -webview-rpc-address "$SOCKET_PATH"; then
|
||||||
|
cat "$LOG_PATH"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
build-desktop:
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- os: windows-2022
|
||||||
|
- os: windows-11-arm
|
||||||
|
llvm_ver: "20251202" # Only ARM64
|
||||||
|
flutter_channel: "main"
|
||||||
|
flutter_version: "7e1c8868"
|
||||||
|
- os: macos-latest
|
||||||
|
- os: ubuntu-22.04
|
||||||
|
- os: ubuntu-22.04-arm
|
||||||
|
flutter_channel: "main"
|
||||||
|
name: Build desktop check (${{ matrix.os }})
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
needs: [ test ]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- name: Enable long paths for flutter main branch checks
|
||||||
|
run: |
|
||||||
|
git config --global core.longpaths true
|
||||||
|
- name: Install llvm-mingw-ucrt-aarch64 (ARM64 only)
|
||||||
|
if: matrix.os == 'windows-11-arm'
|
||||||
|
run: |
|
||||||
|
$ver = "${{ matrix.llvm_ver }}"
|
||||||
|
$url = "https://github.com/mstorsjo/llvm-mingw/releases/download/$ver/llvm-mingw-$ver-ucrt-aarch64.zip"
|
||||||
|
$zip = "$env:RUNNER_TEMP\\llvm.zip"
|
||||||
|
$extract = "$env:RUNNER_TEMP\\extract"
|
||||||
|
$target = "C:\\clangarm64"
|
||||||
|
|
||||||
|
curl -L $url -o $zip
|
||||||
|
rm -r -fo $extract,$target -ea Ignore
|
||||||
|
mkdir $extract | Out-Null
|
||||||
|
|
||||||
|
tar -xf $zip -C $extract
|
||||||
|
mv (Get-ChildItem $extract)[0].FullName $target
|
||||||
|
|
||||||
|
$b = "$target\\bin"
|
||||||
|
"CC=$b\\clang.exe" >> $env:GITHUB_ENV
|
||||||
|
"CXX=$b\\clang++.exe" >> $env:GITHUB_ENV
|
||||||
|
"CLANGARM64_BIN=$b" >> $env:GITHUB_ENV
|
||||||
|
"CGO_ENABLED=1" >> $env:GITHUB_ENV
|
||||||
|
"CLANGARM64_ROOT=$target" >> $env:GITHUB_ENV
|
||||||
|
$b >> $env:GITHUB_PATH
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ${{ env.GO_VERSION }}
|
||||||
|
- uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
channel: ${{ matrix.flutter_channel || 'stable' }}
|
||||||
|
flutter-version: ${{ matrix.flutter_version || env.FLUTTER_VERSION }}
|
||||||
|
- if: runner.os == 'Windows'
|
||||||
|
run: |
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build windows
|
||||||
|
- if: runner.os == 'macOS'
|
||||||
|
run: |
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build macos
|
||||||
|
- if: runner.os == 'Linux'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update -y
|
||||||
|
sudo apt-get install -y ninja-build libgtk-3-dev libwebkit2gtk-4.1-dev libayatana-appindicator3-dev libkeybinder-3.0-dev
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build linux
|
||||||
|
build-mobile:
|
||||||
|
name: Build mobile check
|
||||||
|
runs-on: ${{ matrix.os }}
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ macos-26, ubuntu-latest ]
|
||||||
|
needs: [ test ]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ${{ env.GO_VERSION }}
|
go-version: ${{ env.GO_VERSION }}
|
||||||
- uses: subosito/flutter-action@v2
|
- uses: subosito/flutter-action@v2
|
||||||
with:
|
with:
|
||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- run: |
|
- run: |
|
||||||
sudo apt-get update -y
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
sudo apt-get install -y ninja-build libgtk-3-dev libayatana-appindicator3-dev
|
go get golang.org/x/mobile/bind
|
||||||
|
gomobile init
|
||||||
|
- if: runner.os == 'macOS'
|
||||||
|
run: |
|
||||||
|
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build ipa --no-codesign
|
||||||
|
- if: runner.os == 'Linux'
|
||||||
|
uses: actions/setup-java@v3
|
||||||
|
with:
|
||||||
|
distribution: "zulu"
|
||||||
|
java-version: "17"
|
||||||
|
- if: runner.os == 'Linux'
|
||||||
|
run: |
|
||||||
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg=com.gopeed github.com/GopeedLab/gopeed/bind/mobile
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build apk
|
||||||
|
|
||||||
|
build-web:
|
||||||
|
name: Build web check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [ test ]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ${{ env.GO_VERSION }}
|
||||||
|
- uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
- name: Build
|
- name: Build
|
||||||
run: |
|
run: |
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build linux
|
flutter build web --no-web-resources-cdn
|
||||||
|
dart ../../.github/workflows/scripts/flutter_local_font.dart
|
||||||
|
cd ../../
|
||||||
|
rm -rf cmd/web/dist
|
||||||
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
|
go build -tags nosqlite,web -ldflags="-s -w" github.com/GopeedLab/gopeed/cmd/web
|
||||||
|
build-docker:
|
||||||
|
name: Build docker check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [ test ]
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
- uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ${{ env.GO_VERSION }}
|
||||||
|
- uses: subosito/flutter-action@v2
|
||||||
|
with:
|
||||||
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build web --no-web-resources-cdn
|
||||||
|
cd ../../
|
||||||
|
rm -rf cmd/web/dist
|
||||||
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
|
docker build -t gopeed .
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
*.dll
|
*.dll
|
||||||
*.so
|
*.so
|
||||||
*.dylib
|
*.dylib
|
||||||
|
ui/flutter/dist/
|
||||||
# Test binary, built with `go test -c`
|
# Test binary, built with `go test -c`
|
||||||
*.test
|
*.test
|
||||||
|
|
||||||
@@ -25,4 +25,8 @@ bin/
|
|||||||
|
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
dist/
|
node_modules/
|
||||||
|
cmd/web/dist/
|
||||||
|
.test_storage/
|
||||||
|
.test_download/
|
||||||
|
/extensions
|
||||||
@@ -17,18 +17,60 @@ start the front-end flutter project in `debug` mode to run.
|
|||||||
|
|
||||||
## Translation
|
## Translation
|
||||||
|
|
||||||
The internationalization files of Gopeed are located in the `ui/flutter/assets/locales` directory.
|
Flutter translations are ARB files in `ui/flutter/lib/l10n`. Use `app_en.arb` as the source template,
|
||||||
You only need to add the corresponding language file in this directory.
|
then edit or add `app_<locale>.arb` (for example, `app_de.arb` or `app_zh_TW.arb`). Every locale must
|
||||||
|
contain the same message keys as the English template.
|
||||||
|
|
||||||
|
Translate message values only, and do not rename variables inside braces such as `{count}` and `{name}`.
|
||||||
|
Do not translate metadata keys prefixed with `@`. Submit only the ARB source files you changed; do not generate or commit
|
||||||
|
`app_localizations*.dart`. The pull-request CI automatically validates the catalogs, generates the
|
||||||
|
localization code, and checks its integration.
|
||||||
|
|
||||||
Generate locales after you edit locales:
|
The following examples show both the ARB definition and the text users see after the app supplies values.
|
||||||
|
|
||||||
|
1. Insert a variable into a message
|
||||||
|
|
||||||
```
|
ARB definition:
|
||||||
get generate locales
|
|
||||||
```
|
|
||||||
|
|
||||||
Please refer to `en_us.dart` for translation.
|
```json
|
||||||
|
"welcomeUser": "Hola, {name}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Rendered result: when `name = Ana`, users see “Hola, Ana”. You may reorder the sentence, but keep `{name}`.
|
||||||
|
|
||||||
|
2. Display different text for different quantities
|
||||||
|
|
||||||
|
ARB definition:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"fileCount": "{count, plural, =0{No hay archivos} =1{1 archivo} other{{count} archivos}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Rendered results:
|
||||||
|
|
||||||
|
- `count = 0` → “No hay archivos”
|
||||||
|
- `count = 1` → “1 archivo”
|
||||||
|
- `count = 3` → “3 archivos”
|
||||||
|
|
||||||
|
`=0`, `=1`, and `other` mean zero, one, and every other quantity. Translate only the user-visible text
|
||||||
|
inside each branch.
|
||||||
|
|
||||||
|
3. Display different text for different values
|
||||||
|
|
||||||
|
ARB definition:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"taskState": "{state, select, running{En curso} paused{En pausa} other{Desconocido}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Rendered results:
|
||||||
|
|
||||||
|
- `state = running` → “En curso”
|
||||||
|
- `state = paused` → “En pausa”
|
||||||
|
- Any other value → “Desconocido”
|
||||||
|
|
||||||
|
`running`, `paused`, and `other` are values supplied by the app. Do not translate them; translate only
|
||||||
|
the display text inside the following braces.
|
||||||
|
|
||||||
## flutter development
|
## flutter development
|
||||||
|
|
||||||
@@ -39,16 +81,3 @@ Turn on build_runner watcher if you want to edit api/models:
|
|||||||
```
|
```
|
||||||
flutter pub run build_runner watch
|
flutter pub run build_runner watch
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
get-cli commands usages:
|
|
||||||
|
|
||||||
```
|
|
||||||
create:
|
|
||||||
controller: Generate controller
|
|
||||||
page: Use to generate pages
|
|
||||||
view: Generate view
|
|
||||||
generate:
|
|
||||||
locales: Generate translation file from json files
|
|
||||||
model: generate Class model from json
|
|
||||||
```
|
|
||||||
@@ -17,18 +17,58 @@
|
|||||||
|
|
||||||
## 翻訳
|
## 翻訳
|
||||||
|
|
||||||
Gopeed の国際化ファイルは `ui/flutter/assets/locales` ディレクトリにあります。
|
Flutter の翻訳ファイルは `ui/flutter/lib/l10n` にあります。`app_en.arb` を原文テンプレートとして、
|
||||||
このディレクトリに対応する言語ファイルを追加するだけでよいです。
|
`app_<locale>.arb`(例: `app_de.arb`、`app_zh_TW.arb`)を編集または追加してください。すべての言語で
|
||||||
|
英語テンプレートと同じメッセージ key が必要です。
|
||||||
|
|
||||||
|
翻訳するのはメッセージ値だけです。`{count}` や `{name}` など、中括弧内の変数名は変更しないでください。
|
||||||
|
`@` で始まるメタデータ key は翻訳しません。変更した ARB ソースファイルだけをコミットし、
|
||||||
|
`app_localizations*.dart` は生成もコミットも不要です。PR の CI が全言語を検証し、国際化コードを生成して
|
||||||
|
統合結果を確認します。
|
||||||
|
|
||||||
ロケール編集後にロケールを生成:
|
以下の例では、ARB に記述する定義と、アプリが値を渡した後にユーザーが実際に見る表示を示します。
|
||||||
|
|
||||||
|
1. メッセージに変数を挿入する
|
||||||
|
|
||||||
```
|
ARB 定義:
|
||||||
get generate locales
|
|
||||||
```
|
|
||||||
|
|
||||||
翻訳については `en_us.dart` を参照してください。
|
```json
|
||||||
|
"welcomeUser": "こんにちは、{name}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最終表示:`name = 太郎` の場合は「こんにちは、太郎」と表示されます。語順は変更できますが、`{name}` は残します。
|
||||||
|
|
||||||
|
2. 数量に応じて表示を切り替える
|
||||||
|
|
||||||
|
ARB 定義:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"fileCount": "{count, plural, =0{ファイルなし} =1{1 個のファイル} other{{count} 個のファイル}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最終表示:
|
||||||
|
|
||||||
|
- `count = 0` →「ファイルなし」
|
||||||
|
- `count = 1` →「1 個のファイル」
|
||||||
|
- `count = 3` →「3 個のファイル」
|
||||||
|
|
||||||
|
`=0`、`=1`、`other` はそれぞれ 0、1、その他の数量を表します。各分岐の中で画面に表示される文字だけを翻訳します。
|
||||||
|
|
||||||
|
3. 変数の値に応じて表示を切り替える
|
||||||
|
|
||||||
|
ARB 定義:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"taskState": "{state, select, running{実行中} paused{一時停止} other{不明}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最終表示:
|
||||||
|
|
||||||
|
- `state = running` →「実行中」
|
||||||
|
- `state = paused` →「一時停止」
|
||||||
|
- その他の値 →「不明」
|
||||||
|
|
||||||
|
`running`、`paused`、`other` はアプリが渡す分岐値なので翻訳せず、その後の中括弧内にある表示文字だけを翻訳します。
|
||||||
|
|
||||||
## flutter での開発
|
## flutter での開発
|
||||||
|
|
||||||
@@ -39,16 +79,3 @@ api/models を編集したい場合は build_runner watcher をオンにしま
|
|||||||
```
|
```
|
||||||
flutter pub run build_runner watch
|
flutter pub run build_runner watch
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
get-cli コマンドの使用法:
|
|
||||||
|
|
||||||
```
|
|
||||||
create:
|
|
||||||
controller: Generate controller
|
|
||||||
page: Use to generate pages
|
|
||||||
view: Generate view
|
|
||||||
generate:
|
|
||||||
locales: Generate translation file from json files
|
|
||||||
model: generate Class model from json
|
|
||||||
```
|
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
# Hướng dẫn đóng góp cho Gopeed
|
||||||
|
|
||||||
|
Trước tiên, cảm ơn bạn đã quan tâm đến việc đóng góp cho Gopeed. Hướng dẫn này sẽ giúp bạn tham gia
|
||||||
|
phát triển Gopeed một cách tốt hơn.
|
||||||
|
|
||||||
|
## Mô tả nhánh
|
||||||
|
|
||||||
|
Dự án này chỉ có một nhánh chính duy nhất, đó là nhánh `main`. Nếu bạn muốn tham gia vào
|
||||||
|
phát triển Gopeed, hãy fork dự án này trước, sau đó phát triển trong dự án fork của bạn. Sau khi
|
||||||
|
hoàn thành phát triển, gửi một PR đến dự án này và merge vào nhánh `main`.
|
||||||
|
|
||||||
|
## Phát triển cục bộ
|
||||||
|
|
||||||
|
Đề nghị phát triển và gỡ lỗi thông qua web. Đầu tiên, khởi động dịch vụ backend bằng cách chạy
|
||||||
|
lệnh `go run cmd/api/main.go` trong dòng lệnh, cổng mặc định của dịch vụ là `9999`, sau đó
|
||||||
|
khởi động dự án flutter frontend trong chế độ `debug` để chạy.
|
||||||
|
|
||||||
|
## Dịch thuật
|
||||||
|
|
||||||
|
Các bản dịch Flutter là tệp ARB trong `ui/flutter/lib/l10n`. Hãy dùng `app_en.arb` làm mẫu nguồn,
|
||||||
|
sau đó sửa hoặc thêm `app_<locale>.arb` (ví dụ `app_de.arb` hoặc `app_zh_TW.arb`). Mỗi ngôn ngữ phải
|
||||||
|
có cùng các khóa thông điệp như mẫu tiếng Anh.
|
||||||
|
|
||||||
|
Chỉ dịch giá trị thông điệp; không đổi tên biến trong dấu ngoặc nhọn như `{count}` và `{name}`. Không dịch khóa
|
||||||
|
siêu dữ liệu bắt đầu bằng `@`. Chỉ commit các tệp nguồn ARB đã thay đổi; không cần tạo hoặc commit
|
||||||
|
`app_localizations*.dart`. CI của pull request sẽ tự động
|
||||||
|
kiểm tra tất cả ngôn ngữ, tạo mã bản địa hóa và xác minh việc tích hợp.
|
||||||
|
|
||||||
|
Các ví dụ sau hiển thị cả định nghĩa trong ARB và nội dung người dùng thực sự thấy sau khi ứng dụng truyền giá trị.
|
||||||
|
|
||||||
|
1. Chèn biến vào thông điệp
|
||||||
|
|
||||||
|
Định nghĩa ARB:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"welcomeUser": "Xin chào, {name}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Kết quả hiển thị: khi `name = An`, người dùng thấy “Xin chào, An”. Có thể đổi trật tự câu nhưng phải giữ `{name}`.
|
||||||
|
|
||||||
|
2. Hiển thị nội dung khác nhau theo số lượng
|
||||||
|
|
||||||
|
Định nghĩa ARB:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"fileCount": "{count, plural, =0{Không có tệp} =1{1 tệp} other{{count} tệp}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Kết quả hiển thị:
|
||||||
|
|
||||||
|
- `count = 0` → “Không có tệp”
|
||||||
|
- `count = 1` → “1 tệp”
|
||||||
|
- `count = 3` → “3 tệp”
|
||||||
|
|
||||||
|
`=0`, `=1` và `other` lần lượt biểu thị số lượng bằng 0, bằng 1 và các số lượng còn lại. Chỉ dịch phần chữ
|
||||||
|
hiển thị cho người dùng bên trong mỗi nhánh.
|
||||||
|
|
||||||
|
3. Hiển thị nội dung khác nhau theo giá trị biến
|
||||||
|
|
||||||
|
Định nghĩa ARB:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"taskState": "{state, select, running{Đang chạy} paused{Đã tạm dừng} other{Không xác định}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Kết quả hiển thị:
|
||||||
|
|
||||||
|
- `state = running` → “Đang chạy”
|
||||||
|
- `state = paused` → “Đã tạm dừng”
|
||||||
|
- Giá trị khác → “Không xác định”
|
||||||
|
|
||||||
|
`running`, `paused` và `other` là các giá trị do ứng dụng truyền vào nên không được dịch; chỉ dịch phần chữ
|
||||||
|
hiển thị trong dấu ngoặc theo sau chúng.
|
||||||
|
|
||||||
|
## Phát triển flutter
|
||||||
|
|
||||||
|
Đừng quên chạy `dart format ./ui/flutter` trước khi commit để giữ mã của bạn theo định dạng dart chuẩn.
|
||||||
|
|
||||||
|
Bật build_runner watcher nếu bạn muốn chỉnh sửa api/models:
|
||||||
@@ -13,16 +13,57 @@ PR,合并到 `main` 分支。
|
|||||||
flutter 项目即可运行。
|
flutter 项目即可运行。
|
||||||
|
|
||||||
## 翻译
|
## 翻译
|
||||||
|
|
||||||
Gopeed 的国际化文件位于 `ui/flutter/assets/locales` 目录下,只需要在该目录下添加对应的语言文件即可。
|
|
||||||
|
|
||||||
编辑locales后请运行以下命令:
|
Flutter 国际化文件位于 `ui/flutter/lib/l10n`,请以 `app_en.arb` 为源模板,修改或新增
|
||||||
|
`app_<locale>.arb`(例如 `app_de.arb` 或 `app_zh_TW.arb`)。每个语种必须与英文模板包含相同的文案 key。
|
||||||
|
|
||||||
```
|
只翻译文案值,不要修改 `{count}`、`{name}` 等花括号中的变量名。以 `@` 开头的元数据 key 不需要翻译。
|
||||||
get generate locales
|
提交时只包含修改过的 ARB 源文件,不需要生成或提交 `app_localizations*.dart`。PR 的 CI 会自动校验所有语种、
|
||||||
```
|
生成国际化代码并检查集成结果。
|
||||||
|
|
||||||
请注意以 `en_US.json` 为参照进行翻译。
|
下面的例子同时给出 ARB 中填写的文案定义,以及程序传值后用户最终看到的内容。
|
||||||
|
|
||||||
|
1. 在文案中插入变量
|
||||||
|
|
||||||
|
ARB 定义:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"welcomeUser": "你好,{name}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最终显示:当 `name = 小明` 时,显示“你好,小明”。翻译时可以调整整句话,但必须保留 `{name}`。
|
||||||
|
|
||||||
|
2. 根据数量显示不同文案
|
||||||
|
|
||||||
|
ARB 定义:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"fileCount": "{count, plural, =0{没有文件} =1{1 个文件} other{{count} 个文件}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最终显示:
|
||||||
|
|
||||||
|
- `count = 0` → “没有文件”
|
||||||
|
- `count = 1` → “1 个文件”
|
||||||
|
- `count = 3` → “3 个文件”
|
||||||
|
|
||||||
|
`=0`、`=1`、`other` 分别表示数量为 0、数量为 1 和其他数量。只翻译每个分支花括号内显示给用户的文字。
|
||||||
|
|
||||||
|
3. 根据变量值显示不同文案
|
||||||
|
|
||||||
|
ARB 定义:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"taskState": "{state, select, running{运行中} paused{已暂停} other{未知状态}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最终显示:
|
||||||
|
|
||||||
|
- `state = running` → “运行中”
|
||||||
|
- `state = paused` → “已暂停”
|
||||||
|
- 其他值 → “未知状态”
|
||||||
|
|
||||||
|
`running`、`paused`、`other` 是程序传入的分支值,不能翻译;只翻译它们后面花括号内的显示文字。
|
||||||
|
|
||||||
## flutter开发
|
## flutter开发
|
||||||
|
|
||||||
@@ -33,16 +74,3 @@ get generate locales
|
|||||||
```
|
```
|
||||||
flutter pub run build_runner watch
|
flutter pub run build_runner watch
|
||||||
```
|
```
|
||||||
|
|
||||||
适用get-cli 命令:
|
|
||||||
|
|
||||||
```
|
|
||||||
create:
|
|
||||||
controller: Generate controller
|
|
||||||
page: Use to generate pages
|
|
||||||
view: Generate view
|
|
||||||
generate:
|
|
||||||
locales: Generate translation file from json files
|
|
||||||
model: generate Class model from json
|
|
||||||
```
|
|
||||||
|
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Gopeed 協助指南
|
||||||
|
|
||||||
|
首先感謝您願意幫助我們改進並優化該項目,這份指南將會幫助您更好的參與 Gopeed 的開發。
|
||||||
|
|
||||||
|
## 分支說明
|
||||||
|
|
||||||
|
本項目只有一個分支,即 `main` 分支,如果您想要參與 Gopeed 的開發,請先 fork 該項目,再在您自己的 fork 中進行開發,開發完成後再開啟PR,以合併至 `main` 分支。
|
||||||
|
|
||||||
|
## 離線開發
|
||||||
|
|
||||||
|
建議使用 web 端進行開發與調試,首先啟動服務,使用指令 `go run cmd/api/main.go` 啟動 ,該服務默認連接埠為 `9999`,接著以 `debug` 模式啟動前端 flutter 項目即可。
|
||||||
|
|
||||||
|
## 翻譯
|
||||||
|
|
||||||
|
Flutter 翻譯檔位於 `ui/flutter/lib/l10n`,請以 `app_en.arb` 為來源範本,修改或新增
|
||||||
|
`app_<locale>.arb`(例如 `app_de.arb` 或 `app_zh_TW.arb`)。每個語言都必須與英文範本包含相同的訊息 key。
|
||||||
|
|
||||||
|
只翻譯訊息值,不要修改 `{count}`、`{name}` 等大括號中的變數名稱。以 `@` 開頭的中繼資料 key 不需要翻譯。
|
||||||
|
提交時只需包含修改過的 ARB 來源檔,不需要產生或提交 `app_localizations*.dart`。PR 的 CI
|
||||||
|
會自動驗證所有語言、產生國際化程式碼並檢查整合結果。
|
||||||
|
|
||||||
|
以下範例同時列出 ARB 中填寫的訊息定義,以及程式傳值後使用者最終看到的內容。
|
||||||
|
|
||||||
|
1. 在訊息中插入變數
|
||||||
|
|
||||||
|
ARB 定義:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"welcomeUser": "你好,{name}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最終顯示:當 `name = 小明` 時,顯示「你好,小明」。翻譯時可以調整整句話,但必須保留 `{name}`。
|
||||||
|
|
||||||
|
2. 依數量顯示不同訊息
|
||||||
|
|
||||||
|
ARB 定義:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"fileCount": "{count, plural, =0{沒有檔案} =1{1 個檔案} other{{count} 個檔案}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最終顯示:
|
||||||
|
|
||||||
|
- `count = 0` →「沒有檔案」
|
||||||
|
- `count = 1` →「1 個檔案」
|
||||||
|
- `count = 3` →「3 個檔案」
|
||||||
|
|
||||||
|
`=0`、`=1`、`other` 分別代表數量為 0、數量為 1 和其他數量。只翻譯各分支大括號內顯示給使用者的文字。
|
||||||
|
|
||||||
|
3. 依變數值顯示不同訊息
|
||||||
|
|
||||||
|
ARB 定義:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"taskState": "{state, select, running{執行中} paused{已暫停} other{未知狀態}}"
|
||||||
|
```
|
||||||
|
|
||||||
|
最終顯示:
|
||||||
|
|
||||||
|
- `state = running` →「執行中」
|
||||||
|
- `state = paused` →「已暫停」
|
||||||
|
- 其他值 →「未知狀態」
|
||||||
|
|
||||||
|
`running`、`paused`、`other` 是程式傳入的分支值,不能翻譯;只翻譯其後大括號內的顯示文字。
|
||||||
|
|
||||||
|
## flutter開發
|
||||||
|
|
||||||
|
每次提交PR前請務必執行 `dart format ./ui/flutter`
|
||||||
|
|
||||||
|
如果需要編輯 api/models,請打開build_runner watcher:
|
||||||
|
|
||||||
|
```
|
||||||
|
flutter pub run build_runner watch
|
||||||
|
```
|
||||||
@@ -1,21 +1,23 @@
|
|||||||
FROM instrumentisto/flutter:3.10.6 AS flutter
|
FROM golang:1.25.4-alpine3.22 AS go
|
||||||
WORKDIR /app
|
|
||||||
COPY ./ui/flutter/pubspec.yaml ./ui/flutter/pubspec.lock ./
|
|
||||||
RUN flutter pub get
|
|
||||||
COPY ./ui/flutter ./
|
|
||||||
RUN flutter build web --web-renderer html
|
|
||||||
|
|
||||||
FROM golang:1.19.3 AS go
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY ./go.mod ./go.sum ./
|
COPY ./go.mod ./go.sum ./
|
||||||
RUN go mod download
|
RUN go mod download
|
||||||
COPY . .
|
COPY . .
|
||||||
COPY --from=flutter /app/build/web ./cmd/web/dist
|
ARG VERSION=dev
|
||||||
RUN CGO_ENABLED=0 go build -tags nosqlite,web -ldflags="-s -w" -o dist/gopeed github.com/GopeedLab/gopeed/cmd/web
|
RUN CGO_ENABLED=0 go build -tags nosqlite,web \
|
||||||
|
-ldflags="-s -w -X github.com/GopeedLab/gopeed/pkg/base.Version=$VERSION -X github.com/GopeedLab/gopeed/pkg/base.InDocker=true" \
|
||||||
|
-o dist/gopeed github.com/GopeedLab/gopeed/cmd/web
|
||||||
|
|
||||||
FROM alpine:3.14.2
|
FROM alpine:3.23
|
||||||
LABEL maintainer="monkeyWie"
|
LABEL maintainer="monkeyWie"
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY --from=go /app/dist/gopeed ./
|
COPY --from=go /app/dist/gopeed ./
|
||||||
|
COPY entrypoint.sh ./entrypoint.sh
|
||||||
|
RUN apk update && \
|
||||||
|
apk add --no-cache su-exec ; \
|
||||||
|
chmod +x ./entrypoint.sh && \
|
||||||
|
rm -rf /var/cache/apk/*
|
||||||
|
VOLUME ["/app/storage"]
|
||||||
|
ENV PUID=0 PGID=0 UMASK=022
|
||||||
EXPOSE 9999
|
EXPOSE 9999
|
||||||
ENTRYPOINT ["./gopeed"]
|
ENTRYPOINT ["./entrypoint.sh"]
|
||||||
@@ -1,102 +1,129 @@
|
|||||||
|
# [](https://gopeed.com)
|
||||||
|
|
||||||
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
||||||
[](https://codecov.io/gh/GopeedLab/gopeed)
|
[](https://codecov.io/gh/GopeedLab/gopeed)
|
||||||
[](https://github.com/GopeedLab/gopeed/releases)
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
[](https://github.com/GopeedLab/gopeed/releases)
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
[](https://github.com/GopeedLab/gopeed/blob/main/.donate/index.md#donate)
|
[](https://gopeed.com/docs/donate)
|
||||||
|
[](https://raw.githubusercontent.com/GopeedLab/gopeed/main/_docs/img/weixin.png)
|
||||||
[](https://discord.gg/ZUJqJrwCGB)
|
[](https://discord.gg/ZUJqJrwCGB)
|
||||||
|
|
||||||

|
<a href="https://trendshift.io/repositories/7953" target="_blank"><img src="https://trendshift.io/api/badge/repositories/7953" alt="GopeedLab%2Fgopeed | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
[](https://ko-fi.com/R6R6IJGN6)
|
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md) | [正體中文](/README_zh-TW.md) | [Tiếng Việt](/README_vi-VN.md)
|
||||||
|
|
||||||
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md)
|
## 🚀 Introduction
|
||||||
|
|
||||||
## Introduction
|
Gopeed (short for **Go Speed**) is a fast, modern, free, and open-source download manager built with Go and Flutter. It supports HTTP, HTTPS, BitTorrent, magnet links, and ed2k on desktop, mobile, and the web.
|
||||||
|
|
||||||
Gopeed (full name Go Speed), a high-speed downloader developed by `Golang` + `Flutter`, supports (HTTP, BitTorrent, Magnet) protocol, and supports all platforms.
|
Beyond core download management, Gopeed offers browser integration, JavaScript extensions, a REST API, a CLI, and a self-hosted web UI for customization and automation.
|
||||||
|
|
||||||
Visit ✈ [Official Website](https://gopeed.com) | 📖 [Develop Docs](https://docs.gopeed.com)
|
Visit ✈ [Official Website](https://gopeed.com)
|
||||||
|
|
||||||
## Install
|

|
||||||
|
|
||||||
**Supported platforms**
|
## ✨ Features
|
||||||
|
|
||||||
- [x] windows
|
- ⚡ **High-speed downloads** — combine concurrent tasks, multi-connection HTTP transfers, and peer-to-peer BitTorrent downloads to make the most of your bandwidth.
|
||||||
- [x] macos
|
- 🧲 **Multiple protocols** — download HTTP/HTTPS files, torrents, magnet links, and ed2k resources from a single app.
|
||||||
- [x] linux
|
- 🌱 **Full-featured BitTorrent** — use DHT peer discovery, uTP transport, Web Seeds, selective file downloads, tracker management, peer and piece statistics, and ratio- or time-based seeding limits.
|
||||||
- [x] android
|
- 📋 **Flexible task management** — pause, resume, retry, run batch operations, search, filter by status, organize with categories, and recover tasks after a restart.
|
||||||
- [x] ios
|
- 🪶 **Lightweight native experience** — the main interface is rendered natively with Flutter. No Electron. No WebView shell. Enjoy a smaller footprint, lower overhead, and responsive performance.
|
||||||
- [x] web
|
- 💻 **Cross-platform** — available for Windows, macOS, Linux, Android, iOS, and the web, with Docker and QNAP deployment options.
|
||||||
- [x] docker
|
- 🎨 **Customizable appearance** — follow your system theme or choose light or dark mode, with eight accent colors.
|
||||||
|
- 📐 **Responsive interface** — task lists, navigation, settings, and detail views adapt to phones, tablets, and resizable desktop windows.
|
||||||
|
- 🗣️ **Available in 20+ languages** — including English, Simplified and Traditional Chinese, Japanese, Korean, and many more.
|
||||||
|
- 🌐 **Browser integration** — send downloads from Chrome, Edge, Firefox, and other compatible browsers directly to Gopeed.
|
||||||
|
- 🧩 **JavaScript extensions** — add support for video platforms, AI model hubs, cloud storage services, and other download sources.
|
||||||
|
- 🤖 **AI integration** — use Gopeed's MCP endpoint to connect compatible AI agents and create, inspect, or manage downloads with natural language.
|
||||||
|
- 🔌 **Automation-ready** — integrate with Gopeed through its REST API, CLI, authenticated web UI, webhooks, and post-download scripts.
|
||||||
|
- 🛠️ **Built-in essentials** — customize headers and the User-Agent, use proxies and GitHub mirrors, receive notifications, and extract archives automatically.
|
||||||
|
|
||||||
[Download](https://github.com/GopeedLab/gopeed/releases/latest)
|
## 🤖 AI Integration
|
||||||
|
|
||||||
> Tips: If the macos open failed, please execute the `xattr -d com.apple.quarantine /Applications/Gopeed.app` command in the terminal
|
Connect Gopeed to an AI agent and manage downloads with natural language. For example, you can say:
|
||||||
|
|
||||||
### Command tool
|
> Download the latest Gopeed client for Windows.
|
||||||
|
|
||||||
use `go install`:
|
| Tool | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `resolve_task` | Resolve a download URL or URI and return its resource metadata and files before creating a task. |
|
||||||
|
| `create_task` | Create and start a task from a resolved resource ID or a direct download request. |
|
||||||
|
| `list_tasks` | List tasks, optionally filtering them by ID or status. |
|
||||||
|
| `get_task` | Get the request, resource, options, and current progress for one task. |
|
||||||
|
| `get_task_status` | Get lightweight runtime status and per-file progress for one task. |
|
||||||
|
| `get_task_stats` | Get protocol-specific statistics, including HTTP connections or BitTorrent peers and seeding data. |
|
||||||
|
| `pause_task` | Pause a task. |
|
||||||
|
| `continue_task` | Continue a paused or failed task. |
|
||||||
|
| `delete_task` | Delete a task, optionally deleting its downloaded files. |
|
||||||
|
|
||||||
|
## ⬇️ Download
|
||||||
|
|
||||||
|
### 🧪 Gopeed 2.0.0 Beta
|
||||||
|
|
||||||
|
Gopeed 2.0.0 is currently in public beta, introducing a redesigned interface, a native communication architecture that connects desktop and mobile clients directly to the Go core through FFI, a more consistent cross-platform experience, improved task management, more flexible API support, and MCP-based AI agent integration. Some features may still be incomplete or unstable, so please try it and report any issues you encounter.
|
||||||
|
|
||||||
|
- [Download Gopeed 2.0.0 Beta 1](https://github.com/GopeedLab/gopeed/releases/tag/v2.0.0-beta.1)
|
||||||
|
|
||||||
|
Once the features and stability meet our release standards, we will publish the official Gopeed 2.0.0 release. Beta users will be able to upgrade directly to the final release, while existing stable users will not be automatically moved onto the beta channel.
|
||||||
|
|
||||||
|
### Stable release
|
||||||
|
|
||||||
|
- [Official Download](https://gopeed.com)
|
||||||
|
- [GitHub Releases](https://github.com/GopeedLab/gopeed/releases/latest)
|
||||||
|
|
||||||
|
### 🛠️ Command-line tool
|
||||||
|
|
||||||
|
Install the CLI with `go install`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker
|
## 🔌 Browser Extension
|
||||||
|
|
||||||
#### Start directly
|
Use the Gopeed browser extension to send downloads from Chrome, Edge, Firefox, and other compatible browsers directly to Gopeed: [GopeedLab/browser-extension](https://github.com/GopeedLab/browser-extension)
|
||||||
|
|
||||||
```bash
|
## 📱 WeChat Official Account
|
||||||
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Using Docker Compose
|
Follow Gopeed's official WeChat account for updates and news.
|
||||||
|
|
||||||
```bash
|
<img src="_docs/img/weixin.png" width="200" />
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Access Gopeed
|
## 💝 Donate
|
||||||
|
|
||||||
When the docker container is running, you can access the web page through `http://localhost:9999`.
|
If Gopeed is useful to you, please consider [supporting its development](https://gopeed.com/docs/donate). Thank you!
|
||||||
|
|
||||||
## Donate
|
## 👨💻 Development
|
||||||
|
|
||||||
If you like this project, please consider [donating](/.donate/index.md#donate) to support the development of this project, thank you!
|
Gopeed consists of a Flutter front end and a Go back end. They communicate over HTTP, using Unix sockets on Unix-like systems and TCP on Windows.
|
||||||
|
|
||||||
## Showcase
|
> The front-end source is located in the `ui/flutter` directory.
|
||||||
|
|
||||||

|
### 🌍 Environment
|
||||||
|
|
||||||
## Development
|
1. Go 1.25+
|
||||||
|
2. Flutter 3.41+
|
||||||
|
|
||||||
This project is divided into two parts, the front end uses `flutter`, the back end uses `Golang`, and the two sides communicate through the `http` protocol. On the unix system, `unix socket` is used, and on the windows system, `tcp` protocol is used.
|
### 📋 Clone
|
||||||
|
|
||||||
> The front code is located in the `ui/flutter` directory.
|
|
||||||
|
|
||||||
### Environment
|
|
||||||
|
|
||||||
1. Golang 1.19+
|
|
||||||
2. Flutter 3.10+
|
|
||||||
|
|
||||||
### Clone
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone git@github.com:GopeedLab/gopeed.git
|
git clone git@github.com:GopeedLab/gopeed.git
|
||||||
```
|
```
|
||||||
|
|
||||||
### Contributing
|
### 🤝 Contributing
|
||||||
|
|
||||||
Please refer to [CONTRIBUTING.md](/CONTRIBUTING.md)
|
See [CONTRIBUTING.md](/CONTRIBUTING.md).
|
||||||
|
|
||||||
### Build
|
### 🏗️ Build
|
||||||
|
|
||||||
#### Desktop
|
#### Desktop
|
||||||
|
|
||||||
First, you need to configure the environment according to the official [Flutter desktop website documention](https://docs.flutter.dev/development/platform-integration/desktop), then you will need to ensure the cgo environment is set up accordingly. For detailed instructions on setting up the cgo environment, please refer to relevant resources available online.
|
Set up Flutter desktop development using the official [Flutter desktop guide](https://docs.flutter.dev/development/platform-integration/desktop), and make sure a working C toolchain is available for cgo. Then run the commands for your platform.
|
||||||
|
|
||||||
command:
|
Commands:
|
||||||
|
|
||||||
- windows
|
- Windows
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
||||||
@@ -104,7 +131,7 @@ cd ui/flutter
|
|||||||
flutter build windows
|
flutter build windows
|
||||||
```
|
```
|
||||||
|
|
||||||
- macos
|
- macOS
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
@@ -112,7 +139,7 @@ cd ui/flutter
|
|||||||
flutter build macos
|
flutter build macos
|
||||||
```
|
```
|
||||||
|
|
||||||
- linux
|
- Linux
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
||||||
@@ -122,7 +149,7 @@ flutter build linux
|
|||||||
|
|
||||||
#### Mobile
|
#### Mobile
|
||||||
|
|
||||||
Same as before, you also need to prepare the `cgo` environment, and then install `gomobile`:
|
Mobile builds also require a working cgo toolchain. Install and initialize `gomobile`:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go install golang.org/x/mobile/cmd/gomobile@latest
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
@@ -130,17 +157,17 @@ go get golang.org/x/mobile/bind
|
|||||||
gomobile init
|
gomobile init
|
||||||
```
|
```
|
||||||
|
|
||||||
command:
|
Commands:
|
||||||
|
|
||||||
- android
|
- Android
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 19 -javapkg=com.gopeed github.com/GopeedLab/gopeed/bind/mobile
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg="com.gopeed" github.com/GopeedLab/gopeed/bind/mobile
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build apk
|
flutter build apk
|
||||||
```
|
```
|
||||||
|
|
||||||
- ios
|
- iOS
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
||||||
@@ -150,7 +177,7 @@ flutter build ios --no-codesign
|
|||||||
|
|
||||||
#### Web
|
#### Web
|
||||||
|
|
||||||
command:
|
Build the web app and server:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
@@ -159,21 +186,20 @@ cd ../../
|
|||||||
rm -rf cmd/web/dist
|
rm -rf cmd/web/dist
|
||||||
cp -r ui/flutter/build/web cmd/web/dist
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
||||||
go run cmd/web/main.go
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Credits
|
## ❤️ Credits
|
||||||
|
|
||||||
### Contributors
|
### 👥 Contributors
|
||||||
|
|
||||||
<a href="https://github.com/GopeedLab/gopeed/graphs/contributors">
|
<a href="https://github.com/GopeedLab/gopeed/graphs/contributors">
|
||||||
<img src="https://contrib.rocks/image?repo=GopeedLab/gopeed" />
|
<img src="https://contrib.rocks/image?repo=GopeedLab/gopeed" />
|
||||||
</a>
|
</a>
|
||||||
|
|
||||||
### JetBrains
|
### 🏢 JetBrains
|
||||||
|
|
||||||
[](https://www.jetbrains.com/?from=gopeed)
|
[](https://www.jetbrains.com/?from=gopeed)
|
||||||
|
|
||||||
## License
|
## 📄 License
|
||||||
|
|
||||||
[GPLv3](LICENSE)
|
[GPLv3](LICENSE)
|
||||||
@@ -1,94 +1,111 @@
|
|||||||
|
# [](https://gopeed.com)
|
||||||
|
|
||||||
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
||||||
[](https://codecov.io/gh/GopeedLab/gopeed)
|
[](https://codecov.io/gh/GopeedLab/gopeed)
|
||||||
[](https://github.com/GopeedLab/gopeed/releases)
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
[](https://github.com/GopeedLab/gopeed/releases)
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
[](https://github.com/GopeedLab/gopeed/blob/main/.donate/index.md#donate)
|
[](https://gopeed.com/docs/donate)
|
||||||
|
[](https://raw.githubusercontent.com/GopeedLab/gopeed/main/_docs/img/weixin.png)
|
||||||
[](https://discord.gg/ZUJqJrwCGB)
|
[](https://discord.gg/ZUJqJrwCGB)
|
||||||
|
|
||||||

|
<a href="https://trendshift.io/repositories/7953" target="_blank"><img src="https://trendshift.io/api/badge/repositories/7953" alt="GopeedLab%2Fgopeed | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
[](https://ko-fi.com/R6R6IJGN6)
|
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md) | [正體中文](/README_zh-TW.md) | [Tiếng Việt](/README_vi-VN.md)
|
||||||
|
|
||||||
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md)
|
## 🚀 はじめに
|
||||||
|
|
||||||
## はじめに
|
Gopeed(**Go Speed** の略)は、Go と Flutter で開発された高速でモダンな無料オープンソース・ダウンロードマネージャーです。HTTP、HTTPS、BitTorrent、Magnet、ed2k に対応し、デスクトップ、モバイル、Web で利用できます。
|
||||||
|
|
||||||
Gopeed (正式名 Go Speed) は `Golang` + `Flutter` によって開発された高速ダウンローダーで、(HTTP、BitTorrent、Magnet) プロトコルをサポートし、すべてのプラットフォームをサポートします。
|
ブラウザー連携、JavaScript 拡張、REST API、CLI、セルフホスト可能な Web UI により、日常利用から高度な自動化まで幅広く対応します。
|
||||||
|
|
||||||
見て下さい ✈ [公式ウェブサイト](https://gopeed.com) | 📖 [開発ドキュメント](https://docs.gopeed.com)
|
✈ [公式サイト](https://gopeed.com)
|
||||||
|
|
||||||
## インストール
|

|
||||||
|
|
||||||
**サポートするプラットフォーム**
|
## ✨ 主な機能
|
||||||
|
|
||||||
- [x] windows
|
- ⚡ **高速ダウンロード** — 複数タスク、HTTP のマルチ接続分割転送、BitTorrent の P2P ダウンロードで帯域を最大限に活用します。
|
||||||
- [x] macos
|
- 🧲 **マルチプロトコル** — HTTP、HTTPS、BitTorrent、Magnet、ed2k を一つの画面で管理します。
|
||||||
- [x] linux
|
- 🌱 **充実した BT 機能** — DHT によるピア検出、uTP 転送、Web Seed、ファイル選択、Tracker 管理、Peer/ピース統計、共有率または時間によるシード制御。
|
||||||
- [x] android
|
- 📋 **タスク管理** — 一時停止、再開、再試行、一括操作、検索、状態フィルター、カテゴリ、起動時復元。
|
||||||
- [x] ios
|
- 🪶 **軽量なネイティブ体験** — メイン UI は Flutter でネイティブ描画。Electron 非採用。WebView ラッパーでもありません。パッケージサイズと実行時オーバーヘッドを抑え、軽快な応答性を実現します。
|
||||||
- [x] web
|
- 💻 **クロスプラットフォーム** — Windows、macOS、Linux、Android、iOS、Web、Docker、QNAP に対応。
|
||||||
- [x] docker
|
- 🎨 **カスタマイズ可能なテーマ** — システム連動、ライト、ダークの各モードと 8 色のアクセントカラーに対応。
|
||||||
|
- 📐 **レスポンシブ UI** — タスクリスト、ナビゲーション、設定、詳細画面がスマートフォン、タブレット、サイズ変更可能なデスクトップウィンドウに適応。
|
||||||
|
- 🗣️ **20 以上の UI 言語** — 日本語、英語、簡体字・繁体字中国語、韓国語など多くの言語に対応。
|
||||||
|
- 🌐 **ブラウザー連携** — Chrome、Edge、Firefox などのダウンロードを Gopeed に送信できます。
|
||||||
|
- 🧩 **JavaScript 拡張** — 動画サイト、AI モデルハブ、クラウドストレージなどのダウンロード元を追加できます。
|
||||||
|
- 🤖 **AI 連携** — MCP インターフェースを通じて対応する AI Agent と連携し、自然言語でダウンロードタスクを作成・確認・管理できます。
|
||||||
|
- 🔌 **オープンなインターフェース** — REST API、CLI、認証付き Web UI、Webhook、完了後スクリプトに対応。
|
||||||
|
- 🛠️ **便利な内蔵機能** — カスタム Header/User-Agent、Proxy、GitHub ミラー、通知、自動展開。
|
||||||
|
|
||||||
[ダウンロード](https://github.com/GopeedLab/gopeed/releases/latest)
|
## 🤖 AI 連携
|
||||||
|
|
||||||
> ヒント: macos を開くのに失敗した場合は、ターミナルで `xattr -d com.apple.quarantine /Applications/Gopeed.app` コマンドを実行してください
|
Gopeed を AI Agent と連携すると、自然言語でダウンロードを管理できます。たとえば、AI Agent に次のように依頼できます:
|
||||||
|
|
||||||
### コマンドツール
|
> 最新の Gopeed Windows クライアントをダウンロードして
|
||||||
|
|
||||||
`go install` を使用:
|
| Tool | 説明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `resolve_task` | ダウンロード URL または URI を解析し、タスク作成前にリソース情報とファイル一覧を返します。 |
|
||||||
|
| `create_task` | 解析済みのリソース ID または直接のダウンロードリクエストからタスクを作成して開始します。 |
|
||||||
|
| `list_tasks` | タスクを一覧表示し、必要に応じて ID または状態で絞り込みます。 |
|
||||||
|
| `get_task` | 一つのタスクについて、リクエスト、リソース、オプション、現在の進捗を取得します。 |
|
||||||
|
| `get_task_status` | 一つのタスクの簡易的な実行状態とファイル別の進捗を取得します。 |
|
||||||
|
| `get_task_stats` | HTTP 接続数や BitTorrent の Peer・シード情報など、プロトコル固有の統計を取得します。 |
|
||||||
|
| `pause_task` | タスクを一時停止します。 |
|
||||||
|
| `continue_task` | 一時停止または失敗したタスクを再開します。 |
|
||||||
|
| `delete_task` | タスクを削除し、必要に応じてダウンロード済みファイルも削除します。 |
|
||||||
|
|
||||||
```bash
|
## ⬇️ インストール
|
||||||
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
|
||||||
```
|
|
||||||
|
|
||||||
### Docker
|
### 🧪 Gopeed 2.0.0 Beta
|
||||||
|
|
||||||
#### 直接始める
|
Gopeed 2.0.0 は現在パブリックベータ版です。刷新されたインターフェース、デスクトップおよびモバイルから FFI で Go コアへ直接接続するネイティブ通信アーキテクチャ、より統一されたクロスプラットフォーム体験、強化されたタスク管理、より柔軟な API、MCP による AI Agent 連携機能を導入しています。一部の機能はまだ不完全または不安定な場合がありますので、ぜひお試しいただき、問題があればフィードバックをお寄せください。
|
||||||
|
|
||||||
```bash
|
- [Gopeed 2.0.0 Beta 1 をダウンロード](https://github.com/GopeedLab/gopeed/releases/tag/v2.0.0-beta.1)
|
||||||
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Docker Compose の使用
|
機能と安定性が正式リリースの基準に達した時点で、Gopeed 2.0.0 正式版を公開します。ベータ版のユーザーは正式版へ直接アップデートできます。既存の安定版ユーザーが自動的にベータチャンネルへ移行することはありません。
|
||||||
|
|
||||||
```bash
|
### 安定版
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Gopeed へのアクセス
|
- [公式サイトからダウンロード](https://gopeed.com)
|
||||||
|
- [GitHub Releases](https://github.com/GopeedLab/gopeed/releases/latest)
|
||||||
|
|
||||||
docker コンテナが起動しているときは、`http://localhost:9999` からウェブページにアクセスできます。
|
### 🛠️ コマンドツール
|
||||||
|
|
||||||
## 寄付
|
## 📱 WeChat 公式アカウント
|
||||||
|
|
||||||
もしこのプロジェクトがお気に召しましたら、このプロジェクトの発展を支援するために[寄付](/.donate/index.md#donate)をご検討ください!
|
公式アカウントをフォローして、最新のアップデートやニュースを入手してください。
|
||||||
|
|
||||||
## ショーケース
|
<img src="_docs/img/weixin.png" width="200" />
|
||||||
|
|
||||||

|
## 💝 寄付
|
||||||
|
|
||||||
## 開発
|
もしこのプロジェクトがお気に召しましたら、このプロジェクトの発展を支援するために[寄付](https://gopeed.com/docs/donate)をご検討ください!
|
||||||
|
|
||||||
|
## 👨💻 開発
|
||||||
|
|
||||||
このプロジェクトは二つの部分に分かれており、フロントエンドでは `flutter` を、バックエンドでは `Golang` を使用し、両者は `http` プロトコルで通信する。ユニックスシステムでは `unix socket` を、ウィンドウズシステムでは `tcp` プロトコルを使用します。
|
このプロジェクトは二つの部分に分かれており、フロントエンドでは `flutter` を、バックエンドでは `Golang` を使用し、両者は `http` プロトコルで通信する。ユニックスシステムでは `unix socket` を、ウィンドウズシステムでは `tcp` プロトコルを使用します。
|
||||||
|
|
||||||
> フロントコードは `ui/flutter` ディレクトリにあります。
|
> フロントコードは `ui/flutter` ディレクトリにあります。
|
||||||
|
|
||||||
### 環境
|
### 🌍 環境
|
||||||
|
|
||||||
1. Go 言語 1.19+
|
1. Go 言語 1.25+
|
||||||
2. Flutter 3.10+
|
2. Flutter 3.41+
|
||||||
|
|
||||||
### クローン
|
### 📋 クローン
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone git@github.com:GopeedLab/gopeed.git
|
git clone git@github.com:GopeedLab/gopeed.git
|
||||||
```
|
```
|
||||||
|
|
||||||
### コントリビュート
|
### 🤝 コントリビュート
|
||||||
|
|
||||||
[CONTRIBUTING.md](/CONTRIBUTING_ja-JP.md) をご参照ください
|
[CONTRIBUTING.md](/CONTRIBUTING_ja-JP.md) をご参照ください
|
||||||
|
|
||||||
### ビルド
|
### 🏗️ ビルド
|
||||||
|
|
||||||
#### デスクトップ
|
#### デスクトップ
|
||||||
|
|
||||||
@@ -135,7 +152,7 @@ gomobile init
|
|||||||
- android
|
- android
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 19 -javapkg=com.gopeed github.com/GopeedLab/gopeed/bind/mobile
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg="com.gopeed" github.com/GopeedLab/gopeed/bind/mobile
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build apk
|
flutter build apk
|
||||||
```
|
```
|
||||||
@@ -159,10 +176,9 @@ cd ../../
|
|||||||
rm -rf cmd/web/dist
|
rm -rf cmd/web/dist
|
||||||
cp -r ui/flutter/build/web cmd/web/dist
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
||||||
go run cmd/web/main.go
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 感謝
|
## ❤️ 感謝
|
||||||
|
|
||||||
### コントリビューター
|
### コントリビューター
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
# [](https://gopeed.com)
|
||||||
|
|
||||||
|
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
||||||
|
[](https://codecov.io/gh/GopeedLab/gopeed)
|
||||||
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
|
[](https://gopeed.com/docs/donate)
|
||||||
|
[](https://raw.githubusercontent.com/GopeedLab/gopeed/main/_docs/img/weixin.png)
|
||||||
|
[](https://discord.gg/ZUJqJrwCGB)
|
||||||
|
|
||||||
|
<a href="https://trendshift.io/repositories/7953" target="_blank"><img src="https://trendshift.io/api/badge/repositories/7953" alt="GopeedLab%2Fgopeed | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
|
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md) | [正體中文](/README_zh-TW.md) | [Tiếng Việt](/README_vi-VN.md)
|
||||||
|
|
||||||
|
## 🚀 Giới thiệu
|
||||||
|
|
||||||
|
Gopeed (viết tắt của **Go Speed**) là trình quản lý tải xuống nhanh, hiện đại, miễn phí và mã nguồn mở, được xây dựng bằng Go và Flutter. Gopeed hỗ trợ HTTP, HTTPS, BitTorrent, Magnet và ed2k trên máy tính, thiết bị di động và Web.
|
||||||
|
|
||||||
|
Ngoài việc quản lý tải xuống hằng ngày, Gopeed còn hỗ trợ tích hợp trình duyệt, tiện ích JavaScript, REST API, CLI và Web UI có thể tự lưu trữ để mở rộng và tự động hóa quy trình.
|
||||||
|
|
||||||
|
Truy cập ✈ [Trang web chính thức](https://gopeed.com)
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## ✨ Tính năng chính
|
||||||
|
|
||||||
|
- ⚡ **Tải xuống tốc độ cao** — kết hợp nhiều tác vụ, truyền HTTP phân đoạn qua nhiều kết nối và tải BitTorrent P2P để tận dụng tối đa băng thông.
|
||||||
|
- 🧲 **Đa giao thức** — quản lý HTTP, HTTPS, BitTorrent, Magnet và ed2k trong một giao diện.
|
||||||
|
- 🌱 **Bộ công cụ BT đầy đủ** — hỗ trợ khám phá Peer qua DHT, truyền tải uTP, Web Seed, chọn tệp, quản lý Tracker, xem Peer/mảnh và kiểm soát seed theo tỷ lệ hoặc thời gian.
|
||||||
|
- 📋 **Quản lý tác vụ thực tế** — tạm dừng, tiếp tục, thử lại, thao tác hàng loạt, tìm kiếm, bộ lọc, danh mục và khôi phục khi khởi động.
|
||||||
|
- 🪶 **Trải nghiệm native gọn nhẹ** — giao diện chính được Flutter kết xuất native. Không Electron. Không vỏ bọc WebView. Kích thước nhỏ hơn, ít tốn tài nguyên hơn và phản hồi nhanh hơn.
|
||||||
|
- 💻 **Đa nền tảng** — Windows, macOS, Linux, Android, iOS, Web, Docker và QNAP.
|
||||||
|
- 🎨 **Giao diện tùy biến** — hỗ trợ chế độ theo hệ thống, sáng, tối và 8 màu nhấn.
|
||||||
|
- 📐 **Bố cục thích ứng** — danh sách tác vụ, điều hướng, cài đặt và màn hình chi tiết tự điều chỉnh cho điện thoại, máy tính bảng và cửa sổ desktop có thể thay đổi kích thước.
|
||||||
|
- 🗣️ **Hơn 20 ngôn ngữ giao diện** — gồm tiếng Việt, tiếng Anh, tiếng Trung giản thể và phồn thể, tiếng Nhật, tiếng Hàn cùng nhiều ngôn ngữ khác.
|
||||||
|
- 🌐 **Tích hợp trình duyệt** — gửi tải xuống từ Chrome, Edge, Firefox và các trình duyệt tương thích sang Gopeed.
|
||||||
|
- 🧩 **Tiện ích JavaScript** — thêm nguồn tải từ nền tảng video, kho mô hình AI, lưu trữ đám mây và nhiều dịch vụ khác.
|
||||||
|
- 🤖 **Tích hợp AI** — cung cấp giao diện MCP để kết nối với các AI Agent tương thích và tạo, kiểm tra hoặc quản lý tác vụ tải xuống bằng ngôn ngữ tự nhiên.
|
||||||
|
- 🔌 **Giao diện mở** — REST API, CLI, Web UI có xác thực, webhook và script sau khi tải.
|
||||||
|
- 🛠️ **Công cụ tích hợp** — Header/User-Agent tùy chỉnh, proxy, mirror GitHub, thông báo và tự động giải nén.
|
||||||
|
|
||||||
|
## 🤖 Tích hợp AI
|
||||||
|
|
||||||
|
Sau khi kết nối Gopeed với AI Agent, bạn có thể quản lý tải xuống bằng ngôn ngữ tự nhiên. Ví dụ, hãy nói với AI Agent:
|
||||||
|
|
||||||
|
> Hãy tải xuống phiên bản Gopeed mới nhất dành cho Windows
|
||||||
|
|
||||||
|
| Tool | Mô tả |
|
||||||
|
| --- | --- |
|
||||||
|
| `resolve_task` | Phân tích URL hoặc URI tải xuống và trả về thông tin tài nguyên cùng danh sách tệp trước khi tạo tác vụ. |
|
||||||
|
| `create_task` | Tạo và bắt đầu tác vụ từ ID tài nguyên đã phân tích hoặc từ yêu cầu tải xuống trực tiếp. |
|
||||||
|
| `list_tasks` | Liệt kê tác vụ và có thể lọc theo ID hoặc trạng thái. |
|
||||||
|
| `get_task` | Lấy yêu cầu, tài nguyên, tùy chọn và tiến độ hiện tại của một tác vụ. |
|
||||||
|
| `get_task_status` | Lấy trạng thái chạy rút gọn và tiến độ của từng tệp trong một tác vụ. |
|
||||||
|
| `get_task_stats` | Lấy số liệu thống kê theo giao thức, gồm kết nối HTTP hoặc Peer và dữ liệu seed của BitTorrent. |
|
||||||
|
| `pause_task` | Tạm dừng tác vụ. |
|
||||||
|
| `continue_task` | Tiếp tục tác vụ đã tạm dừng hoặc bị lỗi. |
|
||||||
|
| `delete_task` | Xóa tác vụ và có thể xóa cả các tệp đã tải xuống. |
|
||||||
|
|
||||||
|
## ⬇️ Tải về
|
||||||
|
|
||||||
|
### 🧪 Gopeed 2.0.0 Beta
|
||||||
|
|
||||||
|
Gopeed 2.0.0 hiện đang trong giai đoạn beta công khai, với giao diện được thiết kế lại, kiến trúc giao tiếp native kết nối trực tiếp ứng dụng desktop và di động với lõi Go qua FFI, trải nghiệm đa nền tảng nhất quán hơn, khả năng quản lý tác vụ được cải thiện, API linh hoạt hơn và khả năng tích hợp AI Agent qua MCP. Một số tính năng có thể vẫn chưa hoàn thiện hoặc chưa ổn định, vì vậy hãy dùng thử và gửi phản hồi nếu bạn gặp vấn đề.
|
||||||
|
|
||||||
|
- [Tải Gopeed 2.0.0 Beta 1](https://github.com/GopeedLab/gopeed/releases/tag/v2.0.0-beta.1)
|
||||||
|
|
||||||
|
Khi các tính năng và độ ổn định đáp ứng tiêu chuẩn phát hành, chúng tôi sẽ phát hành Gopeed 2.0.0 chính thức. Người dùng bản beta có thể nâng cấp trực tiếp lên bản chính thức, trong khi người dùng bản ổn định hiện tại sẽ không tự động được chuyển sang kênh beta.
|
||||||
|
|
||||||
|
### Bản ổn định
|
||||||
|
|
||||||
|
- [Tải xuống từ trang web chính thức](https://gopeed.com)
|
||||||
|
- [GitHub Releases](https://github.com/GopeedLab/gopeed/releases/latest)
|
||||||
|
|
||||||
|
### 🛠️ Công cụ lệnh
|
||||||
|
|
||||||
|
Sử dụng `go install`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📱 WeChat Official Account
|
||||||
|
|
||||||
|
Theo dõi tài khoản chính thức để nhận các cập nhật và tin tức mới nhất.
|
||||||
|
|
||||||
|
<img src="_docs/img/weixin.png" width="200" />
|
||||||
|
|
||||||
|
## 💝 Quyên góp
|
||||||
|
|
||||||
|
Nếu bạn thích dự án này, xin vui lòng xem xét [quyên góp](https://gopeed.com/docs/donate) để hỗ trợ phát triển dự án này, cảm ơn bạn!
|
||||||
|
|
||||||
|
## 👨💻 Development
|
||||||
|
|
||||||
|
Dự án này được chia thành hai phần, phần giao diện sử dụng `flutter`, phần backend sử dụng `Golang`, và hai phía giao tiếp thông qua giao thức `http`. Trên hệ thống unix, sử dụng `unix socket`, và trên hệ thống windows, sử dụng giao thức `tcp`.
|
||||||
|
|
||||||
|
> Mã giao diện nằm trong thư mục `ui/flutter`.
|
||||||
|
|
||||||
|
### 🌍 Environment
|
||||||
|
|
||||||
|
1. Golang 1.25+
|
||||||
|
2. Flutter 3.41+
|
||||||
|
|
||||||
|
### 📋 Clone
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone git@github.com:GopeedLab/gopeed.git
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🤝 Đóng góp
|
||||||
|
|
||||||
|
Vui lòng tham khảo [CONTRIBUTING_vi-VN.md](/CONTRIBUTING_vi-VN.md)
|
||||||
|
|
||||||
|
### 🏗️ Xây dựng
|
||||||
|
|
||||||
|
#### Desktop
|
||||||
|
|
||||||
|
Trước tiên, bạn cần cấu hình môi trường theo tài liệu chính thức của [Tài liệu trang web máy tính để bàn Flutter](https://docs.flutter.dev/development/platform-integration/desktop), sau đó bạn cần đảm bảo môi trường cgo được thiết lập đúng. Để biết hướng dẫn chi tiết về cách thiết lập môi trường cgo, vui lòng tham khảo các tài liệu tương ứng có sẵn trực tuyến.
|
||||||
|
|
||||||
|
command:
|
||||||
|
|
||||||
|
- windows
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build windows
|
||||||
|
```
|
||||||
|
|
||||||
|
- macos
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build macos
|
||||||
|
```
|
||||||
|
|
||||||
|
- linux
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build linux
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Mobile
|
||||||
|
|
||||||
|
Giống như trước đây, bạn cũng cần chuẩn bị môi trường `cgo` và sau đó cài đặt `gomobile`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
|
go get golang.org/x/mobile/bind
|
||||||
|
gomobile init
|
||||||
|
```
|
||||||
|
|
||||||
|
command:
|
||||||
|
|
||||||
|
- android
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg="com.gopeed" github.com/GopeedLab/gopeed/bind/mobile
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build apk
|
||||||
|
```
|
||||||
|
|
||||||
|
- ios
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build ios --no-codesign
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Web
|
||||||
|
|
||||||
|
command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build web
|
||||||
|
cd ../../
|
||||||
|
rm -rf cmd/web/dist
|
||||||
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
|
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
||||||
|
```
|
||||||
|
|
||||||
|
## ❤️ Tín dụng
|
||||||
|
|
||||||
|
### Người đóng góp
|
||||||
|
|
||||||
|
<a href="https://github.com/GopeedLab/gopeed/graphs/contributors">
|
||||||
|
<img src="https://contrib.rocks/image?repo=GopeedLab/gopeed" />
|
||||||
|
</a>
|
||||||
|
|
||||||
|
### JetBrains
|
||||||
|
|
||||||
|
[](https://www.jetbrains.com/?from=gopeed)
|
||||||
|
|
||||||
|
## Giấy phép
|
||||||
|
|
||||||
|
[GPLv3](LICENSE)
|
||||||
@@ -1,39 +1,78 @@
|
|||||||
|
# [](https://gopeed.com)
|
||||||
|
|
||||||
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
||||||
[](https://codecov.io/gh/GopeedLab/gopeed)
|
[](https://codecov.io/gh/GopeedLab/gopeed)
|
||||||
[](https://github.com/GopeedLab/gopeed/releases)
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
[](https://github.com/GopeedLab/gopeed/releases)
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
[](https://github.com/GopeedLab/gopeed/blob/main/.donate/index.md#donate)
|
[](https://gopeed.com/docs/donate)
|
||||||
|
[](https://raw.githubusercontent.com/GopeedLab/gopeed/main/_docs/img/weixin.png)
|
||||||
[](https://discord.gg/ZUJqJrwCGB)
|
[](https://discord.gg/ZUJqJrwCGB)
|
||||||
|
|
||||||

|
<a href="https://trendshift.io/repositories/7953" target="_blank"><img src="https://trendshift.io/api/badge/repositories/7953" alt="GopeedLab%2Fgopeed | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
[](https://ko-fi.com/R6R6IJGN6)
|
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md) | [正體中文](/README_zh-TW.md) | [Tiếng Việt](/README_vi-VN.md)
|
||||||
|
|
||||||
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md)
|
## 🚀 介绍
|
||||||
|
|
||||||
## 介绍
|
Gopeed(全称 **Go Speed**,也叫“够快下载器”)是一款使用 Go 和 Flutter 开发的高速、现代、免费开源下载器,支持 HTTP、HTTPS、BitTorrent、磁力链接和 ed2k,并覆盖桌面端、移动端与 Web。
|
||||||
|
|
||||||
Gopeed(全称 Go Speed),是一款由`Golang`+`Flutter`开发的高速下载器,支持(HTTP、BitTorrent、Magnet)协议下载,并且支持全平台使用。
|
除了日常下载任务管理,Gopeed 还提供浏览器接管、JavaScript 扩展、REST API、命令行工具和可自托管 Web UI,方便高级用户扩展和自动化自己的下载流程。
|
||||||
|
|
||||||
访问 ✈ [官方网站](https://gopeed.com/zh-CN) | 📖 [开发文档](https://docs.gopeed.com/zh/)
|
访问 ✈ [官方网站](https://gopeed.com)
|
||||||
|
|
||||||
## 安装
|

|
||||||
|
|
||||||
**已支持平台**
|
## ✨ 主要特性
|
||||||
|
|
||||||
- [x] windows
|
- ⚡ **高速下载** — 多任务并发、HTTP 多连接分段传输和 BitTorrent P2P 下载,充分利用可用带宽。
|
||||||
- [x] macos
|
- 🧲 **多协议支持** — 在同一个界面管理 HTTP、HTTPS、BitTorrent、磁力链接和 ed2k。
|
||||||
- [x] linux
|
- 🌱 **完整 BT 能力** — 支持 DHT 节点发现、uTP 传输、Web Seed、按文件选择下载、Tracker 管理、Peer/分片统计,以及按分享率或时间控制做种。
|
||||||
- [x] android
|
- 📋 **实用任务管理** — 暂停、续传、重试、批量操作、搜索、状态筛选、下载分类和启动恢复。
|
||||||
- [x] ios
|
- 🪶 **轻量原生体验** — 主界面使用 Flutter 原生渲染,非 Electron,非 WebView 的套壳,安装包更轻量、运行开销更低、响应更流畅。
|
||||||
- [x] web
|
- 💻 **全平台覆盖** — 支持 Windows、macOS、Linux、Android、iOS 和 Web,并提供 Docker、QNAP 部署方式。
|
||||||
- [x] docker
|
- 🎨 **个性化主题** — 支持跟随系统、浅色、深色三种模式,以及 8 种主题强调色。
|
||||||
|
- 📐 **响应式界面** — 任务列表、导航、设置和详情视图会针对手机、平板及可调整大小的桌面窗口自动布局。
|
||||||
|
- 🗣️ **20+ 种界面语言** — 支持简体中文、繁体中文、英语、日语、韩语等多种语言。
|
||||||
|
- 🌐 **浏览器接管** — 支持 Chrome、Edge、Firefox 等兼容浏览器,将下载任务直接发送到 Gopeed。
|
||||||
|
- 🧩 **JavaScript 扩展** — 扩展视频网站、AI 模型站、网盘等更多下载源。
|
||||||
|
- 🤖 **AI 接入** — 开放 MCP 接口,可接入 AI Agent,通过自然语言创建、查询和管理下载任务。
|
||||||
|
- 🔌 **开放接口** — 通过 REST API、CLI、带身份认证的 Web UI、Webhook 和下载后脚本进行自动化。
|
||||||
|
- 🛠️ **常用内置能力** — 自定义 Header 与 User-Agent、代理、GitHub 镜像、通知和自动解压。
|
||||||
|
|
||||||
[前往下载](https://github.com/GopeedLab/gopeed/releases/latest)
|
## 🤖 AI 接入
|
||||||
|
|
||||||
> 注:macos 版本运行如果提示损坏,请在终端执行 `xattr -d com.apple.quarantine /Applications/Gopeed.app` 命令
|
将 Gopeed 接入 AI Agent 后,即可通过自然语言管理下载。例如,直接对 AI Agent 说:
|
||||||
|
|
||||||
### 命令行工具
|
> 帮我下载最新的 Gopeed Windows 客户端
|
||||||
|
|
||||||
|
| Tool | 功能说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `resolve_task` | 解析下载 URL 或 URI,在创建任务前返回资源信息及文件列表。 |
|
||||||
|
| `create_task` | 使用已解析的资源 ID 或直接下载请求创建并启动任务。 |
|
||||||
|
| `list_tasks` | 查询任务列表,并可按任务 ID 或状态筛选。 |
|
||||||
|
| `get_task` | 获取单个任务的请求、资源、选项及当前进度等完整信息。 |
|
||||||
|
| `get_task_status` | 获取单个任务的轻量运行状态和各文件下载进度。 |
|
||||||
|
| `get_task_stats` | 获取协议相关统计信息,包括 HTTP 连接或 BitTorrent Peer 与做种数据。 |
|
||||||
|
| `pause_task` | 暂停任务。 |
|
||||||
|
| `continue_task` | 继续已暂停或失败的任务。 |
|
||||||
|
| `delete_task` | 删除任务,并可选择同时删除已下载文件。 |
|
||||||
|
|
||||||
|
## ⬇️ 下载
|
||||||
|
|
||||||
|
### 🧪 Gopeed 2.0.0 Beta
|
||||||
|
|
||||||
|
Gopeed 2.0.0 目前处于公开 Beta 测试阶段,引入了全新界面、通过 FFI 直连 Go 核心的原生通信架构、更一致的跨平台体验、更完善的任务管理、更灵活的 API,以及用于 AI Agent 接入的 MCP 能力。部分功能仍可能不够完善或稳定,欢迎提前体验并向我们反馈问题。
|
||||||
|
|
||||||
|
- [下载 Gopeed 2.0.0 Beta 1](https://github.com/GopeedLab/gopeed/releases/tag/v2.0.0-beta.1)
|
||||||
|
|
||||||
|
当功能完整度和稳定性达到正式发布标准后,我们会发布 Gopeed 2.0.0 正式版。已安装 Beta 版本的用户可以直接升级到最终正式版,现有稳定版用户则不会被自动切换到 Beta 渠道。
|
||||||
|
|
||||||
|
### 正式稳定版
|
||||||
|
|
||||||
|
- [官方网站下载](https://gopeed.com)
|
||||||
|
- [GitHub Releases](https://github.com/GopeedLab/gopeed/releases/latest)
|
||||||
|
|
||||||
|
### 🛠️ 命令行工具
|
||||||
|
|
||||||
使用`go install`安装:
|
使用`go install`安装:
|
||||||
|
|
||||||
@@ -41,54 +80,42 @@ Gopeed(全称 Go Speed),是一款由`Golang`+`Flutter`开发的高速下
|
|||||||
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
||||||
```
|
```
|
||||||
|
|
||||||
### Docker
|
## 🔌 浏览器扩展
|
||||||
|
|
||||||
#### 直接运行
|
Gopeed 还提供了浏览器扩展用于接管浏览器下载,支持 Chrome、Edge、Firefox 等浏览器,具体请参考:[https://github.com/GopeedLab/browser-extension](https://github.com/GopeedLab/browser-extension)
|
||||||
|
|
||||||
```bash
|
## 📱 微信公众号
|
||||||
docker run -d -p 9999:9999 -v /path/to/download:/root/Downloads liwei2633/gopeed
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 使用 Docker Compose
|
关注公众号获取项目最新动态和资讯。
|
||||||
|
|
||||||
```bash
|
<img src="_docs/img/weixin.png" width="200" />
|
||||||
docker-compose up -d
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 访问服务
|
## 💝 赞助
|
||||||
|
|
||||||
当 docker 容器运行时,可以通过 `http://localhost:9999` 访问 web 页面。
|
如果觉得项目对你有帮助,请考虑[赞助](https://gopeed.com/docs/donate)以支持这个项目的发展,非常感谢!
|
||||||
|
|
||||||
## 打赏
|
## 👨💻 开发
|
||||||
|
|
||||||
如果觉得项目对你有帮助,请考虑[打赏](/.donate/index.md#donate)以支持这个项目的发展,非常感谢!
|
|
||||||
|
|
||||||
## 界面展示
|
|
||||||
|
|
||||||

|
|
||||||
|
|
||||||
## 开发
|
|
||||||
|
|
||||||
本项目分为前端和后端两个部分,前端使用`flutter`,后端使用`Golang`,两边通过`http`协议进行通讯,在 unix 系统下,使用的是`unix socket`,在 windows 系统下,使用的是`tcp`协议。
|
本项目分为前端和后端两个部分,前端使用`flutter`,后端使用`Golang`,两边通过`http`协议进行通讯,在 unix 系统下,使用的是`unix socket`,在 windows 系统下,使用的是`tcp`协议。
|
||||||
|
|
||||||
> 前端代码位于`ui/flutter`目录下。
|
> 前端代码位于`ui/flutter`目录下。
|
||||||
|
|
||||||
### 环境要求
|
### 🌍 环境要求
|
||||||
|
|
||||||
1. Golang 1.19+
|
1. Golang 1.25+
|
||||||
2. Flutter 3.10+
|
2. Flutter 3.41+
|
||||||
|
|
||||||
### 克隆项目
|
### 📋 克隆项目
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone git@github.com:GopeedLab/gopeed.git
|
git clone git@github.com:GopeedLab/gopeed.git
|
||||||
```
|
```
|
||||||
|
|
||||||
### 贡献代码
|
### 🤝 贡献代码
|
||||||
|
|
||||||
请参考[贡献指南](CONTRIBUTING_zh-CN.md)
|
请参考[贡献指南](CONTRIBUTING_zh-CN.md)
|
||||||
|
|
||||||
### 编译
|
### 🏗️ 编译
|
||||||
|
|
||||||
#### 桌面端
|
#### 桌面端
|
||||||
|
|
||||||
@@ -135,7 +162,7 @@ gomobile init
|
|||||||
- android
|
- android
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 19 -javapkg=com.gopeed github.com/GopeedLab/gopeed/bind/mobile
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg="com.gopeed" github.com/GopeedLab/gopeed/bind/mobile
|
||||||
cd ui/flutter
|
cd ui/flutter
|
||||||
flutter build apk
|
flutter build apk
|
||||||
```
|
```
|
||||||
@@ -159,10 +186,9 @@ cd ../../
|
|||||||
rm -rf cmd/web/dist
|
rm -rf cmd/web/dist
|
||||||
cp -r ui/flutter/build/web cmd/web/dist
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
||||||
go run cmd/web/main.go
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 感谢
|
## ❤️ 感谢
|
||||||
|
|
||||||
### 贡献者
|
### 贡献者
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
# [](https://gopeed.com)
|
||||||
|
|
||||||
|
[](https://github.com/GopeedLab/gopeed/actions?query=workflow%3Atest)
|
||||||
|
[](https://codecov.io/gh/GopeedLab/gopeed)
|
||||||
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
|
[](https://github.com/GopeedLab/gopeed/releases)
|
||||||
|
[](https://gopeed.com/docs/donate)
|
||||||
|
[](https://raw.githubusercontent.com/GopeedLab/gopeed/main/_docs/img/weixin.png)
|
||||||
|
[](https://discord.gg/ZUJqJrwCGB)
|
||||||
|
|
||||||
|
<a href="https://trendshift.io/repositories/7953" target="_blank"><img src="https://trendshift.io/api/badge/repositories/7953" alt="GopeedLab%2Fgopeed | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
|
||||||
|
|
||||||
|
[English](/README.md) | [中文](/README_zh-CN.md) | [日本語](/README_ja-JP.md) | [正體中文](/README_zh-TW.md) | [Tiếng Việt](/README_vi-VN.md)
|
||||||
|
|
||||||
|
## 🚀 簡介
|
||||||
|
|
||||||
|
Gopeed(**Go Speed** 的縮寫)是一款以 Go 與 Flutter 開發的高速、現代化、免費開源下載器,支援 HTTP、HTTPS、BitTorrent、磁力連結與 ed2k,並涵蓋桌面、行動裝置及 Web。
|
||||||
|
|
||||||
|
除了日常任務管理,Gopeed 也提供瀏覽器整合、JavaScript 擴充、REST API、命令列工具及可自行託管的 Web UI,方便進階使用者擴充與自動化下載流程。
|
||||||
|
|
||||||
|
瀏覽 ✈ [官方網站](https://gopeed.com)
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## ✨ 主要功能
|
||||||
|
|
||||||
|
- ⚡ **高速下載** — 多任務並行、HTTP 多連線分段傳輸與 BitTorrent P2P 下載,充分利用可用頻寬。
|
||||||
|
- 🧲 **多協定支援** — 在同一介面管理 HTTP、HTTPS、BitTorrent、磁力連結與 ed2k。
|
||||||
|
- 🌱 **完整 BT 功能** — 支援 DHT 節點探索、uTP 傳輸、Web Seed、逐檔選擇、Tracker 管理、Peer/分片統計,以及依分享率或時間控制做種。
|
||||||
|
- 📋 **實用任務管理** — 暫停、續傳、重試、批次操作、搜尋、狀態篩選、分類及啟動恢復。
|
||||||
|
- 🪶 **輕量原生體驗** — 主介面使用 Flutter 原生渲染,非 Electron,非 WebView 套殼,安裝包更輕量、執行開銷更低、操作回應更流暢。
|
||||||
|
- 💻 **跨平台** — 支援 Windows、macOS、Linux、Android、iOS、Web、Docker 與 QNAP。
|
||||||
|
- 🎨 **個人化主題** — 支援跟隨系統、淺色、深色模式及 8 種主題強調色。
|
||||||
|
- 📐 **響應式介面** — 任務列表、導覽、設定與詳細資訊會配合手機、平板及可調整大小的桌面視窗自動配置。
|
||||||
|
- 🗣️ **20+ 種介面語言** — 支援繁體中文、簡體中文、英文、日文、韓文等多種語言。
|
||||||
|
- 🌐 **瀏覽器整合** — 可接管 Chrome、Edge、Firefox 等相容瀏覽器的下載。
|
||||||
|
- 🧩 **JavaScript 擴充** — 新增影音網站、AI 模型平台、雲端儲存等下載來源。
|
||||||
|
- 🤖 **AI 整合** — 提供 MCP 介面,可串接相容的 AI Agent,以自然語言建立、查詢及管理下載任務。
|
||||||
|
- 🔌 **開放介面** — 支援 REST API、CLI、認證 Web UI、Webhook 及下載後腳本。
|
||||||
|
- 🛠️ **實用內建能力** — 自訂 Header/User-Agent、Proxy、GitHub 鏡像、通知及自動解壓縮。
|
||||||
|
|
||||||
|
## 🤖 AI 整合
|
||||||
|
|
||||||
|
將 Gopeed 與 AI Agent 串接後,即可透過自然語言管理下載。例如,直接對 AI Agent 說:
|
||||||
|
|
||||||
|
> 幫我下載最新的 Gopeed Windows 用戶端
|
||||||
|
|
||||||
|
| Tool | 功能說明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `resolve_task` | 解析下載 URL 或 URI,在建立任務前回傳資源資訊及檔案清單。 |
|
||||||
|
| `create_task` | 使用已解析的資源 ID 或直接下載請求建立並啟動任務。 |
|
||||||
|
| `list_tasks` | 查詢任務清單,並可依任務 ID 或狀態篩選。 |
|
||||||
|
| `get_task` | 取得單一任務的請求、資源、選項及目前進度等完整資訊。 |
|
||||||
|
| `get_task_status` | 取得單一任務的簡要執行狀態及各檔案下載進度。 |
|
||||||
|
| `get_task_stats` | 取得協定相關統計資訊,包括 HTTP 連線或 BitTorrent Peer 與做種資料。 |
|
||||||
|
| `pause_task` | 暫停任務。 |
|
||||||
|
| `continue_task` | 繼續已暫停或失敗的任務。 |
|
||||||
|
| `delete_task` | 刪除任務,並可選擇同時刪除已下載檔案。 |
|
||||||
|
|
||||||
|
## ⬇️ 下載
|
||||||
|
|
||||||
|
### 🧪 Gopeed 2.0.0 Beta
|
||||||
|
|
||||||
|
Gopeed 2.0.0 目前處於公開 Beta 測試階段,引入了全新介面、透過 FFI 直連 Go 核心的原生通訊架構、更一致的跨平台體驗、更完善的任務管理、更靈活的 API,以及透過 MCP 串接 AI Agent 的能力。部分功能仍可能不夠完善或穩定,歡迎搶先體驗並向我們回報問題。
|
||||||
|
|
||||||
|
- [下載 Gopeed 2.0.0 Beta 1](https://github.com/GopeedLab/gopeed/releases/tag/v2.0.0-beta.1)
|
||||||
|
|
||||||
|
當功能完整度與穩定性達到正式發布標準後,我們會發布 Gopeed 2.0.0 正式版。已安裝 Beta 版本的使用者可以直接升級至最終正式版,現有穩定版使用者則不會被自動切換至 Beta 頻道。
|
||||||
|
|
||||||
|
### 正式穩定版
|
||||||
|
|
||||||
|
- [官方網站下載](https://gopeed.com)
|
||||||
|
- [GitHub Releases](https://github.com/GopeedLab/gopeed/releases/latest)
|
||||||
|
|
||||||
|
### 🛠️ 使用 CLI 安裝
|
||||||
|
|
||||||
|
使用`go install`安裝:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
## 📱 微信公眾號
|
||||||
|
|
||||||
|
關注公眾號獲取項目最新動態和資訊。
|
||||||
|
|
||||||
|
<img src="_docs/img/weixin.png" width="200" />
|
||||||
|
|
||||||
|
## 💝 贊助
|
||||||
|
|
||||||
|
如果你認為該項目對你有所幫助,請考慮[贊助](https://gopeed.com/docs/donate)以支持該項目的持續發展,謝謝!
|
||||||
|
|
||||||
|
## 👨💻 開發
|
||||||
|
|
||||||
|
該項目分為前端與後端,前端使用`flutter`編寫,後端使用`Golang`編寫,兩邊通過`http`協定進行通訊,在 unix 系統下,則使用`unix socket`,在 windows 系統下,則使用`tcp`協定。
|
||||||
|
|
||||||
|
> 前端代碼位於`ui/flutter`目錄內。
|
||||||
|
|
||||||
|
### 🌍 開發環境
|
||||||
|
|
||||||
|
1. Golang 1.25+
|
||||||
|
2. Flutter 3.41+
|
||||||
|
|
||||||
|
### 📋 克隆項目
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone git@github.com:GopeedLab/gopeed.git
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🤝 協助開發
|
||||||
|
|
||||||
|
請參考[協助指南](CONTRIBUTING_zh-TW.md)
|
||||||
|
|
||||||
|
### 🏗️ 編譯
|
||||||
|
|
||||||
|
#### 桌面端
|
||||||
|
|
||||||
|
首先需要按照[flutter desktop 官方文檔](https://docs.flutter.dev/development/platform-integration/desktop)配置開發環境,並準備好`cgo`環境,具體方法可以自行搜索。
|
||||||
|
|
||||||
|
組建指令:
|
||||||
|
|
||||||
|
- windows
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build windows
|
||||||
|
```
|
||||||
|
|
||||||
|
- macos
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/macos/Frameworks/libgopeed.dylib github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build macos
|
||||||
|
```
|
||||||
|
|
||||||
|
- linux
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/linux/bundle/lib/libgopeed.so github.com/GopeedLab/gopeed/bind/desktop
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build linux
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 移動設備
|
||||||
|
|
||||||
|
需要`cgo`環境,並安裝`gomobile`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go install golang.org/x/mobile/cmd/gomobile@latest
|
||||||
|
go get golang.org/x/mobile/bind
|
||||||
|
gomobile init
|
||||||
|
```
|
||||||
|
|
||||||
|
組建指令:
|
||||||
|
|
||||||
|
- android
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gomobile bind -tags nosqlite -ldflags="-w -s -checklinkname=0" -o ui/flutter/android/app/libs/libgopeed.aar -target=android -androidapi 21 -javapkg="com.gopeed" github.com/GopeedLab/gopeed/bind/mobile
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build apk
|
||||||
|
```
|
||||||
|
|
||||||
|
- ios
|
||||||
|
|
||||||
|
```bash
|
||||||
|
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build ios --no-codesign
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 網頁端
|
||||||
|
|
||||||
|
組建指令:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ui/flutter
|
||||||
|
flutter build web
|
||||||
|
cd ../../
|
||||||
|
rm -rf cmd/web/dist
|
||||||
|
cp -r ui/flutter/build/web cmd/web/dist
|
||||||
|
go build -tags nosqlite,web -ldflags="-s -w" -o bin/ github.com/GopeedLab/gopeed/cmd/web
|
||||||
|
```
|
||||||
|
|
||||||
|
## ❤️ 感謝
|
||||||
|
|
||||||
|
### 貢獻者
|
||||||
|
|
||||||
|
<a href="https://github.com/GopeedLab/gopeed/graphs/contributors">
|
||||||
|
<img src="https://contrib.rocks/image?repo=GopeedLab/gopeed" />
|
||||||
|
</a>
|
||||||
|
|
||||||
|
### JetBrains
|
||||||
|
|
||||||
|
[](https://www.jetbrains.com/?from=gopeed)
|
||||||
|
|
||||||
|
## 軟體許可
|
||||||
|
|
||||||
|
該軟體遵循 [GPLv3](LICENSE) 。
|
||||||
|
Before Width: | Height: | Size: 26 KiB |
@@ -0,0 +1,54 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 400" width="1200" height="400">
|
||||||
|
<rect width="1200" height="400" fill="#040605"/>
|
||||||
|
<g fill="#5dc76c">
|
||||||
|
<rect x="-100" y="50" width="150" height="2" opacity="0.6">
|
||||||
|
<animate attributeName="x" from="-200" to="1300" dur="0.8s" repeatCount="indefinite"/>
|
||||||
|
</rect>
|
||||||
|
<rect x="-200" y="150" width="200" height="1" opacity="0.4">
|
||||||
|
<animate attributeName="x" from="-300" to="1300" dur="1.2s" repeatCount="indefinite"/>
|
||||||
|
</rect>
|
||||||
|
<rect x="-50" y="250" width="180" height="3" opacity="0.8">
|
||||||
|
<animate attributeName="x" from="-200" to="1300" dur="0.6s" repeatCount="indefinite"/>
|
||||||
|
</rect>
|
||||||
|
<rect x="-150" y="350" width="220" height="2" opacity="0.5">
|
||||||
|
<animate attributeName="x" from="-300" to="1300" dur="1s" repeatCount="indefinite"/>
|
||||||
|
</rect>
|
||||||
|
<rect x="-100" y="100" width="100" height="1" opacity="0.7">
|
||||||
|
<animate attributeName="x" from="-150" to="1300" dur="0.9s" repeatCount="indefinite"/>
|
||||||
|
</rect>
|
||||||
|
<rect x="-250" y="300" width="250" height="2" opacity="0.3">
|
||||||
|
<animate attributeName="x" from="-400" to="1300" dur="1.5s" repeatCount="indefinite"/>
|
||||||
|
</rect>
|
||||||
|
</g>
|
||||||
|
<defs>
|
||||||
|
<filter id="logoGlow" x="-50%" y="-50%" width="200%" height="200%">
|
||||||
|
<feGaussianBlur stdDeviation="12" result="blur" />
|
||||||
|
<feComposite in="SourceGraphic" in2="blur" operator="over" />
|
||||||
|
</filter>
|
||||||
|
</defs>
|
||||||
|
<g transform="translate(600, 160)">
|
||||||
|
<!-- Floating animation -->
|
||||||
|
<g>
|
||||||
|
<animateTransform attributeName="transform" type="translate" values="0,-8; 0,8; 0,-8" dur="3s" repeatCount="indefinite" />
|
||||||
|
|
||||||
|
<!-- Pulsing glow behind logo -->
|
||||||
|
<circle cx="0" cy="0" r="45" fill="#5dc76c" filter="url(#logoGlow)" opacity="0.3">
|
||||||
|
<animate attributeName="opacity" values="0.1; 0.6; 0.1" dur="2s" repeatCount="indefinite" />
|
||||||
|
<animate attributeName="r" values="40; 65; 40" dur="2s" repeatCount="indefinite" />
|
||||||
|
</circle>
|
||||||
|
|
||||||
|
<!-- Breathing scale animation -->
|
||||||
|
<g>
|
||||||
|
<animateTransform attributeName="transform" type="scale" values="0.95; 1.05; 0.95" dur="2s" repeatCount="indefinite" />
|
||||||
|
<g transform="scale(0.12) translate(-512, -512)">
|
||||||
|
<path style="opacity:0.998" fill="#5dc76c" d="M 951.5,763.5 C 940.739,755.276 929.405,747.776 917.5,741C 908.477,736.319 899.143,732.485 889.5,729.5C 885.844,625.779 840.844,545.613 754.5,489C 674.802,441.453 590.135,430.12 500.5,455C 419.755,480.605 359.588,530.771 320,605.5C 278.585,565.816 230.752,555.649 176.5,575C 131.948,594.935 106.448,629.102 100,677.5C 99.3333,685.833 99.3333,694.167 100,702.5C 102.081,714.824 105.081,726.824 109,738.5C 95.4882,745.492 82.9882,753.826 71.5,763.5C 37.7121,705.639 16.5454,643.306 8,576.5C -9.41698,416.759 35.9164,278.093 144,160.5C 244.661,58.2827 367.161,5.94939 511.5,3.5C 678.975,7.48829 814.142,74.8216 917,205.5C 1011.33,336.426 1040,480.759 1003,638.5C 991.564,682.671 974.397,724.337 951.5,763.5 Z"/>
|
||||||
|
<path style="opacity:0.999" fill="#fefefe" d="M 951.5,763.5 C 949.28,768.272 946.78,772.938 944,777.5C 938.305,786.913 932.138,795.913 925.5,804.5C 915.954,796.888 905.288,791.055 893.5,787C 878.282,782.958 863.115,778.791 848,774.5C 854.013,716.891 841.346,663.891 810,615.5C 768.341,553.228 711.174,512.395 638.5,493C 560.311,479.566 490.311,497.566 428.5,547C 411.963,560.536 397.13,575.703 384,592.5C 366.745,616.923 348.911,640.923 330.5,664.5C 310.135,651.302 290.469,637.135 271.5,622C 238.448,602.307 206.782,604.307 176.5,628C 159.375,642.752 148.875,661.252 145,683.5C 143.968,692.716 144.968,701.716 148,710.5C 154.334,725.339 160.167,740.339 165.5,755.5C 138.118,764.688 114.451,779.688 94.5,800.5C 85.653,788.968 77.9863,776.635 71.5,763.5C 82.9882,753.826 95.4882,745.492 109,738.5C 105.081,726.824 102.081,714.824 100,702.5C 99.3333,694.167 99.3333,685.833 100,677.5C 106.448,629.102 131.948,594.935 176.5,575C 230.752,555.649 278.585,565.816 320,605.5C 359.588,530.771 419.755,480.605 500.5,455C 590.135,430.12 674.802,441.453 754.5,489C 840.844,545.613 885.844,625.779 889.5,729.5C 899.143,732.485 908.477,736.319 917.5,741C 929.405,747.776 940.739,755.276 951.5,763.5 Z"/>
|
||||||
|
<path style="opacity:0.998" fill="#5dc76c" d="M 925.5,804.5 C 850.791,908.608 750.791,975.775 625.5,1006C 609.308,1009.7 592.975,1012.53 576.5,1014.5C 615.708,969.938 655.042,925.438 694.5,881C 664.168,880.5 633.835,880.333 603.5,880.5C 603.5,811.167 603.5,741.833 603.5,672.5C 542.167,672.5 480.833,672.5 419.5,672.5C 419.5,741.5 419.5,810.5 419.5,879.5C 388.493,879.167 357.493,879.5 326.5,880.5C 326.624,881.107 326.957,881.44 327.5,881.5C 366.805,925.808 406.138,970.141 445.5,1014.5C 318.63,996.317 212.796,939.651 128,844.5C 115.85,830.525 104.683,815.859 94.5,800.5C 114.451,779.688 138.118,764.688 165.5,755.5C 160.167,740.339 154.334,725.339 148,710.5C 144.968,701.716 143.968,692.716 145,683.5C 148.875,661.252 159.375,642.752 176.5,628C 206.782,604.307 238.448,602.307 271.5,622C 290.469,637.135 310.135,651.302 330.5,664.5C 348.911,640.923 366.745,616.923 384,592.5C 397.13,575.703 411.963,560.536 428.5,547C 490.311,497.566 560.311,479.566 638.5,493C 711.174,512.395 768.341,553.228 810,615.5C 841.346,663.891 854.013,716.891 848,774.5C 863.115,778.791 878.282,782.958 893.5,787C 905.288,791.055 915.954,796.888 925.5,804.5 Z"/>
|
||||||
|
<path style="opacity:0.999" fill="#fefefe" d="M 576.5,1014.5 C 532.836,1019.82 489.169,1019.82 445.5,1014.5C 406.138,970.141 366.805,925.808 327.5,881.5C 358.167,880.833 388.833,880.167 419.5,879.5C 419.5,810.5 419.5,741.5 419.5,672.5C 480.833,672.5 542.167,672.5 603.5,672.5C 603.5,741.833 603.5,811.167 603.5,880.5C 633.835,880.333 664.168,880.5 694.5,881C 655.042,925.438 615.708,969.938 576.5,1014.5 Z"/>
|
||||||
|
<path style="opacity:1" fill="#ade2b5" d="M 419.5,879.5 C 388.833,880.167 358.167,880.833 327.5,881.5C 326.957,881.44 326.624,881.107 326.5,880.5C 357.493,879.5 388.493,879.167 419.5,879.5 Z"/>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
</g>
|
||||||
|
<text x="600" y="300" font-family="sans-serif" font-size="72" font-style="italic" font-weight="900" text-anchor="middle" fill="#fff" letter-spacing="8">GOPEED</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 391 KiB |
|
After Width: | Height: | Size: 357 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 55 KiB |
@@ -2,6 +2,7 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/GopeedLab/gopeed/pkg/base"
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
"github.com/GopeedLab/gopeed/pkg/download"
|
"github.com/GopeedLab/gopeed/pkg/download"
|
||||||
"github.com/GopeedLab/gopeed/pkg/protocol/http"
|
"github.com/GopeedLab/gopeed/pkg/protocol/http"
|
||||||
|
|||||||
@@ -1,8 +1,28 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
|
/*
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
typedef void (*TaskEventCallback)(char* payload);
|
||||||
|
|
||||||
|
typedef void (*InvokeResultCallback)(uint64_t request_id, int success, char* payload);
|
||||||
|
|
||||||
|
static void callTaskEventCallback(uintptr_t callback, char* payload) {
|
||||||
|
((TaskEventCallback)callback)(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void callInvokeResultCallback(uintptr_t callback, uint64_t request_id, int success, char* payload) {
|
||||||
|
((InvokeResultCallback)callback)(request_id, success, payload);
|
||||||
|
}
|
||||||
|
*/
|
||||||
import "C"
|
import "C"
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
nativebridge "github.com/GopeedLab/gopeed/bind/native"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest"
|
"github.com/GopeedLab/gopeed/pkg/rest"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
)
|
)
|
||||||
@@ -15,14 +35,105 @@ func Start(cfg *C.char) (int, *C.char) {
|
|||||||
if err := json.Unmarshal([]byte(C.GoString(cfg)), &config); err != nil {
|
if err := json.Unmarshal([]byte(C.GoString(cfg)), &config); err != nil {
|
||||||
return 0, C.CString(err.Error())
|
return 0, C.CString(err.Error())
|
||||||
}
|
}
|
||||||
|
config.ProductionMode = true
|
||||||
|
config.NativeMode = true
|
||||||
|
applyWebViewProvider(&config)
|
||||||
realPort, err := rest.Start(&config)
|
realPort, err := rest.Start(&config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, C.CString(err.Error())
|
return 0, C.CString(err.Error())
|
||||||
}
|
}
|
||||||
|
nativebridge.ResumeInvokes()
|
||||||
return realPort, nil
|
return realPort, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
//export Stop
|
//export Stop
|
||||||
func Stop() {
|
func Stop() {
|
||||||
rest.Stop()
|
nativebridge.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
//export GetAPIServerState
|
||||||
|
func GetAPIServerState() *C.char {
|
||||||
|
return C.CString(apiServerResult(rest.GetAPIServerState()))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export StartAPIServer
|
||||||
|
func StartAPIServer() *C.char {
|
||||||
|
return C.CString(apiServerResult(rest.StartAPIServer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export StopAPIServer
|
||||||
|
func StopAPIServer() *C.char {
|
||||||
|
return C.CString(apiServerResult(rest.StopAPIServer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
//export RestartAPIServer
|
||||||
|
func RestartAPIServer() *C.char {
|
||||||
|
return C.CString(apiServerResult(rest.RestartAPIServer()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func apiServerResult(state *model.APIServerState, err error) string {
|
||||||
|
result := &model.APIServerOperationResult{State: state}
|
||||||
|
if err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
}
|
||||||
|
data, marshalErr := json.Marshal(result)
|
||||||
|
if marshalErr != nil {
|
||||||
|
return fmt.Sprintf(`{"state":null,"error":%q}`, marshalErr.Error())
|
||||||
|
}
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export InvokeAsync
|
||||||
|
func InvokeAsync(
|
||||||
|
method *C.char,
|
||||||
|
path *C.char,
|
||||||
|
query *C.char,
|
||||||
|
body *C.char,
|
||||||
|
requestID C.ulonglong,
|
||||||
|
callback C.uintptr_t,
|
||||||
|
) {
|
||||||
|
if callback == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
complete := func(result string, err error) {
|
||||||
|
success := C.int(1)
|
||||||
|
payload := result
|
||||||
|
if err != nil {
|
||||||
|
success = 0
|
||||||
|
payload = err.Error()
|
||||||
|
}
|
||||||
|
C.callInvokeResultCallback(
|
||||||
|
callback,
|
||||||
|
C.uint64_t(requestID),
|
||||||
|
success,
|
||||||
|
C.CString(payload),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
nativebridge.InvokeAsync(
|
||||||
|
C.GoString(method),
|
||||||
|
C.GoString(path),
|
||||||
|
C.GoString(query),
|
||||||
|
C.GoString(body),
|
||||||
|
complete,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
//export SubscribeTaskEvents
|
||||||
|
func SubscribeTaskEvents(mask C.ulonglong, callback C.uintptr_t) {
|
||||||
|
if mask == 0 || callback == 0 {
|
||||||
|
rest.SubscribeTaskEvents(0, nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rest.SubscribeTaskEvents(uint64(mask), func(payload string) {
|
||||||
|
// Ownership crosses the asynchronous Dart callback boundary. Dart frees
|
||||||
|
// this string with FreeCString after decoding it.
|
||||||
|
C.callTaskEventCallback(callback, C.CString(payload))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
//export FreeCString
|
||||||
|
func FreeCString(value *C.char) {
|
||||||
|
if value != nil {
|
||||||
|
C.free(unsafe.Pointer(value))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
//go:build darwin
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/GopeedLab/gopeed/internal/webview/rpcprovider"
|
||||||
|
enginewebview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func applyWebViewProvider(config *model.StartConfig) {
|
||||||
|
if config == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
config.WebViewProvider = newDesktopWebViewProvider(config.WebViewRPCConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newDesktopWebViewProvider(rpcCfg *enginewebview.RPCConfig) enginewebview.Provider {
|
||||||
|
if rpcCfg != nil && rpcCfg.Enabled() {
|
||||||
|
return rpcprovider.New(*rpcCfg)
|
||||||
|
}
|
||||||
|
return enginewebview.NewUnavailableProvider()
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
//go:build !darwin
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/GopeedLab/gopeed/internal/webview/goprovider"
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func applyWebViewProvider(config *model.StartConfig) {
|
||||||
|
if config == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
config.WebViewProvider = goprovider.New()
|
||||||
|
}
|
||||||
@@ -4,6 +4,9 @@ package libgopeed
|
|||||||
import "C"
|
import "C"
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
|
nativebridge "github.com/GopeedLab/gopeed/bind/native"
|
||||||
|
"github.com/GopeedLab/gopeed/internal/webview/rpcprovider"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest"
|
"github.com/GopeedLab/gopeed/pkg/rest"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
)
|
)
|
||||||
@@ -13,9 +16,77 @@ func Start(cfg string) (int, error) {
|
|||||||
if err := json.Unmarshal([]byte(cfg), &config); err != nil {
|
if err := json.Unmarshal([]byte(cfg), &config); err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
return rest.Start(&config)
|
config.ProductionMode = true
|
||||||
|
config.NativeMode = true
|
||||||
|
applyWebViewProvider(&config)
|
||||||
|
port, err := rest.Start(&config)
|
||||||
|
if err == nil {
|
||||||
|
nativebridge.ResumeInvokes()
|
||||||
|
}
|
||||||
|
return port, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func Stop() {
|
func Stop() {
|
||||||
rest.Stop()
|
nativebridge.Stop()
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetAPIServerState() string {
|
||||||
|
return apiServerResult(rest.GetAPIServerState())
|
||||||
|
}
|
||||||
|
|
||||||
|
func StartAPIServer() string {
|
||||||
|
return apiServerResult(rest.StartAPIServer())
|
||||||
|
}
|
||||||
|
|
||||||
|
func StopAPIServer() string {
|
||||||
|
return apiServerResult(rest.StopAPIServer())
|
||||||
|
}
|
||||||
|
|
||||||
|
func RestartAPIServer() string {
|
||||||
|
return apiServerResult(rest.RestartAPIServer())
|
||||||
|
}
|
||||||
|
|
||||||
|
func apiServerResult(state *model.APIServerState, err error) string {
|
||||||
|
result := &model.APIServerOperationResult{State: state}
|
||||||
|
if err != nil {
|
||||||
|
result.Error = err.Error()
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(result)
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
type InvokeResultListener interface {
|
||||||
|
OnResult(requestID int64, success bool, payload string)
|
||||||
|
}
|
||||||
|
|
||||||
|
func InvokeAsync(method, path, query, body string, requestID int64, listener InvokeResultListener) {
|
||||||
|
if listener == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nativebridge.InvokeAsync(method, path, query, body, func(result string, err error) {
|
||||||
|
if err != nil {
|
||||||
|
listener.OnResult(requestID, false, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
listener.OnResult(requestID, true, result)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type TaskEventListener interface {
|
||||||
|
OnTaskEvent(payload string)
|
||||||
|
}
|
||||||
|
|
||||||
|
func SubscribeTaskEvents(mask int64, listener TaskEventListener) {
|
||||||
|
if mask == 0 || listener == nil {
|
||||||
|
rest.SubscribeTaskEvents(0, nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
rest.SubscribeTaskEvents(uint64(mask), listener.OnTaskEvent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyWebViewProvider(config *model.StartConfig) {
|
||||||
|
if config == nil || config.WebViewRPCConfig == nil || !config.WebViewRPCConfig.Enabled() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
config.WebViewProvider = rpcprovider.New(*config.WebViewRPCConfig)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
// Package nativebridge contains transport-neutral behavior shared by the
|
||||||
|
// Desktop C FFI and gomobile bridge adapters.
|
||||||
|
package nativebridge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/rest"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StopTimeout bounds native shutdown even when an in-process request never returns.
|
||||||
|
const StopTimeout = 3 * time.Second
|
||||||
|
|
||||||
|
var errNativeBridgeStopping = errors.New("native bridge is stopping")
|
||||||
|
|
||||||
|
type invokeRequest struct {
|
||||||
|
method string
|
||||||
|
path string
|
||||||
|
query string
|
||||||
|
body string
|
||||||
|
}
|
||||||
|
|
||||||
|
type invokeTask struct {
|
||||||
|
id uint64
|
||||||
|
request invokeRequest
|
||||||
|
complete func(result string, err error)
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *invokeTask) finish(result string, err error) {
|
||||||
|
t.once.Do(func() {
|
||||||
|
completeCallback(t.complete, result, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvokeAsync starts an in-process API request and completes it through the
|
||||||
|
// supplied callback. Desktop and mobile adapters share this executor.
|
||||||
|
func InvokeAsync(method, path, query, body string, callback func(result string, err error)) {
|
||||||
|
if callback == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
task := invokeTask{
|
||||||
|
request: invokeRequest{
|
||||||
|
method: method,
|
||||||
|
path: path,
|
||||||
|
query: query,
|
||||||
|
body: body,
|
||||||
|
},
|
||||||
|
complete: callback,
|
||||||
|
}
|
||||||
|
if !getInvokeExecutor().submit(task) {
|
||||||
|
completeCallback(callback, "", errNativeBridgeStopping)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResumeInvokes enables request submission after the native runtime starts.
|
||||||
|
func ResumeInvokes() {
|
||||||
|
getInvokeExecutor().resume()
|
||||||
|
}
|
||||||
|
|
||||||
|
// PauseInvokesAndWait prevents new submissions and gives running requests a
|
||||||
|
// bounded opportunity to finish before a native runtime is stopped.
|
||||||
|
// Requests still pending after StopTimeout are failed and detached so shutdown
|
||||||
|
// can continue without invoking their callbacks a second time.
|
||||||
|
func PauseInvokesAndWait() bool {
|
||||||
|
return getInvokeExecutor().pauseAndWait(StopTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop pauses native requests and shuts down the shared runtime, but never
|
||||||
|
// keeps the host application waiting longer than StopTimeout. Cleanup that
|
||||||
|
// cannot finish within the deadline is allowed to continue in the background.
|
||||||
|
func Stop() {
|
||||||
|
stopWithin(getInvokeExecutor(), rest.Stop, StopTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
func stopWithin(executor *invokeExecutor, cleanup func(), timeout time.Duration) {
|
||||||
|
deadline := time.Now().Add(timeout)
|
||||||
|
executor.pauseAndWait(time.Until(deadline))
|
||||||
|
|
||||||
|
stopped := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
defer close(stopped)
|
||||||
|
cleanup()
|
||||||
|
}()
|
||||||
|
|
||||||
|
remaining := time.Until(deadline)
|
||||||
|
if remaining <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
timer := time.NewTimer(remaining)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case <-stopped:
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
invokeExecutorOnce sync.Once
|
||||||
|
sharedInvoker *invokeExecutor
|
||||||
|
)
|
||||||
|
|
||||||
|
func getInvokeExecutor() *invokeExecutor {
|
||||||
|
invokeExecutorOnce.Do(func() {
|
||||||
|
sharedInvoker = newInvokeExecutor(func(request invokeRequest) string {
|
||||||
|
return rest.Dispatch(request.method, request.path, request.query, request.body)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
return sharedInvoker
|
||||||
|
}
|
||||||
|
|
||||||
|
// invokeExecutor starts every native API request in its own goroutine, matching
|
||||||
|
// net/http's request concurrency. It only tracks them to support bounded drain
|
||||||
|
// during shutdown; one stuck request must never prevent another from starting.
|
||||||
|
type invokeExecutor struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
closed bool
|
||||||
|
accepting bool
|
||||||
|
nextID uint64
|
||||||
|
pending map[uint64]*invokeTask
|
||||||
|
drained chan struct{}
|
||||||
|
running sync.WaitGroup
|
||||||
|
handler func(invokeRequest) string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newInvokeExecutor(handler func(invokeRequest) string) *invokeExecutor {
|
||||||
|
drained := make(chan struct{})
|
||||||
|
close(drained)
|
||||||
|
return &invokeExecutor{
|
||||||
|
handler: handler,
|
||||||
|
accepting: true,
|
||||||
|
pending: make(map[uint64]*invokeTask),
|
||||||
|
drained: drained,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *invokeExecutor) submit(task invokeTask) bool {
|
||||||
|
e.mu.Lock()
|
||||||
|
if e.closed || !e.accepting {
|
||||||
|
e.mu.Unlock()
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if len(e.pending) == 0 {
|
||||||
|
e.drained = make(chan struct{})
|
||||||
|
}
|
||||||
|
taskID := e.nextID
|
||||||
|
e.nextID++
|
||||||
|
task.id = taskID
|
||||||
|
taskPtr := &task
|
||||||
|
e.pending[taskID] = taskPtr
|
||||||
|
e.running.Add(1)
|
||||||
|
e.mu.Unlock()
|
||||||
|
|
||||||
|
go e.run(taskPtr)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *invokeExecutor) resume() {
|
||||||
|
e.mu.Lock()
|
||||||
|
e.accepting = true
|
||||||
|
e.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *invokeExecutor) pauseAndWait(timeout time.Duration) bool {
|
||||||
|
e.mu.Lock()
|
||||||
|
e.accepting = false
|
||||||
|
if len(e.pending) == 0 {
|
||||||
|
e.mu.Unlock()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
drained := e.drained
|
||||||
|
e.mu.Unlock()
|
||||||
|
|
||||||
|
timer := time.NewTimer(timeout)
|
||||||
|
defer timer.Stop()
|
||||||
|
select {
|
||||||
|
case <-drained:
|
||||||
|
return true
|
||||||
|
case <-timer.C:
|
||||||
|
}
|
||||||
|
|
||||||
|
e.mu.Lock()
|
||||||
|
if len(e.pending) == 0 {
|
||||||
|
e.mu.Unlock()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
pending := make([]*invokeTask, 0, len(e.pending))
|
||||||
|
for _, task := range e.pending {
|
||||||
|
pending = append(pending, task)
|
||||||
|
}
|
||||||
|
e.pending = make(map[uint64]*invokeTask)
|
||||||
|
close(e.drained)
|
||||||
|
e.mu.Unlock()
|
||||||
|
|
||||||
|
for _, task := range pending {
|
||||||
|
task.finish("", errNativeBridgeStopping)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *invokeExecutor) close() {
|
||||||
|
e.mu.Lock()
|
||||||
|
e.closed = true
|
||||||
|
e.accepting = false
|
||||||
|
e.mu.Unlock()
|
||||||
|
e.running.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *invokeExecutor) run(task *invokeTask) {
|
||||||
|
defer e.running.Done()
|
||||||
|
result, err := e.execute(task.request)
|
||||||
|
task.finish(result, err)
|
||||||
|
e.mu.Lock()
|
||||||
|
if _, exists := e.pending[task.id]; exists {
|
||||||
|
delete(e.pending, task.id)
|
||||||
|
if len(e.pending) == 0 {
|
||||||
|
close(e.drained)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
e.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *invokeExecutor) execute(request invokeRequest) (result string, err error) {
|
||||||
|
defer func() {
|
||||||
|
if recovered := recover(); recovered != nil {
|
||||||
|
err = fmt.Errorf("invoke panic: %v", recovered)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return e.handler(request), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func completeCallback(callback func(string, error), result string, err error) {
|
||||||
|
defer func() {
|
||||||
|
_ = recover()
|
||||||
|
}()
|
||||||
|
callback(result, err)
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
package nativebridge
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInvokeExecutorStartsEveryRequestIndependently(t *testing.T) {
|
||||||
|
const taskCount = 64
|
||||||
|
release := make(chan struct{})
|
||||||
|
started := make(chan struct{}, taskCount)
|
||||||
|
executor := newInvokeExecutor(func(request invokeRequest) string {
|
||||||
|
started <- struct{}{}
|
||||||
|
<-release
|
||||||
|
return request.path
|
||||||
|
})
|
||||||
|
|
||||||
|
var completed sync.WaitGroup
|
||||||
|
completed.Add(taskCount)
|
||||||
|
for i := range taskCount {
|
||||||
|
accepted := executor.submit(invokeTask{
|
||||||
|
request: invokeRequest{path: strconv.Itoa(i)},
|
||||||
|
complete: func(string, error) {
|
||||||
|
completed.Done()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if !accepted {
|
||||||
|
t.Fatalf("request %d was rejected", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Every handler must start before any of them is released. A worker pool
|
||||||
|
// would stall here once all of its workers were occupied.
|
||||||
|
for range taskCount {
|
||||||
|
select {
|
||||||
|
case <-started:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("a request waited behind other blocked requests")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close(release)
|
||||||
|
completed.Wait()
|
||||||
|
executor.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeExecutorConvertsPanicsToErrors(t *testing.T) {
|
||||||
|
executor := newInvokeExecutor(func(invokeRequest) string {
|
||||||
|
panic("boom")
|
||||||
|
})
|
||||||
|
completed := make(chan error, 1)
|
||||||
|
executor.submit(invokeTask{complete: func(_ string, err error) {
|
||||||
|
completed <- err
|
||||||
|
}})
|
||||||
|
select {
|
||||||
|
case err := <-completed:
|
||||||
|
if err == nil || err.Error() != "invoke panic: boom" {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("panic result was not completed")
|
||||||
|
}
|
||||||
|
executor.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeExecutorSurvivesCallbackPanic(t *testing.T) {
|
||||||
|
executor := newInvokeExecutor(func(request invokeRequest) string {
|
||||||
|
return request.path
|
||||||
|
})
|
||||||
|
executor.submit(invokeTask{complete: func(string, error) {
|
||||||
|
panic("callback failed")
|
||||||
|
}})
|
||||||
|
|
||||||
|
completed := make(chan string, 1)
|
||||||
|
executor.submit(invokeTask{
|
||||||
|
request: invokeRequest{path: "next"},
|
||||||
|
complete: func(result string, _ error) {
|
||||||
|
completed <- result
|
||||||
|
},
|
||||||
|
})
|
||||||
|
select {
|
||||||
|
case result := <-completed:
|
||||||
|
if result != "next" {
|
||||||
|
t.Fatalf("unexpected result: %q", result)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("worker stopped after callback panic")
|
||||||
|
}
|
||||||
|
executor.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeExecutorPausesAndDrains(t *testing.T) {
|
||||||
|
release := make(chan struct{})
|
||||||
|
started := make(chan struct{})
|
||||||
|
executor := newInvokeExecutor(func(request invokeRequest) string {
|
||||||
|
if request.path == "running" {
|
||||||
|
close(started)
|
||||||
|
<-release
|
||||||
|
}
|
||||||
|
return request.path
|
||||||
|
})
|
||||||
|
completed := make(chan struct{})
|
||||||
|
if !executor.submit(invokeTask{
|
||||||
|
request: invokeRequest{path: "running"},
|
||||||
|
complete: func(string, error) {
|
||||||
|
close(completed)
|
||||||
|
},
|
||||||
|
}) {
|
||||||
|
t.Fatal("initial task was rejected")
|
||||||
|
}
|
||||||
|
<-started
|
||||||
|
|
||||||
|
drained := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
executor.pauseAndWait(time.Second)
|
||||||
|
close(drained)
|
||||||
|
}()
|
||||||
|
deadline := time.Now().Add(time.Second)
|
||||||
|
for {
|
||||||
|
executor.mu.Lock()
|
||||||
|
paused := !executor.accepting
|
||||||
|
executor.mu.Unlock()
|
||||||
|
if paused {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatal("executor did not pause")
|
||||||
|
}
|
||||||
|
runtime.Gosched()
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-drained:
|
||||||
|
t.Fatal("pause returned before the running request completed")
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
if executor.submit(invokeTask{}) {
|
||||||
|
t.Fatal("paused executor accepted a new request")
|
||||||
|
}
|
||||||
|
|
||||||
|
close(release)
|
||||||
|
<-completed
|
||||||
|
select {
|
||||||
|
case <-drained:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("pause did not return after pending requests drained")
|
||||||
|
}
|
||||||
|
|
||||||
|
executor.resume()
|
||||||
|
resumed := make(chan struct{})
|
||||||
|
if !executor.submit(invokeTask{complete: func(string, error) {
|
||||||
|
close(resumed)
|
||||||
|
}}) {
|
||||||
|
t.Fatal("resumed executor rejected a request")
|
||||||
|
}
|
||||||
|
<-resumed
|
||||||
|
executor.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvokeExecutorPauseTimesOutAndFailsPendingRequests(t *testing.T) {
|
||||||
|
release := make(chan struct{})
|
||||||
|
started := make(chan struct{})
|
||||||
|
executor := newInvokeExecutor(func(request invokeRequest) string {
|
||||||
|
started <- struct{}{}
|
||||||
|
<-release
|
||||||
|
return request.path
|
||||||
|
})
|
||||||
|
|
||||||
|
errors := make(chan error, 2)
|
||||||
|
for _, path := range []string{"first", "second"} {
|
||||||
|
if !executor.submit(invokeTask{
|
||||||
|
request: invokeRequest{path: path},
|
||||||
|
complete: func(_ string, err error) {
|
||||||
|
errors <- err
|
||||||
|
},
|
||||||
|
}) {
|
||||||
|
t.Fatalf("request %q was rejected", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
<-started
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeout = 30 * time.Millisecond
|
||||||
|
startedAt := time.Now()
|
||||||
|
if executor.pauseAndWait(timeout) {
|
||||||
|
t.Fatal("pause unexpectedly reported a complete drain")
|
||||||
|
}
|
||||||
|
if elapsed := time.Since(startedAt); elapsed < timeout || elapsed > 10*timeout {
|
||||||
|
t.Fatalf("pause returned after %s, want close to %s", elapsed, timeout)
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
select {
|
||||||
|
case err := <-errors:
|
||||||
|
if err == nil || err.Error() != errNativeBridgeStopping.Error() {
|
||||||
|
t.Fatalf("unexpected timeout error: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("pending request was not failed after the timeout")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close(release)
|
||||||
|
executor.close()
|
||||||
|
select {
|
||||||
|
case err := <-errors:
|
||||||
|
t.Fatalf("request callback ran more than once: %v", err)
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestStopWithinUsesOneDeadlineForRequestsAndCleanup(t *testing.T) {
|
||||||
|
releaseRequest := make(chan struct{})
|
||||||
|
requestStarted := make(chan struct{})
|
||||||
|
executor := newInvokeExecutor(func(invokeRequest) string {
|
||||||
|
close(requestStarted)
|
||||||
|
<-releaseRequest
|
||||||
|
return "done"
|
||||||
|
})
|
||||||
|
requestResult := make(chan error, 1)
|
||||||
|
executor.submit(invokeTask{complete: func(_ string, err error) {
|
||||||
|
requestResult <- err
|
||||||
|
}})
|
||||||
|
<-requestStarted
|
||||||
|
|
||||||
|
releaseCleanup := make(chan struct{})
|
||||||
|
cleanupStarted := make(chan struct{})
|
||||||
|
cleanup := func() {
|
||||||
|
close(cleanupStarted)
|
||||||
|
<-releaseCleanup
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeout = 40 * time.Millisecond
|
||||||
|
startedAt := time.Now()
|
||||||
|
stopWithin(executor, cleanup, timeout)
|
||||||
|
if elapsed := time.Since(startedAt); elapsed < timeout || elapsed > 10*timeout {
|
||||||
|
t.Fatalf("stop returned after %s, want close to %s", elapsed, timeout)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-cleanupStarted:
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("cleanup was not started after the request deadline")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case err := <-requestResult:
|
||||||
|
if err == nil || err.Error() != errNativeBridgeStopping.Error() {
|
||||||
|
t.Fatalf("unexpected request result: %v", err)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("timed-out request was not failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
close(releaseRequest)
|
||||||
|
close(releaseCleanup)
|
||||||
|
executor.close()
|
||||||
|
}
|
||||||
@@ -1,16 +1,17 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
_ "embed"
|
|
||||||
"github.com/GopeedLab/gopeed/cmd"
|
"github.com/GopeedLab/gopeed/cmd"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// only for local development
|
||||||
func main() {
|
func main() {
|
||||||
cfg := &model.StartConfig{
|
cfg := &model.StartConfig{
|
||||||
Network: "tcp",
|
Network: "tcp",
|
||||||
Address: "127.0.0.1:9999",
|
Address: "127.0.0.1:9999",
|
||||||
Storage: model.StorageBolt,
|
Storage: model.StorageBolt,
|
||||||
|
WebEnable: true,
|
||||||
}
|
}
|
||||||
cmd.Start(cfg)
|
cmd.Start(cfg)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,723 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/GopeedLab/gopeed/internal/webview/goprovider"
|
||||||
|
"github.com/GopeedLab/gopeed/internal/webview/rpcprovider"
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/download"
|
||||||
|
enginewebview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
|
||||||
|
)
|
||||||
|
|
||||||
|
type kvFlag map[string]string
|
||||||
|
|
||||||
|
type webViewConfig struct {
|
||||||
|
provider string
|
||||||
|
network string
|
||||||
|
address string
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *kvFlag) String() string {
|
||||||
|
if l == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
data, _ := json.Marshal(map[string]string(*l))
|
||||||
|
return string(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *kvFlag) Set(value string) error {
|
||||||
|
if *l == nil {
|
||||||
|
*l = make(map[string]string)
|
||||||
|
}
|
||||||
|
idx := -1
|
||||||
|
for i := 0; i < len(value); i++ {
|
||||||
|
if value[i] == '=' {
|
||||||
|
idx = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if idx <= 0 {
|
||||||
|
return fmt.Errorf("invalid label %q, expected key=value", value)
|
||||||
|
}
|
||||||
|
(*l)[value[:idx]] = value[idx+1:]
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
os.Exit(goprovider.RunMainThreadLoop(run))
|
||||||
|
}
|
||||||
|
|
||||||
|
func run() int {
|
||||||
|
if len(os.Args) < 2 {
|
||||||
|
usage()
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
switch os.Args[1] {
|
||||||
|
case "resolve":
|
||||||
|
if err := runResolve(os.Args[2:]); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
case "download":
|
||||||
|
if err := runDownload(os.Args[2:]); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
case "eval":
|
||||||
|
if err := runEval(os.Args[2:]); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, err)
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
case "-h", "--help", "help":
|
||||||
|
usage()
|
||||||
|
default:
|
||||||
|
fmt.Fprintf(os.Stderr, "unknown subcommand %q\n", os.Args[1])
|
||||||
|
usage()
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func usage() {
|
||||||
|
fmt.Fprintf(os.Stderr, `gopeed extmock CLI
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
extmock resolve [flags] <extension-dir> <url>
|
||||||
|
extmock download [flags] <extension-dir> <url> <output-dir>
|
||||||
|
extmock eval [flags] [script-file]
|
||||||
|
|
||||||
|
Flags:
|
||||||
|
-label key=value Request label, repeatable
|
||||||
|
-setting key=value Extension setting override, repeatable
|
||||||
|
-webview-provider WebView provider: go|rpc
|
||||||
|
-webview-network RPC network when provider=rpc: unix|tcp
|
||||||
|
-webview-address RPC address when provider=rpc
|
||||||
|
-webview-token RPC bearer token when provider=rpc
|
||||||
|
-verb Print download progress while running
|
||||||
|
-pretty Pretty-print JSON output
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
extmock resolve ./ https://www.google.com
|
||||||
|
extmock download ./ https://example.com/video /tmp/extmock-download
|
||||||
|
extmock resolve ./ https://example.com/video -label env=test -setting token=abc
|
||||||
|
extmock eval ./test.js
|
||||||
|
extmock eval -e "new Blob(['hello']).size"
|
||||||
|
`)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runResolve(args []string) error {
|
||||||
|
fs := flag.NewFlagSet("resolve", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(os.Stderr)
|
||||||
|
var labels kvFlag
|
||||||
|
var settings kvFlag
|
||||||
|
var pretty bool
|
||||||
|
cfg := webViewConfig{}
|
||||||
|
fs.Var(&labels, "label", "Request label in key=value form (repeatable)")
|
||||||
|
fs.Var(&settings, "setting", "Extension setting override in key=value form (repeatable)")
|
||||||
|
fs.StringVar(&cfg.provider, "webview-provider", "", "WebView provider: go|rpc")
|
||||||
|
fs.StringVar(&cfg.network, "webview-network", "", "WebView RPC network: unix|tcp")
|
||||||
|
fs.StringVar(&cfg.address, "webview-address", "", "WebView RPC address")
|
||||||
|
fs.StringVar(&cfg.token, "webview-token", "", "WebView RPC bearer token")
|
||||||
|
fs.BoolVar(&pretty, "pretty", false, "Pretty-print JSON output")
|
||||||
|
|
||||||
|
flagArgs, positionalArgs, err := splitResolveArgs(args)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := fs.Parse(flagArgs); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
return fmt.Errorf("unexpected trailing args: %v", fs.Args())
|
||||||
|
}
|
||||||
|
if len(positionalArgs) != 2 {
|
||||||
|
return fmt.Errorf("resolve expects exactly 2 args: <extension-dir> <url>")
|
||||||
|
}
|
||||||
|
|
||||||
|
extDir, err := filepath.Abs(positionalArgs[0])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
url := positionalArgs[1]
|
||||||
|
|
||||||
|
d, cleanup, err := newExtMockDownloader(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ext, err := d.InstallExtensionByFolder(extDir, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(settings) > 0 {
|
||||||
|
if err := d.UpdateExtensionSettings(ext.Identity, toAnyMap(settings)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result, err := d.Resolve(&base.Request{
|
||||||
|
URL: url,
|
||||||
|
Labels: map[string]string(labels),
|
||||||
|
}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return printJSON(result, pretty)
|
||||||
|
}
|
||||||
|
|
||||||
|
type downloadResult struct {
|
||||||
|
Resolve *download.ResolveResult `json:"resolve"`
|
||||||
|
OutputDir string `json:"outputDir"`
|
||||||
|
Files []*downloadedFileResult `json:"files"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type downloadedFileResult struct {
|
||||||
|
Index int `json:"index"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Path string `json:"path"`
|
||||||
|
TaskID string `json:"taskId"`
|
||||||
|
Status base.Status `json:"status"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
Req *base.Request `json:"req,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func runDownload(args []string) error {
|
||||||
|
fs := flag.NewFlagSet("download", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(os.Stderr)
|
||||||
|
var labels kvFlag
|
||||||
|
var settings kvFlag
|
||||||
|
var pretty bool
|
||||||
|
var verbose bool
|
||||||
|
cfg := webViewConfig{}
|
||||||
|
fs.Var(&labels, "label", "Request label in key=value form (repeatable)")
|
||||||
|
fs.Var(&settings, "setting", "Extension setting override in key=value form (repeatable)")
|
||||||
|
fs.StringVar(&cfg.provider, "webview-provider", "", "WebView provider: go|rpc")
|
||||||
|
fs.StringVar(&cfg.network, "webview-network", "", "WebView RPC network: unix|tcp")
|
||||||
|
fs.StringVar(&cfg.address, "webview-address", "", "WebView RPC address")
|
||||||
|
fs.StringVar(&cfg.token, "webview-token", "", "WebView RPC bearer token")
|
||||||
|
fs.BoolVar(&verbose, "verb", false, "Print download progress while running")
|
||||||
|
fs.BoolVar(&verbose, "verbose", false, "Print download progress while running")
|
||||||
|
fs.BoolVar(&pretty, "pretty", false, "Pretty-print JSON output")
|
||||||
|
|
||||||
|
flagArgs, positionalArgs, err := splitDownloadArgs(args)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := fs.Parse(flagArgs); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
return fmt.Errorf("unexpected trailing args: %v", fs.Args())
|
||||||
|
}
|
||||||
|
if len(positionalArgs) != 3 {
|
||||||
|
return fmt.Errorf("download expects exactly 3 args: <extension-dir> <url> <output-dir>")
|
||||||
|
}
|
||||||
|
|
||||||
|
extDir, err := filepath.Abs(positionalArgs[0])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
url := positionalArgs[1]
|
||||||
|
outputDir, err := filepath.Abs(positionalArgs[2])
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
d, cleanup, err := newExtMockDownloader(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
ext, err := d.InstallExtensionByFolder(extDir, true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(settings) > 0 {
|
||||||
|
if err := d.UpdateExtensionSettings(ext.Identity, toAnyMap(settings)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := d.Resolve(&base.Request{
|
||||||
|
URL: url,
|
||||||
|
Labels: map[string]string(labels),
|
||||||
|
}, nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if result == nil || result.Res == nil {
|
||||||
|
return fmt.Errorf("resolve returned empty resource")
|
||||||
|
}
|
||||||
|
if len(result.Res.Files) == 0 {
|
||||||
|
return fmt.Errorf("resolve returned no files")
|
||||||
|
}
|
||||||
|
|
||||||
|
resourceOutputDir := outputDir
|
||||||
|
if result.Res.Name != "" {
|
||||||
|
resourceOutputDir = filepath.Join(outputDir, result.Res.Name)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(resourceOutputDir, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
waiter := newTaskTerminalWaiter(d)
|
||||||
|
summary := &downloadResult{
|
||||||
|
Resolve: result,
|
||||||
|
OutputDir: resourceOutputDir,
|
||||||
|
Files: make([]*downloadedFileResult, 0, len(result.Res.Files)),
|
||||||
|
}
|
||||||
|
|
||||||
|
for idx, file := range result.Res.Files {
|
||||||
|
if file == nil {
|
||||||
|
return fmt.Errorf("file %d is nil", idx)
|
||||||
|
}
|
||||||
|
if file.Req == nil {
|
||||||
|
return fmt.Errorf("file %d request is nil", idx)
|
||||||
|
}
|
||||||
|
|
||||||
|
targetDir := resourceOutputDir
|
||||||
|
if file.Path != "" {
|
||||||
|
targetDir = filepath.Join(resourceOutputDir, file.Path)
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(targetDir, 0o755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
taskID, err := d.CreateDirect(file.Req, &base.Options{
|
||||||
|
Path: targetDir,
|
||||||
|
Name: file.Name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create task for %q failed: %w", file.Name, err)
|
||||||
|
}
|
||||||
|
waiter.Register(taskID)
|
||||||
|
|
||||||
|
summary.Files = append(summary.Files, &downloadedFileResult{
|
||||||
|
Index: idx,
|
||||||
|
Name: file.Name,
|
||||||
|
Path: filepath.Join(targetDir, file.Name),
|
||||||
|
TaskID: taskID,
|
||||||
|
Req: file.Req,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var stopVerbose func()
|
||||||
|
if verbose {
|
||||||
|
stopVerbose = startVerboseTaskListener(d, summary.Files)
|
||||||
|
defer stopVerbose()
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, file := range summary.Files {
|
||||||
|
task, err := waiter.Wait(file.TaskID, 5*time.Minute)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("download %q failed: %w", file.Name, err)
|
||||||
|
}
|
||||||
|
file.Status = task.Status
|
||||||
|
if info, statErr := os.Stat(file.Path); statErr == nil {
|
||||||
|
file.Size = info.Size()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return printJSON(summary, pretty)
|
||||||
|
}
|
||||||
|
|
||||||
|
func runEval(args []string) error {
|
||||||
|
fs := flag.NewFlagSet("eval", flag.ContinueOnError)
|
||||||
|
fs.SetOutput(os.Stderr)
|
||||||
|
var (
|
||||||
|
script string
|
||||||
|
pretty bool
|
||||||
|
)
|
||||||
|
cfg := webViewConfig{}
|
||||||
|
fs.StringVar(&script, "e", "", "Inline JavaScript to execute")
|
||||||
|
fs.StringVar(&script, "eval", "", "Inline JavaScript to execute")
|
||||||
|
fs.StringVar(&cfg.provider, "webview-provider", "", "WebView provider: go|rpc")
|
||||||
|
fs.StringVar(&cfg.network, "webview-network", "", "WebView RPC network: unix|tcp")
|
||||||
|
fs.StringVar(&cfg.address, "webview-address", "", "WebView RPC address")
|
||||||
|
fs.StringVar(&cfg.token, "webview-token", "", "WebView RPC bearer token")
|
||||||
|
fs.BoolVar(&pretty, "pretty", false, "Pretty-print JSON output")
|
||||||
|
|
||||||
|
flagArgs, positionalArgs, err := splitEvalArgs(args)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := fs.Parse(flagArgs); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if fs.NArg() != 0 {
|
||||||
|
return fmt.Errorf("unexpected trailing args: %v", fs.Args())
|
||||||
|
}
|
||||||
|
if script == "" && len(positionalArgs) == 0 {
|
||||||
|
return fmt.Errorf("eval expects inline code via -e/--eval or a script file path")
|
||||||
|
}
|
||||||
|
if script != "" && len(positionalArgs) > 0 {
|
||||||
|
return fmt.Errorf("eval accepts either inline code or a script file path, not both")
|
||||||
|
}
|
||||||
|
if len(positionalArgs) > 1 {
|
||||||
|
return fmt.Errorf("eval expects at most 1 script file path")
|
||||||
|
}
|
||||||
|
|
||||||
|
d, cleanup, err := newExtMockDownloader(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer cleanup()
|
||||||
|
|
||||||
|
runtime, err := d.NewExtensionEngine(newExtMockExtension(), map[string]any{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer runtime.Close()
|
||||||
|
|
||||||
|
var value any
|
||||||
|
if script != "" {
|
||||||
|
value, err = runtime.Eval(script)
|
||||||
|
} else {
|
||||||
|
scriptPath, pathErr := filepath.Abs(positionalArgs[0])
|
||||||
|
if pathErr != nil {
|
||||||
|
return pathErr
|
||||||
|
}
|
||||||
|
value, err = runtime.EvalFile(scriptPath)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return printJSON(value, pretty)
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitResolveArgs(args []string) ([]string, []string, error) {
|
||||||
|
var flagArgs []string
|
||||||
|
var positionalArgs []string
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
arg := args[i]
|
||||||
|
switch {
|
||||||
|
case arg == "-pretty":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case arg == "-webview-provider", arg == "-webview-network", arg == "-webview-address", arg == "-webview-token":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case arg == "-label":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case arg == "-setting":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case len(arg) > len("-label=") && arg[:len("-label=")] == "-label=":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case len(arg) > len("-setting=") && arg[:len("-setting=")] == "-setting=":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case hasFlagValue(arg, "-webview-provider"), hasFlagValue(arg, "-webview-network"),
|
||||||
|
hasFlagValue(arg, "-webview-address"), hasFlagValue(arg, "-webview-token"):
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case len(arg) > 0 && arg[0] == '-':
|
||||||
|
return nil, nil, fmt.Errorf("unknown flag %q", arg)
|
||||||
|
default:
|
||||||
|
positionalArgs = append(positionalArgs, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return flagArgs, positionalArgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitDownloadArgs(args []string) ([]string, []string, error) {
|
||||||
|
var flagArgs []string
|
||||||
|
var positionalArgs []string
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
arg := args[i]
|
||||||
|
switch {
|
||||||
|
case arg == "-pretty", arg == "-verb", arg == "-verbose":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case arg == "-webview-provider", arg == "-webview-network", arg == "-webview-address", arg == "-webview-token":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case arg == "-label":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case arg == "-setting":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case len(arg) > len("-label=") && arg[:len("-label=")] == "-label=":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case len(arg) > len("-setting=") && arg[:len("-setting=")] == "-setting=":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case hasFlagValue(arg, "-webview-provider"), hasFlagValue(arg, "-webview-network"),
|
||||||
|
hasFlagValue(arg, "-webview-address"), hasFlagValue(arg, "-webview-token"):
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case len(arg) > 0 && arg[0] == '-':
|
||||||
|
return nil, nil, fmt.Errorf("unknown flag %q", arg)
|
||||||
|
default:
|
||||||
|
positionalArgs = append(positionalArgs, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return flagArgs, positionalArgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitEvalArgs(args []string) ([]string, []string, error) {
|
||||||
|
var flagArgs []string
|
||||||
|
var positionalArgs []string
|
||||||
|
for i := 0; i < len(args); i++ {
|
||||||
|
arg := args[i]
|
||||||
|
switch {
|
||||||
|
case arg == "-pretty":
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case arg == "-webview-provider", arg == "-webview-network", arg == "-webview-address", arg == "-webview-token":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case arg == "-e", arg == "--eval":
|
||||||
|
if i+1 >= len(args) {
|
||||||
|
return nil, nil, fmt.Errorf("flag %q requires a value", arg)
|
||||||
|
}
|
||||||
|
flagArgs = append(flagArgs, arg, args[i+1])
|
||||||
|
i++
|
||||||
|
case hasFlagValue(arg, "-e"), hasFlagValue(arg, "--eval"),
|
||||||
|
hasFlagValue(arg, "-webview-provider"), hasFlagValue(arg, "-webview-network"),
|
||||||
|
hasFlagValue(arg, "-webview-address"), hasFlagValue(arg, "-webview-token"):
|
||||||
|
flagArgs = append(flagArgs, arg)
|
||||||
|
case len(arg) > 0 && arg[0] == '-':
|
||||||
|
return nil, nil, fmt.Errorf("unknown flag %q", arg)
|
||||||
|
default:
|
||||||
|
positionalArgs = append(positionalArgs, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return flagArgs, positionalArgs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func hasFlagValue(arg string, prefix string) bool {
|
||||||
|
return len(arg) > len(prefix)+1 && arg[:len(prefix)+1] == prefix+"="
|
||||||
|
}
|
||||||
|
|
||||||
|
func toAnyMap(values kvFlag) map[string]any {
|
||||||
|
result := make(map[string]any, len(values))
|
||||||
|
for key, value := range values {
|
||||||
|
result[key] = value
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func newExtMockDownloader(cfg webViewConfig) (*download.Downloader, func(), error) {
|
||||||
|
webViewProvider, err := newExtMockWebViewProvider(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
d := download.NewDownloader(&download.DownloaderConfig{
|
||||||
|
Storage: download.NewMemStorage(),
|
||||||
|
WebViewProvider: webViewProvider,
|
||||||
|
})
|
||||||
|
if err := d.Setup(); err != nil {
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
cleanup := func() {
|
||||||
|
_ = d.Clear()
|
||||||
|
}
|
||||||
|
return d, cleanup, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newExtMockExtension() *download.Extension {
|
||||||
|
return &download.Extension{
|
||||||
|
Name: "extmock",
|
||||||
|
Author: "gopeed",
|
||||||
|
Title: "Gopeed ExtMock Runtime",
|
||||||
|
Version: "0.0.0",
|
||||||
|
DevMode: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newExtMockWebViewProvider(cfg webViewConfig) (enginewebview.Provider, error) {
|
||||||
|
switch cfg.provider {
|
||||||
|
case "", "go":
|
||||||
|
return goprovider.New(), nil
|
||||||
|
case "rpc":
|
||||||
|
rpcCfg, err := resolveRPCConfig(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return rpcprovider.New(rpcCfg), nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported webview provider %q", cfg.provider)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveRPCConfig(cfg webViewConfig) (enginewebview.RPCConfig, error) {
|
||||||
|
network := cfg.network
|
||||||
|
address := cfg.address
|
||||||
|
if network == "" && address == "" {
|
||||||
|
defaultAddress, err := defaultWebViewRPCUnixSocket()
|
||||||
|
if err != nil {
|
||||||
|
return enginewebview.RPCConfig{}, err
|
||||||
|
}
|
||||||
|
network = "unix"
|
||||||
|
address = defaultAddress
|
||||||
|
}
|
||||||
|
if network == "" || address == "" {
|
||||||
|
return enginewebview.RPCConfig{}, fmt.Errorf("webview rpc requires both network and address")
|
||||||
|
}
|
||||||
|
return enginewebview.RPCConfig{
|
||||||
|
Network: network,
|
||||||
|
Address: address,
|
||||||
|
Token: cfg.token,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func defaultWebViewRPCUnixSocket() (string, error) {
|
||||||
|
homeDir, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return filepath.Join(homeDir, "gopeed_webview.sock"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type taskTerminalWaiter struct {
|
||||||
|
downloader *download.Downloader
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTaskTerminalWaiter(d *download.Downloader) *taskTerminalWaiter {
|
||||||
|
return &taskTerminalWaiter{downloader: d}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *taskTerminalWaiter) Register(id string) {
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *taskTerminalWaiter) Wait(id string, timeout time.Duration) (*download.Task, error) {
|
||||||
|
deadline := time.Now().Add(timeout)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
if task, ok := w.currentTerminalTask(id); ok {
|
||||||
|
return task, w.taskError(task)
|
||||||
|
}
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("timeout waiting for task %s", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *taskTerminalWaiter) currentTerminalTask(id string) (*download.Task, bool) {
|
||||||
|
task := w.downloader.GetTask(id)
|
||||||
|
if task == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
if task.Status != base.DownloadStatusDone && task.Status != base.DownloadStatusError {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
return task, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *taskTerminalWaiter) taskError(task *download.Task) error {
|
||||||
|
if task == nil {
|
||||||
|
return fmt.Errorf("task is nil")
|
||||||
|
}
|
||||||
|
if task.Status == base.DownloadStatusError {
|
||||||
|
return fmt.Errorf("task %s finished with status %s", task.ID, task.Status)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func startVerboseTaskListener(d *download.Downloader, files []*downloadedFileResult) func() {
|
||||||
|
tracked := make(map[string]string, len(files))
|
||||||
|
for _, file := range files {
|
||||||
|
tracked[file.TaskID] = file.Name
|
||||||
|
}
|
||||||
|
d.Listener(func(event *download.Event) {
|
||||||
|
if event == nil || event.Task == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name, ok := tracked[event.Task.ID]
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch event.Key {
|
||||||
|
case download.EventKeyStart, download.EventKeyProgress, download.EventKeyDone, download.EventKeyError:
|
||||||
|
printVerboseTaskEvent(event, name)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return func() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
func printVerboseTaskEvent(event *download.Event, name string) {
|
||||||
|
task := event.Task
|
||||||
|
ts := time.Now().Format("15:04:05.000")
|
||||||
|
if task == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
total := int64(0)
|
||||||
|
if task.Meta != nil && task.Meta.Res != nil {
|
||||||
|
total = task.Meta.Res.Size
|
||||||
|
}
|
||||||
|
downloaded := int64(0)
|
||||||
|
speed := int64(0)
|
||||||
|
if task.Progress != nil {
|
||||||
|
downloaded = task.Progress.Downloaded
|
||||||
|
speed = task.Progress.Speed
|
||||||
|
}
|
||||||
|
if event.Key == download.EventKeyError && event.Err != nil {
|
||||||
|
fmt.Fprintf(
|
||||||
|
os.Stderr,
|
||||||
|
"[%s] event=%s task=%s status=%s downloaded=%d total=%d speed=%d name=%q err=%v\n",
|
||||||
|
ts,
|
||||||
|
event.Key,
|
||||||
|
task.ID,
|
||||||
|
task.Status,
|
||||||
|
downloaded,
|
||||||
|
total,
|
||||||
|
speed,
|
||||||
|
name,
|
||||||
|
event.Err,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.Fprintf(
|
||||||
|
os.Stderr,
|
||||||
|
"[%s] event=%s task=%s status=%s downloaded=%d total=%d speed=%d name=%q\n",
|
||||||
|
ts,
|
||||||
|
event.Key,
|
||||||
|
task.ID,
|
||||||
|
task.Status,
|
||||||
|
downloaded,
|
||||||
|
total,
|
||||||
|
speed,
|
||||||
|
name,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printJSON(v any, pretty bool) error {
|
||||||
|
var (
|
||||||
|
data []byte
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if pretty {
|
||||||
|
data, err = json.MarshalIndent(v, "", " ")
|
||||||
|
} else {
|
||||||
|
data, err = json.Marshal(v)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
fmt.Println(string(data))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -2,12 +2,14 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/GopeedLab/gopeed/internal/fetcher"
|
||||||
"github.com/GopeedLab/gopeed/pkg/base"
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
"github.com/GopeedLab/gopeed/pkg/download"
|
"github.com/GopeedLab/gopeed/pkg/download"
|
||||||
"github.com/GopeedLab/gopeed/pkg/protocol/http"
|
"github.com/GopeedLab/gopeed/pkg/protocol/http"
|
||||||
"github.com/GopeedLab/gopeed/pkg/util"
|
"github.com/GopeedLab/gopeed/pkg/util"
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const progressWidth = 20
|
const progressWidth = 20
|
||||||
@@ -47,16 +49,31 @@ func main() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
|
printProgress(emptyTask, "downloading...")
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
lastLineLen = 0
|
lastLineLen = 0
|
||||||
sb = new(strings.Builder)
|
sb = new(strings.Builder)
|
||||||
|
emptyTask = &download.Task{
|
||||||
|
Progress: &download.Progress{},
|
||||||
|
Meta: &fetcher.FetcherMeta{
|
||||||
|
Res: &base.Resource{},
|
||||||
|
},
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
func printProgress(task *download.Task, title string) {
|
func printProgress(task *download.Task, title string) {
|
||||||
rate := float64(task.Progress.Downloaded) / float64(task.Meta.Res.Size)
|
var rate float64
|
||||||
|
if task.Meta.Res == nil {
|
||||||
|
task = emptyTask
|
||||||
|
}
|
||||||
|
if task.Meta.Res.Size <= 0 {
|
||||||
|
rate = 0
|
||||||
|
} else {
|
||||||
|
rate = float64(task.Progress.Downloaded) / float64(task.Meta.Res.Size)
|
||||||
|
}
|
||||||
completeWidth := int(progressWidth * rate)
|
completeWidth := int(progressWidth * rate)
|
||||||
speed := util.ByteFmt(task.Progress.Speed)
|
speed := util.ByteFmt(task.Progress.Speed)
|
||||||
totalSize := util.ByteFmt(task.Meta.Res.Size)
|
totalSize := util.ByteFmt(task.Meta.Res.Size)
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
//go:build !windows
|
||||||
|
// +build !windows
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Dial() (net.Conn, error) {
|
||||||
|
// Get binary path
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return net.Dial("unix", filepath.Join(filepath.Dir(exe), "gopeed_host.sock"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/Microsoft/go-winio"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Dial() (net.Conn, error) {
|
||||||
|
return winio.DialPipe(`\\.\pipe\gopeed_host`, nil)
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/binary"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/browser"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
Method string `json:"method"`
|
||||||
|
Meta map[string]any `json:"meta"`
|
||||||
|
Params json.RawMessage `json:"params"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Response struct {
|
||||||
|
Code int `json:"code"`
|
||||||
|
Data any `json:"data,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func check() (data bool, err error) {
|
||||||
|
conn, err := Dial()
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func wakeup(hidden bool) error {
|
||||||
|
running, _ := check()
|
||||||
|
if running {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
uri := "gopeed:"
|
||||||
|
if hidden {
|
||||||
|
uri = uri + "?hidden=true"
|
||||||
|
}
|
||||||
|
if err := browser.OpenURL(uri); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
if ok, _ := check(); ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("start gopeed failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// postToFlutter sends a POST request to Flutter RPC server
|
||||||
|
func postToFlutter(path string, body []byte, headers map[string]string, timeout time.Duration) (*http.Response, error) {
|
||||||
|
client := &http.Client{
|
||||||
|
Transport: &http.Transport{
|
||||||
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
|
return Dial()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Timeout: timeout,
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest("POST", "http://127.0.0.1"+path, bytes.NewBuffer(body))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
for k, v := range headers {
|
||||||
|
req.Header.Set(k, v)
|
||||||
|
}
|
||||||
|
return client.Do(req)
|
||||||
|
}
|
||||||
|
|
||||||
|
var apiMap = map[string]func(message *Message) (data any, err error){
|
||||||
|
"ping": func(message *Message) (data any, err error) {
|
||||||
|
return check()
|
||||||
|
},
|
||||||
|
"wakeup": func(message *Message) (data any, err error) {
|
||||||
|
silent := false
|
||||||
|
if v, ok := message.Meta["silent"]; ok {
|
||||||
|
silent, _ = v.(bool)
|
||||||
|
}
|
||||||
|
err = wakeup(silent)
|
||||||
|
return
|
||||||
|
},
|
||||||
|
"create": func(message *Message) (data any, err error) {
|
||||||
|
buf, err := message.Params.MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Task creation owns its presentation: silent requests stay in the
|
||||||
|
// background, while non-silent requests open a dedicated create window.
|
||||||
|
// Always bootstrap the main process hidden so it never flashes first.
|
||||||
|
if err := wakeup(true); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
headers := make(map[string]string)
|
||||||
|
if message.Meta != nil {
|
||||||
|
metaJson, _ := json.Marshal(message.Meta)
|
||||||
|
headers["X-Gopeed-Host-Meta"] = string(metaJson)
|
||||||
|
}
|
||||||
|
_, err = postToFlutter("/create", buf, headers, 10*time.Second)
|
||||||
|
return
|
||||||
|
},
|
||||||
|
"forward": func(message *Message) (data any, err error) {
|
||||||
|
buf, err := message.Params.MarshalJSON()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := postToFlutter("/forward", buf, nil, 60*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
respBody, err := io.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var respData map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(respBody, &respData); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return respData, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// go build -ldflags="-s -w" -o ui/flutter/assets/exec/ github.com/GopeedLab/gopeed/cmd/host
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
for {
|
||||||
|
// Read message length (first 4 bytes)
|
||||||
|
var length uint32
|
||||||
|
if err := binary.Read(os.Stdin, binary.NativeEndian, &length); err != nil {
|
||||||
|
if err == io.EOF {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sendError("Failed to read message length: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the message
|
||||||
|
input := make([]byte, length)
|
||||||
|
if _, err := io.ReadFull(os.Stdin, input); err != nil {
|
||||||
|
sendError("Failed to read message: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse message
|
||||||
|
var message Message
|
||||||
|
if err := json.Unmarshal(input, &message); err != nil {
|
||||||
|
sendError("Failed to parse message: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle request
|
||||||
|
var data any
|
||||||
|
var err error
|
||||||
|
if handler, ok := apiMap[message.Method]; ok {
|
||||||
|
data, err = handler(&message)
|
||||||
|
} else {
|
||||||
|
err = errors.New("Unknown method: " + message.Method)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
sendError(err.Error())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
sendResponse(0, data, "")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendResponse(code int, data interface{}, message string) {
|
||||||
|
response := Response{
|
||||||
|
Code: code,
|
||||||
|
Data: data,
|
||||||
|
Message: message,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encode response
|
||||||
|
responseBytes, err := json.Marshal(response)
|
||||||
|
if err != nil {
|
||||||
|
sendError("Failed to encode response: " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write message length
|
||||||
|
binary.Write(os.Stdout, binary.NativeEndian, uint32(len(responseBytes)))
|
||||||
|
// Write message
|
||||||
|
os.Stdout.Write(responseBytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendError(msg string) {
|
||||||
|
sendResponse(1, nil, msg)
|
||||||
|
}
|
||||||
@@ -3,11 +3,14 @@ package cmd
|
|||||||
import (
|
import (
|
||||||
_ "embed"
|
_ "embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest"
|
"github.com/GopeedLab/gopeed/pkg/rest"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed banner.txt
|
//go:embed banner.txt
|
||||||
@@ -24,17 +27,46 @@ func Start(cfg *model.StartConfig) {
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
if downloadCfg.FirstLoad {
|
if downloadCfg.FirstLoad {
|
||||||
// Set default download dir to user download dir
|
// Set default download config
|
||||||
userDir, err := os.UserHomeDir()
|
if cfg.DownloadConfig != nil {
|
||||||
if err == nil {
|
cfg.DownloadConfig.Merge(downloadCfg)
|
||||||
downloadDir := filepath.Join(userDir, "Downloads")
|
// TODO Use PatchConfig
|
||||||
downloadCfg.DownloadDir = downloadDir
|
rest.Downloader.PutConfig(cfg.DownloadConfig)
|
||||||
rest.Downloader.PutConfig(downloadCfg)
|
downloadCfg = cfg.DownloadConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
downloadDir := downloadCfg.DownloadDir
|
||||||
|
// Set default download dir, in docker, it will be ${exe}/Downloads, else it will be ${user}/Downloads
|
||||||
|
if downloadDir == "" {
|
||||||
|
if base.InDocker == "true" {
|
||||||
|
downloadDir = filepath.Join(filepath.Dir(cfg.StorageDir), "Downloads")
|
||||||
|
} else {
|
||||||
|
userDir, err := os.UserHomeDir()
|
||||||
|
if err == nil {
|
||||||
|
downloadDir = filepath.Join(userDir, "Downloads")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if downloadDir != "" {
|
||||||
|
downloadCfg.DownloadDir = downloadDir
|
||||||
|
rest.Downloader.PutConfig(downloadCfg)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
watchExit()
|
||||||
|
|
||||||
fmt.Printf("Server start success on http://%s\n", listener.Addr().String())
|
fmt.Printf("Server start success on http://%s\n", listener.Addr().String())
|
||||||
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
if err := srv.Serve(listener); err != nil && err != http.ErrServerClosed {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func watchExit() {
|
||||||
|
sigs := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
|
||||||
|
go func() {
|
||||||
|
sig := <-sigs
|
||||||
|
fmt.Printf("Server is shutting down due to signal: %s\n", sig)
|
||||||
|
rest.Downloader.Close()
|
||||||
|
os.Exit(0)
|
||||||
|
}()
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/browser"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// go build -ldflags="-s -w" -o ui/flutter/assets/exec/ github.com/GopeedLab/gopeed/cmd/updater
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
pid := flag.Int("pid", 0, "PID of the process to update")
|
||||||
|
updateChannel := flag.String("channel", "", "Update channel")
|
||||||
|
packagePath := flag.String("asset", "", "Path to the package asset")
|
||||||
|
exeDir := flag.String("exeDir", "", "Directory of the entry executable")
|
||||||
|
logPath := flag.String("log", "", "Log file path")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if *pid == 0 {
|
||||||
|
log.Println("Invalid PID")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
if *updateChannel == "" {
|
||||||
|
log.Println("Invalid update channel")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if *logPath != "" {
|
||||||
|
logFile, err := os.OpenFile(*logPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
|
||||||
|
if err == nil {
|
||||||
|
defer logFile.Close()
|
||||||
|
log.SetOutput(logFile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
restart bool
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if restart, err = update(*pid, *updateChannel, *packagePath, *exeDir); err != nil {
|
||||||
|
log.Printf("Update failed: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restart the application
|
||||||
|
if restart {
|
||||||
|
browser.OpenURL("gopeed:///")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete package asset
|
||||||
|
if *packagePath != "" {
|
||||||
|
os.Remove(*packagePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func update(pid int, updateChannel, packagePath, exeDir string) (restart bool, err error) {
|
||||||
|
killSignalChan := make(chan any, 1)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
<-killSignalChan
|
||||||
|
|
||||||
|
if err = killProcess(pid); err != nil {
|
||||||
|
log.Printf("Failed to kill process: %v\n", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = waitForProcessExit(pid); err != nil {
|
||||||
|
log.Printf("Failed to wait for process exit: %v\n", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
log.Printf("Updating process updateChannel=%s packagePath=%s exeDir=%s\n", updateChannel, packagePath, exeDir)
|
||||||
|
if restart, err = install(killSignalChan, updateChannel, packagePath, exeDir); err != nil {
|
||||||
|
return false, errors.Wrap(err, "failed to install package")
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitForProcessExit(pid int) error {
|
||||||
|
deadline := time.Now().Add(10 * time.Second)
|
||||||
|
for time.Now().Before(deadline) {
|
||||||
|
process, err := os.FindProcess(pid)
|
||||||
|
if err != nil {
|
||||||
|
// On some systems, error is returned if process doesn't exist
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send null signal to test if process exists
|
||||||
|
err = process.Signal(syscall.Signal(0))
|
||||||
|
if err != nil {
|
||||||
|
// If error occurs, the process no longer exists
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
time.Sleep(100 * time.Millisecond)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("process %d still running after timeout", pid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func killProcess(pid int) error {
|
||||||
|
process, err := os.FindProcess(pid)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return process.Kill()
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
//go:build darwin
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func install(killSignalChan chan<- any, updateChannel, packagePath, destDir string) (bool, error) {
|
||||||
|
return true, installByDmg(killSignalChan, packagePath, destDir)
|
||||||
|
}
|
||||||
|
|
||||||
|
// installByDmg handles macOS dmg package installation
|
||||||
|
func installByDmg(killSignalChan chan<- any, packagePath, destDir string) error {
|
||||||
|
// /Applications/Gopeed.app/Contents/MacOS -> /Applications
|
||||||
|
appPath := getParentDir(getParentDir(getParentDir(destDir)))
|
||||||
|
output, err := exec.Command("hdiutil", "attach", packagePath, "-nobrowse").Output()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
mountPoint := ""
|
||||||
|
for _, line := range strings.Split(string(output), "\n") {
|
||||||
|
if strings.Contains(line, "/Volumes/") {
|
||||||
|
// Find the /Volumes/ path in the line
|
||||||
|
// hdiutil output format: /dev/disk4s1 Apple_HFS /Volumes/Gopeed
|
||||||
|
// or with sequence number: /dev/disk4s1 Apple_HFS /Volumes/Gopeed 1
|
||||||
|
idx := strings.Index(line, "/Volumes/")
|
||||||
|
if idx != -1 {
|
||||||
|
// Extract everything from /Volumes/ onwards and trim whitespace
|
||||||
|
mountPoint = strings.TrimSpace(line[idx:])
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if mountPoint == "" {
|
||||||
|
return fmt.Errorf("failed to get mount point from hdiutil output: %s", string(output))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Detach the mounted DMG
|
||||||
|
defer exec.Command("hdiutil", "detach", mountPoint, "-quiet").Run()
|
||||||
|
|
||||||
|
matches, err := filepath.Glob(filepath.Join(mountPoint, "*.app"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(matches) == 0 {
|
||||||
|
return fmt.Errorf("no .app found in dmg, mountPoint: %s", mountPoint)
|
||||||
|
}
|
||||||
|
|
||||||
|
killSignalChan <- nil
|
||||||
|
|
||||||
|
// Copy the new app to the destination
|
||||||
|
// cp -Rf /Volumes/GoPeed/GoPeed.app /Applications
|
||||||
|
if err := exec.Command("cp", "-Rf", matches[0], appPath).Run(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get parent directory safely, handling trailing separators
|
||||||
|
func getParentDir(path string) string {
|
||||||
|
// Remove trailing separators if they exist
|
||||||
|
path = strings.TrimRight(path, string(filepath.Separator))
|
||||||
|
// Now get the parent directory
|
||||||
|
return filepath.Dir(path)
|
||||||
|
}
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
//go:build linux
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
)
|
||||||
|
|
||||||
|
func install(killSignalChan chan<- any, updateChannel, packagePath, destDir string) (bool, error) {
|
||||||
|
killSignalChan <- nil
|
||||||
|
switch updateChannel {
|
||||||
|
case "linuxDeb":
|
||||||
|
return true, installByDeb(packagePath)
|
||||||
|
case "linuxFlathub":
|
||||||
|
return true, installByFlathub()
|
||||||
|
case "linuxSnap":
|
||||||
|
return true, installBySnap()
|
||||||
|
default:
|
||||||
|
return false, fmt.Errorf("unsupported update channel for Linux: %s", updateChannel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// executeInTerminal tries to execute a command in one of several common terminal emulators
|
||||||
|
func executeInTerminal(command string) error {
|
||||||
|
terminals := []string{
|
||||||
|
"gnome-terminal", // GNOME
|
||||||
|
"konsole", // KDE
|
||||||
|
"xfce4-terminal", // XFCE
|
||||||
|
"xterm", // X11
|
||||||
|
}
|
||||||
|
|
||||||
|
command = fmt.Sprintf(`echo "Starting update..." && echo "[CMD] %s" && %s`, command, command)
|
||||||
|
|
||||||
|
for _, term := range terminals {
|
||||||
|
if _, err := exec.LookPath(term); err == nil {
|
||||||
|
var cmd *exec.Cmd
|
||||||
|
switch term {
|
||||||
|
case "gnome-terminal", "xfce4-terminal":
|
||||||
|
cmd = exec.Command(term, "--", "bash", "-c", command)
|
||||||
|
case "konsole":
|
||||||
|
cmd = exec.Command(term, "-e", "bash", "-c", command)
|
||||||
|
case "xterm":
|
||||||
|
cmd = exec.Command(term, "-e", command)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := cmd.Start(); err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Errorf("no suitable terminal emulator found. Please install gnome-terminal, konsole, xfce4-terminal or xterm")
|
||||||
|
}
|
||||||
|
|
||||||
|
// installByDeb installs the .deb package
|
||||||
|
func installByDeb(packagePath string) error {
|
||||||
|
command := fmt.Sprintf(`sudo dpkg -i "%s"`, packagePath)
|
||||||
|
return executeInTerminal(command)
|
||||||
|
}
|
||||||
|
|
||||||
|
// installByFlathub updates the application via Flathub
|
||||||
|
func installByFlathub() error {
|
||||||
|
command := "flatpak update com.gopeed.Gopeed -y"
|
||||||
|
return executeInTerminal(command)
|
||||||
|
}
|
||||||
|
|
||||||
|
// installBySnap updates the application via Snap
|
||||||
|
func installBySnap() error {
|
||||||
|
command := "sudo snap refresh gopeed"
|
||||||
|
return executeInTerminal(command)
|
||||||
|
}
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"os/exec"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func install(killSignalChan chan<- any, updateChannel, packagePath, destDir string) (bool, error) {
|
||||||
|
switch updateChannel {
|
||||||
|
case "windowsInstaller":
|
||||||
|
return false, installByInstaller(killSignalChan, packagePath, destDir)
|
||||||
|
default:
|
||||||
|
return true, installByPortable(killSignalChan, packagePath, destDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// installByInstaller extracts the installer from the zip file and runs it
|
||||||
|
func installByInstaller(killSignalChan chan<- any, packagePath, destDir string) error {
|
||||||
|
// Create a temp directory for extraction
|
||||||
|
tempDir, err := os.MkdirTemp("", "gopeed_update")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(tempDir)
|
||||||
|
|
||||||
|
// Extract the zip file
|
||||||
|
reader, err := zip.OpenReader(packagePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
|
||||||
|
// Find the installer file
|
||||||
|
var installerPath string
|
||||||
|
for _, file := range reader.File {
|
||||||
|
if file.FileInfo().IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract file
|
||||||
|
path := filepath.Join(tempDir, file.Name)
|
||||||
|
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dstFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
srcFile, err := file.Open()
|
||||||
|
if err != nil {
|
||||||
|
dstFile.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.Copy(dstFile, srcFile)
|
||||||
|
srcFile.Close()
|
||||||
|
dstFile.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If this is likely an installer (.exe, .msi), save its path
|
||||||
|
ext := strings.ToLower(filepath.Ext(file.Name))
|
||||||
|
if ext == ".exe" || ext == ".msi" {
|
||||||
|
installerPath = path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if installerPath == "" {
|
||||||
|
return fmt.Errorf("no installer found in the update package")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run the installer
|
||||||
|
cmd := exec.Command(installerPath)
|
||||||
|
if err := cmd.Start(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
killSignalChan <- nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// installByPortable extracts the portable version to the destination directory
|
||||||
|
func installByPortable(killSignalChan chan<- any, packagePath, destDir string) error {
|
||||||
|
killSignalChan <- nil
|
||||||
|
|
||||||
|
reader, err := zip.OpenReader(packagePath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
|
||||||
|
for _, file := range reader.File {
|
||||||
|
path := filepath.Join(destDir, file.Name)
|
||||||
|
|
||||||
|
if file.FileInfo().IsDir() {
|
||||||
|
os.MkdirAll(path, file.Mode())
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
dstFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
srcFile, err := file.Open()
|
||||||
|
if err != nil {
|
||||||
|
dstFile.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = io.Copy(dstFile, srcFile)
|
||||||
|
srcFile.Close()
|
||||||
|
dstFile.Close()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -3,75 +3,212 @@ package main
|
|||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"reflect"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
)
|
)
|
||||||
|
|
||||||
type args struct {
|
type args struct {
|
||||||
Address *string `json:"address"`
|
Address *string `json:"address"`
|
||||||
Port *int `json:"port"`
|
Port *int `json:"port"`
|
||||||
Username *string `json:"username"`
|
Username *string `json:"username"`
|
||||||
Password *string `json:"password"`
|
Password *string `json:"password"`
|
||||||
ApiToken *string `json:"apiToken"`
|
ApiToken *string `json:"apiToken"`
|
||||||
|
MCPEnable bool `json:"mcpEnable"`
|
||||||
|
StorageDir *string `json:"storageDir"`
|
||||||
|
WhiteDownloadDirs []string `json:"whiteDownloadDirs"`
|
||||||
|
// DownloadConfig when the first time to start the server, it will be configured as initial value
|
||||||
|
DownloadConfig *base.DownloaderStoreConfig `json:"downloadConfig"`
|
||||||
|
|
||||||
configPath *string
|
configPath *string
|
||||||
}
|
}
|
||||||
|
|
||||||
func parse() *args {
|
func parse() *args {
|
||||||
var cliArgs args
|
cfg := &args{}
|
||||||
cliArgs.Address = flag.String("A", "0.0.0.0", "Bind Address")
|
|
||||||
cliArgs.Port = flag.Int("P", 9999, "Bind Port")
|
cliConfig := loadCliArgs()
|
||||||
cliArgs.Username = flag.String("u", "gopeed", "HTTP Basic Auth Username")
|
loadConfigFile(cfg, *cliConfig.configPath)
|
||||||
cliArgs.Password = flag.String("p", "", "HTTP Basic Auth Password")
|
loadEnvVars(cfg)
|
||||||
cliArgs.ApiToken = flag.String("T", "", "API token, that can only be used when basic authentication is enabled.")
|
// override with non-default command line arguments
|
||||||
cliArgs.configPath = flag.String("c", "./config.json", "Config file path")
|
overrideWithCliArgs(cfg, cliConfig)
|
||||||
|
// set default values
|
||||||
|
setDefaults(cfg, cliConfig)
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadCliArgs parses command line arguments and returns initial config
|
||||||
|
func loadCliArgs() *args {
|
||||||
|
cfg := &args{}
|
||||||
|
cfg.Address = flag.String("A", "0.0.0.0", "Bind Address")
|
||||||
|
flag.StringVar(cfg.Address, "address", "0.0.0.0", "Bind Address")
|
||||||
|
cfg.Port = flag.Int("P", 9999, "Bind Port")
|
||||||
|
flag.IntVar(cfg.Port, "port", 9999, "Bind Port")
|
||||||
|
cfg.Username = flag.String("u", "gopeed", "Web Authentication Username")
|
||||||
|
flag.StringVar(cfg.Username, "username", "gopeed", "Web Authentication Username")
|
||||||
|
cfg.Password = flag.String("p", "", "Web Authentication Password, if no password is set, web authentication will not be enabled")
|
||||||
|
flag.StringVar(cfg.Password, "password", "", "Web Authentication Password, if no password is set, web authentication will not be enabled")
|
||||||
|
cfg.ApiToken = flag.String("T", "", "API token, it must be configured when using HTTP API in the case of enabling web authentication")
|
||||||
|
flag.StringVar(cfg.ApiToken, "api-token", "", "API token, it must be configured when using HTTP API in the case of enabling web authentication")
|
||||||
|
flag.BoolVar(&cfg.MCPEnable, "mcp-enable", false, "Enable MCP endpoint")
|
||||||
|
cfg.StorageDir = flag.String("d", "", "Storage directory")
|
||||||
|
flag.StringVar(cfg.StorageDir, "storage-dir", "", "Storage directory")
|
||||||
|
whiteDownloadDirs := flag.String("white-download-dirs", "", "White download directories, comma-separated")
|
||||||
|
cfg.configPath = flag.String("c", "./config.json", "Config file path")
|
||||||
|
flag.StringVar(cfg.configPath, "config", "./config.json", "Config file path")
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
fmt.Println("parse")
|
// Parse white download directories from comma-separated string
|
||||||
|
if whiteDownloadDirs != nil && *whiteDownloadDirs != "" {
|
||||||
|
dirs := strings.Split(*whiteDownloadDirs, ",")
|
||||||
|
for i := range dirs {
|
||||||
|
dirs[i] = strings.TrimSpace(dirs[i])
|
||||||
|
}
|
||||||
|
cfg.WhiteDownloadDirs = dirs
|
||||||
|
}
|
||||||
|
|
||||||
// args priority: config file > cli args
|
return cfg
|
||||||
cfgArgs := loadConfig(*cliArgs.configPath)
|
|
||||||
if cfgArgs.Address == nil {
|
|
||||||
cfgArgs.Address = cliArgs.Address
|
|
||||||
}
|
|
||||||
if cfgArgs.Port == nil {
|
|
||||||
cfgArgs.Port = cliArgs.Port
|
|
||||||
}
|
|
||||||
if cfgArgs.Username == nil {
|
|
||||||
cfgArgs.Username = cliArgs.Username
|
|
||||||
}
|
|
||||||
if cfgArgs.Password == nil {
|
|
||||||
cfgArgs.Password = cliArgs.Password
|
|
||||||
}
|
|
||||||
if cfgArgs.ApiToken == nil {
|
|
||||||
cfgArgs.ApiToken = cliArgs.ApiToken
|
|
||||||
}
|
|
||||||
return cfgArgs
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadConfig(path string) *args {
|
// overrideWithCliArgs overrides config with non-empty command line arguments
|
||||||
var args args
|
func overrideWithCliArgs(cfg *args, cliConfig *args) {
|
||||||
|
flag.Visit(func(f *flag.Flag) {
|
||||||
if !filepath.IsAbs(path) {
|
switch f.Name {
|
||||||
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
|
case "A", "address":
|
||||||
if err != nil {
|
cfg.Address = cliConfig.Address
|
||||||
return &args
|
case "P", "port":
|
||||||
|
cfg.Port = cliConfig.Port
|
||||||
|
case "u", "username":
|
||||||
|
cfg.Username = cliConfig.Username
|
||||||
|
case "p", "password":
|
||||||
|
cfg.Password = cliConfig.Password
|
||||||
|
case "T", "api-token":
|
||||||
|
cfg.ApiToken = cliConfig.ApiToken
|
||||||
|
case "mcp-enable":
|
||||||
|
cfg.MCPEnable = cliConfig.MCPEnable
|
||||||
|
case "d", "storage-dir":
|
||||||
|
cfg.StorageDir = cliConfig.StorageDir
|
||||||
|
case "white-download-dirs":
|
||||||
|
cfg.WhiteDownloadDirs = cliConfig.WhiteDownloadDirs
|
||||||
|
case "c", "config":
|
||||||
|
cfg.configPath = cliConfig.configPath
|
||||||
}
|
}
|
||||||
path = filepath.Join(dir, path)
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// setDefaults sets default values for any unset configuration fields
|
||||||
|
func setDefaults(cfg *args, cliConfig *args) {
|
||||||
|
if cfg.Address == nil {
|
||||||
|
cfg.Address = cliConfig.Address
|
||||||
}
|
}
|
||||||
file, err := os.ReadFile(path)
|
if cfg.Port == nil {
|
||||||
|
cfg.Port = cliConfig.Port
|
||||||
|
}
|
||||||
|
if cfg.Username == nil {
|
||||||
|
cfg.Username = cliConfig.Username
|
||||||
|
}
|
||||||
|
if cfg.Password == nil {
|
||||||
|
cfg.Password = cliConfig.Password
|
||||||
|
}
|
||||||
|
if cfg.ApiToken == nil {
|
||||||
|
cfg.ApiToken = cliConfig.ApiToken
|
||||||
|
}
|
||||||
|
if cfg.StorageDir == nil {
|
||||||
|
cfg.StorageDir = cliConfig.StorageDir
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadConfigFile loads configuration from file
|
||||||
|
func loadConfigFile(cfg *args, configPath string) {
|
||||||
|
if !filepath.IsAbs(configPath) {
|
||||||
|
dir, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
configPath = filepath.Join(dir, configPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.ReadFile(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
return &args
|
return
|
||||||
}
|
}
|
||||||
fmt.Println("config file read failed, reason:" + err.Error())
|
return
|
||||||
return &args
|
|
||||||
}
|
}
|
||||||
if err = json.Unmarshal(file, &args); err != nil {
|
|
||||||
fmt.Println("config file parse failed, reason:" + err.Error())
|
if err = json.Unmarshal(file, cfg); err != nil {
|
||||||
return &args
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadEnvVars loads configuration from environment variables with prefix GOPEED_
|
||||||
|
func loadEnvVars(cfg *args) {
|
||||||
|
v := reflect.ValueOf(cfg).Elem()
|
||||||
|
t := reflect.TypeOf(cfg).Elem()
|
||||||
|
|
||||||
|
for i := 0; i < v.NumField(); i++ {
|
||||||
|
field := v.Field(i)
|
||||||
|
fieldType := t.Field(i)
|
||||||
|
|
||||||
|
// Get json tag as environment variable suffix
|
||||||
|
jsonTag := fieldType.Tag.Get("json")
|
||||||
|
if jsonTag == "" || jsonTag == "-" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove options like omitempty
|
||||||
|
if commaIdx := strings.Index(jsonTag, ","); commaIdx != -1 {
|
||||||
|
jsonTag = jsonTag[:commaIdx]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to uppercase and add GOPEED_ prefix
|
||||||
|
envKey := "GOPEED_" + strings.ToUpper(jsonTag)
|
||||||
|
envValue := os.Getenv(envKey)
|
||||||
|
|
||||||
|
if envValue == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set value based on field type
|
||||||
|
if field.Kind() == reflect.Ptr {
|
||||||
|
if field.IsNil() {
|
||||||
|
// Create new pointer instance
|
||||||
|
newVal := reflect.New(field.Type().Elem())
|
||||||
|
field.Set(newVal)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch field.Type().Elem().Kind() {
|
||||||
|
case reflect.String:
|
||||||
|
field.Elem().SetString(envValue)
|
||||||
|
case reflect.Int:
|
||||||
|
if intVal, err := strconv.Atoi(envValue); err == nil {
|
||||||
|
field.Elem().SetInt(int64(intVal))
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// For complex types like DownloadConfig, try JSON unmarshaling
|
||||||
|
if field.Type().Elem() == reflect.TypeOf(base.DownloaderStoreConfig{}) {
|
||||||
|
var config base.DownloaderStoreConfig
|
||||||
|
if err := json.Unmarshal([]byte(envValue), &config); err == nil {
|
||||||
|
field.Set(reflect.ValueOf(&config))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if field.Kind() == reflect.Slice {
|
||||||
|
// Handle non-pointer slice types (like []string for WhiteDownloadDirs)
|
||||||
|
if field.Type().Elem().Kind() == reflect.String {
|
||||||
|
dirs := strings.Split(envValue, ",")
|
||||||
|
for i := range dirs {
|
||||||
|
dirs[i] = strings.TrimSpace(dirs[i])
|
||||||
|
}
|
||||||
|
field.Set(reflect.ValueOf(dirs))
|
||||||
|
}
|
||||||
|
} else if field.Kind() == reflect.Bool {
|
||||||
|
if boolVal, err := strconv.ParseBool(envValue); err == nil {
|
||||||
|
field.SetBool(boolVal)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
fmt.Printf("config file loaded: %s\n", path)
|
|
||||||
return &args
|
|
||||||
}
|
}
|
||||||
@@ -6,9 +6,12 @@ package main
|
|||||||
import (
|
import (
|
||||||
"embed"
|
"embed"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/GopeedLab/gopeed/cmd"
|
"github.com/GopeedLab/gopeed/cmd"
|
||||||
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
"github.com/GopeedLab/gopeed/pkg/rest/model"
|
||||||
"io/fs"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed dist/*
|
//go:embed dist/*
|
||||||
@@ -21,22 +24,38 @@ func main() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
args := parse()
|
args := parse()
|
||||||
var webBasicAuth *model.WebBasicAuth
|
var webAuth *model.WebAuth
|
||||||
if isNotBlank(args.Username) && isNotBlank(args.Password) {
|
if isNotBlank(args.Username) && isNotBlank(args.Password) {
|
||||||
webBasicAuth = &model.WebBasicAuth{
|
webAuth = &model.WebAuth{
|
||||||
Username: *args.Username,
|
Username: *args.Username,
|
||||||
Password: *args.Password,
|
Password: *args.Password,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var storageDir string
|
||||||
|
if args.StorageDir != nil && *args.StorageDir != "" {
|
||||||
|
storageDir = *args.StorageDir
|
||||||
|
} else {
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
storageDir = filepath.Join(filepath.Dir(exe), "storage")
|
||||||
|
}
|
||||||
|
|
||||||
cfg := &model.StartConfig{
|
cfg := &model.StartConfig{
|
||||||
Network: "tcp",
|
Network: "tcp",
|
||||||
Address: fmt.Sprintf("%s:%d", *args.Address, *args.Port),
|
Address: fmt.Sprintf("%s:%d", *args.Address, *args.Port),
|
||||||
Storage: model.StorageBolt,
|
Storage: model.StorageBolt,
|
||||||
ApiToken: *args.ApiToken,
|
StorageDir: storageDir,
|
||||||
WebEnable: true,
|
WhiteDownloadDirs: args.WhiteDownloadDirs,
|
||||||
WebFS: sub,
|
ApiToken: *args.ApiToken,
|
||||||
WebBasicAuth: webBasicAuth,
|
MCPEnable: args.MCPEnable,
|
||||||
|
DownloadConfig: args.DownloadConfig,
|
||||||
|
ProductionMode: true,
|
||||||
|
WebEnable: true,
|
||||||
|
WebFS: sub,
|
||||||
|
WebAuth: webAuth,
|
||||||
}
|
}
|
||||||
cmd.Start(cfg)
|
cmd.Start(cfg)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# 文件分类图标源物料
|
||||||
|
|
||||||
|
此目录是 Gopeed 文件分类图标的唯一源物料目录,位于 Flutter 工程之外,不得加入 `ui/flutter/pubspec.yaml` 的 `assets` 配置。
|
||||||
|
|
||||||
|
## 维护限制
|
||||||
|
|
||||||
|
- 不要绕过 `$gopeed-file-category-icons` 技能直接修改、移动或批量替换这里的 SVG 与 manifest。
|
||||||
|
- 需要调整图标时,必须配套使用该技能的安全区、码位兼容、字体生成和多尺寸预览流程。
|
||||||
|
- 不要直接编辑生成的 `GopeedIcons.ttf` 或 `gopeed_icons.dart`。
|
||||||
|
- 不要复用或重排 manifest 中已有的 codepoint。
|
||||||
|
|
||||||
|
## 目录内容
|
||||||
|
|
||||||
|
- `svg/`:24×24 的可编辑 SVG 源文件。
|
||||||
|
- `manifest.json`:图标名称、SVG、稳定码位与产物路径的唯一映射。
|
||||||
|
- `preview/`:生成的 16/20/24/32px 明暗预览,用于整套视觉审查。
|
||||||
|
|
||||||
|
## 生成产物
|
||||||
|
|
||||||
|
- Flutter 字体:`ui/flutter/assets/fonts/GopeedIcons.ttf`
|
||||||
|
- Flutter 常量:`ui/flutter/lib/core/icons/gopeed_icons.dart`
|
||||||
|
|
||||||
|
所有修改都应遵循:
|
||||||
|
|
||||||
|
```text
|
||||||
|
使用 $gopeed-file-category-icons 修改 SVG/manifest
|
||||||
|
→ 重新生成完整 TTF 和 Dart 常量
|
||||||
|
→ 检查多尺寸明暗预览
|
||||||
|
→ 运行 Flutter 静态分析与测试
|
||||||
|
```
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
{
|
||||||
|
"fontFamily": "GopeedIcons",
|
||||||
|
"fontOutput": "../../ui/flutter/assets/fonts/GopeedIcons.ttf",
|
||||||
|
"dartOutput": "../../ui/flutter/lib/core/icons/gopeed_icons.dart",
|
||||||
|
"previewOutput": "preview/gopeed_icons_preview.png",
|
||||||
|
"dartClass": "GopeedIcons",
|
||||||
|
"codepointStart": "0xE900",
|
||||||
|
"unitsPerEm": 1024,
|
||||||
|
"ascent": 896,
|
||||||
|
"descent": -128,
|
||||||
|
"padding": 0,
|
||||||
|
"version": "1.3.2",
|
||||||
|
"icons": [
|
||||||
|
{
|
||||||
|
"name": "protocol_bt",
|
||||||
|
"source": "svg/protocol-bt.svg",
|
||||||
|
"codepoint": "0xE900"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "protocol_ed2k",
|
||||||
|
"source": "svg/protocol-ed2k.svg",
|
||||||
|
"codepoint": "0xE901"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "folder",
|
||||||
|
"source": "svg/folder.svg",
|
||||||
|
"codepoint": "0xE902"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "folder_bt",
|
||||||
|
"source": "svg/folder-bt.svg",
|
||||||
|
"codepoint": "0xE903"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file",
|
||||||
|
"source": "svg/file.svg",
|
||||||
|
"codepoint": "0xE904"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_installer",
|
||||||
|
"source": "svg/file-installer.svg",
|
||||||
|
"codepoint": "0xE905"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_android",
|
||||||
|
"source": "svg/file-android.svg",
|
||||||
|
"codepoint": "0xE906"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_ios",
|
||||||
|
"source": "svg/file-ios.svg",
|
||||||
|
"codepoint": "0xE907"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_disk_image",
|
||||||
|
"source": "svg/file-disk-image.svg",
|
||||||
|
"codepoint": "0xE908"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_web",
|
||||||
|
"source": "svg/file-web.svg",
|
||||||
|
"codepoint": "0xE909"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_text",
|
||||||
|
"source": "svg/file-text.svg",
|
||||||
|
"codepoint": "0xE90A"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_pdf",
|
||||||
|
"source": "svg/file-pdf.svg",
|
||||||
|
"codepoint": "0xE90B"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_document",
|
||||||
|
"source": "svg/file-document.svg",
|
||||||
|
"codepoint": "0xE90C"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_spreadsheet",
|
||||||
|
"source": "svg/file-spreadsheet.svg",
|
||||||
|
"codepoint": "0xE90D"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_presentation",
|
||||||
|
"source": "svg/file-presentation.svg",
|
||||||
|
"codepoint": "0xE90E"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_archive",
|
||||||
|
"source": "svg/file-archive.svg",
|
||||||
|
"codepoint": "0xE90F"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_image",
|
||||||
|
"source": "svg/file-image.svg",
|
||||||
|
"codepoint": "0xE910"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_audio",
|
||||||
|
"source": "svg/file-audio.svg",
|
||||||
|
"codepoint": "0xE911"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_video",
|
||||||
|
"source": "svg/file-video.svg",
|
||||||
|
"codepoint": "0xE912"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_code",
|
||||||
|
"source": "svg/file-code.svg",
|
||||||
|
"codepoint": "0xE913"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_ebook",
|
||||||
|
"source": "svg/file-ebook.svg",
|
||||||
|
"codepoint": "0xE914"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_font",
|
||||||
|
"source": "svg/file-font.svg",
|
||||||
|
"codepoint": "0xE915"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "file_database",
|
||||||
|
"source": "svg/file-database.svg",
|
||||||
|
"codepoint": "0xE916"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 94 KiB |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M8.15 10.2L9.25 9.5L10.15 10.9C10.72 10.65 11.35 10.5 12 10.5C12.65 10.5 13.28 10.65 13.85 10.9L14.75 9.5L15.85 10.2L14.95 11.6C15.62 12.22 16 13.05 16 14V18.5H8V14C8 13.05 8.38 12.22 9.05 11.6L8.15 10.2ZM9.5 14V17H14.5V14C14.5 12.9 13.38 12 12 12C10.62 12 9.5 12.9 9.5 14ZM9.75 13.75H11.25V15.25H9.75V13.75ZM12.75 13.75H14.25V15.25H12.75V13.75Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 526 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M10.25 9.5H12V11H10.25V9.5ZM12 11H13.75V12.5H12V11ZM10.25 12.5H12V14H10.25V12.5ZM12 14H13.75V15.5H12V14ZM10 15.75H14V17.25H13.5L13 18.75H11L10.5 17.25H10V15.75ZM11.5 16.75L11.85 17.75H12.15L12.5 16.75H11.5Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 387 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M11 9.75H16.5V11.5H12.75V16C12.75 17.52 11.52 18.75 10 18.75C8.48 18.75 7.25 17.75 7.25 16.5C7.25 15.25 8.48 14.25 10 14.25C10.35 14.25 10.69 14.3 11 14.42V9.75Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 342 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M10.25 10L11.5 11.25L9 13.75L11.5 16.25L10.25 17.5L6.5 13.75L10.25 10ZM13.75 10L17.5 13.75L13.75 17.5L12.5 16.25L15 13.75L12.5 11.25L13.75 10Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 323 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M7.75 11C7.75 10.17 9.65 9.5 12 9.5C14.35 9.5 16.25 10.17 16.25 11C16.25 11.83 14.35 12.5 12 12.5C9.65 12.5 7.75 11.83 7.75 11ZM7.75 13C8.82 13.65 10.2 13.95 12 13.95C13.8 13.95 15.18 13.65 16.25 13V15C16.25 15.83 14.35 16.5 12 16.5C9.65 16.5 7.75 15.83 7.75 15V13ZM7.75 16.75C8.82 17.4 10.2 17.7 12 17.7C13.8 17.7 15.18 17.4 16.25 16.75V17.25C16.25 18.08 14.35 18.75 12 18.75C9.65 18.75 7.75 18.08 7.75 17.25V16.75Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 597 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M12 9.5C14.49 9.5 16.5 11.51 16.5 14C16.5 16.49 14.49 18.5 12 18.5C9.51 18.5 7.5 16.49 7.5 14C7.5 11.51 9.51 9.5 12 9.5ZM12 12.75C11.31 12.75 10.75 13.31 10.75 14C10.75 14.69 11.31 15.25 12 15.25C12.69 15.25 13.25 14.69 13.25 14C13.25 13.31 12.69 12.75 12 12.75ZM13.2 12.2L13.5 13.5L15.85 12.5L15.2 11.3L13.2 12.2Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 495 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M7.5 10H13.5V11.5H7.5V10ZM7.5 12.75H16.5V14H7.5V12.75ZM7.5 15.13H15V16.38H7.5V15.13ZM7.5 17.5H12V18.75H7.5V17.5Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 293 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M6.75 9.75L11.25 10.75V19L6.75 18V9.75ZM8.25 11.65V16.8L9.75 17.15V11.98L8.25 11.65ZM12.75 10.75L17.25 9.75V18L12.75 19V10.75ZM14.25 11.98V17.15L15.75 16.8V11.65L14.25 11.98Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 355 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M10.5 9.75H13.5L16.75 18.5H14.65L14.05 16.75H9.95L9.35 18.5H7.25L10.5 9.75ZM12 11.25L10.55 15.25H13.45L12 11.25Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 293 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M14.75 9.75C15.58 9.75 16.25 10.42 16.25 11.25C16.25 12.08 15.58 12.75 14.75 12.75C13.92 12.75 13.25 12.08 13.25 11.25C13.25 10.42 13.92 9.75 14.75 9.75ZM7.25 18.5L10.75 13.75L12.5 15.75L14.25 13.5L17.25 18.5H7.25Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 395 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M11.1 9.5H12.9V13.5H15L12 16.5L9 13.5H11.1V9.5ZM7.75 17H16.25V18.5H7.75V17Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 256 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M8.5 9.5H15.5V18.75H8.5V9.5ZM10 11V16.25H14V11H10ZM11.25 17V18.25H12.75V17H11.25Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 262 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M11.1 9.5H12.75C12.85 11.18 13.22 12.6 13.9 13.86L12.45 14.5C11.62 13 11.2 11.38 11.1 9.5ZM12.05 13.45L12.9 14.9C11.35 15.36 10.08 16.02 8.6 17.12L7.3 16.05C8.98 14.82 10.44 14.06 12.05 13.45ZM13.25 13.12L14.55 12.25C15.38 13.52 16.3 14.35 17.55 15.05L16.9 16.58C15.28 15.7 14.12 14.64 13.25 13.12Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 479 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M12.75 9.5C15.12 9.82 16.93 11.68 17.25 14H12.75V9.5ZM11.25 11.25V15.5H15.5C15.13 17.38 13.43 18.75 11.25 18.75C8.77 18.75 6.75 17.07 6.75 15C6.75 13.02 8.68 11.55 11.25 11.25Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 357 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M7.5 10H16.5V11.5H7.5V10ZM7.5 11.5H8.75V17.25H11.38V11.5H12.63V17.25H15.25V11.5H16.5V18.5H7.5V11.5ZM8.75 13.88H15.25V15.13H8.75V13.88Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 315 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M7.75 10H16.25V11.5H12.88V18.5H11.13V11.5H7.75V10Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 231 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M7.25 10.75H14.5V17.75H7.25V10.75ZM8.75 12.25V16.25H13V12.25H8.75ZM14.25 12.6L17.5 10.85V17.65L14.25 15.9V12.6Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 292 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M12 9.5C14.49 9.5 16.5 11.51 16.5 14C16.5 16.49 14.49 18.5 12 18.5C9.51 18.5 7.5 16.49 7.5 14C7.5 11.51 9.51 9.5 12 9.5ZM12 11C10.34 11 9 12.34 9 14C9 15.66 10.34 17 12 17C13.66 17 15 15.66 15 14C15 12.34 13.66 11 12 11ZM11.25 10.5H12.75V17.5H11.25V10.5ZM8.5 13.25H15.5V14.75H8.5V13.25Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 467 B |
@@ -0,0 +1,3 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 166 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M2 4C2 3.17 2.67 2.5 3.5 2.5H9.25L11.25 4.5H20.5C21.33 4.5 22 5.17 22 6V6.75H2V4ZM2 5.75H3.5V20H20.5V5.75H22V20.5C22 21.05 21.55 21.5 21 21.5H3C2.45 21.5 2 21.05 2 20.5V5.75Z"/>
|
||||||
|
<path d="M7.5 9.25H9.75V11H7.5V9.25ZM14.25 9.25H16.5V11H14.25V9.25ZM8 10.5H9.75V14C9.75 15.5 10.55 16.5 12 16.5C13.45 16.5 14.25 15.5 14.25 14V10.5H16V14C16 16.6 14.4 18.25 12 18.25C9.6 18.25 8 16.6 8 14V10.5Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 472 B |
@@ -0,0 +1,3 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M2 4C2 3.17 2.67 2.5 3.5 2.5H9.25L11.25 4.5H20.5C21.33 4.5 22 5.17 22 6V6.75H2V4ZM2 5.75H3.5V20H20.5V5.75H22V20.5C22 21.05 21.55 21.5 21 21.5H3C2.45 21.5 2 21.05 2 20.5V5.75Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 257 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M7.5 9.5H9.75V11.25H7.5V9.5ZM14.25 9.5H16.5V11.25H14.25V9.5ZM8 10.75H9.75V14C9.75 15.5 10.55 16.5 12 16.5C13.45 16.5 14.25 15.5 14.25 14V10.75H16V14C16 16.6 14.4 18.25 12 18.25C9.6 18.25 8 16.6 8 14V10.75Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 386 B |
@@ -0,0 +1,4 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
|
||||||
|
<path d="M3 2H14V3.5H4.5V20.5H19.5V8H21V22H3V2ZM13.25 2H14.5L21 8.5V9.75H19.75L13.25 3.25V2Z"/>
|
||||||
|
<path d="M11.25 11.45L9.05 15.35L7.75 14.6L10.05 10.6L11.25 11.45ZM12.75 11.45L13.95 10.6L16.25 14.6L14.95 15.35L12.75 11.45ZM12 9.25C13.1 9.25 14 10.15 14 11.25C14 12.35 13.1 13.25 12 13.25C10.9 13.25 10 12.35 10 11.25C10 10.15 10.9 9.25 12 9.25ZM8.25 14.75C9.35 14.75 10.25 15.65 10.25 16.75C10.25 17.85 9.35 18.75 8.25 18.75C7.15 18.75 6.25 17.85 6.25 16.75C6.25 15.65 7.15 14.75 8.25 14.75ZM15.75 14.75C16.85 14.75 17.75 15.65 17.75 16.75C17.75 17.85 16.85 18.75 15.75 18.75C14.65 18.75 13.75 17.85 13.75 16.75C13.75 15.65 14.65 14.75 15.75 14.75Z"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 723 B |
@@ -1,11 +1,15 @@
|
|||||||
version: '3'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
gopeed:
|
gopeed:
|
||||||
container_name: gopeed
|
container_name: gopeed
|
||||||
ports:
|
ports:
|
||||||
- 9999:9999 # HTTP port (host:container)
|
- 9999:9999 # HTTP port (host:container)
|
||||||
image: liwei2633/gopeed
|
environment:
|
||||||
volumes:
|
- PUID=0
|
||||||
- ~/Downloads:/root/Downloads # replace with your prefer path
|
- PGID=0
|
||||||
restart: unless-stopped
|
- UMASK=022
|
||||||
|
volumes:
|
||||||
|
- ~/gopeed/Downloads:/app/Downloads # mount download path
|
||||||
|
#- ~/gopeed/storage:/app/storage # if you need to mount storage path, uncomment this line
|
||||||
|
restart: unless-stopped
|
||||||
|
image: liwei2633/gopeed
|
||||||
|
# command: -u Username -p Password # optional authentication
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
chown -R ${PUID}:${PGID} /app
|
||||||
|
|
||||||
|
umask ${UMASK}
|
||||||
|
|
||||||
|
exec su-exec ${PUID}:${PGID} ./gopeed "$@"
|
||||||
@@ -1,79 +1,170 @@
|
|||||||
module github.com/GopeedLab/gopeed
|
module github.com/GopeedLab/gopeed
|
||||||
|
|
||||||
go 1.19
|
go 1.25.4
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/anacrolix/missinggo/v2 v2.7.2-0.20230527121029-a582b4f397b9
|
github.com/GopeedLab/webview_go v0.0.0-20260423085439-7a2f88b6e9b5
|
||||||
github.com/anacrolix/torrent v1.52.5
|
github.com/anacrolix/torrent v1.60.1-0.20251217073903-486bcbe758e0
|
||||||
|
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5
|
||||||
|
github.com/bodgit/sevenzip v1.6.1
|
||||||
|
github.com/dop251/goja v0.0.0-20260106131823-651366fbe6e3
|
||||||
|
github.com/dop251/goja_nodejs v0.0.0-20240728170619-29b559befffc
|
||||||
|
github.com/go-git/go-git/v5 v5.8.1
|
||||||
github.com/gorilla/handlers v1.5.1
|
github.com/gorilla/handlers v1.5.1
|
||||||
github.com/gorilla/mux v1.8.0
|
github.com/gorilla/mux v1.8.0
|
||||||
|
github.com/imroc/req/v3 v3.52.2
|
||||||
github.com/matoous/go-nanoid/v2 v2.0.0
|
github.com/matoous/go-nanoid/v2 v2.0.0
|
||||||
github.com/virtuald/go-paniclog v0.0.0-20190812204905-43a7fa316459
|
github.com/mattn/go-ieproxy v0.0.12
|
||||||
go.etcd.io/bbolt v1.3.6
|
github.com/mholt/archives v0.1.5
|
||||||
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde
|
github.com/modelcontextprotocol/go-sdk v1.7.0
|
||||||
|
github.com/monkeyWie/goed2k v0.0.0-20260317100435-7a7575cf2447
|
||||||
|
github.com/pkg/errors v0.9.1
|
||||||
|
github.com/rs/dnscache v0.0.0-20230804202142-fc85eb664529
|
||||||
|
github.com/rs/zerolog v1.31.0
|
||||||
|
github.com/xiaoqidun/setft v0.0.0-20220310121541-be86327699ad
|
||||||
|
go.etcd.io/bbolt v1.4.3
|
||||||
|
golang.org/x/exp v0.0.0-20251219203646-944ab1f22d93
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
crawshaw.io/sqlite v0.3.3-0.20220618202545-d1964889ea3c // indirect
|
github.com/STARRY-S/zip v0.2.3 // indirect
|
||||||
github.com/RoaringBitmap/roaring v1.2.3 // indirect
|
github.com/anacrolix/btree v0.1.1 // indirect
|
||||||
github.com/ajwerner/btree v0.0.0-20211221152037-f427b3e689c0 // indirect
|
github.com/anacrolix/missinggo/v2 v2.10.0 // indirect
|
||||||
|
github.com/andybalholm/brotli v1.2.0 // indirect
|
||||||
|
github.com/bodgit/plumbing v1.3.0 // indirect
|
||||||
|
github.com/bodgit/windows v1.0.1 // indirect
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707 // indirect
|
||||||
|
github.com/felixge/fgprof v0.9.5 // indirect
|
||||||
|
github.com/go-task/slim-sprig/v3 v3.0.0 // indirect
|
||||||
|
github.com/google/go-cmp v0.7.0 // indirect
|
||||||
|
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||||
|
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||||
|
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||||
|
github.com/icholy/digest v1.1.0 // indirect
|
||||||
|
github.com/klauspost/compress v1.18.0 // indirect
|
||||||
|
github.com/klauspost/pgzip v1.2.6 // indirect
|
||||||
|
github.com/mikelolasagasti/xz v1.0.1 // indirect
|
||||||
|
github.com/minio/minlz v1.0.1 // indirect
|
||||||
|
github.com/nwaples/rardecode/v2 v2.2.0 // indirect
|
||||||
|
github.com/onsi/ginkgo/v2 v2.23.4 // indirect
|
||||||
|
github.com/pierrec/lz4/v4 v4.1.22 // indirect
|
||||||
|
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||||
|
github.com/quic-go/qpack v0.5.1 // indirect
|
||||||
|
github.com/quic-go/quic-go v0.51.0 // indirect
|
||||||
|
github.com/refraction-networking/utls v1.6.7 // indirect
|
||||||
|
github.com/segmentio/asm v1.1.3 // indirect
|
||||||
|
github.com/segmentio/encoding v0.5.4 // indirect
|
||||||
|
github.com/sorairolake/lzip-go v0.3.8 // indirect
|
||||||
|
github.com/spf13/afero v1.15.0 // indirect
|
||||||
|
github.com/ulikunitz/xz v0.5.15 // indirect
|
||||||
|
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
|
go.uber.org/automaxprocs v1.6.0 // indirect
|
||||||
|
go.uber.org/mock v0.5.1 // indirect
|
||||||
|
go4.org v0.0.0-20230225012048-214862532bf5 // indirect
|
||||||
|
golang.org/x/oauth2 v0.35.0 // indirect
|
||||||
|
golang.org/x/sync v0.20.0 // indirect
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
dario.cat/mergo v1.0.0 // indirect
|
||||||
|
github.com/Microsoft/go-winio v0.6.1
|
||||||
|
github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 // indirect
|
||||||
|
github.com/RoaringBitmap/roaring v1.9.4
|
||||||
|
github.com/acomagu/bufpipe v1.0.4 // indirect
|
||||||
github.com/alecthomas/atomic v0.1.0-alpha2 // indirect
|
github.com/alecthomas/atomic v0.1.0-alpha2 // indirect
|
||||||
github.com/anacrolix/chansync v0.3.0 // indirect
|
github.com/anacrolix/chansync v0.7.0 // indirect
|
||||||
github.com/anacrolix/dht/v2 v2.19.2-0.20221121215055-066ad8494444 // indirect
|
github.com/anacrolix/dht/v2 v2.23.0 // indirect
|
||||||
github.com/anacrolix/envpprof v1.2.1 // indirect
|
github.com/anacrolix/envpprof v1.5.0 // indirect
|
||||||
github.com/anacrolix/generics v0.0.0-20230428105757-683593396d68 // indirect
|
github.com/anacrolix/generics v0.2.0 // indirect
|
||||||
github.com/anacrolix/go-libutp v1.3.1 // indirect
|
github.com/anacrolix/go-libutp v1.3.2 // indirect
|
||||||
github.com/anacrolix/log v0.14.0 // indirect
|
github.com/anacrolix/log v0.17.1-0.20251118025802-918f1157b7bb // indirect
|
||||||
github.com/anacrolix/missinggo v1.3.0 // indirect
|
github.com/anacrolix/missinggo v1.3.0 // indirect
|
||||||
github.com/anacrolix/missinggo/perf v1.0.0 // indirect
|
github.com/anacrolix/missinggo/perf v1.0.0 // indirect
|
||||||
github.com/anacrolix/mmsg v1.0.0 // indirect
|
github.com/anacrolix/mmsg v1.1.1 // indirect
|
||||||
github.com/anacrolix/multiless v0.3.0 // indirect
|
github.com/anacrolix/multiless v0.4.0 // indirect
|
||||||
github.com/anacrolix/stm v0.4.0 // indirect
|
github.com/anacrolix/stm v0.5.0 // indirect
|
||||||
github.com/anacrolix/sync v0.4.0 // indirect
|
github.com/anacrolix/sync v0.6.0 // indirect
|
||||||
github.com/anacrolix/upnp v0.1.3-0.20220123035249-922794e51c96 // indirect
|
github.com/anacrolix/upnp v0.1.4 // indirect
|
||||||
github.com/anacrolix/utp v0.1.0 // indirect
|
github.com/anacrolix/utp v0.2.0 // indirect
|
||||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||||
github.com/benbjohnson/immutable v0.3.0 // indirect
|
github.com/benbjohnson/immutable v0.4.3 // indirect
|
||||||
github.com/bits-and-blooms/bitset v1.2.2 // indirect
|
github.com/bits-and-blooms/bitset v1.24.4 // indirect
|
||||||
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
github.com/bradfitz/iter v0.0.0-20191230175014-e8f45d346db8 // indirect
|
||||||
|
github.com/cespare/xxhash v1.1.0 // indirect
|
||||||
|
github.com/cloudflare/circl v1.6.1 // indirect
|
||||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
github.com/dustin/go-humanize v1.0.0 // indirect
|
github.com/dlclark/regexp2 v1.11.5 // indirect
|
||||||
github.com/edsrzf/mmap-go v1.1.0 // indirect
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
|
github.com/edsrzf/mmap-go v1.2.0 // indirect
|
||||||
|
github.com/emirpasic/gods v1.18.1 // indirect
|
||||||
github.com/felixge/httpsnoop v1.0.1 // indirect
|
github.com/felixge/httpsnoop v1.0.1 // indirect
|
||||||
github.com/go-logr/logr v1.2.3 // indirect
|
github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect
|
||||||
|
github.com/go-git/go-billy/v5 v5.4.1 // indirect
|
||||||
|
github.com/go-llsqlite/adapter v0.2.0 // indirect
|
||||||
|
github.com/go-llsqlite/crawshaw v0.6.0 // indirect
|
||||||
|
github.com/go-logr/logr v1.4.3 // indirect
|
||||||
github.com/go-logr/stdr v1.2.2 // indirect
|
github.com/go-logr/stdr v1.2.2 // indirect
|
||||||
github.com/google/btree v1.1.2 // indirect
|
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
|
||||||
github.com/google/uuid v1.3.0 // indirect
|
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||||
github.com/gorilla/websocket v1.5.0 // indirect
|
github.com/google/btree v1.1.3 // indirect
|
||||||
github.com/huandu/xstrings v1.3.2 // indirect
|
github.com/google/pprof v0.0.0-20260115054156-294ebfa9ad83 // indirect
|
||||||
github.com/lispad/go-generics-tools v1.1.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
|
github.com/gorilla/websocket v1.5.3 // indirect
|
||||||
|
github.com/huandu/xstrings v1.5.0 // indirect
|
||||||
|
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
|
||||||
|
github.com/kevinburke/ssh_config v1.2.0 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/minio/sha256-simd v1.0.1 // indirect
|
||||||
|
github.com/mr-tron/base58 v1.2.0 // indirect
|
||||||
github.com/mschoch/smat v0.2.0 // indirect
|
github.com/mschoch/smat v0.2.0 // indirect
|
||||||
github.com/pion/datachannel v1.5.2 // indirect
|
github.com/multiformats/go-multihash v0.2.3 // indirect
|
||||||
github.com/pion/dtls/v2 v2.2.4 // indirect
|
github.com/multiformats/go-varint v0.1.0 // indirect
|
||||||
github.com/pion/ice/v2 v2.2.6 // indirect
|
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||||
github.com/pion/interceptor v0.1.11 // indirect
|
github.com/pion/datachannel v1.6.0 // indirect
|
||||||
github.com/pion/logging v0.2.2 // indirect
|
github.com/pion/dtls/v3 v3.0.10 // indirect
|
||||||
github.com/pion/mdns v0.0.5 // indirect
|
github.com/pion/ice/v4 v4.2.0 // indirect
|
||||||
|
github.com/pion/interceptor v0.1.42 // indirect
|
||||||
|
github.com/pion/logging v0.2.4 // indirect
|
||||||
|
github.com/pion/mdns/v2 v2.1.0 // indirect
|
||||||
github.com/pion/randutil v0.1.0 // indirect
|
github.com/pion/randutil v0.1.0 // indirect
|
||||||
github.com/pion/rtcp v1.2.9 // indirect
|
github.com/pion/rtcp v1.2.16 // indirect
|
||||||
github.com/pion/rtp v1.7.13 // indirect
|
github.com/pion/rtp v1.10.0 // indirect
|
||||||
github.com/pion/sctp v1.8.2 // indirect
|
github.com/pion/sctp v1.9.1 // indirect
|
||||||
github.com/pion/sdp/v3 v3.0.5 // indirect
|
github.com/pion/sdp/v3 v3.0.17 // indirect
|
||||||
github.com/pion/srtp/v2 v2.0.9 // indirect
|
github.com/pion/srtp/v3 v3.0.10 // indirect
|
||||||
github.com/pion/stun v0.3.5 // indirect
|
github.com/pion/stun/v3 v3.1.1 // indirect
|
||||||
github.com/pion/transport v0.13.1 // indirect
|
github.com/pion/turn/v4 v4.1.4 // indirect
|
||||||
github.com/pion/transport/v2 v2.0.0 // indirect
|
github.com/pion/webrtc/v4 v4.2.2-0.20260109001657-a5962f314db7 // indirect
|
||||||
github.com/pion/turn/v2 v2.0.8 // indirect
|
github.com/pjbgf/sha1cd v0.3.0 // indirect
|
||||||
github.com/pion/udp v0.1.4 // indirect
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
|
||||||
github.com/pion/webrtc/v3 v3.1.42 // indirect
|
github.com/protolambda/ctxlock v0.1.0 // indirect
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417 // indirect
|
github.com/sergi/go-diff v1.1.0 // indirect
|
||||||
github.com/tidwall/btree v1.6.0 // indirect
|
github.com/skeema/knownhosts v1.2.0 // indirect
|
||||||
go.opentelemetry.io/otel v1.8.0 // indirect
|
github.com/spaolacci/murmur3 v1.1.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace v1.8.0 // indirect
|
github.com/tidwall/btree v1.8.1 // indirect
|
||||||
golang.org/x/crypto v0.5.0 // indirect
|
github.com/wlynxg/anet v0.0.5 // indirect
|
||||||
golang.org/x/exp v0.0.0-20220613132600-b0d781184e0d // indirect
|
github.com/xanzy/ssh-agent v0.3.3 // indirect
|
||||||
golang.org/x/net v0.7.0 // indirect
|
go.opentelemetry.io/otel v1.39.0 // indirect
|
||||||
golang.org/x/sys v0.5.0 // indirect
|
go.opentelemetry.io/otel/metric v1.39.0 // indirect
|
||||||
golang.org/x/time v0.0.0-20220609170525-579cf78fd858 // indirect
|
go.opentelemetry.io/otel/trace v1.39.0 // indirect
|
||||||
|
golang.org/x/crypto v0.48.0 // indirect
|
||||||
|
golang.org/x/mod v0.33.0 // indirect
|
||||||
|
golang.org/x/net v0.50.0
|
||||||
|
golang.org/x/sys v0.41.0 // indirect
|
||||||
|
golang.org/x/text v0.34.0
|
||||||
|
golang.org/x/time v0.15.0 // indirect
|
||||||
|
golang.org/x/tools v0.42.0 // indirect
|
||||||
|
gopkg.in/warnings.v0 v0.1.2 // indirect
|
||||||
|
lukechampine.com/blake3 v1.4.1 // indirect
|
||||||
|
modernc.org/libc v1.67.4 // indirect
|
||||||
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
modernc.org/memory v1.11.0 // indirect
|
||||||
|
modernc.org/sqlite v1.43.0 // indirect
|
||||||
|
zombiezen.com/go/sqlite v1.4.2 // indirect
|
||||||
)
|
)
|
||||||
@@ -0,0 +1,677 @@
|
|||||||
|
package blob
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"path"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const urlPathPrefix = "/__blob/"
|
||||||
|
|
||||||
|
const rangeSourceFailureLimit = 2
|
||||||
|
|
||||||
|
// unclaimedSourceTTL bounds how long a session-backed source may keep its
|
||||||
|
// engine alive without ever being claimed by a download task.
|
||||||
|
var unclaimedSourceTTL = 10 * time.Minute
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrInvalidURL = errors.New("invalid blob url")
|
||||||
|
ErrInvalidOptions = errors.New("invalid blob options")
|
||||||
|
ErrSourceNotFound = errors.New("blob source not found")
|
||||||
|
ErrSourceRevoked = errors.New("blob source revoked")
|
||||||
|
ErrSourceClosed = errors.New("blob source closed")
|
||||||
|
ErrRangeNotAllowed = errors.New("blob range not allowed")
|
||||||
|
)
|
||||||
|
|
||||||
|
type SessionRef interface {
|
||||||
|
Retain()
|
||||||
|
Release()
|
||||||
|
}
|
||||||
|
|
||||||
|
type OpenRequest struct {
|
||||||
|
Offset int64
|
||||||
|
End int64
|
||||||
|
}
|
||||||
|
|
||||||
|
type OpenFunc func(ctx context.Context, req OpenRequest) (io.ReadCloser, error)
|
||||||
|
|
||||||
|
type CreateOptions struct {
|
||||||
|
ContentType string
|
||||||
|
Size int64
|
||||||
|
Range bool
|
||||||
|
Session SessionRef
|
||||||
|
}
|
||||||
|
|
||||||
|
type Metadata struct {
|
||||||
|
ContentType string
|
||||||
|
Size int64
|
||||||
|
Range bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Source struct {
|
||||||
|
ID string
|
||||||
|
URL string
|
||||||
|
ContentType string
|
||||||
|
|
||||||
|
mu sync.Mutex
|
||||||
|
size int64
|
||||||
|
rangeEnabled bool
|
||||||
|
revoked bool
|
||||||
|
taskRefs int
|
||||||
|
readErr error
|
||||||
|
rangeFailures int
|
||||||
|
session SessionRef
|
||||||
|
open OpenFunc
|
||||||
|
unclaimed *time.Timer
|
||||||
|
}
|
||||||
|
|
||||||
|
type Registry struct {
|
||||||
|
dir string
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
sources map[string]*Source
|
||||||
|
|
||||||
|
serverMu sync.Mutex
|
||||||
|
listener net.Listener
|
||||||
|
server *http.Server
|
||||||
|
baseURL string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRegistry(dir string) *Registry {
|
||||||
|
return &Registry{
|
||||||
|
dir: dir,
|
||||||
|
sources: make(map[string]*Source),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) Dir() string {
|
||||||
|
if r == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return r.dir
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) IsURL(raw string) bool {
|
||||||
|
if r == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
src, err := r.get(raw)
|
||||||
|
return err == nil && src != nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) CreateBlob(data []byte, contentType string) (string, error) {
|
||||||
|
buf := append([]byte(nil), data...)
|
||||||
|
return r.CreateOpener(func(ctx context.Context, req OpenRequest) (io.ReadCloser, error) {
|
||||||
|
if req.Offset < 0 || req.Offset > int64(len(buf)) {
|
||||||
|
return nil, ErrSourceNotFound
|
||||||
|
}
|
||||||
|
end := int64(len(buf))
|
||||||
|
if req.End >= req.Offset && req.End+1 < end {
|
||||||
|
end = req.End + 1
|
||||||
|
}
|
||||||
|
return io.NopCloser(bytes.NewReader(buf[req.Offset:end])), nil
|
||||||
|
}, &CreateOptions{
|
||||||
|
ContentType: contentType,
|
||||||
|
Size: int64(len(buf)),
|
||||||
|
Range: len(buf) > 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) CreateOpener(open OpenFunc, opts *CreateOptions) (string, error) {
|
||||||
|
if r == nil {
|
||||||
|
return "", ErrSourceNotFound
|
||||||
|
}
|
||||||
|
if open == nil {
|
||||||
|
return "", ErrInvalidOptions
|
||||||
|
}
|
||||||
|
if opts == nil {
|
||||||
|
opts = &CreateOptions{}
|
||||||
|
}
|
||||||
|
if opts.Size < 0 {
|
||||||
|
opts.Size = 0
|
||||||
|
}
|
||||||
|
if opts.Range && opts.Size <= 0 {
|
||||||
|
return "", fmt.Errorf("%w: range requires positive size", ErrInvalidOptions)
|
||||||
|
}
|
||||||
|
// Keep server generation selection and source insertion atomic with Close.
|
||||||
|
r.serverMu.Lock()
|
||||||
|
baseURL, err := r.ensureServerLocked()
|
||||||
|
if err != nil {
|
||||||
|
r.serverMu.Unlock()
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
id, err := randomID(18)
|
||||||
|
if err != nil {
|
||||||
|
r.serverMu.Unlock()
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if opts.Session != nil {
|
||||||
|
opts.Session.Retain()
|
||||||
|
}
|
||||||
|
srcURL := fmt.Sprintf("%s%s", baseURL, id)
|
||||||
|
src := &Source{
|
||||||
|
ID: id,
|
||||||
|
URL: srcURL,
|
||||||
|
ContentType: opts.ContentType,
|
||||||
|
size: opts.Size,
|
||||||
|
rangeEnabled: opts.Range,
|
||||||
|
session: opts.Session,
|
||||||
|
open: open,
|
||||||
|
}
|
||||||
|
r.mu.Lock()
|
||||||
|
r.sources[id] = src
|
||||||
|
r.mu.Unlock()
|
||||||
|
r.serverMu.Unlock()
|
||||||
|
if opts.Session != nil && unclaimedSourceTTL > 0 {
|
||||||
|
src.mu.Lock()
|
||||||
|
if !src.revoked {
|
||||||
|
src.unclaimed = time.AfterFunc(unclaimedSourceTTL, func() {
|
||||||
|
r.expireUnclaimed(src)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
src.mu.Unlock()
|
||||||
|
}
|
||||||
|
return src.URL, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) Metadata(raw string) (Metadata, error) {
|
||||||
|
src, err := r.get(raw)
|
||||||
|
if err != nil {
|
||||||
|
return Metadata{}, err
|
||||||
|
}
|
||||||
|
src.mu.Lock()
|
||||||
|
defer src.mu.Unlock()
|
||||||
|
return Metadata{
|
||||||
|
ContentType: src.ContentType,
|
||||||
|
Size: src.size,
|
||||||
|
Range: src.rangeEnabled,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Acquire retains a source for a task. A source remains available until every
|
||||||
|
// task that acquired it calls Release, unless it is explicitly revoked.
|
||||||
|
func (r *Registry) Acquire(raw string) error {
|
||||||
|
src, err := r.get(raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return src.acquireTask()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release releases a task's reference to a source. Releasing the final task
|
||||||
|
// reference revokes the source. Sources that have never been acquired remain
|
||||||
|
// registered until Revoke or Registry.Close is called; session-backed sources
|
||||||
|
// are also bounded by the unclaimed-source TTL.
|
||||||
|
func (r *Registry) Release(raw string) error {
|
||||||
|
src, err := r.get(raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
session, last, err := src.releaseTask()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !last {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
r.deleteSource(src)
|
||||||
|
if session != nil {
|
||||||
|
session.Release()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SourceError returns the first error encountered while opening or reading a
|
||||||
|
// source. Invalid and missing sources have no source error. HTTP response write
|
||||||
|
// errors are deliberately not recorded here.
|
||||||
|
func (r *Registry) SourceError(raw string) error {
|
||||||
|
src, err := r.get(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return src.sourceError()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) Revoke(raw string) error {
|
||||||
|
src, err := r.get(raw)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
r.removeSource(src)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) Close() error {
|
||||||
|
if r == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
r.serverMu.Lock()
|
||||||
|
server := r.server
|
||||||
|
listener := r.listener
|
||||||
|
r.server = nil
|
||||||
|
r.listener = nil
|
||||||
|
r.baseURL = ""
|
||||||
|
r.mu.Lock()
|
||||||
|
sources := make([]*Source, 0, len(r.sources))
|
||||||
|
for _, src := range r.sources {
|
||||||
|
sources = append(sources, src)
|
||||||
|
}
|
||||||
|
r.sources = make(map[string]*Source)
|
||||||
|
r.mu.Unlock()
|
||||||
|
r.serverMu.Unlock()
|
||||||
|
if server != nil {
|
||||||
|
_ = server.Close()
|
||||||
|
}
|
||||||
|
if listener != nil {
|
||||||
|
_ = listener.Close()
|
||||||
|
}
|
||||||
|
for _, src := range sources {
|
||||||
|
src.close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ensureServerLocked returns the current server URL or starts a new server.
|
||||||
|
// The caller must hold serverMu.
|
||||||
|
func (r *Registry) ensureServerLocked() (string, error) {
|
||||||
|
if r.baseURL != "" {
|
||||||
|
return r.baseURL, nil
|
||||||
|
}
|
||||||
|
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
r.listener = listener
|
||||||
|
r.baseURL = "http://" + listener.Addr().String() + urlPathPrefix
|
||||||
|
server := &http.Server{Handler: r}
|
||||||
|
r.server = server
|
||||||
|
go func() {
|
||||||
|
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
_ = r.Close()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return r.baseURL, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
||||||
|
if req.Method != http.MethodGet {
|
||||||
|
w.Header().Set("Allow", "GET")
|
||||||
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
id := parseRequest(req)
|
||||||
|
if id == "" {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
src, err := r.getByID(id)
|
||||||
|
if err != nil {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
meta, open, session := src.acquireOpen()
|
||||||
|
if open == nil {
|
||||||
|
http.NotFound(w, req)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if session != nil {
|
||||||
|
defer session.Release()
|
||||||
|
}
|
||||||
|
if src.sourceError() != nil {
|
||||||
|
http.Error(w, "blob source unavailable", http.StatusGone)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
start, end, ranged, err := parseRange(req.Header.Get("Range"), meta.Size, meta.Range)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusRequestedRangeNotSatisfiable)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !meta.Range {
|
||||||
|
start, end, ranged = 0, -1, false
|
||||||
|
}
|
||||||
|
reader, err := open(req.Context(), OpenRequest{
|
||||||
|
Offset: start,
|
||||||
|
End: end,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
if req.Context().Err() == nil || !errors.Is(err, req.Context().Err()) {
|
||||||
|
src.recordSourceError(err, meta.Range)
|
||||||
|
}
|
||||||
|
http.Error(w, "blob source unavailable", http.StatusGone)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if reader == nil {
|
||||||
|
err = fmt.Errorf("%w: opener returned a nil reader", ErrSourceClosed)
|
||||||
|
src.recordSourceError(err, meta.Range)
|
||||||
|
http.Error(w, "blob source unavailable", http.StatusGone)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
|
||||||
|
writeHeaders(w, meta, start, end, ranged)
|
||||||
|
if ranged {
|
||||||
|
w.WriteHeader(http.StatusPartialContent)
|
||||||
|
}
|
||||||
|
limit := int64(-1)
|
||||||
|
if end >= start {
|
||||||
|
limit = end - start + 1
|
||||||
|
} else if meta.Size > 0 {
|
||||||
|
limit = meta.Size
|
||||||
|
}
|
||||||
|
_, readErr, writeErr := copyWithFlush(w, reader, limit)
|
||||||
|
if readErr != nil {
|
||||||
|
if ctxErr := req.Context().Err(); ctxErr == nil || !errors.Is(readErr, ctxErr) {
|
||||||
|
src.recordSourceError(readErr, meta.Range)
|
||||||
|
}
|
||||||
|
} else if writeErr == nil && req.Context().Err() == nil {
|
||||||
|
src.recordSourceSuccess(meta.Range)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) acquireOpen() (Metadata, OpenFunc, SessionRef) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if s.revoked {
|
||||||
|
return Metadata{}, nil, nil
|
||||||
|
}
|
||||||
|
if s.session != nil {
|
||||||
|
// The source's own retain guarantees that the session cannot become
|
||||||
|
// closed while this additional active-reader retain is acquired.
|
||||||
|
s.session.Retain()
|
||||||
|
}
|
||||||
|
return Metadata{
|
||||||
|
ContentType: s.ContentType,
|
||||||
|
Size: s.size,
|
||||||
|
Range: s.rangeEnabled,
|
||||||
|
}, s.open, s.session
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) acquireTask() error {
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.revoked {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return ErrSourceRevoked
|
||||||
|
}
|
||||||
|
s.taskRefs++
|
||||||
|
timer := s.unclaimed
|
||||||
|
s.unclaimed = nil
|
||||||
|
s.mu.Unlock()
|
||||||
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) releaseTask() (session SessionRef, last bool, err error) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
if s.revoked {
|
||||||
|
return nil, false, ErrSourceRevoked
|
||||||
|
}
|
||||||
|
if s.taskRefs == 0 {
|
||||||
|
return nil, false, ErrSourceClosed
|
||||||
|
}
|
||||||
|
s.taskRefs--
|
||||||
|
if s.taskRefs > 0 {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
s.revoked = true
|
||||||
|
s.open = nil
|
||||||
|
session = s.session
|
||||||
|
s.session = nil
|
||||||
|
return session, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) sourceError() error {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.readErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) recordSourceError(err error, ranged bool) {
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.readErr == nil && ranged {
|
||||||
|
s.rangeFailures++
|
||||||
|
if s.rangeFailures < rangeSourceFailureLimit {
|
||||||
|
s.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.readErr == nil {
|
||||||
|
s.readErr = err
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) recordSourceSuccess(ranged bool) {
|
||||||
|
if !ranged {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.readErr == nil {
|
||||||
|
s.rangeFailures = 0
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) close() {
|
||||||
|
s.mu.Lock()
|
||||||
|
alreadyRevoked := s.revoked
|
||||||
|
s.revoked = true
|
||||||
|
s.open = nil
|
||||||
|
session := s.session
|
||||||
|
s.session = nil
|
||||||
|
timer := s.unclaimed
|
||||||
|
s.unclaimed = nil
|
||||||
|
s.mu.Unlock()
|
||||||
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
if !alreadyRevoked && session != nil {
|
||||||
|
session.Release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Source) expireUnclaimed() (SessionRef, bool) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.unclaimed = nil
|
||||||
|
if s.revoked || s.taskRefs > 0 {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
s.revoked = true
|
||||||
|
s.open = nil
|
||||||
|
session := s.session
|
||||||
|
s.session = nil
|
||||||
|
return session, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) expireUnclaimed(src *Source) {
|
||||||
|
session, expired := src.expireUnclaimed()
|
||||||
|
if !expired {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
r.deleteSource(src)
|
||||||
|
if session != nil {
|
||||||
|
session.Release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) removeSource(src *Source) {
|
||||||
|
src.close()
|
||||||
|
r.deleteSource(src)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) deleteSource(src *Source) {
|
||||||
|
r.mu.Lock()
|
||||||
|
if current := r.sources[src.ID]; current == src {
|
||||||
|
delete(r.sources, src.ID)
|
||||||
|
}
|
||||||
|
r.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeHeaders(w http.ResponseWriter, meta Metadata, start, end int64, ranged bool) {
|
||||||
|
if meta.ContentType != "" {
|
||||||
|
w.Header().Set("Content-Type", meta.ContentType)
|
||||||
|
}
|
||||||
|
if meta.Range {
|
||||||
|
w.Header().Set("Accept-Ranges", "bytes")
|
||||||
|
}
|
||||||
|
if meta.Size > 0 {
|
||||||
|
if ranged {
|
||||||
|
w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", start, end, meta.Size))
|
||||||
|
w.Header().Set("Content-Length", strconv.FormatInt(end-start+1, 10))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Length", strconv.FormatInt(meta.Size, 10))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyWithFlush(w http.ResponseWriter, reader io.Reader, limit int64) (written int64, readErr error, writeErr error) {
|
||||||
|
if limit >= 0 {
|
||||||
|
reader = io.LimitReader(reader, limit)
|
||||||
|
}
|
||||||
|
buf := make([]byte, 32*1024)
|
||||||
|
flusher, canFlush := w.(http.Flusher)
|
||||||
|
for {
|
||||||
|
nr, er := reader.Read(buf)
|
||||||
|
if er != nil && !errors.Is(er, io.EOF) {
|
||||||
|
readErr = er
|
||||||
|
}
|
||||||
|
if nr > 0 {
|
||||||
|
nw, ew := w.Write(buf[:nr])
|
||||||
|
if nw > 0 {
|
||||||
|
written += int64(nw)
|
||||||
|
if canFlush {
|
||||||
|
flusher.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ew != nil {
|
||||||
|
return written, readErr, ew
|
||||||
|
}
|
||||||
|
if nr != nw {
|
||||||
|
return written, readErr, io.ErrShortWrite
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if er != nil {
|
||||||
|
if errors.Is(er, io.EOF) {
|
||||||
|
if limit >= 0 && written < limit {
|
||||||
|
return written, io.ErrUnexpectedEOF, nil
|
||||||
|
}
|
||||||
|
return written, nil, nil
|
||||||
|
}
|
||||||
|
return written, readErr, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRange(header string, size int64, rangeEnabled bool) (start int64, end int64, ranged bool, err error) {
|
||||||
|
if header == "" || !rangeEnabled {
|
||||||
|
return 0, -1, false, nil
|
||||||
|
}
|
||||||
|
if size <= 0 {
|
||||||
|
return 0, 0, false, ErrRangeNotAllowed
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(header, "bytes=") {
|
||||||
|
return 0, 0, false, fmt.Errorf("unsupported range")
|
||||||
|
}
|
||||||
|
parts := strings.SplitN(strings.TrimPrefix(header, "bytes="), "-", 2)
|
||||||
|
if len(parts) != 2 || parts[0] == "" {
|
||||||
|
return 0, 0, false, fmt.Errorf("unsupported range")
|
||||||
|
}
|
||||||
|
start, err = strconv.ParseInt(parts[0], 10, 64)
|
||||||
|
if err != nil || start < 0 {
|
||||||
|
return 0, 0, false, fmt.Errorf("invalid range")
|
||||||
|
}
|
||||||
|
if start >= size {
|
||||||
|
return 0, 0, false, fmt.Errorf("range out of bounds")
|
||||||
|
}
|
||||||
|
end = size - 1
|
||||||
|
if parts[1] != "" {
|
||||||
|
end, err = strconv.ParseInt(parts[1], 10, 64)
|
||||||
|
if err != nil || end < start {
|
||||||
|
return 0, 0, false, fmt.Errorf("invalid range")
|
||||||
|
}
|
||||||
|
if end >= size {
|
||||||
|
end = size - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return start, end, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) get(raw string) (*Source, error) {
|
||||||
|
id, ok := r.parseURL(raw)
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrInvalidURL
|
||||||
|
}
|
||||||
|
src, err := r.getByID(id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
src.mu.Lock()
|
||||||
|
revoked := src.revoked
|
||||||
|
src.mu.Unlock()
|
||||||
|
if revoked {
|
||||||
|
return nil, ErrSourceRevoked
|
||||||
|
}
|
||||||
|
return src, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) getByID(id string) (*Source, error) {
|
||||||
|
r.mu.RLock()
|
||||||
|
defer r.mu.RUnlock()
|
||||||
|
src := r.sources[id]
|
||||||
|
if src == nil {
|
||||||
|
return nil, ErrSourceNotFound
|
||||||
|
}
|
||||||
|
return src, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Registry) parseURL(raw string) (id string, ok bool) {
|
||||||
|
u, err := url.Parse(raw)
|
||||||
|
if err != nil || u.Scheme != "http" || !strings.HasPrefix(u.Path, urlPathPrefix) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
r.serverMu.Lock()
|
||||||
|
baseURL := r.baseURL
|
||||||
|
r.serverMu.Unlock()
|
||||||
|
if baseURL == "" || !strings.HasPrefix(raw, baseURL) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
id = strings.TrimPrefix(u.Path, urlPathPrefix)
|
||||||
|
if id == "" || path.Base(id) != id {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return id, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseRequest(req *http.Request) string {
|
||||||
|
id := strings.TrimPrefix(req.URL.Path, urlPathPrefix)
|
||||||
|
if id == "" || id == req.URL.Path || path.Base(id) != id {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
|
||||||
|
func randomID(size int) (string, error) {
|
||||||
|
buf := make([]byte, size)
|
||||||
|
if _, err := rand.Read(buf); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(buf), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,898 @@
|
|||||||
|
package blob
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type terminalErrorReader struct {
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *terminalErrorReader) Read([]byte) (int, error) {
|
||||||
|
return 0, r.err
|
||||||
|
}
|
||||||
|
|
||||||
|
type contextErrorReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *contextErrorReader) Read([]byte) (int, error) {
|
||||||
|
<-r.ctx.Done()
|
||||||
|
return 0, r.ctx.Err()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *contextErrorReader) Close() error { return nil }
|
||||||
|
|
||||||
|
type failingResponseWriter struct {
|
||||||
|
header http.Header
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *failingResponseWriter) Header() http.Header {
|
||||||
|
return w.header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *failingResponseWriter) Write([]byte) (int, error) {
|
||||||
|
return 0, w.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *failingResponseWriter) WriteHeader(int) {}
|
||||||
|
|
||||||
|
type countingSession struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
refs int
|
||||||
|
zero chan struct{}
|
||||||
|
zeroOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func newCountingSession() *countingSession {
|
||||||
|
return &countingSession{zero: make(chan struct{})}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *countingSession) Retain() {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.refs++
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *countingSession) Release() {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.refs--
|
||||||
|
refs := s.refs
|
||||||
|
s.mu.Unlock()
|
||||||
|
if refs == 0 {
|
||||||
|
s.zeroOnce.Do(func() { close(s.zero) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *countingSession) RefCount() int {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
return s.refs
|
||||||
|
}
|
||||||
|
|
||||||
|
func setUnclaimedSourceTTLForTest(t *testing.T, ttl time.Duration) {
|
||||||
|
t.Helper()
|
||||||
|
previous := unclaimedSourceTTL
|
||||||
|
unclaimedSourceTTL = ttl
|
||||||
|
t.Cleanup(func() {
|
||||||
|
unclaimedSourceTTL = previous
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryBlobHTTPGetAndRange(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateBlob([]byte("hello world"), "text/plain")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !registry.IsURL(url) {
|
||||||
|
t.Fatal("expected registry to recognize created url")
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("unexpected GET status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Content-Length"); got != "11" {
|
||||||
|
t.Fatalf("unexpected content length: %q", got)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Accept-Ranges"); got != "bytes" {
|
||||||
|
t.Fatalf("unexpected accept ranges: %q", got)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Content-Type"); !strings.HasPrefix(got, "text/plain") {
|
||||||
|
t.Fatalf("unexpected content type: %q", got)
|
||||||
|
}
|
||||||
|
if string(body) != "hello world" {
|
||||||
|
t.Fatalf("unexpected GET body: %q", string(body))
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", "bytes=6-10")
|
||||||
|
resp, err = http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, err = io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusPartialContent {
|
||||||
|
t.Fatalf("unexpected range status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Content-Range"); got != "bytes 6-10/11" {
|
||||||
|
t.Fatalf("unexpected content range: %q", got)
|
||||||
|
}
|
||||||
|
if string(body) != "world" {
|
||||||
|
t.Fatalf("unexpected range body: %q", string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryEmptyBlob(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateBlob(nil, "application/octet-stream")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
meta, err := registry.Metadata(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if meta.Size != 0 || meta.Range {
|
||||||
|
t.Fatalf("unexpected empty blob metadata: %#v", meta)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, readErr := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if readErr != nil {
|
||||||
|
t.Fatal(readErr)
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("unexpected status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if len(body) != 0 {
|
||||||
|
t.Fatalf("unexpected body: %q", body)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Content-Length"); got != "0" {
|
||||||
|
t.Fatalf("unexpected content length: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryOpenerSizeWithoutRange(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
payload := []byte("hello opener")
|
||||||
|
url, err := registry.CreateOpener(func(ctx context.Context, req OpenRequest) (io.ReadCloser, error) {
|
||||||
|
if req.Offset != 0 || req.End != -1 {
|
||||||
|
t.Fatalf("unexpected non-range request: %#v", req)
|
||||||
|
}
|
||||||
|
return io.NopCloser(bytes.NewReader(payload)), nil
|
||||||
|
}, &CreateOptions{
|
||||||
|
ContentType: "text/plain",
|
||||||
|
Size: int64(len(payload)),
|
||||||
|
Range: false,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", "bytes=6-11")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
t.Fatalf("unexpected status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Content-Length"); got != "12" {
|
||||||
|
t.Fatalf("unexpected content length: %q", got)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("Accept-Ranges"); got != "" {
|
||||||
|
t.Fatalf("unexpected accept ranges: %q", got)
|
||||||
|
}
|
||||||
|
if string(body) != string(payload) {
|
||||||
|
t.Fatalf("unexpected body: %q", string(body))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryOpenerRangeConcurrentRequests(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
payload := []byte("abcdefghijklmnopqrstuvwxyz")
|
||||||
|
var mu sync.Mutex
|
||||||
|
var calls []OpenRequest
|
||||||
|
url, err := registry.CreateOpener(func(ctx context.Context, req OpenRequest) (io.ReadCloser, error) {
|
||||||
|
mu.Lock()
|
||||||
|
calls = append(calls, req)
|
||||||
|
mu.Unlock()
|
||||||
|
|
||||||
|
start := int(req.Offset)
|
||||||
|
end := len(payload)
|
||||||
|
if req.End >= 0 {
|
||||||
|
end = int(req.End) + 1
|
||||||
|
}
|
||||||
|
if start < 0 || start > end || end > len(payload) {
|
||||||
|
return nil, errors.New("bad test range")
|
||||||
|
}
|
||||||
|
return io.NopCloser(bytes.NewReader(payload[start:end])), nil
|
||||||
|
}, &CreateOptions{
|
||||||
|
Size: int64(len(payload)),
|
||||||
|
Range: true,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ranges := []struct {
|
||||||
|
header string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{header: "bytes=0-4", want: "abcde"},
|
||||||
|
{header: "bytes=10-15", want: "klmnop"},
|
||||||
|
{header: "bytes=20-25", want: "uvwxyz"},
|
||||||
|
}
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
for _, item := range ranges {
|
||||||
|
item := item
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", item.header)
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if resp.StatusCode != http.StatusPartialContent {
|
||||||
|
t.Errorf("unexpected status for %s: %d", item.header, resp.StatusCode)
|
||||||
|
}
|
||||||
|
if string(body) != item.want {
|
||||||
|
t.Errorf("unexpected body for %s: %q", item.header, string(body))
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
defer mu.Unlock()
|
||||||
|
if len(calls) != len(ranges) {
|
||||||
|
t.Fatalf("unexpected opener call count: %d", len(calls))
|
||||||
|
}
|
||||||
|
seen := map[OpenRequest]bool{}
|
||||||
|
for _, call := range calls {
|
||||||
|
seen[call] = true
|
||||||
|
}
|
||||||
|
for _, want := range []OpenRequest{{Offset: 0, End: 4}, {Offset: 10, End: 15}, {Offset: 20, End: 25}} {
|
||||||
|
if !seen[want] {
|
||||||
|
t.Fatalf("missing opener request %#v, got %#v", want, calls)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryRejectsRangeWithoutSize(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
_, err := registry.CreateOpener(func(ctx context.Context, req OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("")), nil
|
||||||
|
}, &CreateOptions{Range: true})
|
||||||
|
if !errors.Is(err, ErrInvalidOptions) {
|
||||||
|
t.Fatalf("expected invalid options error, got %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryTracksSourceErrors(t *testing.T) {
|
||||||
|
t.Run("reader error", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
boom := errors.New("reader failed")
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(io.MultiReader(strings.NewReader("partial"), &terminalErrorReader{err: boom})), nil
|
||||||
|
}, &CreateOptions{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, readErr := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if readErr != nil {
|
||||||
|
t.Fatalf("the HTTP transport should end normally, got %v", readErr)
|
||||||
|
}
|
||||||
|
if string(body) != "partial" {
|
||||||
|
t.Fatalf("unexpected partial body: %q", body)
|
||||||
|
}
|
||||||
|
if got := registry.SourceError(url); !errors.Is(got, boom) {
|
||||||
|
t.Fatalf("expected source error %v, got %v", boom, got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("short known-size reader", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("short")), nil
|
||||||
|
}, &CreateOptions{Size: 10})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if got := registry.SourceError(url); !errors.Is(got, io.ErrUnexpectedEOF) {
|
||||||
|
t.Fatalf("expected unexpected EOF, got %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("range reader error becomes terminal", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
boom := errors.New("range reader failed")
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(io.MultiReader(strings.NewReader("partial"), &terminalErrorReader{err: boom})), nil
|
||||||
|
}, &CreateOptions{Size: 10, Range: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for attempt := 0; attempt < rangeSourceFailureLimit; attempt++ {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", "bytes=0-9")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}
|
||||||
|
if got := registry.SourceError(url); !errors.Is(got, boom) {
|
||||||
|
t.Fatalf("expected range source error %v, got %v", boom, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusGone {
|
||||||
|
t.Fatalf("expected terminal source status %d, got %d", http.StatusGone, resp.StatusCode)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("short range reader", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("short")), nil
|
||||||
|
}, &CreateOptions{Size: 10, Range: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for attempt := 0; attempt < rangeSourceFailureLimit; attempt++ {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", "bytes=0-9")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}
|
||||||
|
if got := registry.SourceError(url); !errors.Is(got, io.ErrUnexpectedEOF) {
|
||||||
|
t.Fatalf("expected range unexpected EOF, got %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("successful range retry clears transient failure", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
attempt := 0
|
||||||
|
boom := errors.New("transient range failure")
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
attempt++
|
||||||
|
if attempt == 1 {
|
||||||
|
return io.NopCloser(&terminalErrorReader{err: boom}), nil
|
||||||
|
}
|
||||||
|
return io.NopCloser(strings.NewReader("0123456789")), nil
|
||||||
|
}, &CreateOptions{Size: 10, Range: true})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", "bytes=0-9")
|
||||||
|
resp, err := http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_, _ = io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}
|
||||||
|
if got := registry.SourceError(url); got != nil {
|
||||||
|
t.Fatalf("successful retry left transient source error: %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("request cancellation is not a source error", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
opened := make(chan struct{})
|
||||||
|
url, err := registry.CreateOpener(func(ctx context.Context, _ OpenRequest) (io.ReadCloser, error) {
|
||||||
|
close(opened)
|
||||||
|
return &contextErrorReader{ctx: ctx}, nil
|
||||||
|
}, &CreateOptions{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
resp, _ := http.DefaultClient.Do(req)
|
||||||
|
if resp != nil {
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
}
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
<-opened
|
||||||
|
cancel()
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("cancelled request did not finish")
|
||||||
|
}
|
||||||
|
if got := registry.SourceError(url); got != nil {
|
||||||
|
t.Fatalf("request cancellation was recorded as source error: %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("nil reader", func(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return nil, nil
|
||||||
|
}, &CreateOptions{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusGone {
|
||||||
|
t.Fatalf("expected nil reader status %d, got %d", http.StatusGone, resp.StatusCode)
|
||||||
|
}
|
||||||
|
if got := registry.SourceError(url); !errors.Is(got, ErrSourceClosed) {
|
||||||
|
t.Fatalf("expected closed source error, got %v", got)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryDoesNotRecordResponseWriteError(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("payload")), nil
|
||||||
|
}, &CreateOptions{Size: 7})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
writerErr := errors.New("client connection closed")
|
||||||
|
registry.ServeHTTP(&failingResponseWriter{header: make(http.Header), err: writerErr}, req)
|
||||||
|
if got := registry.SourceError(url); got != nil {
|
||||||
|
t.Fatalf("response write error was recorded as a source error: %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryTaskReferencesShareSource(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateBlob([]byte("shared"), "text/plain")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := registry.Acquire(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := registry.Acquire(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := registry.Release(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !registry.IsURL(url) {
|
||||||
|
t.Fatal("the first task release revoked a source still used by another task")
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
body, readErr := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if readErr != nil || string(body) != "shared" {
|
||||||
|
t.Fatalf("unexpected shared response body %q, error %v", body, readErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := registry.Release(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if registry.IsURL(url) {
|
||||||
|
t.Fatal("the final task release did not revoke the source")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryUnclaimedSessionSourceExpires(t *testing.T) {
|
||||||
|
setUnclaimedSourceTTLForTest(t, 25*time.Millisecond)
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
session := newCountingSession()
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("unused")), nil
|
||||||
|
}, &CreateOptions{Size: 6, Session: session})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := session.RefCount(); got != 1 {
|
||||||
|
t.Fatalf("unexpected initial session ref count: %d", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-session.zero:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("unclaimed source did not expire")
|
||||||
|
}
|
||||||
|
if registry.IsURL(url) {
|
||||||
|
t.Fatal("expired source is still registered")
|
||||||
|
}
|
||||||
|
if got := session.RefCount(); got != 0 {
|
||||||
|
t.Fatalf("expired source retained its session: %d", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryAcquireStopsUnclaimedSourceExpiration(t *testing.T) {
|
||||||
|
const ttl = 25 * time.Millisecond
|
||||||
|
setUnclaimedSourceTTLForTest(t, ttl)
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
session := newCountingSession()
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("claimed")), nil
|
||||||
|
}, &CreateOptions{Size: 7, Session: session})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := registry.Acquire(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-session.zero:
|
||||||
|
t.Fatal("claimed source expired")
|
||||||
|
case <-time.After(4 * ttl):
|
||||||
|
}
|
||||||
|
if !registry.IsURL(url) {
|
||||||
|
t.Fatal("claimed source was removed")
|
||||||
|
}
|
||||||
|
if err := registry.Release(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-session.zero:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("final task release did not release the session")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryUnclaimedExpirationKeepsActiveReaderSession(t *testing.T) {
|
||||||
|
setUnclaimedSourceTTLForTest(t, 100*time.Millisecond)
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
session := newCountingSession()
|
||||||
|
reader, writer := io.Pipe()
|
||||||
|
opened := make(chan struct{})
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
close(opened)
|
||||||
|
return reader, nil
|
||||||
|
}, &CreateOptions{Size: 7, Session: session})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
body []byte
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
resultCh := make(chan result, 1)
|
||||||
|
go func() {
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
resultCh <- result{err: err}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
resultCh <- result{body: body, err: err}
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-opened:
|
||||||
|
case got := <-resultCh:
|
||||||
|
t.Fatalf("request ended before the opener ran: body %q, error %v", got.body, got.err)
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("active request did not open")
|
||||||
|
}
|
||||||
|
deadline := time.NewTimer(2 * time.Second)
|
||||||
|
ticker := time.NewTicker(5 * time.Millisecond)
|
||||||
|
defer deadline.Stop()
|
||||||
|
defer ticker.Stop()
|
||||||
|
for registry.IsURL(url) {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
case <-deadline.C:
|
||||||
|
t.Fatal("unclaimed source did not expire while its reader was active")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := session.RefCount(); got != 1 {
|
||||||
|
t.Fatalf("expiration released the active-reader session ref: %d", got)
|
||||||
|
}
|
||||||
|
if _, err := writer.Write([]byte("payload")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = writer.Close()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case got := <-resultCh:
|
||||||
|
if got.err != nil || string(got.body) != "payload" {
|
||||||
|
t.Fatalf("active response was interrupted: body %q, error %v", got.body, got.err)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("active response did not finish after source expiration")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-session.zero:
|
||||||
|
if got := session.RefCount(); got != 0 {
|
||||||
|
t.Fatalf("unexpected final session ref count: %d", got)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("active-reader session ref was not released")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryCloseCancelsUnclaimedExpiration(t *testing.T) {
|
||||||
|
const ttl = 25 * time.Millisecond
|
||||||
|
setUnclaimedSourceTTLForTest(t, ttl)
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
|
||||||
|
session := newCountingSession()
|
||||||
|
_, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
return io.NopCloser(strings.NewReader("unused")), nil
|
||||||
|
}, &CreateOptions{Size: 6, Session: session})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := registry.Close(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-session.zero:
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("registry close did not release the session")
|
||||||
|
}
|
||||||
|
<-time.After(4 * ttl)
|
||||||
|
if got := session.RefCount(); got != 0 {
|
||||||
|
t.Fatalf("expiration released the session again after close: %d", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryRevokeKeepsActiveReaderSession(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
session := newCountingSession()
|
||||||
|
reader, writer := io.Pipe()
|
||||||
|
opened := make(chan struct{})
|
||||||
|
url, err := registry.CreateOpener(func(context.Context, OpenRequest) (io.ReadCloser, error) {
|
||||||
|
close(opened)
|
||||||
|
return reader, nil
|
||||||
|
}, &CreateOptions{Size: 7, Session: session})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
type result struct {
|
||||||
|
body []byte
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
resultCh := make(chan result, 1)
|
||||||
|
go func() {
|
||||||
|
resp, err := http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
resultCh <- result{err: err}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
body, err := io.ReadAll(resp.Body)
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
resultCh <- result{body: body, err: err}
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-opened
|
||||||
|
if got := session.RefCount(); got != 2 {
|
||||||
|
t.Fatalf("expected source and active-reader session refs, got %d", got)
|
||||||
|
}
|
||||||
|
if err := registry.Revoke(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := session.RefCount(); got != 1 {
|
||||||
|
t.Fatalf("revoke released the active-reader session ref: %d", got)
|
||||||
|
}
|
||||||
|
if _, err := writer.Write([]byte("payload")); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = writer.Close()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case got := <-resultCh:
|
||||||
|
if got.err != nil || string(got.body) != "payload" {
|
||||||
|
t.Fatalf("active response was interrupted: body %q, error %v", got.body, got.err)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("active response did not finish after revoke")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-session.zero:
|
||||||
|
if got := session.RefCount(); got != 0 {
|
||||||
|
t.Fatalf("unexpected final session ref count: %d", got)
|
||||||
|
}
|
||||||
|
case <-time.After(2 * time.Second):
|
||||||
|
t.Fatal("active-reader session ref was not released")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegistryHTTPErrorStatuses(t *testing.T) {
|
||||||
|
registry := NewRegistry(t.TempDir())
|
||||||
|
defer registry.Close()
|
||||||
|
|
||||||
|
url, err := registry.CreateBlob([]byte("secret"), "text/plain")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
badURL := url + "-missing"
|
||||||
|
resp, err := http.Get(badURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusNotFound {
|
||||||
|
t.Fatalf("unexpected missing source status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(http.MethodHead, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp, err = http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusMethodNotAllowed {
|
||||||
|
t.Fatalf("unexpected method status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err = http.NewRequest(http.MethodGet, url, nil)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Range", "bytes=99-100")
|
||||||
|
resp, err = http.DefaultClient.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusRequestedRangeNotSatisfiable {
|
||||||
|
t.Fatalf("unexpected invalid range status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := registry.Revoke(url); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
resp, err = http.Get(url)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
_ = resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusNotFound {
|
||||||
|
t.Fatalf("unexpected revoked source status: %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if registry.IsURL(url) {
|
||||||
|
t.Fatal("revoked source should not be usable")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
package controller
|
package controller
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Controller struct {
|
type Controller struct {
|
||||||
GetConfig func(v any) (bool, error)
|
GetConfig func(v any)
|
||||||
|
GetProxy func(requestProxy *base.RequestProxy) func(*http.Request) (*url.URL, error)
|
||||||
FileController
|
FileController
|
||||||
//ContextDialer() (proxy.Dialer, error)
|
//ContextDialer() (proxy.Dialer, error)
|
||||||
}
|
}
|
||||||
@@ -21,10 +24,11 @@ type DefaultFileController struct {
|
|||||||
|
|
||||||
func NewController() *Controller {
|
func NewController() *Controller {
|
||||||
return &Controller{
|
return &Controller{
|
||||||
FileController: &DefaultFileController{},
|
GetConfig: func(v any) {},
|
||||||
GetConfig: func(v any) (bool, error) {
|
GetProxy: func(requestProxy *base.RequestProxy) func(*http.Request) (*url.URL, error) {
|
||||||
return false, nil
|
return requestProxy.ToHandler()
|
||||||
},
|
},
|
||||||
|
FileController: &DefaultFileController{},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,7 +38,7 @@ func (c *DefaultFileController) Touch(name string, size int64) (file *os.File, e
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
file, err = os.Create(name)
|
file, err = os.Create(name)
|
||||||
if err != nil && !errors.Is(err, os.ErrExist) {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if size > 0 {
|
if size > 0 {
|
||||||
|
|||||||
@@ -1,27 +1,29 @@
|
|||||||
package fetcher
|
package fetcher
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/GopeedLab/gopeed/internal/controller"
|
"github.com/GopeedLab/gopeed/internal/controller"
|
||||||
"github.com/GopeedLab/gopeed/pkg/base"
|
"github.com/GopeedLab/gopeed/pkg/base"
|
||||||
"path"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Fetcher defines the interface for a download protocol.
|
// Fetcher defines the interface for a download protocol.
|
||||||
// One fetcher for each download task
|
// Each download task will have a corresponding Fetcher instance for the management of the download task
|
||||||
type Fetcher interface {
|
type Fetcher interface {
|
||||||
// Name return the name of the protocol.
|
Setup(ctl *controller.Controller)
|
||||||
Name() string
|
Resolve(req *base.Request, opts *base.Options) error
|
||||||
|
|
||||||
Setup(ctl *controller.Controller) error
|
|
||||||
// Resolve resource info from request
|
|
||||||
Resolve(req *base.Request) error
|
|
||||||
// Create ready to download, but not started
|
|
||||||
Create(opts *base.Options) error
|
|
||||||
Start() error
|
Start() error
|
||||||
|
// Patch modifies task-specific data based on the protocol.
|
||||||
|
// For HTTP: can modify Request info (URL, headers, etc.)
|
||||||
|
// For BT: can modify SelectFiles (via opts.SelectFiles)
|
||||||
|
Patch(req *base.Request, opts *base.Options) error
|
||||||
Pause() error
|
Pause() error
|
||||||
Continue() error
|
|
||||||
Close() error
|
Close() error
|
||||||
|
|
||||||
|
// Stats returns both the durable protocol snapshot and transient runtime
|
||||||
|
// telemetry. Downloader persists Snapshot and keeps Runtime in memory only.
|
||||||
|
Stats() *Stats
|
||||||
// Meta returns the meta information of the download.
|
// Meta returns the meta information of the download.
|
||||||
Meta() *FetcherMeta
|
Meta() *FetcherMeta
|
||||||
// Progress returns the progress of the download.
|
// Progress returns the progress of the download.
|
||||||
@@ -30,6 +32,20 @@ type Fetcher interface {
|
|||||||
Wait() error
|
Wait() error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stats separates protocol information that remains meaningful after a task
|
||||||
|
// stops from telemetry that is valid only while the fetcher is active.
|
||||||
|
// Protocols own both payload schemas; Downloader treats them as opaque values.
|
||||||
|
type Stats struct {
|
||||||
|
Snapshot any `json:"snapshot"`
|
||||||
|
Runtime any `json:"runtime"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Uploader interface {
|
||||||
|
Upload() error
|
||||||
|
UploadedBytes() int64
|
||||||
|
WaitUpload() error
|
||||||
|
}
|
||||||
|
|
||||||
// FetcherMeta defines the meta information of a fetcher.
|
// FetcherMeta defines the meta information of a fetcher.
|
||||||
type FetcherMeta struct {
|
type FetcherMeta struct {
|
||||||
Req *base.Request `json:"req"`
|
Req *base.Request `json:"req"`
|
||||||
@@ -37,25 +53,102 @@ type FetcherMeta struct {
|
|||||||
Opts *base.Options `json:"opts"`
|
Opts *base.Options `json:"opts"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *FetcherMeta) Filepath(file *base.FileInfo) string {
|
// FolderPath return the folder path of the meta info.
|
||||||
finalName := m.Opts.Name
|
func (m *FetcherMeta) FolderPath() string {
|
||||||
if finalName == "" {
|
// check if rename folder
|
||||||
finalName = file.Name
|
folder := m.Res.Name
|
||||||
|
if m.Opts.Name != "" {
|
||||||
|
folder = m.Opts.Name
|
||||||
}
|
}
|
||||||
return path.Join(m.Opts.Path, m.Res.RootDir, finalName)
|
return path.Join(m.Opts.Path, folder)
|
||||||
}
|
}
|
||||||
|
|
||||||
// FetcherBuilder defines the interface for a fetcher builder.
|
// SingleFilepath return the single file path of the meta info.
|
||||||
type FetcherBuilder interface {
|
func (m *FetcherMeta) SingleFilepath() string {
|
||||||
// Schemes returns the schemes supported by the fetcher.
|
// check if rename file
|
||||||
Schemes() []string
|
file := m.Res.Files[0]
|
||||||
|
fileName := file.Name
|
||||||
|
if m.Opts.Name != "" {
|
||||||
|
fileName = m.Opts.Name
|
||||||
|
}
|
||||||
|
return path.Join(m.Opts.Path, file.Path, fileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RootDirPath return the root dir path of the task file.
|
||||||
|
func (m *FetcherMeta) RootDirPath() string {
|
||||||
|
if m.Res.Name != "" {
|
||||||
|
return m.FolderPath()
|
||||||
|
} else {
|
||||||
|
return m.Opts.Path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type FilterType int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// FilterTypeUrl url type, pattern is the scheme, e.g. http://github.com -> http
|
||||||
|
FilterTypeUrl FilterType = iota
|
||||||
|
// FilterTypeFile file type, pattern is the file extension name, e.g. test.torrent -> torrent
|
||||||
|
FilterTypeFile
|
||||||
|
// FilterTypeBase64 base64 data type, pattern is the data mime type, e.g. data:application/x-bittorrent;base64 -> application/x-bittorrent
|
||||||
|
FilterTypeBase64
|
||||||
|
)
|
||||||
|
|
||||||
|
type SchemeFilter struct {
|
||||||
|
Type FilterType
|
||||||
|
Pattern string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SchemeFilter) Match(uri string) bool {
|
||||||
|
uriUpper := strings.ToUpper(uri)
|
||||||
|
patternUpper := strings.ToUpper(s.Pattern)
|
||||||
|
switch s.Type {
|
||||||
|
case FilterTypeUrl:
|
||||||
|
return strings.HasPrefix(uriUpper, patternUpper+":")
|
||||||
|
case FilterTypeFile:
|
||||||
|
return strings.HasSuffix(uriUpper, "."+patternUpper)
|
||||||
|
case FilterTypeBase64:
|
||||||
|
return strings.HasPrefix(uriUpper, "DATA:"+patternUpper+";BASE64,")
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// FetcherManager manage and control the fetcher
|
||||||
|
type FetcherManager interface {
|
||||||
|
// Name return the name of the protocol.
|
||||||
|
Name() string
|
||||||
|
// Filters registers the supported schemes.
|
||||||
|
Filters() []*SchemeFilter
|
||||||
// Build returns a new fetcher.
|
// Build returns a new fetcher.
|
||||||
Build() Fetcher
|
Build() Fetcher
|
||||||
|
// ParseName name displayed when the task is not yet resolved, parsed from the request URL
|
||||||
|
ParseName(u string) string
|
||||||
|
// AutoRename returns whether the fetcher need renaming the download file when has the same name file.
|
||||||
|
AutoRename() bool
|
||||||
|
|
||||||
|
// DefaultConfig returns the default configuration of the protocol.
|
||||||
|
DefaultConfig() any
|
||||||
// Store fetcher
|
// Store fetcher
|
||||||
Store(fetcher Fetcher) (any, error)
|
Store(fetcher Fetcher) (any, error)
|
||||||
// Restore fetcher
|
// Restore fetcher
|
||||||
Restore() (v any, f func(meta *FetcherMeta, v any) Fetcher)
|
Restore() (v any, f func(meta *FetcherMeta, v any) Fetcher)
|
||||||
|
// Close the fetcher manager, release resources.
|
||||||
|
Close() error
|
||||||
|
}
|
||||||
|
|
||||||
|
// StatefulFetcherManager is an optional extension for protocols that keep
|
||||||
|
// shared client state outside individual task fetchers.
|
||||||
|
type StatefulFetcherManager interface {
|
||||||
|
SetStateStore(store ProtocolStateStore)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ProtocolStateStore persists shared protocol state for a fetcher manager.
|
||||||
|
// Downloader provides the concrete storage backend, while the protocol decides
|
||||||
|
// when state should be loaded or flushed.
|
||||||
|
type ProtocolStateStore interface {
|
||||||
|
Load(v any) (bool, error)
|
||||||
|
Save(v any) error
|
||||||
|
Delete() error
|
||||||
}
|
}
|
||||||
|
|
||||||
type DefaultFetcher struct {
|
type DefaultFetcher struct {
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
package fetcher
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestStatsMarshalRawSnapshotWithoutRuntime(t *testing.T) {
|
||||||
|
stats := &Stats{
|
||||||
|
Snapshot: json.RawMessage(`{"value":1}`),
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := json.Marshal(stats)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("Marshal() error = %v", err)
|
||||||
|
}
|
||||||
|
if got, want := string(data), `{"snapshot":{"value":1},"runtime":null}`; got != want {
|
||||||
|
t.Fatalf("Marshal() = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSchemeFilter_Match(t *testing.T) {
|
||||||
|
type fields struct {
|
||||||
|
Type FilterType
|
||||||
|
Pattern string
|
||||||
|
}
|
||||||
|
type args struct {
|
||||||
|
uri string
|
||||||
|
}
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
fields fields
|
||||||
|
args args
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "url match",
|
||||||
|
fields: fields{
|
||||||
|
Type: FilterTypeUrl,
|
||||||
|
Pattern: "https",
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
uri: "https://github.com",
|
||||||
|
},
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "url not match",
|
||||||
|
fields: fields{
|
||||||
|
Type: FilterTypeUrl,
|
||||||
|
Pattern: "https",
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
uri: "ftp://github.com",
|
||||||
|
},
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "file match",
|
||||||
|
fields: fields{
|
||||||
|
Type: FilterTypeFile,
|
||||||
|
Pattern: "torrent",
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
uri: "d:/temp/test.torrent",
|
||||||
|
},
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "file not match",
|
||||||
|
fields: fields{
|
||||||
|
Type: FilterTypeFile,
|
||||||
|
Pattern: "torrent",
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
uri: "d:/temp/test.txt",
|
||||||
|
},
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "base64 match",
|
||||||
|
fields: fields{
|
||||||
|
Type: FilterTypeBase64,
|
||||||
|
Pattern: "application/x-bittorrent",
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
uri: "data:application/x-bittorrent;base64,xxx",
|
||||||
|
},
|
||||||
|
want: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "base64 not match",
|
||||||
|
fields: fields{
|
||||||
|
Type: FilterTypeBase64,
|
||||||
|
Pattern: "application/x-bittorrent",
|
||||||
|
},
|
||||||
|
args: args{
|
||||||
|
uri: "data:application/javascript;base64,xxx",
|
||||||
|
},
|
||||||
|
want: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
s := &SchemeFilter{
|
||||||
|
Type: tt.fields.Type,
|
||||||
|
Pattern: tt.fields.Pattern,
|
||||||
|
}
|
||||||
|
if got := s.Match(tt.args.uri); got != tt.want {
|
||||||
|
t.Errorf("Match() = %v, want %v", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,346 @@
|
|||||||
|
package httpclient
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/imroc/req/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ImpersonationMode string
|
||||||
|
|
||||||
|
const (
|
||||||
|
ImpersonationNative ImpersonationMode = "native"
|
||||||
|
ImpersonationFixed ImpersonationMode = "fixed"
|
||||||
|
ImpersonationAuto ImpersonationMode = "auto"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Browser string
|
||||||
|
|
||||||
|
const (
|
||||||
|
BrowserChrome Browser = "chrome"
|
||||||
|
BrowserFirefox Browser = "firefox"
|
||||||
|
BrowserSafari Browser = "safari"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
Client ClientOptions
|
||||||
|
Transport TransportOptions
|
||||||
|
Impersonation ImpersonationOptions
|
||||||
|
}
|
||||||
|
|
||||||
|
type ClientOptions struct {
|
||||||
|
Jar http.CookieJar
|
||||||
|
CheckRedirect func(req *http.Request, via []*http.Request) error
|
||||||
|
Timeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type TransportOptions struct {
|
||||||
|
Proxy func(*http.Request) (*url.URL, error)
|
||||||
|
DialContext func(ctx context.Context, network, address string) (net.Conn, error)
|
||||||
|
TLSClientConfig *tls.Config
|
||||||
|
TLSHandshakeTimeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImpersonationOptions struct {
|
||||||
|
Mode ImpersonationMode
|
||||||
|
Browser Browser
|
||||||
|
Session *ImpersonationSession
|
||||||
|
}
|
||||||
|
|
||||||
|
type ImpersonationSession struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
selections map[string]impersonationSelection
|
||||||
|
}
|
||||||
|
|
||||||
|
type impersonationSelection struct {
|
||||||
|
browser Browser
|
||||||
|
fallbackDisabled bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewImpersonationSession() *ImpersonationSession {
|
||||||
|
return &ImpersonationSession{
|
||||||
|
selections: make(map[string]impersonationSelection),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ImpersonationSession) load(url string) (impersonationSelection, bool) {
|
||||||
|
s.mu.RLock()
|
||||||
|
defer s.mu.RUnlock()
|
||||||
|
selection, ok := s.selections[url]
|
||||||
|
return selection, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ImpersonationSession) store(url string, browser Browser) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.selections[url] = impersonationSelection{browser: browser}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ImpersonationSession) disableFallback(url string) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.selections[url] = impersonationSelection{fallbackDisabled: true}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *ImpersonationSession) Clear() {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
clear(s.selections)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewClient(options Options) (*http.Client, error) {
|
||||||
|
var transport http.RoundTripper
|
||||||
|
switch options.Impersonation.Mode {
|
||||||
|
case "", ImpersonationNative:
|
||||||
|
transport = newNativeTransport(options.Transport)
|
||||||
|
case ImpersonationFixed:
|
||||||
|
browserTransport, err := newBrowserTransport(options.Transport, options.Impersonation.Browser)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
transport = browserTransport
|
||||||
|
case ImpersonationAuto:
|
||||||
|
browserTransports := make(map[Browser]http.RoundTripper, 3)
|
||||||
|
for _, browser := range []Browser{BrowserChrome, BrowserFirefox, BrowserSafari} {
|
||||||
|
browserTransport, err := newBrowserTransport(options.Transport, browser)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
browserTransports[browser] = browserTransport
|
||||||
|
}
|
||||||
|
transport = &adaptiveTransport{
|
||||||
|
native: newNativeTransport(options.Transport),
|
||||||
|
browsers: browserTransports,
|
||||||
|
jar: options.Client.Jar,
|
||||||
|
session: options.Impersonation.Session,
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported impersonation mode %q", options.Impersonation.Mode)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &http.Client{
|
||||||
|
Transport: transport,
|
||||||
|
Jar: options.Client.Jar,
|
||||||
|
CheckRedirect: options.Client.CheckRedirect,
|
||||||
|
Timeout: options.Client.Timeout,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newNativeTransport(options TransportOptions) *http.Transport {
|
||||||
|
var tlsConfig *tls.Config
|
||||||
|
if options.TLSClientConfig != nil {
|
||||||
|
tlsConfig = options.TLSClientConfig.Clone()
|
||||||
|
}
|
||||||
|
return &http.Transport{
|
||||||
|
Proxy: options.Proxy,
|
||||||
|
DialContext: options.DialContext,
|
||||||
|
TLSClientConfig: tlsConfig,
|
||||||
|
TLSHandshakeTimeout: options.TLSHandshakeTimeout,
|
||||||
|
ForceAttemptHTTP2: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func newBrowserTransport(options TransportOptions, browser Browser) (http.RoundTripper, error) {
|
||||||
|
client := req.NewClient()
|
||||||
|
client.SetProxy(options.Proxy)
|
||||||
|
if options.DialContext != nil {
|
||||||
|
client.SetDial(options.DialContext)
|
||||||
|
}
|
||||||
|
client.SetTLSHandshakeTimeout(options.TLSHandshakeTimeout)
|
||||||
|
if options.TLSClientConfig != nil {
|
||||||
|
tlsConfig := options.TLSClientConfig.Clone()
|
||||||
|
if len(tlsConfig.NextProtos) == 0 {
|
||||||
|
tlsConfig.NextProtos = []string{"h2", "http/1.1"}
|
||||||
|
}
|
||||||
|
client.SetTLSClientConfig(tlsConfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch browser {
|
||||||
|
case BrowserChrome:
|
||||||
|
client.ImpersonateChrome()
|
||||||
|
case BrowserFirefox:
|
||||||
|
client.ImpersonateFirefox()
|
||||||
|
case BrowserSafari:
|
||||||
|
client.ImpersonateSafari()
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported browser %q", browser)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &defaultHeaderTransport{
|
||||||
|
next: client.GetClient().Transport,
|
||||||
|
defaults: client.Headers.Clone(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type defaultHeaderTransport struct {
|
||||||
|
next http.RoundTripper
|
||||||
|
defaults http.Header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *defaultHeaderTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||||
|
request = request.Clone(request.Context())
|
||||||
|
request.Header = request.Header.Clone()
|
||||||
|
for key, values := range t.defaults {
|
||||||
|
if len(request.Header.Values(key)) == 0 {
|
||||||
|
request.Header[key] = append([]string(nil), values...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return t.next.RoundTrip(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *defaultHeaderTransport) CloseIdleConnections() {
|
||||||
|
closeIdleConnections(t.next)
|
||||||
|
}
|
||||||
|
|
||||||
|
type adaptiveTransport struct {
|
||||||
|
native http.RoundTripper
|
||||||
|
browsers map[Browser]http.RoundTripper
|
||||||
|
jar http.CookieJar
|
||||||
|
session *ImpersonationSession
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *adaptiveTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||||
|
cacheKey := requestCacheKey(request.URL)
|
||||||
|
if t.session != nil {
|
||||||
|
if selected, ok := t.session.load(cacheKey); ok {
|
||||||
|
if selected.fallbackDisabled {
|
||||||
|
return t.native.RoundTrip(request)
|
||||||
|
}
|
||||||
|
return t.browsers[selected.browser].RoundTrip(request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := t.native.RoundTrip(request)
|
||||||
|
if !shouldFallback(response, err) {
|
||||||
|
return response, err
|
||||||
|
}
|
||||||
|
|
||||||
|
retry, ok := cloneRequestForRetry(request)
|
||||||
|
if !ok {
|
||||||
|
return response, err
|
||||||
|
}
|
||||||
|
if response != nil {
|
||||||
|
applyResponseCookies(t.jar, request, retry, response)
|
||||||
|
_ = response.Body.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
browser := browserFromUserAgent(request.UserAgent())
|
||||||
|
response, err = t.browsers[browser].RoundTrip(retry)
|
||||||
|
if t.session != nil {
|
||||||
|
if isSuccessfulFallback(response, err) {
|
||||||
|
t.session.store(cacheKey, browser)
|
||||||
|
} else if err == nil && response != nil {
|
||||||
|
t.session.disableFallback(cacheKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return response, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func requestCacheKey(requestURL *url.URL) string {
|
||||||
|
cacheURL := *requestURL
|
||||||
|
cacheURL.Fragment = ""
|
||||||
|
cacheURL.RawFragment = ""
|
||||||
|
return cacheURL.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyResponseCookies(jar http.CookieJar, request, retry *http.Request, response *http.Response) {
|
||||||
|
if jar == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
jar.SetCookies(request.URL, response.Cookies())
|
||||||
|
jarCookies := jar.Cookies(request.URL)
|
||||||
|
jarCookieNames := make(map[string]struct{}, len(jarCookies))
|
||||||
|
for _, cookie := range jarCookies {
|
||||||
|
jarCookieNames[cookie.Name] = struct{}{}
|
||||||
|
}
|
||||||
|
existingCookies := retry.Cookies()
|
||||||
|
retry.Header.Del("Cookie")
|
||||||
|
for _, cookie := range existingCookies {
|
||||||
|
if _, replaced := jarCookieNames[cookie.Name]; !replaced {
|
||||||
|
retry.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, cookie := range jarCookies {
|
||||||
|
retry.AddCookie(cookie)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *adaptiveTransport) CloseIdleConnections() {
|
||||||
|
closeIdleConnections(t.native)
|
||||||
|
for _, transport := range t.browsers {
|
||||||
|
closeIdleConnections(transport)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeIdleConnections(transport http.RoundTripper) {
|
||||||
|
if closer, ok := transport.(interface{ CloseIdleConnections() }); ok {
|
||||||
|
closer.CloseIdleConnections()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func shouldFallback(response *http.Response, err error) bool {
|
||||||
|
if err != nil {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if response == nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return response.StatusCode == http.StatusForbidden ||
|
||||||
|
strings.EqualFold(response.Header.Get("Cf-Mitigated"), "challenge")
|
||||||
|
}
|
||||||
|
|
||||||
|
func isSuccessfulFallback(response *http.Response, err error) bool {
|
||||||
|
return err == nil && response != nil &&
|
||||||
|
response.StatusCode >= http.StatusOK &&
|
||||||
|
response.StatusCode < http.StatusBadRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneRequestForRetry(request *http.Request) (*http.Request, bool) {
|
||||||
|
if !isIdempotent(request) {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
retry := request.Clone(request.Context())
|
||||||
|
if request.Body == nil || request.Body == http.NoBody {
|
||||||
|
return retry, true
|
||||||
|
}
|
||||||
|
if request.GetBody == nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
body, err := request.GetBody()
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
retry.Body = body
|
||||||
|
return retry, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func isIdempotent(request *http.Request) bool {
|
||||||
|
switch request.Method {
|
||||||
|
case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return request.Header.Get("Idempotency-Key") != "" ||
|
||||||
|
request.Header.Get("X-Idempotency-Key") != ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func browserFromUserAgent(userAgent string) Browser {
|
||||||
|
userAgent = strings.ToLower(userAgent)
|
||||||
|
switch {
|
||||||
|
case strings.Contains(userAgent, "firefox"):
|
||||||
|
return BrowserFirefox
|
||||||
|
case strings.Contains(userAgent, "safari") &&
|
||||||
|
!strings.Contains(userAgent, "chrome") &&
|
||||||
|
!strings.Contains(userAgent, "chromium"):
|
||||||
|
return BrowserSafari
|
||||||
|
default:
|
||||||
|
return BrowserChrome
|
||||||
|
}
|
||||||
|
}
|
||||||