Compare commits

..
874 changed files with 76952 additions and 7772 deletions

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
+20 -8
View File
@@ -13,7 +13,7 @@ on:
default: "false"
env:
GO_VERSION: "1.25"
GO_VERSION: "1.25.4"
FLUTTER_VERSION: "3.41.6"
GA4_MEASUREMENT_ID: ${{ secrets.GA4_MEASUREMENT_ID }}
GA4_API_SECRET: ${{ secrets.GA4_API_SECRET }}
@@ -93,7 +93,7 @@ jobs:
VERSION: ${{ needs.get-release.outputs.version }}
GOARCH: ${{ matrix.arch }}
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\"
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
@@ -407,13 +407,17 @@ jobs:
overwrite: true
build-snap:
if: ${{ github.event.inputs.platform == 'all' || github.event.inputs.platform == 'snap' }}
runs-on: ubuntu-latest
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:
@@ -477,6 +481,8 @@ jobs:
\$CRAFT_PART_INSTALL/usr/bin/flutter doctor
build-packages:
- clang
- llvm-18
- lld
- cmake
- curl
- libgtk-3-dev
@@ -505,6 +511,9 @@ jobs:
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/
@@ -687,12 +696,15 @@ jobs:
VERSION: ${{ needs.get-release.outputs.version }}
run: |
sudo apt update -y
sudo apt install -y pv bsdmainutils
wget -O qdk2_0.32.bionic_amd64.deb "https://github.com/qnap-dev/qdk2/releases/download/v0.32/qdk2_0.32.bionic_amd64.deb"
dpkg -X qdk2_0.32.bionic_amd64.deb qdk2 # Direct installs will fail due to missing dependencies!
[[ -d qdk2 ]] || exit 1
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
export PATH=$(pwd)/qdk2/usr/bin:$(pwd)/qdk2/usr/share/qdk2/QDK/bin:${PATH}
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
+50
View File
@@ -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
+1 -1
View File
@@ -17,7 +17,7 @@ on:
- "Dockerfile"
env:
GO_VERSION: "1.25"
GO_VERSION: "1.25.4"
permissions:
contents: write
+104
View File
@@ -0,0 +1,104 @@
// 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.
// - Every locale has exactly the same message keys as app_en.arb.
// - Every translation preserves the placeholder variables used by app_en.arb.
//
// 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.
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) {
stderr.writeln('${file.path}: empty messages $empty');
failed = true;
}
if (file.path == templateFile.path) continue;
final missing = templateKeys.difference(keys);
final extra = keys.difference(templateKeys);
if (missing.isNotEmpty || extra.isNotEmpty) {
stderr.writeln(
'${file.path}: missing ${missing.toList()..sort()}, extra ${extra.toList()..sort()}',
);
failed = true;
}
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)) {
stderr.writeln(
'${file.path}: $key placeholders $actual do not match $expected',
);
failed = true;
}
}
}
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);
@@ -10,7 +10,7 @@
// (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 message.dart)
// - 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.
@@ -23,15 +23,18 @@ import 'dart:io';
/// 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 lang = locale.toLowerCase().split('_').first;
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 (locale.contains('cn') || locale.contains('sg')) {
return {'notosanssc'}; // Simplified Chinese
if (normalizedLocale.contains('_tw') ||
normalizedLocale.contains('_hk') ||
normalizedLocale.contains('_mo')) {
return {'notosanstc', 'notosanshk'}; // Traditional Chinese (TW, HK, 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
@@ -95,29 +98,25 @@ const _baseFontFamilies = <String>{
// to reduce bundle size. Add them back if emoji support is needed.
};
/// Parse supported locales from message.dart file.
/// Reads the import statements and extracts locale codes like 'zh_cn', 'en_us', etc.
Set<String> _parseSupportedLocales(File messageFile) {
/// 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 (!messageFile.existsSync()) {
_fail('Warning: message.dart not found, only base fonts will be used');
if (!l10nDirectory.existsSync()) {
_fail('Localization directory not found: ${l10nDirectory.path}');
}
final content = messageFile.readAsStringSync();
// Match import statements like: import 'langs/zh_cn.dart';
final importRegex = RegExp(r"import\s+'langs/(\w+)\.dart'");
for (final match in importRegex.allMatches(content)) {
final locale = match.group(1);
if (locale != null) {
locales.add(locale);
}
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(
'Warning: No locales found in message.dart, only base fonts will be used');
_fail('No app_<locale>.arb files found in ${l10nDirectory.path}');
}
return locales;
@@ -139,7 +138,9 @@ Set<String> _getRequiredFontFamilies(Set<String> locales) {
/// 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) {
String fontPath,
Set<String> requiredFamilies,
) {
// Extract font family from path (first segment before '/')
final slashIndex = fontPath.indexOf('/');
if (slashIndex == -1) {
@@ -158,10 +159,9 @@ Future<void> main(List<String> args) async {
// but will also try to locate pubspec.yaml by walking up.
final flutterDir = _findFlutterProjectRoot(Directory.current);
// Parse supported locales from message.dart
final messageFile =
File(_join(flutterDir.path, 'lib', 'i18n', 'message.dart'));
final supportedLocales = _parseSupportedLocales(messageFile);
// 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
@@ -203,7 +203,8 @@ Future<void> main(List<String> args) async {
if (p.contains('://') || p.startsWith('data:')) continue;
if (p.startsWith('/') ||
p.startsWith('assets/') ||
p.startsWith('packages/')) continue;
p.startsWith('packages/'))
continue;
if (p.contains('..')) continue;
relAssetsUnderS.add(p);
}
+23 -4
View File
@@ -28,7 +28,7 @@ on:
workflow_dispatch:
env:
GO_VERSION: "1.25"
GO_VERSION: "1.25.4"
FLUTTER_VERSION: "3.41.6"
jobs:
@@ -91,7 +91,7 @@ jobs:
flutter-version: ${{ env.FLUTTER_VERSION }}
- name: Test webview
if: runner.os == 'Windows'
run: go test -tags webview -v -timeout 300s ./internal/webview/goprovider/
run: go test -tags webview -v -count=1 -timeout 300s ./internal/webview/goprovider/
env:
CGO_ENABLED: 1
- name: Test webview
@@ -107,7 +107,7 @@ jobs:
cd ui/flutter
flutter pub get
flutter run -d macos >"$LOG_PATH" 2>&1 &
flutter run --machine -d macos >"$LOG_PATH" 2>&1 &
FLUTTER_PID=$!
cd ../..
@@ -116,7 +116,26 @@ jobs:
}
trap cleanup EXIT
if ! go test -tags webview -v -timeout 600s ./internal/webview/rpcprovider/ -args -webview-rpc-network unix -webview-rpc-address "$SOCKET_PATH"; then
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
+54 -5
View File
@@ -17,11 +17,60 @@ start the front-end flutter project in `debug` mode to run.
## Translation
The internationalization files of Gopeed are located in the `ui/flutter/lib/i18n/langs` directory.
You only need to add the corresponding language file in this directory.
Flutter translations are ARB files in `ui/flutter/lib/l10n`. Use `app_en.arb` as the source template,
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.
Please refer to `en_us.dart` for translation.
words prefixed with `@` are not meant to be translated.
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.
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:
```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
@@ -31,4 +80,4 @@ Turn on build_runner watcher if you want to edit api/models:
```
flutter pub run build_runner watch
```
```
+51 -3
View File
@@ -17,10 +17,58 @@
## 翻訳
Gopeed の国際化ファイルは `ui/flutter/lib/i18n/langs` ディレクトリにあります。
このディレクトリに対応する言語ファイルを追加するだけでよいです。
Flutter の翻訳ファイルは `ui/flutter/lib/l10n` にあります。`app_en.arb` を原文テンプレートとして、
`app_<locale>.arb`(例: `app_de.arb`、`app_zh_TW.arb`)を編集または追加してください。すべての言語で
英語テンプレートと同じメッセージ key が必要です。
翻訳については `en_us.dart` を参照してください。
翻訳するのはメッセージ値だけです。`{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 での開発
+53 -3
View File
@@ -17,10 +17,60 @@ khởi động dự án flutter frontend trong chế độ `debug` để chạy.
## Dịch thuật
Các tệp quốc tế hóa của Gopeed được đặt trong thư mục `ui/flutter/lib/i18n/langs`.
Bạn chỉ cần thêm tệp ngôn ngữ tương ứng trong thư mục này.
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.
Vui lòng tham khảo `en_us.dart` để biết cách dịch thuật.
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
+50 -4
View File
@@ -13,10 +13,57 @@ PR,合并到 `main` 分支。
flutter 项目即可运行。
## 翻译
Gopeed 的国际化文件位于 `ui/flutter/lib/i18n/langs` 目录下,只需要在该目录下添加对应的语言文件即可。
请注意以 `en_us.dart` 为参照进行翻译。
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开发
@@ -27,4 +74,3 @@ Gopeed 的国际化文件位于 `ui/flutter/lib/i18n/langs` 目录下,只需
```
flutter pub run build_runner watch
```
+49 -3
View File
@@ -11,11 +11,57 @@
建議使用 web 端進行開發與調試,首先啟動服務,使用指令 `go run cmd/api/main.go` 啟動 ,該服務默認連接埠為 `9999`,接著以 `debug` 模式啟動前端 flutter 項目即可。
## 翻譯
Gopeed 的翻譯文件位於 `ui/flutter/lib/i18n/langs` 目錄中,只需要修改或新建翻譯文件即可。
Flutter 翻譯檔位於 `ui/flutter/lib/l10n`,請以 `app_en.arb` 為來源範本,修改或新增
`app_<locale>.arb`(例如 `app_de.arb` 或 `app_zh_TW.arb`)。每個語言都必須與英文範本包含相同的訊息 key。
請以 `en_us.dart` 作為參照。
只翻譯訊息值,不要修改 `{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開發
+72 -171
View File
@@ -10,166 +10,71 @@
<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>
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](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)
## 🚀 Introduction
Gopeed (full name Go Speed), a high-speed downloader developed by `Golang` + `Flutter`, supports (HTTP, BitTorrent, Magnet, ED2K) protocol, and supports all platforms. In addition to basic download functions, Gopeed is also a highly customizable downloader that supports implementing more features through integration with [APIs](https://gopeed.com/docs/dev-api) or installation and development of [extensions](https://gopeed.com/docs/dev-extension).
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.
Visit ✈ [Official Website](https://gopeed.com) | 📖 [Official Docs](https://gopeed.com/docs)
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)
![Application screenshot](_docs/img/ui-concept-en.png)
## ✨ Features
- ⚡ **High-speed downloads** — combine concurrent tasks, multi-connection HTTP transfers, and peer-to-peer BitTorrent downloads to make the most of your bandwidth.
- 🧲 **Multiple protocols** — download HTTP/HTTPS files, torrents, magnet links, and ed2k resources from a single app.
- 🌱 **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.
- 📋 **Flexible task management** — pause, resume, retry, run batch operations, search, filter by status, organize with categories, and recover tasks after a restart.
- 🪶 **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.
- 💻 **Cross-platform** — available for Windows, macOS, Linux, Android, iOS, and the web, with Docker and QNAP deployment options.
- 🎨 **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.
## 🤖 AI Integration
Connect Gopeed to an AI agent and manage downloads with natural language. For example, you can say:
> Download the latest Gopeed client for Windows.
| 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
<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-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-windows-amd64-portable.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-macos.dmg">📥</a></td>
</tr>
<tr>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-macos-amd64.dmg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.deb">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.AppImage">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-android.apk">📥</a></td>
</tr>
<tr>
<td>armeabi-v7a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-armeabi-v7a.apk">📥</a></td>
</tr>
<tr>
<td>arm64-v8a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-arm64-v8a.apk">📥</a></td>
</tr>
<tr>
<td>x86_64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$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-$version-qnap-amd64.qpkg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-$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-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-windows-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-macos-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-linux-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-386.zip">📥</a></td>
</tr>
</tbody>
</table>
### 🧪 Gopeed 2.0.0 Beta
More about installation, please refer to [Installation](https://gopeed.com/docs/install)
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.
### 🛠️ Command tool
- [Download Gopeed 2.0.0 Beta 1](https://github.com/GopeedLab/gopeed/releases/tag/v2.0.0-beta.1)
use `go install`:
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
go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
@@ -177,32 +82,28 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
## 🔌 Browser Extension
Gopeed also provides a browser extension to take over browser downloads, supporting browsers such as Chrome, Edge, Firefox, etc., please refer to: [https://github.com/GopeedLab/browser-extension](https://github.com/GopeedLab/browser-extension)
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)
## 📱 WeChat Official Account
Follow our WeChat Official Account to get the latest updates and news.
Follow Gopeed's official WeChat account for updates and news.
<img src="_docs/img/weixin.png" width="200" />
## 💝 Donate
If you like this project, please consider [donating](https://gopeed.com/docs/donate) to support the development of this project, thank you!
## 🖼️ Showcase
![](_docs/img/ui-demo.png)
If Gopeed is useful to you, please consider [supporting its development](https://gopeed.com/docs/donate). Thank you!
## 👨‍💻 Development
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.
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.
> The front code is located in the `ui/flutter` directory.
> The front-end source is located in the `ui/flutter` directory.
### 🌍 Environment
1. Golang 1.25+
2. Flutter 3.38+
1. Go 1.25+
2. Flutter 3.41+
### 📋 Clone
@@ -212,17 +113,17 @@ git clone [email protected]:GopeedLab/gopeed.git
### 🤝 Contributing
Please refer to [CONTRIBUTING.md](/CONTRIBUTING.md)
See [CONTRIBUTING.md](/CONTRIBUTING.md).
### 🏗️ Build
#### 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
go build -tags nosqlite -ldflags="-w -s" -buildmode=c-shared -o ui/flutter/windows/libgopeed.dll github.com/GopeedLab/gopeed/bind/desktop
@@ -230,7 +131,7 @@ cd ui/flutter
flutter build windows
```
- macos
- 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
@@ -238,7 +139,7 @@ cd ui/flutter
flutter build macos
```
- linux
- 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
@@ -248,7 +149,7 @@ flutter build linux
#### 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
go install golang.org/x/mobile/cmd/gomobile@latest
@@ -256,9 +157,9 @@ go get golang.org/x/mobile/bind
gomobile init
```
command:
Commands:
- android
- 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
@@ -266,7 +167,7 @@ cd ui/flutter
flutter build apk
```
- ios
- iOS
```bash
gomobile bind -tags nosqlite -ldflags="-w -s" -o ui/flutter/ios/Frameworks/Libgopeed.xcframework -target=ios github.com/GopeedLab/gopeed/bind/mobile
@@ -276,7 +177,7 @@ flutter build ios --no-codesign
#### Web
command:
Build the web app and server:
```bash
cd ui/flutter
+54 -144
View File
@@ -10,153 +10,67 @@
<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>
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](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)
## 🚀 はじめに
Gopeed (正式名 Go Speed) は `Golang` + `Flutter` によって開発された高速ダウンローダーで、(HTTP、BitTorrent、Magnet、ED2K) プロトコルをサポートし、すべてのプラットフォームをサポートします。基本的なダウンロード機能に加え、[APIs](https://gopeed.com/docs/dev-api)との連動や[拡張機能](https://gopeed.com/docs/dev-extension)のインストール・開発による追加機能にも対応した、カスタマイズ性の高いダウンローダーです。
Gopeed(**Go Speed** の略)は、Go と Flutter で開発された高速でモダンな無料オープンソース・ダウンロードマネージャーです。HTTP、HTTPS、BitTorrent、Magnet、ed2k に対応し、デスクトップ、モバイル、Web で利用できます。
見て下さい ✈ [公式ウェブサイト](https://gopeed.com) | 📖 [開発ドキュメント](https://gopeed.com/docs)
ブラウザー連携、JavaScript 拡張、REST API、CLI、セルフホスト可能な Web UI により、日常利用から高度な自動化まで幅広く対応します。
✈ [公式サイト](https://gopeed.com)
![アプリのスクリーンショット](_docs/img/ui-concept-en.png)
## ✨ 主な機能
- ⚡ **高速ダウンロード** — 複数タスク、HTTP のマルチ接続分割転送、BitTorrent の P2P ダウンロードで帯域を最大限に活用します。
- 🧲 **マルチプロトコル** — HTTP、HTTPS、BitTorrent、Magnet、ed2k を一つの画面で管理します。
- 🌱 **充実した BT 機能** — DHT によるピア検出、uTP 転送、Web Seed、ファイル選択、Tracker 管理、Peer/ピース統計、共有率または時間によるシード制御。
- 📋 **タスク管理** — 一時停止、再開、再試行、一括操作、検索、状態フィルター、カテゴリ、起動時復元。
- 🪶 **軽量なネイティブ体験** — メイン UI は Flutter でネイティブ描画。Electron 非採用。WebView ラッパーでもありません。パッケージサイズと実行時オーバーヘッドを抑え、軽快な応答性を実現します。
- 💻 **クロスプラットフォーム** — Windows、macOS、Linux、Android、iOS、Web、Docker、QNAP に対応。
- 🎨 **カスタマイズ可能なテーマ** — システム連動、ライト、ダークの各モードと 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 ミラー、通知、自動展開。
## 🤖 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` | タスクを削除し、必要に応じてダウンロード済みファイルも削除します。 |
## ⬇️ インストール
<table>
<tbody>
<tr>
<td rowspan="2">🪟 Windows</td>
<td><code>EXE</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td><code>Portable</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64-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-$version-macos.dmg">📥</a></td>
</tr>
<tr>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-macos-amd64.dmg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.deb">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.AppImage">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-android.apk">📥</a></td>
</tr>
<tr>
<td>armeabi-v7a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-armeabi-v7a.apk">📥</a></td>
</tr>
<tr>
<td>arm64-v8a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-arm64-v8a.apk">📥</a></td>
</tr>
<tr>
<td>x86_64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$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-$version-qnap-amd64.qpkg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-$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-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-windows-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-macos-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-linux-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-386.zip">📥</a></td>
</tr>
</tbody>
</table>
インストールについての詳細は、[インストール](https://gopeed.com/docs/install)を参照してください。
### 🧪 Gopeed 2.0.0 Beta
Gopeed 2.0.0 は現在パブリックベータ版です。刷新されたインターフェース、デスクトップおよびモバイルから 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 正式版を公開します。ベータ版のユーザーは正式版へ直接アップデートできます。既存の安定版ユーザーが自動的にベータチャンネルへ移行することはありません。
### 安定版
- [公式サイトからダウンロード](https://gopeed.com)
- [GitHub Releases](https://github.com/GopeedLab/gopeed/releases/latest)
### 🛠️ コマンドツール
@@ -170,10 +84,6 @@ Gopeed (正式名 Go Speed) は `Golang` + `Flutter` によって開発された
もしこのプロジェクトがお気に召しましたら、このプロジェクトの発展を支援するために[寄付](https://gopeed.com/docs/donate)をご検討ください!
## 🖼️ ショーケース
![](_docs/img/ui-demo.png)
## 👨‍💻 開発
このプロジェクトは二つの部分に分かれており、フロントエンドでは `flutter` を、バックエンドでは `Golang` を使用し、両者は `http` プロトコルで通信する。ユニックスシステムでは `unix socket` を、ウィンドウズシステムでは `tcp` プロトコルを使用します。
@@ -183,7 +93,7 @@ Gopeed (正式名 Go Speed) は `Golang` + `Flutter` によって開発された
### 🌍 環境
1. Go 言語 1.25+
2. Flutter 3.38+
2. Flutter 3.41+
### 📋 クローン
+54 -144
View File
@@ -10,153 +10,67 @@
<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>
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](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)
## 🚀 Giới thiệu
Gopeed (tên đầy đủ Go Speed), một công cụ tải xuống tốc độ cao được phát triển bởi `Golang` + `Flutter`, hỗ trợ giao thức (HTTP, BitTorrent, Magnet, ED2K) và hỗ trợ tất cả các nền tảng. Ngoài các chức năng tải xuống cơ bản, Gopeed còn là một công cụ tải xuống có thể tùy chỉnh cao cho phép triển khai thêm tính năng thông qua việc tích hợp với [APIs](https://gopeed.com/docs/dev-api) hoặc cài đặt và phát triển các [tiện ích mở rộng](https://gopeed.com/docs/dev-extension).
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.
Truy cập ✈ [Trang web chính thức](https://gopeed.com) | 📖 [Tài liệu chính thức](https://gopeed.com/docs)
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)
![Ảnh chụp màn hình ứng dụng](_docs/img/ui-concept-en.png)
## ✨ 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ề
<table>
<tbody>
<tr>
<td rowspan="2">🪟 Windows</td>
<td><code>EXE</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td><code>Portable</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64-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-$version-macos.dmg">📥</a></td>
</tr>
<tr>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-macos-amd64.dmg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.deb">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.AppImage">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-android.apk">📥</a></td>
</tr>
<tr>
<td>armeabi-v7a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-armeabi-v7a.apk">📥</a></td>
</tr>
<tr>
<td>arm64-v8a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-arm64-v8a.apk">📥</a></td>
</tr>
<tr>
<td>x86_64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$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-$version-qnap-amd64.qpkg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-$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-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-windows-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-macos-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-linux-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-386.zip">📥</a></td>
</tr>
</tbody>
</table>
Thêm thông tin về cài đặt, vui lòng tham khảo [Cài đặt](https://gopeed.com/docs/install)
### 🧪 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
@@ -176,10 +90,6 @@ Theo dõi tài khoản chính thức để nhận các cập nhật và tin tứ
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!
## 🖼️ Trưng bày
![](_docs/img/ui-demo.png)
## 👨‍💻 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`.
@@ -189,7 +99,7 @@ Dự án này được chia thành hai phần, phần giao diện sử dụng `f
### 🌍 Environment
1. Golang 1.25+
2. Flutter 3.38+
2. Flutter 3.41+
### 📋 Clone
+54 -144
View File
@@ -10,153 +10,67 @@
<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>
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](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)
## 🚀 介绍
Gopeed(全称 Go Speed),直译过来中文名叫做`够快下载器`(不是狗屁下载器!),是一款由`Golang`+`Flutter`开发的高速下载器,支持(HTTP、BitTorrent、Magnet、ED2K)协议下载,并且支持全平台使用。除了基本的下载功能外,Gopeed 还是一款高度可定制化的下载器,支持通过对接[APIs](https://gopeed.com/docs/dev-api)或者安装和开发[扩展](https://gopeed.com/docs/dev-extension)来实现更多的功能。
Gopeed(全称 **Go Speed**,也叫“够快下载器”)是一款使用 Go 和 Flutter 开发的高速、现代、免费开源下载器,支持 HTTP、HTTPS、BitTorrent、磁力链接和 ed2k,并覆盖桌面端、移动端与 Web。
访问 ✈ [官方网站](https://gopeed.com/zh-CN) | 📖 [官方文档](https://gopeed.com/docs)
除了日常下载任务管理,Gopeed 还提供浏览器接管、JavaScript 扩展、REST API、命令行工具和可自托管 Web UI,方便高级用户扩展和自动化自己的下载流程。
访问 ✈ [官方网站](https://gopeed.com)
![应用截图](_docs/img/ui-concept-zh-CN.png)
## ✨ 主要特性
- ⚡ **高速下载** — 多任务并发、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 等兼容浏览器,将下载任务直接发送到 Gopeed。
- 🧩 **JavaScript 扩展** — 扩展视频网站、AI 模型站、网盘等更多下载源。
- 🤖 **AI 接入** — 开放 MCP 接口,可接入 AI Agent,通过自然语言创建、查询和管理下载任务。
- 🔌 **开放接口** — 通过 REST API、CLI、带身份认证的 Web UI、Webhook 和下载后脚本进行自动化。
- 🛠️ **常用内置能力** — 自定义 Header 与 User-Agent、代理、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` | 删除任务,并可选择同时删除已下载文件。 |
## ⬇️ 下载
<table>
<tbody>
<tr>
<td rowspan="2">🪟 Windows</td>
<td><code>EXE</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td><code>Portable</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64-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-$version-macos.dmg">📥</a></td>
</tr>
<tr>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-macos-amd64.dmg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.deb">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.AppImage">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-android.apk">📥</a></td>
</tr>
<tr>
<td>armeabi-v7a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-armeabi-v7a.apk">📥</a></td>
</tr>
<tr>
<td>arm64-v8a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-arm64-v8a.apk">📥</a></td>
</tr>
<tr>
<td>x86_64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$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-$version-qnap-amd64.qpkg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-$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-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-windows-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-macos-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-linux-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-386.zip">📥</a></td>
</tr>
</tbody>
</table>
更多关于安装的内容请参考[安装文档](https://gopeed.com/docs/install)
### 🧪 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)
### 🛠️ 命令行工具
@@ -180,10 +94,6 @@ Gopeed 还提供了浏览器扩展用于接管浏览器下载,支持 Chrome、
如果觉得项目对你有帮助,请考虑[赞助](https://gopeed.com/docs/donate)以支持这个项目的发展,非常感谢!
## 🖼️ 界面展示
![](_docs/img/ui-demo.png)
## 👨‍💻 开发
本项目分为前端和后端两个部分,前端使用`flutter`,后端使用`Golang`,两边通过`http`协议进行通讯,在 unix 系统下,使用的是`unix socket`,在 windows 系统下,使用的是`tcp`协议。
@@ -193,7 +103,7 @@ Gopeed 还提供了浏览器扩展用于接管浏览器下载,支持 Chrome、
### 🌍 环境要求
1. Golang 1.25+
2. Flutter 3.38+
2. Flutter 3.41+
### 📋 克隆项目
+53 -144
View File
@@ -10,154 +10,67 @@
<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>
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](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)
## 🚀 簡介
Gopeed(全稱 Go Speed),是一款使用`Golang`+`Flutter`編寫的高速下載軟體,支援(HTTP、BitTorrent、Magnet、ED2K)協定,同時支援所有的平台。
Gopeed(**Go Speed** 的縮寫)是一款以 Go 與 Flutter 開發的高速、現代化、免費開源下載器,支援 HTTP、HTTPS、BitTorrent、磁力連結與 ed2k,並涵蓋桌面、行動裝置及 Web。
前往 ✈ [主頁](https://gopeed.com/zh-CN) | 📖 [文檔](https://gopeed.com/docs)
除了日常任務管理,Gopeed 也提供瀏覽器整合、JavaScript 擴充、REST API、命令列工具及可自行託管的 Web UI,方便進階使用者擴充與自動化下載流程。
瀏覽 ✈ [官方網站](https://gopeed.com)
![應用程式截圖](_docs/img/ui-concept-en.png)
## ✨ 主要功能
- ⚡ **高速下載** — 多任務並行、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` | 刪除任務,並可選擇同時刪除已下載檔案。 |
## ⬇️ 下載
<table>
<tbody>
<tr>
<td rowspan="2">🪟 Windows</td>
<td><code>EXE</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td><code>Portable</code></td>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-windows-amd64-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-$version-macos.dmg">📥</a></td>
</tr>
<tr>
<td>amd64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-macos-amd64.dmg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.deb">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-linux-amd64.AppImage">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$version-android.apk">📥</a></td>
</tr>
<tr>
<td>armeabi-v7a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-armeabi-v7a.apk">📥</a></td>
</tr>
<tr>
<td>arm64-v8a</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$version-android-arm64-v8a.apk">📥</a></td>
</tr>
<tr>
<td>x86_64</td>
<td><a href="https://gopeed.com/api/download?tpl=Gopeed-$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-$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-$version-qnap-amd64.qpkg">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-$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-$version-windows-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-windows-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-macos-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$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-$version-linux-amd64.zip">📥</a></td>
</tr>
<tr>
<td>arm64</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-arm64.zip">📥</a></td>
</tr>
<tr>
<td>386</td>
<td><a href="https://gopeed.com/api/download?tpl=gopeed-web-$version-linux-386.zip">📥</a></td>
</tr>
</tbody>
</table>
### 🧪 Gopeed 2.0.0 Beta
更多關於安裝的內容請參考[安裝文檔](https://gopeed.com/docs/install)
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 安裝
@@ -177,10 +90,6 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
如果你認為該項目對你有所幫助,請考慮[贊助](https://gopeed.com/docs/donate)以支持該項目的持續發展,謝謝!
## 🖼️ 軟體介面
![](_docs/img/ui-demo.png)
## 👨‍💻 開發
該項目分為前端與後端,前端使用`flutter`編寫,後端使用`Golang`編寫,兩邊通過`http`協定進行通訊,在 unix 系統下,則使用`unix socket`,在 windows 系統下,則使用`tcp`協定。
@@ -190,7 +99,7 @@ go install github.com/GopeedLab/gopeed/cmd/gopeed@latest
### 🌍 開發環境
1. Golang 1.25+
2. Flutter 3.38+
2. Flutter 3.41+
### 📋 克隆項目
Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

+76
View File
@@ -1,8 +1,21 @@
package main
/*
#include <stdlib.h>
#include <stdint.h>
typedef void (*TaskEventCallback)(char* payload);
static void callTaskEventCallback(uintptr_t callback, char* payload) {
((TaskEventCallback)callback)(payload);
}
*/
import "C"
import (
"encoding/json"
"fmt"
"unsafe"
"github.com/GopeedLab/gopeed/pkg/rest"
"github.com/GopeedLab/gopeed/pkg/rest/model"
)
@@ -16,6 +29,7 @@ func Start(cfg *C.char) (int, *C.char) {
return 0, C.CString(err.Error())
}
config.ProductionMode = true
config.NativeMode = true
applyWebViewProvider(&config)
realPort, err := rest.Start(&config)
if err != nil {
@@ -28,3 +42,65 @@ func Start(cfg *C.char) (int, *C.char) {
func Stop() {
rest.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 Invoke
func Invoke(method *C.char, path *C.char, query *C.char, body *C.char) *C.char {
return C.CString(rest.Invoke(
C.GoString(method),
C.GoString(path),
C.GoString(query),
C.GoString(body),
))
}
//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))
}
}
+43
View File
@@ -4,6 +4,7 @@ package libgopeed
import "C"
import (
"encoding/json"
"github.com/GopeedLab/gopeed/internal/webview/rpcprovider"
"github.com/GopeedLab/gopeed/pkg/rest"
"github.com/GopeedLab/gopeed/pkg/rest/model"
@@ -15,6 +16,7 @@ func Start(cfg string) (int, error) {
return 0, err
}
config.ProductionMode = true
config.NativeMode = true
applyWebViewProvider(&config)
return rest.Start(&config)
}
@@ -23,6 +25,47 @@ func Stop() {
rest.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)
}
func Invoke(method, path, query, body string) string {
return rest.Invoke(method, path, query, body)
}
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
+4 -6
View File
@@ -99,12 +99,10 @@ var apiMap = map[string]func(message *Message) (data any, err error){
return
}
silent := false
if v, ok := message.Meta["silent"]; ok {
silent, _ = v.(bool)
}
if err := wakeup(silent); err != nil {
// 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
}
+24 -9
View File
@@ -18,6 +18,7 @@ type args struct {
Username *string `json:"username"`
Password *string `json:"password"`
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
@@ -43,13 +44,21 @@ func parse() *args {
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")
whiteDownloadDirs := flag.String("w", "", "White download directories, comma-separated")
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()
// Parse white download directories from comma-separated string
@@ -68,21 +77,23 @@ func loadCliArgs() *args {
func overrideWithCliArgs(cfg *args, cliConfig *args) {
flag.Visit(func(f *flag.Flag) {
switch f.Name {
case "A":
case "A", "address":
cfg.Address = cliConfig.Address
case "P":
case "P", "port":
cfg.Port = cliConfig.Port
case "u":
case "u", "username":
cfg.Username = cliConfig.Username
case "p":
case "p", "password":
cfg.Password = cliConfig.Password
case "T":
case "T", "api-token":
cfg.ApiToken = cliConfig.ApiToken
case "d":
case "mcp-enable":
cfg.MCPEnable = cliConfig.MCPEnable
case "d", "storage-dir":
cfg.StorageDir = cliConfig.StorageDir
case "w":
case "white-download-dirs":
cfg.WhiteDownloadDirs = cliConfig.WhiteDownloadDirs
case "c":
case "c", "config":
cfg.configPath = cliConfig.configPath
}
})
@@ -194,6 +205,10 @@ func loadEnvVars(cfg *args) {
}
field.Set(reflect.ValueOf(dirs))
}
} else if field.Kind() == reflect.Bool {
if boolVal, err := strconv.ParseBool(envValue); err == nil {
field.SetBool(boolVal)
}
}
}
}
+85 -18
View File
@@ -1,7 +1,9 @@
package main
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
@@ -10,6 +12,50 @@ import (
"github.com/GopeedLab/gopeed/pkg/base"
)
func TestLoadCliArgsLongNames(t *testing.T) {
originalCommandLine := flag.CommandLine
originalArgs := os.Args
t.Cleanup(func() {
flag.CommandLine = originalCommandLine
os.Args = originalArgs
})
flags := flag.NewFlagSet("gopeed-web-test", flag.ContinueOnError)
flags.SetOutput(io.Discard)
flag.CommandLine = flags
os.Args = []string{
"gopeed-web",
"--address", "127.0.0.2",
"--port", "8080",
"--username", "admin",
"--password", "password",
"--api-token", "token",
"--mcp-enable",
"--storage-dir", "/tmp/gopeed",
"--white-download-dirs", "/tmp/one,/tmp/two",
"--config", "/tmp/gopeed.json",
}
cfg := loadCliArgs()
if *cfg.Address != "127.0.0.2" || *cfg.Port != 8080 || *cfg.Username != "admin" ||
*cfg.Password != "password" || *cfg.ApiToken != "token" || !cfg.MCPEnable ||
*cfg.StorageDir != "/tmp/gopeed" || !reflect.DeepEqual(cfg.WhiteDownloadDirs, []string{"/tmp/one", "/tmp/two"}) ||
*cfg.configPath != "/tmp/gopeed.json" {
t.Fatalf("unexpected long-name CLI config: %+v", cfg)
}
for _, name := range []string{"A", "P", "u", "p", "T", "d", "c"} {
if flags.Lookup(name) == nil {
t.Errorf("legacy short flag %q is missing", name)
}
}
for _, name := range []string{"M", "w"} {
if flags.Lookup(name) != nil {
t.Errorf("new option unexpectedly has short flag %q", name)
}
}
}
func TestSetDefaults(t *testing.T) {
// Create mock CLI configuration with command line default values
cliDefaults := &args{
@@ -165,14 +211,15 @@ func TestOverrideWithCliArgs(t *testing.T) {
t.Run("flag override documentation", func(t *testing.T) {
// Document the expected behavior for each flag:
flagBehaviors := map[string]string{
"A": "Should override cfg.Address with cliConfig.Address",
"P": "Should override cfg.Port with cliConfig.Port",
"u": "Should override cfg.Username with cliConfig.Username",
"p": "Should override cfg.Password with cliConfig.Password",
"T": "Should override cfg.ApiToken with cliConfig.ApiToken",
"d": "Should override cfg.StorageDir with cliConfig.StorageDir",
"w": "Should override cfg.WhiteDownloadDirs with cliConfig.WhiteDownloadDirs",
"c": "Should override cfg.configPath with cliConfig.configPath",
"A/address": "Should override cfg.Address with cliConfig.Address",
"P/port": "Should override cfg.Port with cliConfig.Port",
"u/username": "Should override cfg.Username with cliConfig.Username",
"p/password": "Should override cfg.Password with cliConfig.Password",
"T/api-token": "Should override cfg.ApiToken with cliConfig.ApiToken",
"mcp-enable": "Should override cfg.MCPEnable with cliConfig.MCPEnable",
"d/storage-dir": "Should override cfg.StorageDir with cliConfig.StorageDir",
"white-download-dirs": "Should override cfg.WhiteDownloadDirs with cliConfig.WhiteDownloadDirs",
"c/config": "Should override cfg.configPath with cliConfig.configPath",
}
t.Log("Expected flag override behaviors:")
@@ -187,21 +234,23 @@ func TestOverrideWithCliArgs(t *testing.T) {
mockFlagVisit := func(config *args, cliConfig *args, flagName string) {
// Simulate the switch statement in overrideWithCliArgs
switch flagName {
case "A":
case "A", "address":
config.Address = cliConfig.Address
case "P":
case "P", "port":
config.Port = cliConfig.Port
case "u":
case "u", "username":
config.Username = cliConfig.Username
case "p":
case "p", "password":
config.Password = cliConfig.Password
case "T":
case "T", "api-token":
config.ApiToken = cliConfig.ApiToken
case "d":
case "mcp-enable":
config.MCPEnable = cliConfig.MCPEnable
case "d", "storage-dir":
config.StorageDir = cliConfig.StorageDir
case "w":
case "white-download-dirs":
config.WhiteDownloadDirs = cliConfig.WhiteDownloadDirs
case "c":
case "c", "config":
config.configPath = cliConfig.configPath
default:
t.Errorf("Unknown flag: %s", flagName)
@@ -285,6 +334,20 @@ func TestOverrideWithCliArgs(t *testing.T) {
}
},
},
{
flagName: "mcp-enable",
setupConfig: func() *args {
return &args{MCPEnable: false}
},
setupCliConfig: func() *args {
return &args{MCPEnable: true}
},
verify: func(t *testing.T, cfg *args) {
if !cfg.MCPEnable {
t.Error("MCPEnable flag override failed: got false, want true")
}
},
},
{
flagName: "d",
setupConfig: func() *args {
@@ -300,7 +363,7 @@ func TestOverrideWithCliArgs(t *testing.T) {
},
},
{
flagName: "w",
flagName: "white-download-dirs",
setupConfig: func() *args {
return &args{WhiteDownloadDirs: []string{"/original/dir1", "/original/dir2"}}
},
@@ -402,6 +465,7 @@ func TestLoadConfigFile(t *testing.T) {
"username": "testuser",
"password": "testpass",
"apiToken": "testtoken",
"mcpEnable": true,
"storageDir": "/test/storage",
"downloadConfig": {
"downloadDir": "/test/downloads",
@@ -415,6 +479,7 @@ func TestLoadConfigFile(t *testing.T) {
Username: stringPtr("testuser"),
Password: stringPtr("testpass"),
ApiToken: stringPtr("testtoken"),
MCPEnable: true,
StorageDir: stringPtr("/test/storage"),
DownloadConfig: &base.DownloaderStoreConfig{
DownloadDir: "/test/downloads",
@@ -476,7 +541,7 @@ func TestLoadEnvVars(t *testing.T) {
originalEnv := make(map[string]string)
envKeys := []string{
"GOPEED_ADDRESS", "GOPEED_PORT", "GOPEED_USERNAME",
"GOPEED_PASSWORD", "GOPEED_APITOKEN", "GOPEED_STORAGEDIR",
"GOPEED_PASSWORD", "GOPEED_APITOKEN", "GOPEED_MCPENABLE", "GOPEED_STORAGEDIR",
"GOPEED_DOWNLOADCONFIG", "GOPEED_WHITEDOWNLOADDIRS",
}
for _, key := range envKeys {
@@ -508,6 +573,7 @@ func TestLoadEnvVars(t *testing.T) {
"GOPEED_USERNAME": "envuser",
"GOPEED_PASSWORD": "envpass",
"GOPEED_APITOKEN": "envtoken",
"GOPEED_MCPENABLE": "true",
"GOPEED_STORAGEDIR": "/env/storage",
},
expected: &args{
@@ -516,6 +582,7 @@ func TestLoadEnvVars(t *testing.T) {
Username: stringPtr("envuser"),
Password: stringPtr("envpass"),
ApiToken: stringPtr("envtoken"),
MCPEnable: true,
StorageDir: stringPtr("/env/storage"),
},
},
+1
View File
@@ -50,6 +50,7 @@ func main() {
StorageDir: storageDir,
WhiteDownloadDirs: args.WhiteDownloadDirs,
ApiToken: *args.ApiToken,
MCPEnable: args.MCPEnable,
DownloadConfig: args.DownloadConfig,
ProductionMode: true,
WebEnable: true,
+30
View File
@@ -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 静态分析与测试
```
+130
View File
@@ -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"
}
]
}
Binary file not shown.

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

+3
View File
@@ -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

+15 -9
View File
@@ -16,6 +16,7 @@ require (
github.com/matoous/go-nanoid/v2 v2.0.0
github.com/mattn/go-ieproxy v0.0.12
github.com/mholt/archives v0.1.5
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
@@ -37,6 +38,7 @@ require (
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
@@ -52,21 +54,25 @@ require (
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/sync v0.19.0 // 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 // 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/anacrolix/chansync v0.7.0 // indirect
@@ -147,13 +153,13 @@ require (
go.opentelemetry.io/otel v1.39.0 // indirect
go.opentelemetry.io/otel/metric v1.39.0 // indirect
go.opentelemetry.io/otel/trace v1.39.0 // indirect
golang.org/x/crypto v0.46.0 // indirect
golang.org/x/mod v0.31.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sys v0.40.0 // indirect
golang.org/x/text v0.33.0
golang.org/x/time v0.14.0 // indirect
golang.org/x/tools v0.40.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
+32 -18
View File
@@ -244,6 +244,8 @@ github.com/gobwas/ws v1.2.1/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/K
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
@@ -279,6 +281,8 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
@@ -384,6 +388,8 @@ github.com/minio/minlz v1.0.1 h1:OUZUzXcib8diiX+JYxyRLIdomyZYzHct6EShOKtQY2A=
github.com/minio/minlz v1.0.1/go.mod h1:qT0aEB35q79LLornSzeDH75LBf3aH1MV+jB5w9Wasec=
github.com/minio/sha256-simd v1.0.1 h1:6kaan5IFmwTNynnKKpDHe6FWHohJOHhCPchzK49dzMM=
github.com/minio/sha256-simd v1.0.1/go.mod h1:Pz6AKMiUdngCLpeTL/RJY1M9rUuPMYujV5xJjtbRSN8=
github.com/modelcontextprotocol/go-sdk v1.7.0 h1:yqjY2dsbKAC0LSuWZVBMrHgiG8ukXv6NRo0JiALay44=
github.com/modelcontextprotocol/go-sdk v1.7.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
@@ -507,6 +513,10 @@ github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWR
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46 h1:GHRpF1pTW19a8tTFrMLUcfWwyC0pnifVo2ClaLq+hP8=
github.com/ryszard/goskiplist v0.0.0-20150312221310-2dfbae5fcf46/go.mod h1:uAQ5PCi+MFsC7HjREoAz1BU+Mq60+05gifQSsHSDG/8=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
@@ -560,6 +570,8 @@ github.com/xiaoqidun/setft v0.0.0-20220310121541-be86327699ad h1:QtuWk6dsrNXc/ug
github.com/xiaoqidun/setft v0.0.0-20220310121541-be86327699ad/go.mod h1:Jj8p9bgKGTPQ+M8CdUMS9p7Mmdoxa3OAcAjJQBu0CcI=
github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU=
github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
go.etcd.io/bbolt v1.4.3 h1:dEadXpI6G79deX5prL3QRNP6JB8UxVkqo4UPnHaNXJo=
@@ -596,8 +608,8 @@ golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0
golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -630,8 +642,8 @@ golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
golang.org/x/mod v0.6.0-dev.0.20211013180041-c96bc1413d57/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -659,13 +671,15 @@ golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc=
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -675,8 +689,8 @@ golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -716,8 +730,8 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
@@ -725,8 +739,8 @@ golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
golang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=
golang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -739,12 +753,12 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -773,8 +787,8 @@ golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapK
golang.org/x/tools v0.1.8-0.20211029000441-d6a9af8af023/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+11 -2
View File
@@ -21,8 +21,9 @@ type Fetcher interface {
Pause() error
Close() error
// Stats refreshes health statistics and returns the latest information
Stats() any
// 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() *FetcherMeta
// Progress returns the progress of the download.
@@ -31,6 +32,14 @@ type Fetcher interface {
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
+18 -1
View File
@@ -1,6 +1,23 @@
package fetcher
import "testing"
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 {
+346
View File
@@ -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
}
}
+962
View File
@@ -0,0 +1,962 @@
package httpclient_test
import (
"context"
"crypto/tls"
"errors"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"slices"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/GopeedLab/gopeed/internal/httpclient"
"github.com/GopeedLab/gopeed/internal/httpclient/httpclienttest"
)
func TestFixedChromeUsesBrowserTLSFingerprintAndHTTP2(t *testing.T) {
server := httpclienttest.NewFingerprintServer(t, httpclienttest.FingerprintServerOptions{
RequiredProfile: httpclienttest.ProfileAnyBrowser,
})
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationFixed,
Browser: httpclient.BrowserChrome,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", response.StatusCode, http.StatusOK)
}
if response.ProtoMajor != 2 {
t.Fatalf("protocol = %q, want HTTP/2", response.Proto)
}
}
func TestAutoFallsBackFromNativeToBrowserFingerprint(t *testing.T) {
server := httpclienttest.NewFingerprintServer(t, httpclienttest.FingerprintServerOptions{
RequiredProfile: httpclienttest.ProfileAnyBrowser,
})
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
request, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36")
response, err := client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
defer response.Body.Close()
if response.ProtoMajor != 2 {
t.Fatalf("protocol = %q, want HTTP/2", response.Proto)
}
if got, want := server.Profiles(), []httpclienttest.Profile{
httpclienttest.ProfileNative,
httpclienttest.ProfileChrome,
}; !slices.Equal(got, want) {
t.Fatalf("ClientHello profiles = %v, want %v", got, want)
}
}
func TestAutoChoosesBrowserFingerprintFromUserAgent(t *testing.T) {
tests := []struct {
name string
userAgent string
wantBrowser httpclient.Browser
}{
{
name: "chrome",
userAgent: "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36",
wantBrowser: httpclient.BrowserChrome,
},
{
name: "firefox",
userAgent: "Mozilla/5.0 Firefox/120.0",
wantBrowser: httpclient.BrowserFirefox,
},
{
name: "safari",
userAgent: "Mozilla/5.0 Version/16.6 Safari/605.1.15",
wantBrowser: httpclient.BrowserSafari,
},
{
name: "unknown defaults to chrome",
userAgent: "Gopeed/1.0",
wantBrowser: httpclient.BrowserChrome,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
server := httpclienttest.NewFingerprintServer(t, httpclienttest.FingerprintServerOptions{
RequiredProfile: httpclienttest.Profile(test.wantBrowser),
})
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationAuto},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
request, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.Header.Set("User-Agent", test.userAgent)
response, err := client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
response.Body.Close()
if response.ProtoMajor != 2 {
t.Fatalf("protocol = %q, want HTTP/2", response.Proto)
}
if got, want := server.Profiles(), []httpclienttest.Profile{
httpclienttest.ProfileNative,
httpclienttest.Profile(test.wantBrowser),
}; !slices.Equal(got, want) {
t.Fatalf("profiles = %v, want %v", got, want)
}
})
}
}
func TestAutoFallsBackOnForbiddenAndPinsBrowserPerURL(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requests.Add(1)
if request.Header.Get("Sec-Ch-Ua") == "" {
http.Error(w, "browser required", http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: httpclient.NewImpersonationSession(),
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
for range 2 {
request, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36")
response, err := client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", response.StatusCode, http.StatusOK)
}
}
if requests.Load() != 3 {
t.Fatalf("requests = %d, want 3 (native + fallback + pinned)", requests.Load())
}
}
func TestAutoDisablesFallbackWhenBrowserReturnsHTTPFailure(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requests.Add(1)
if request.Header.Get("Sec-Ch-Ua") == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusNotFound)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: httpclient.NewImpersonationSession(),
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
wantStatuses := []int{http.StatusNotFound, http.StatusForbidden}
for _, wantStatus := range wantStatuses {
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
if response.StatusCode != wantStatus {
t.Fatalf("status = %d, want %d", response.StatusCode, wantStatus)
}
}
if requests.Load() != 3 {
t.Fatalf("requests = %d, want 3 (native + one fallback + native)", requests.Load())
}
}
func TestAutoDoesNotDisableFallbackAfterTransportFailure(t *testing.T) {
server := httpclienttest.NewFingerprintServer(t, httpclienttest.FingerprintServerOptions{
RequiredProfile: httpclienttest.Profile("unsupported"),
})
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: httpclient.NewImpersonationSession(),
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
for range 2 {
if _, err := client.Get(server.URL); err == nil {
t.Fatal("Get() error = nil, want TLS failure")
}
}
if got, want := server.Profiles(), []httpclienttest.Profile{
httpclienttest.ProfileNative,
httpclienttest.ProfileChrome,
httpclienttest.ProfileNative,
httpclienttest.ProfileChrome,
}; !slices.Equal(got, want) {
t.Fatalf("ClientHello profiles = %v, want %v", got, want)
}
}
func TestAutoWithoutSessionDoesNotCacheSelectedBrowser(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requests.Add(1)
if request.Header.Get("Sec-Ch-Ua") == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationAuto},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
for range 2 {
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
}
if requests.Load() != 4 {
t.Fatalf("requests = %d, want 4 (native + fallback without caching)", requests.Load())
}
}
func TestAutoSharesSelectedBrowserAcrossClientsInSession(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requests.Add(1)
if request.Header.Get("Sec-Ch-Ua") == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
session := httpclient.NewImpersonationSession()
for range 2 {
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: session,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
request, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.Header.Set("User-Agent", "Mozilla/5.0 Chrome/120.0.0.0 Safari/537.36")
response, err := client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
response.Body.Close()
}
if requests.Load() != 3 {
t.Fatalf("requests = %d, want 3 (native + fallback + session pinned)", requests.Load())
}
}
func TestAutoDoesNotShareSelectedBrowserAcrossSessions(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requests.Add(1)
if request.Header.Get("Sec-Ch-Ua") == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
for range 2 {
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: httpclient.NewImpersonationSession(),
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
}
if requests.Load() != 4 {
t.Fatalf("requests = %d, want 4 (native + fallback per session)", requests.Load())
}
}
func TestAutoCachesSelectedBrowserByFullURL(t *testing.T) {
var publicBrowserRequests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
browserRequest := request.Header.Get("Sec-Ch-Ua") != ""
switch request.URL.Query().Get("access") {
case "protected":
if !browserRequest {
w.WriteHeader(http.StatusForbidden)
return
}
case "public":
if browserRequest {
publicBrowserRequests.Add(1)
}
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: httpclient.NewImpersonationSession(),
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
for range 2 {
response, err := client.Get(server.URL + "/file?access=protected")
if err != nil {
t.Fatalf("protected Get() error = %v", err)
}
response.Body.Close()
}
response, err := client.Get(server.URL + "/file?access=public")
if err != nil {
t.Fatalf("public Get() error = %v", err)
}
response.Body.Close()
if publicBrowserRequests.Load() != 0 {
t.Fatalf("public browser requests = %d, want 0", publicBrowserRequests.Load())
}
}
func TestImpersonationSessionClearRemovesSelections(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
requests.Add(1)
if request.Header.Get("Sec-Ch-Ua") == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
session := httpclient.NewImpersonationSession()
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: session,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
for range 2 {
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
session.Clear()
}
if requests.Load() != 4 {
t.Fatalf("requests = %d, want 4 (native + fallback after each clear)", requests.Load())
}
}
func TestGlobalAutoSelectionDoesNotAffectNativeMode(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
if request.Header.Get("Sec-Ch-Ua") == "" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
autoClient, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationAuto},
})
if err != nil {
t.Fatalf("NewClient(auto) error = %v", err)
}
autoResponse, err := autoClient.Get(server.URL)
if err != nil {
t.Fatalf("auto Get() error = %v", err)
}
autoResponse.Body.Close()
if autoResponse.StatusCode != http.StatusOK {
t.Fatalf("auto status = %d, want %d", autoResponse.StatusCode, http.StatusOK)
}
nativeClient, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationNative},
})
if err != nil {
t.Fatalf("NewClient(native) error = %v", err)
}
nativeResponse, err := nativeClient.Get(server.URL)
if err != nil {
t.Fatalf("native Get() error = %v", err)
}
nativeResponse.Body.Close()
if nativeResponse.StatusCode != http.StatusForbidden {
t.Fatalf("native status = %d, want %d", nativeResponse.StatusCode, http.StatusForbidden)
}
}
func TestAutoAppliesFallbackResponseCookiesBeforeRetry(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
if request.Header.Get("Sec-Ch-Ua") == "" {
http.SetCookie(w, &http.Cookie{Name: "challenge", Value: "passed", Path: "/"})
w.WriteHeader(http.StatusForbidden)
return
}
cookie, err := request.Cookie("challenge")
if err != nil || cookie.Value != "passed" {
w.WriteHeader(http.StatusForbidden)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("cookiejar.New() error = %v", err)
}
client, err := httpclient.NewClient(httpclient.Options{
Client: httpclient.ClientOptions{Jar: jar},
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationAuto},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", response.StatusCode, http.StatusOK)
}
}
func TestAutoDoesNotRetryRequestWithNonReplayableBody(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
w.WriteHeader(http.StatusForbidden)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationAuto},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
bodyReader, bodyWriter := io.Pipe()
t.Cleanup(func() {
bodyReader.Close()
bodyWriter.Close()
})
go func() {
_, _ = bodyWriter.Write([]byte("payload"))
_ = bodyWriter.Close()
}()
request, err := http.NewRequest(http.MethodPost, server.URL, bodyReader)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
response.Body.Close()
if requests.Load() != 1 {
t.Fatalf("requests = %d, want 1", requests.Load())
}
}
func TestAutoDoesNotRetryReplayablePost(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
w.WriteHeader(http.StatusForbidden)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationAuto},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
request, err := http.NewRequest(http.MethodPost, server.URL, strings.NewReader("payload"))
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
response, err := client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
response.Body.Close()
if requests.Load() != 1 {
t.Fatalf("requests = %d, want 1", requests.Load())
}
}
func TestNativeUsesStandardTransportWithHTTP2(t *testing.T) {
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
server.EnableHTTP2 = true
server.StartTLS()
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationNative,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
defer response.Body.Close()
if response.ProtoMajor != 2 {
t.Fatalf("protocol = %q, want HTTP/2", response.Proto)
}
}
func TestClientOptionsPreserveCookiesAcrossRedirects(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/start":
http.SetCookie(w, &http.Cookie{Name: "session", Value: "gopeed", Path: "/"})
http.Redirect(w, request, "/download", http.StatusFound)
case "/download":
cookie, err := request.Cookie("session")
if err != nil || cookie.Value != "gopeed" {
http.Error(w, "cookie missing", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, request)
}
}))
t.Cleanup(server.Close)
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatalf("cookiejar.New() error = %v", err)
}
var redirects atomic.Int32
client, err := httpclient.NewClient(httpclient.Options{
Client: httpclient.ClientOptions{
Jar: jar,
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
redirects.Add(1)
return nil
},
},
Impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationNative},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL + "/start")
if err != nil {
t.Fatalf("Get() error = %v", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", response.StatusCode, http.StatusOK)
}
if redirects.Load() != 1 {
t.Fatalf("redirect calls = %d, want 1", redirects.Load())
}
}
func TestClientTimeoutCancelsRequest(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, request *http.Request) {
<-request.Context().Done()
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Client: httpclient.ClientOptions{Timeout: 50 * time.Millisecond},
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationNative,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
_, err = client.Get(server.URL)
if err == nil {
t.Fatal("Get() error = nil, want timeout")
}
var networkError net.Error
if !errors.As(err, &networkError) || !networkError.Timeout() {
t.Fatalf("Get() error = %v, want net.Error timeout", err)
}
}
func TestTransportOptionsUseProxyInNativeAndFixedModes(t *testing.T) {
proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
if request.URL.Host != "download.example" {
http.Error(w, "unexpected target", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(proxy.Close)
proxyURL, err := url.Parse(proxy.URL)
if err != nil {
t.Fatalf("url.Parse() error = %v", err)
}
tests := []struct {
name string
impersonation httpclient.ImpersonationOptions
}{
{
name: "native",
impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationNative},
},
{
name: "fixed chrome",
impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationFixed,
Browser: httpclient.BrowserChrome,
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{Proxy: http.ProxyURL(proxyURL)},
Impersonation: test.impersonation,
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get("http://download.example/file")
if err != nil {
t.Fatalf("Get() error = %v", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want %d", response.StatusCode, http.StatusOK)
}
})
}
}
func TestTransportOptionsUseDialContextInNativeAndFixedModes(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
tests := []struct {
name string
impersonation httpclient.ImpersonationOptions
}{
{
name: "native",
impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationNative},
},
{
name: "fixed chrome",
impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationFixed,
Browser: httpclient.BrowserChrome,
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var calls atomic.Int32
dialer := &net.Dialer{}
client, err := httpclient.NewClient(httpclient.Options{
Transport: httpclient.TransportOptions{
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
calls.Add(1)
return dialer.DialContext(ctx, network, address)
},
},
Impersonation: test.impersonation,
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
if calls.Load() == 0 {
t.Fatal("DialContext() was not called")
}
})
}
}
func TestTransportOptionsApplyTLSHandshakeTimeoutInNativeAndFixedModes(t *testing.T) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("net.Listen() error = %v", err)
}
closed := make(chan struct{})
t.Cleanup(func() {
close(closed)
listener.Close()
})
go func() {
for {
connection, err := listener.Accept()
if err != nil {
return
}
go func() {
<-closed
connection.Close()
}()
}
}()
tests := []struct {
name string
impersonation httpclient.ImpersonationOptions
}{
{
name: "native",
impersonation: httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationNative},
},
{
name: "fixed chrome",
impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationFixed,
Browser: httpclient.BrowserChrome,
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
client, err := httpclient.NewClient(httpclient.Options{
Client: httpclient.ClientOptions{Timeout: time.Second},
Transport: httpclient.TransportOptions{
TLSHandshakeTimeout: 50 * time.Millisecond,
},
Impersonation: test.impersonation,
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
started := time.Now()
_, err = client.Get("https://" + listener.Addr().String())
if err == nil {
t.Fatal("Get() error = nil, want TLS handshake timeout")
}
if elapsed := time.Since(started); elapsed >= 500*time.Millisecond {
t.Fatalf("TLS handshake took %s, want less than 500ms", elapsed)
}
})
}
}
func TestFixedBrowserAddsProfileHeadersWithoutOverwritingExplicitHeaders(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Seen-User-Agent", request.UserAgent())
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationFixed,
Browser: httpclient.BrowserChrome,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
response.Body.Close()
if userAgent := response.Header.Get("Seen-User-Agent"); !strings.Contains(userAgent, "Chrome/120") {
t.Fatalf("profile User-Agent = %q, want Chrome/120", userAgent)
}
request, err := http.NewRequest(http.MethodGet, server.URL, nil)
if err != nil {
t.Fatalf("NewRequest() error = %v", err)
}
request.Header.Set("User-Agent", "Gopeed-Custom/1.0")
response, err = client.Do(request)
if err != nil {
t.Fatalf("Do() error = %v", err)
}
response.Body.Close()
if userAgent := response.Header.Get("Seen-User-Agent"); userAgent != "Gopeed-Custom/1.0" {
t.Fatalf("explicit User-Agent = %q, want Gopeed-Custom/1.0", userAgent)
}
}
func TestFixedClientCloseIdleConnectionsReachesBrowserTransport(t *testing.T) {
var connections atomic.Int32
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
server.Config.ConnState = func(_ net.Conn, state http.ConnState) {
if state == http.StateNew {
connections.Add(1)
}
}
server.Start()
t.Cleanup(server.Close)
client, err := httpclient.NewClient(httpclient.Options{
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationFixed,
Browser: httpclient.BrowserChrome,
},
})
if err != nil {
t.Fatalf("NewClient() error = %v", err)
}
for attempt := range 2 {
response, err := client.Get(server.URL)
if err != nil {
t.Fatalf("Get() error = %v", err)
}
_, _ = io.Copy(io.Discard, response.Body)
response.Body.Close()
if attempt == 0 {
client.CloseIdleConnections()
}
}
if connections.Load() != 2 {
t.Fatalf("connections = %d, want 2", connections.Load())
}
}
@@ -0,0 +1,100 @@
package httpclienttest
import (
"crypto/tls"
"errors"
"io"
"log"
"net/http"
"net/http/httptest"
"sync"
"testing"
)
type Profile string
const (
ProfileNative Profile = "native"
ProfileChrome Profile = "chrome"
ProfileFirefox Profile = "firefox"
ProfileSafari Profile = "safari"
ProfileAnyBrowser Profile = "browser"
)
type FingerprintServerOptions struct {
RequiredProfile Profile
Handler http.Handler
}
type FingerprintServer struct {
*httptest.Server
mu sync.Mutex
profiles []Profile
}
func NewFingerprintServer(t testing.TB, options FingerprintServerOptions) *FingerprintServer {
t.Helper()
handler := options.Handler
if handler == nil {
handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
}
server := &FingerprintServer{
Server: httptest.NewUnstartedServer(handler),
}
server.EnableHTTP2 = true
server.Config.ErrorLog = log.New(io.Discard, "", 0)
server.TLS = &tls.Config{
GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
profile := classifyProfile(hello.CipherSuites)
server.mu.Lock()
server.profiles = append(server.profiles, profile)
server.mu.Unlock()
if profileMatches(profile, options.RequiredProfile) {
return nil, nil
}
return nil, errors.New("required TLS fingerprint was not presented")
},
}
server.StartTLS()
t.Cleanup(server.Close)
return server
}
func (s *FingerprintServer) Profiles() []Profile {
s.mu.Lock()
defer s.mu.Unlock()
return append([]Profile(nil), s.profiles...)
}
func profileMatches(actual, required Profile) bool {
if required == ProfileAnyBrowser {
return actual != ProfileNative
}
return actual == required
}
func classifyProfile(cipherSuites []uint16) Profile {
if len(cipherSuites) >= 5 && isGREASE(cipherSuites[0]) {
switch cipherSuites[4] {
case tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
return ProfileChrome
case tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384:
return ProfileSafari
}
}
if len(cipherSuites) >= 3 &&
cipherSuites[0] == tls.TLS_AES_128_GCM_SHA256 &&
cipherSuites[1] == tls.TLS_CHACHA20_POLY1305_SHA256 &&
cipherSuites[2] == tls.TLS_AES_256_GCM_SHA384 {
return ProfileFirefox
}
return ProfileNative
}
func isGREASE(value uint16) bool {
return value&0x0f0f == 0x0a0a && byte(value) == byte(value>>8)
}
+198 -8
View File
@@ -18,6 +18,7 @@ import (
"github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/protocol/bt"
"github.com/GopeedLab/gopeed/pkg/util"
"github.com/RoaringBitmap/roaring"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/metainfo"
"github.com/anacrolix/torrent/storage"
@@ -162,20 +163,209 @@ func (f *Fetcher) Meta() *fetcher.FetcherMeta {
return f.meta
}
func (f *Fetcher) Stats() any {
func (f *Fetcher) Stats() *fetcher.Stats {
var stats torrent.TorrentStats
var pieceMap *base.PieceMap
pieceMapReady := false
peers := make([]*base.PeerStats, 0)
if f.torrent != nil {
stats = f.torrent.Stats()
pieceMap, pieceMapReady = buildBTPieceMap(f.torrent)
peers = buildBTPeers(f.torrent)
} else {
stats = torrent.TorrentStats{}
}
return &bt.Stats{
TotalPeers: stats.TotalPeers,
ActivePeers: stats.ActivePeers,
ConnectedSeeders: stats.ConnectedSeeders,
SeedBytes: f.data.SeedBytes,
SeedRatio: f.seedRadio(),
SeedTime: f.data.SeedTime,
var snapshot any
if pieceMapReady {
snapshot = &bt.StatsSnapshot{
SeedBytes: f.data.SeedBytes,
SeedRatio: f.seedRadio(),
SeedTime: f.data.SeedTime,
PieceMap: pieceMap.Clone(),
}
}
// When completion is temporarily unknown while anacrolix restores storage
// or verifies pieces, the nil Snapshot tells Downloader to retain the last
// trusted bitset instead of replacing it with an all-empty map.
return &fetcher.Stats{
Snapshot: snapshot,
Runtime: &bt.StatsRuntime{
TotalPeers: stats.TotalPeers,
ActivePeers: stats.ActivePeers,
ConnectedSeeders: stats.ConnectedSeeders,
ConnectedLeechers: stats.ActivePeers - stats.ConnectedSeeders,
Peers: peers,
},
}
}
// buildBTPieceMap converts anacrolix's ordered completion runs to Gopeed's
// one-bit map. ready is false until storage knows the completion state of every
// piece; this prevents initial hash checking from briefly replacing a restored
// map with an all-empty value.
func buildBTPieceMap(t *torrent.Torrent) (pieceMap *base.PieceMap, ready bool) {
info := t.Info()
if info == nil {
return nil, false
}
pieceMap = base.NewPieceMap(info.NumPieces(), info.PieceLength)
ready = applyBTPieceRuns(pieceMap, t.PieceStateRuns())
return pieceMap, ready
}
func applyBTPieceRuns(pieceMap *base.PieceMap, runs []torrent.PieceStateRun) (ready bool) {
ready = true
pieceIndex := 0
for _, run := range runs {
if !run.Ok {
ready = false
}
completed := run.Ok && run.Complete
for range run.Length {
if pieceIndex >= pieceMap.PieceCount() {
return ready
}
_ = pieceMap.Update(pieceIndex, completed)
pieceIndex++
}
}
return ready && pieceIndex == pieceMap.PieceCount()
}
func buildBTPeers(t *torrent.Torrent) []*base.PeerStats {
connections := t.PeerConns()
totalPieces := 0
var missingWantedPieces *roaring.Bitmap
// Magnet torrents can connect to peers before their metadata arrives. Keep
// those runtime peer stats, but leave completion and relevance unavailable
// until the metadata provides a trusted total piece count.
if info := t.Info(); info != nil {
totalPieces = info.NumPieces()
missingWantedPieces = btMissingWantedPieces(t.PieceStateRuns(), totalPieces)
}
peers := make([]*base.PeerStats, 0, len(connections))
for _, connection := range connections {
peerStats := connection.Stats()
peers = append(peers, &base.PeerStats{
Address: safeBTPeerAddress(connection),
Client: btPeerClient(connection),
DownloadSpeed: int64(peerStats.DownloadRate),
UploadSpeed: int64(peerStats.LastWriteUploadRate),
PieceCount: peerStats.RemotePieceCount,
Completion: btPeerCompletion(peerStats.RemotePieceCount, totalPieces),
Relevance: btPeerRelevance(connection.PeerPieces(), missingWantedPieces),
Source: normalizeBTPeerSource(connection.Discovery),
Transport: normalizeBTTransport(connection.Network),
})
}
return peers
}
// btPeerCompletion converts anacrolix's remote piece count into the ratio the
// API exposes. A nil value distinguishes unavailable metadata from a real 0%.
func btPeerCompletion(pieceCount, totalPieces int) *float64 {
if totalPieces <= 0 {
return nil
}
if pieceCount < 0 {
pieceCount = 0
} else if pieceCount > totalPieces {
pieceCount = totalPieces
}
completion := float64(pieceCount) / float64(totalPieces)
return &completion
}
// btMissingWantedPieces builds the denominator used by peer relevance. Pieces
// belonging only to skipped files are excluded because their priority is none.
func btMissingWantedPieces(runs []torrent.PieceStateRun, totalPieces int) *roaring.Bitmap {
if totalPieces <= 0 {
return nil
}
missing := roaring.New()
pieceIndex := 0
for _, run := range runs {
for range run.Length {
if pieceIndex >= totalPieces {
return nil
}
if run.Priority != torrent.PiecePriorityNone && !(run.Ok && run.Complete) {
missing.Add(uint32(pieceIndex))
}
pieceIndex++
}
}
if pieceIndex != totalPieces {
return nil
}
return missing
}
// btPeerRelevance reports how much of the local wanted, missing set the remote
// peer can provide. A zero value is meaningful; nil means there is no denominator.
func btPeerRelevance(peerPieces, missingWantedPieces *roaring.Bitmap) *float64 {
if peerPieces == nil || missingWantedPieces == nil || missingWantedPieces.IsEmpty() {
return nil
}
relevantPieces := roaring.And(peerPieces, missingWantedPieces).GetCardinality()
relevance := float64(relevantPieces) / float64(missingWantedPieces.GetCardinality())
return &relevance
}
// A uTP socket may close between PeerConns and this snapshot. Some uTP address
// implementations panic after close, so one disappearing address must not make
// the entire stats endpoint fail.
func safeBTPeerAddress(connection *torrent.PeerConn) (address string) {
defer func() {
if recover() != nil {
address = ""
}
}()
if connection.RemoteAddr == nil {
return ""
}
return connection.RemoteAddr.String()
}
func btPeerClient(connection *torrent.PeerConn) string {
value := connection.PeerClientName.Load()
if value == nil {
return ""
}
return fmt.Sprint(value)
}
func normalizeBTPeerSource(source torrent.PeerSource) string {
switch source {
case torrent.PeerSourceTracker:
return "tracker"
case torrent.PeerSourceDhtGetPeers, torrent.PeerSourceDhtAnnouncePeer:
return "dht"
case torrent.PeerSourcePex:
return "pex"
case torrent.PeerSourceIncoming:
return "incoming"
case torrent.PeerSourceDirect:
return "direct"
case torrent.PeerSourceUtHolepunch:
return "holepunch"
default:
return "unknown"
}
}
func normalizeBTTransport(network string) string {
network = strings.ToLower(network)
switch {
case strings.Contains(network, "webrtc"):
return "webrtc"
case strings.Contains(network, "udp"):
// anacrolix labels uTP sockets with their underlying udp network.
return "utp"
case strings.Contains(network, "tcp"):
return "tcp"
default:
return "unknown"
}
}
+199
View File
@@ -0,0 +1,199 @@
package bt
import (
"testing"
"github.com/GopeedLab/gopeed/internal/fetcher"
"github.com/GopeedLab/gopeed/pkg/base"
protocolbt "github.com/GopeedLab/gopeed/pkg/protocol/bt"
"github.com/RoaringBitmap/roaring"
"github.com/anacrolix/torrent"
"github.com/anacrolix/torrent/storage"
)
func TestStatsSeparatesSnapshotAndRuntime(t *testing.T) {
frame := (&Fetcher{
meta: &fetcher.FetcherMeta{Res: &base.Resource{Size: 256}},
data: &fetcherData{SeedBytes: 128, SeedTime: 64},
}).Stats()
if frame.Snapshot != nil {
t.Fatalf("snapshot = %T, want nil until piece completion is known", frame.Snapshot)
}
runtime, ok := frame.Runtime.(*protocolbt.StatsRuntime)
if !ok {
t.Fatalf("runtime type = %T", frame.Runtime)
}
if len(runtime.Peers) != 0 || runtime.TotalPeers != 0 {
t.Fatalf("unexpected runtime: %+v", runtime)
}
}
func TestStatsBeforeTorrentMetadataIsAvailable(t *testing.T) {
config := torrent.TestingConfig(t)
config.DisableTCP = true
config.DisableUTP = true
client, err := torrent.NewClient(config)
if err != nil {
t.Fatal(err)
}
defer client.Close()
torrentWithoutMetadata, err := client.AddMagnet(
"magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567",
)
if err != nil {
t.Fatal(err)
}
if info := torrentWithoutMetadata.Info(); info != nil {
t.Fatalf("torrent info = %+v, want nil before metadata is available", info)
}
frame := (&Fetcher{
torrent: torrentWithoutMetadata,
meta: &fetcher.FetcherMeta{},
data: &fetcherData{},
}).Stats()
if frame.Snapshot != nil {
t.Fatalf("snapshot = %T, want nil before metadata is available", frame.Snapshot)
}
runtime, ok := frame.Runtime.(*protocolbt.StatsRuntime)
if !ok {
t.Fatalf("runtime type = %T", frame.Runtime)
}
if len(runtime.Peers) != 0 || runtime.TotalPeers != 0 {
t.Fatalf("unexpected runtime before metadata is available: %+v", runtime)
}
}
func TestApplyBTPieceRunsPublishesVerifiedCompletionOnly(t *testing.T) {
pieceMap := base.NewPieceMap(4, 1024)
ready := applyBTPieceRuns(pieceMap, []torrent.PieceStateRun{
{PieceState: torrent.PieceState{Completion: torrentCompletion(true, true)}, Length: 1},
{PieceState: torrent.PieceState{Completion: torrentCompletion(true, false), Partial: true}, Length: 2},
{PieceState: torrent.PieceState{Completion: torrentCompletion(false, false), Hashing: true}, Length: 1},
})
if ready {
t.Fatal("piece map became ready while one completion is unknown")
}
want := []bool{true, false, false, false}
for index, expected := range want {
got, err := pieceMap.Get(index)
if err != nil || got != expected {
t.Fatalf("piece %d = %v, %v; want %v", index, got, err, expected)
}
}
knownMap := base.NewPieceMap(2, 1024)
if !applyBTPieceRuns(knownMap, []torrent.PieceStateRun{
{PieceState: torrent.PieceState{Completion: torrentCompletion(true, true)}, Length: 1},
{PieceState: torrent.PieceState{Completion: torrentCompletion(true, false)}, Length: 1},
}) {
t.Fatal("fully known completion map was not ready")
}
if applyBTPieceRuns(base.NewPieceMap(2, 1024), []torrent.PieceStateRun{
{PieceState: torrent.PieceState{Completion: torrentCompletion(true, true)}, Length: 1},
}) {
t.Fatal("incomplete piece runs were published")
}
}
func torrentCompletion(ok, complete bool) storage.Completion {
return storage.Completion{Ok: ok, Complete: complete}
}
func TestNormalizeBTPeerMetadata(t *testing.T) {
if got := normalizeBTPeerSource(torrent.PeerSourceDhtGetPeers); got != "dht" {
t.Fatalf("DHT source = %q", got)
}
if got := normalizeBTPeerSource(torrent.PeerSourcePex); got != "pex" {
t.Fatalf("PEX source = %q", got)
}
transports := map[string]string{
"udp4": "utp",
"udp6": "utp",
"tcp4": "tcp",
"tcp6": "tcp",
"webrtc": "webrtc",
"unix": "unknown",
}
for network, want := range transports {
if got := normalizeBTTransport(network); got != want {
t.Errorf("normalizeBTTransport(%q) = %q, want %q", network, got, want)
}
}
}
func TestBTPeerCompletion(t *testing.T) {
if got := btPeerCompletion(1, 4); got == nil || *got != 0.25 {
t.Fatalf("completion = %v, want 0.25", got)
}
if got := btPeerCompletion(5, 4); got == nil || *got != 1 {
t.Fatalf("clamped completion = %v, want 1", got)
}
if got := btPeerCompletion(-1, 4); got == nil || *got != 0 {
t.Fatalf("negative completion = %v, want 0", got)
}
if got := btPeerCompletion(0, 0); got != nil {
t.Fatalf("completion without metadata = %v, want nil", *got)
}
}
func TestBTPeerRelevanceUsesWantedMissingPieces(t *testing.T) {
missing := btMissingWantedPieces([]torrent.PieceStateRun{
{
PieceState: torrent.PieceState{
Completion: torrentCompletion(true, true),
Priority: torrent.PiecePriorityNormal,
},
Length: 2,
},
{
PieceState: torrent.PieceState{
Completion: torrentCompletion(true, false),
Priority: torrent.PiecePriorityNormal,
},
Length: 2,
},
{
PieceState: torrent.PieceState{
Completion: torrentCompletion(true, false),
Priority: torrent.PiecePriorityNone,
},
Length: 2,
},
}, 6)
if missing == nil || !missing.Equals(roaring.BitmapOf(2, 3)) {
t.Fatalf("missing wanted pieces = %v, want {2, 3}", missing)
}
if got := btPeerRelevance(roaring.BitmapOf(0, 2, 4), missing); got == nil || *got != 0.5 {
t.Fatalf("relevance = %v, want 0.5", got)
}
if got := btPeerRelevance(roaring.BitmapOf(0, 1, 4), missing); got == nil || *got != 0 {
t.Fatalf("zero relevance = %v, want 0", got)
}
if got := btPeerRelevance(roaring.BitmapOf(2, 3), roaring.New()); got != nil {
t.Fatalf("relevance with no missing pieces = %v, want nil", *got)
}
if got := btMissingWantedPieces(nil, 6); got != nil {
t.Fatalf("incomplete piece states = %v, want nil", got)
}
}
func TestBTPeerRelevanceTracksRemainingDownload(t *testing.T) {
missing := roaring.BitmapOf(90, 91, 92, 93, 94, 95, 96, 97, 98, 99)
if got := btPeerRelevance(missing.Clone(), missing); got == nil || *got != 1 {
t.Fatalf("peer covering every missing piece = %v, want 1", got)
}
oneRelevantPiece := roaring.BitmapOf(90)
if got := btPeerRelevance(oneRelevantPiece, missing); got == nil || *got != 0.1 {
t.Fatalf("peer covering one of ten missing pieces = %v, want 0.1", got)
}
missingAfterTransfer := missing.Clone()
missingAfterTransfer.Remove(90)
if got := btPeerRelevance(oneRelevantPiece, missingAfterTransfer); got == nil || *got != 0 {
t.Fatalf("peer after transferring its only relevant piece = %v, want 0", got)
}
}
+65 -12
View File
@@ -210,23 +210,76 @@ func (f *Fetcher) Meta() *fetcher.FetcherMeta {
return f.meta
}
func (f *Fetcher) Stats() any {
func (f *Fetcher) Stats() *fetcher.Stats {
handle := f.currentHandle()
if !handle.IsValid() {
return &ped2k.Stats{}
return &fetcher.Stats{
Runtime: &ped2k.StatsRuntime{
Peers: make([]*base.PeerStats, 0),
},
}
}
status := handle.GetStatus()
return &ped2k.Stats{
State: string(status.State),
ActivePeers: handle.ActiveConnections(),
TotalPeers: status.NumPeers,
DownloadRate: status.DownloadRate,
Upload: status.Upload,
UploadRate: status.UploadRate,
TotalDone: status.TotalDone,
TotalReceived: status.TotalReceived,
TotalWanted: status.TotalWanted,
pieceMap := buildED2KPieceMap(handle.PieceSnapshots())
mapReady := pieceMap != nil && status.State != goed2k.LoadingResumeData && status.State != goed2k.Verifying
var snapshot any
if mapReady {
snapshot = &ped2k.StatsSnapshot{
Upload: status.Upload,
TotalDone: status.TotalDone,
TotalReceived: status.TotalReceived,
TotalWanted: status.TotalWanted,
PieceMap: pieceMap.Clone(),
}
}
// Resume loading and verification are transitional. A nil Snapshot retains
// the last trusted completion bitset until goed2k publishes a stable map.
return &fetcher.Stats{
Snapshot: snapshot,
Runtime: &ped2k.StatsRuntime{
State: string(status.State),
Paused: status.Paused,
ActivePeers: handle.ActiveConnections(),
TotalPeers: status.NumPeers,
DownloadRate: status.DownloadRate,
UploadRate: status.UploadRate,
Peers: buildED2KPeers(handle.GetPeersInfo()),
},
}
}
func buildED2KPieceMap(snapshots []goed2k.PieceSnapshot) *base.PieceMap {
if len(snapshots) == 0 {
return nil
}
pieceMap := base.NewPieceMap(len(snapshots), goed2k.PieceSize)
for _, snapshot := range snapshots {
if snapshot.Index < 0 || snapshot.Index >= pieceMap.PieceCount() {
continue
}
_ = pieceMap.Update(snapshot.Index, snapshot.State == goed2k.PieceSnapshotFinished)
}
return pieceMap
}
func buildED2KPeers(peerInfos []goed2k.PeerInfo) []*base.PeerStats {
peers := make([]*base.PeerStats, 0, len(peerInfos))
for _, peerInfo := range peerInfos {
peers = append(peers, &base.PeerStats{
Address: peerInfo.Endpoint.String(),
Client: ed2kPeerClient(peerInfo),
DownloadSpeed: int64(peerInfo.PayloadDownloadSpeed),
UploadSpeed: int64(peerInfo.PayloadUploadSpeed),
PieceCount: peerInfo.RemotePieces.Count(),
Source: peerInfo.SourceString(),
Transport: "tcp",
})
}
return peers
}
func ed2kPeerClient(peerInfo goed2k.PeerInfo) string {
return strings.TrimSpace(peerInfo.ModName + " " + peerInfo.StrModVersion)
}
func (f *Fetcher) Progress() fetcher.Progress {
+72
View File
@@ -0,0 +1,72 @@
package ed2k
import (
"testing"
ped2k "github.com/GopeedLab/gopeed/pkg/protocol/ed2k"
"github.com/monkeyWie/goed2k"
"github.com/monkeyWie/goed2k/protocol"
)
func TestStatsSeparatesSnapshotAndRuntimeWithoutHandle(t *testing.T) {
frame := (&Fetcher{}).Stats()
if frame.Snapshot != nil {
t.Fatalf("snapshot = %T, want nil without a valid handle", frame.Snapshot)
}
runtime, ok := frame.Runtime.(*ped2k.StatsRuntime)
if !ok {
t.Fatalf("runtime type = %T", frame.Runtime)
}
if runtime.Peers == nil || len(runtime.Peers) != 0 {
t.Fatalf("unexpected runtime peers: %+v", runtime.Peers)
}
}
func TestBuildED2KPieceMapPreservesIndexes(t *testing.T) {
snapshots := []goed2k.PieceSnapshot{
{Index: 0, State: goed2k.PieceSnapshotFinished},
{Index: 1, State: goed2k.PieceSnapshotMissing},
{Index: 2, State: goed2k.PieceSnapshotDownloading},
{Index: 3, State: goed2k.PieceSnapshotFinished},
}
pieceMap := buildED2KPieceMap(snapshots)
if pieceMap == nil {
t.Fatal("buildED2KPieceMap returned nil")
}
want := []bool{true, false, false, true}
for index, expected := range want {
got, err := pieceMap.Get(index)
if err != nil || got != expected {
t.Fatalf("piece %d = %v, %v; want %v", index, got, err, expected)
}
}
if pieceMap.CompletedPieces() != 2 {
t.Fatalf("CompletedPieces() = %d, want 2", pieceMap.CompletedPieces())
}
}
func TestBuildED2KPeers(t *testing.T) {
remotePieces := protocol.NewBitField(4)
remotePieces.SetBit(0)
remotePieces.SetBit(2)
endpoint, err := protocol.EndpointFromString("127.0.0.1", 4662)
if err != nil {
t.Fatalf("EndpointFromString: %v", err)
}
peers := buildED2KPeers([]goed2k.PeerInfo{{
PayloadDownloadSpeed: 2048,
PayloadUploadSpeed: 1024,
RemotePieces: remotePieces,
Endpoint: endpoint,
ModName: "aMule",
StrModVersion: "2.3.3",
SourceFlag: int(goed2k.PeerServer | goed2k.PeerDHT),
}})
if len(peers) != 1 {
t.Fatalf("len(peers) = %d, want 1", len(peers))
}
peer := peers[0]
if peer.Client != "aMule 2.3.3" || peer.PieceCount != 2 || peer.Source != "server|kad" || peer.Transport != "tcp" {
t.Fatalf("unexpected peer: %+v", peer)
}
}
File diff suppressed because it is too large. Load diff
+88 -4
View File
@@ -14,8 +14,15 @@ import (
// ============================================================================
type fetcherData struct {
Connections []*connection
RedirectURL string // Saved redirect URL for resume
Connections []*connection
RedirectURL string // Saved redirect URL for resume
IfRange string // Strong ETag or Last-Modified validator for safe resume
RangeReprobeEligible bool // Origin advertised Range before falling back to sequential mode
RangeValidatorPinned bool // Recovered Range mode must keep the same If-Range validator
SequentialSizeUnknown bool // Interrupted chunked restart must retry from byte zero
Range *bool // Authoritative Range mode; nil for records saved by older versions
ResourceSize *int64 // Authoritative resource size from the same snapshot as Connections
FileSize *int64 // Authoritative single-file size; nil for older records
}
// ============================================================================
@@ -75,12 +82,73 @@ func (fm *FetcherManager) Store(f fetcher.Fetcher) (data any, err error) {
_f.redirectLock.Lock()
redirectURL := _f.redirectURL
_f.redirectLock.Unlock()
// Build an immutable snapshot while holding the same lock used by download
// workers to update Range mode and connection progress. The storage layer
// marshals this value after Store returns, so returning live pointers would
// otherwise race with the active download and could persist a mixed state.
_f.connMu.Lock()
connections := snapshotConnectionsLocked(_f.connections)
ifRange := _f.ifRange
rangeReprobeEligible := _f.rangeReprobeEligible
rangeValidatorPinned := _f.rangeValidatorPinned
sequentialSizeUnknown := _f.sequentialSizeUnknown
var rangeMode *bool
var resourceSize *int64
var fileSize *int64
if _f.meta != nil && _f.meta.Res != nil {
value := _f.meta.Res.Range
rangeMode = &value
size := _f.meta.Res.Size
resourceSize = &size
if len(_f.meta.Res.Files) > 0 && _f.meta.Res.Files[0] != nil {
size := _f.meta.Res.Files[0].Size
fileSize = &size
}
}
_f.connMu.Unlock()
return &fetcherData{
Connections: _f.connections,
RedirectURL: redirectURL,
Connections: connections,
RedirectURL: redirectURL,
IfRange: ifRange,
RangeReprobeEligible: rangeReprobeEligible,
RangeValidatorPinned: rangeValidatorPinned,
SequentialSizeUnknown: sequentialSizeUnknown,
Range: rangeMode,
ResourceSize: resourceSize,
FileSize: fileSize,
}, nil
}
// snapshotConnectionsLocked copies only the serialized connection state and
// deep-copies chunks. The caller must hold the fetcher's connMu.
func snapshotConnectionsLocked(connections []*connection) []*connection {
snapshot := make([]*connection, len(connections))
for i, conn := range connections {
if conn == nil {
continue
}
copyConn := &connection{
ID: conn.ID,
Role: conn.Role,
State: conn.State,
Downloaded: conn.Downloaded,
Completed: conn.Completed,
}
if conn.Chunk != nil {
copyChunk := *conn.Chunk
if conn.Chunk.End != nil {
end := *conn.Chunk.End
copyChunk.End = &end
}
copyConn.Chunk = &copyChunk
}
snapshot[i] = copyConn
}
return snapshot
}
func (fm *FetcherManager) Restore() (v any, f func(meta *fetcher.FetcherMeta, v any) fetcher.Fetcher) {
return &fetcherData{}, func(meta *fetcher.FetcherMeta, v any) fetcher.Fetcher {
fd := v.(*fetcherData)
@@ -96,6 +164,22 @@ func (fm *FetcherManager) Restore() (v any, f func(meta *fetcher.FetcherMeta, v
if fd.RedirectURL != "" {
fetcher.redirectURL = fd.RedirectURL
}
fetcher.ifRange = fd.IfRange
fetcher.rangeReprobeEligible = fd.RangeReprobeEligible
fetcher.rangeValidatorPinned = fd.RangeValidatorPinned
fetcher.sequentialSizeUnknown = fd.SequentialSizeUnknown
if fd.Range != nil && fetcher.meta.Res != nil {
// Recovery-critical resource fields live in the same persisted snapshot
// as Connections, making them authoritative over task metadata that may
// have been saved just before or after this record.
fetcher.meta.Res.Range = *fd.Range
}
if fd.ResourceSize != nil && fetcher.meta.Res != nil {
fetcher.meta.Res.Size = *fd.ResourceSize
}
if fd.FileSize != nil && fetcher.meta.Res != nil && len(fetcher.meta.Res.Files) > 0 && fetcher.meta.Res.Files[0] != nil {
fetcher.meta.Res.Files[0].Size = *fd.FileSize
}
return fetcher
}
}
File diff suppressed because it is too large. Load diff
+75 -17
View File
@@ -16,6 +16,7 @@ import (
"time"
"unicode/utf8"
"github.com/GopeedLab/gopeed/internal/httpclient"
"github.com/GopeedLab/gopeed/pkg/base"
fhttp "github.com/GopeedLab/gopeed/pkg/protocol/http"
"github.com/GopeedLab/gopeed/pkg/util"
@@ -26,6 +27,45 @@ type RequestError struct {
Code int
}
// extractIfRangeValidator returns only validators that are strong enough for
// If-Range. Any entity-tag header blocks Last-Modified fallback: a weak or
// malformed ETag does not make the date validator strong.
func extractIfRangeValidator(header http.Header) string {
etag := strings.TrimSpace(header.Get(base.HttpHeaderETag))
if etag != "" {
if isStrongETag(etag) {
return etag
}
return ""
}
lastModified := strings.TrimSpace(header.Get(base.HttpHeaderLastModified))
date := strings.TrimSpace(header.Get("Date"))
if lastModified == "" || date == "" {
return ""
}
modifiedAt, modifiedErr := http.ParseTime(lastModified)
responseAt, responseErr := http.ParseTime(date)
if modifiedErr != nil || responseErr != nil || responseAt.Sub(modifiedAt) < time.Second {
return ""
}
return lastModified
}
func isStrongETag(value string) bool {
if len(value) < 2 || value[0] != '"' || value[len(value)-1] != '"' {
return false
}
for i := 1; i < len(value)-1; i++ {
b := value[i]
if b == 0x21 || (b >= 0x23 && b <= 0x7e) || b >= 0x80 {
continue
}
return false
}
return true
}
func NewRequestError(code int) *RequestError {
return &RequestError{Code: code}
}
@@ -165,15 +205,17 @@ func isRedirectExpiredError(err error) bool {
// tryFallbackToOriginalURL attempts to make a request using the original URL
// when the redirect URL has expired. Returns the response if successful.
func (f *Fetcher) tryFallbackToOriginalURL(ctx context.Context, client *http.Client, rangeStart, rangeEnd int64) (*http.Response, error) {
func (f *Fetcher) tryFallbackToOriginalURL(ctx context.Context, client *http.Client, rangeStart int64, rangeEnd *int64, rangeRequested bool, ifRange string) (*http.Response, error) {
httpReq, err := f.buildRequestWithOriginalURL(ctx, f.meta.Req)
if err != nil {
return nil, err
}
if f.meta.Res.Range && rangeEnd > 0 {
httpReq.Header.Set(base.HttpHeaderRange,
fmt.Sprintf(base.HttpHeaderRangeFormat, rangeStart, rangeEnd))
if rangeRequested {
httpReq.Header.Set(base.HttpHeaderRange, formatRangeHeader(rangeStart, rangeEnd))
if ifRange != "" {
httpReq.Header.Set(base.HttpHeaderIfRange, ifRange)
}
}
resp, err := client.Do(httpReq)
@@ -189,6 +231,13 @@ func (f *Fetcher) tryFallbackToOriginalURL(ctx context.Context, client *http.Cli
return resp, nil
}
func formatRangeHeader(start int64, end *int64) string {
if end == nil {
return fmt.Sprintf("bytes=%d-", start)
}
return fmt.Sprintf(base.HttpHeaderRangeFormat, start, *end)
}
// buildClient creates an HTTP client with the default connection timeout.
// Used for resolve phase where we don't have connection time data yet.
func (f *Fetcher) buildClient() *http.Client {
@@ -216,21 +265,30 @@ func (f *Fetcher) buildFastFailClient() *http.Client {
// buildClientWithTimeout creates an HTTP client with the specified connection timeout.
func (f *Fetcher) buildClientWithTimeout(timeout time.Duration) *http.Client {
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: timeout,
}).DialContext,
Proxy: f.ctl.GetProxy(f.meta.Req.Proxy),
TLSClientConfig: &tls.Config{
InsecureSkipVerify: f.meta.Req.SkipVerifyCert,
},
TLSHandshakeTimeout: timeout,
}
jar, _ := cookiejar.New(nil)
return &http.Client{
Transport: transport,
Jar: jar,
client, err := httpclient.NewClient(httpclient.Options{
Client: httpclient.ClientOptions{
Jar: jar,
},
Transport: httpclient.TransportOptions{
DialContext: (&net.Dialer{
Timeout: timeout,
}).DialContext,
Proxy: f.ctl.GetProxy(f.meta.Req.Proxy),
TLSClientConfig: &tls.Config{
InsecureSkipVerify: f.meta.Req.SkipVerifyCert,
},
TLSHandshakeTimeout: timeout,
},
Impersonation: httpclient.ImpersonationOptions{
Mode: httpclient.ImpersonationAuto,
Session: f.impersonationSession,
},
})
if err != nil {
panic(fmt.Sprintf("build HTTP client: %v", err))
}
return client
}
// ============================================================================
+39
View File
@@ -372,6 +372,45 @@ func StartTestNoRangeSlowServer(delayPerChunk time.Duration) net.Listener {
})
}
// StartTestIgnoredRangeServer advertises byte-range support but ignores Range
// requests and always returns the full representation with 200 OK.
func StartTestIgnoredRangeServer(delayPerChunk time.Duration) net.Listener {
return startTestServer(func(sl *shutdownListener) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/"+BuildName, func(writer http.ResponseWriter, request *http.Request) {
writer.Header().Set("Content-Length", fmt.Sprintf("%d", BuildSize))
writer.Header().Set("Accept-Ranges", "bytes")
writer.WriteHeader(http.StatusOK)
if flusher, ok := writer.(http.Flusher); ok {
flusher.Flush()
}
file, err := os.Open(BuildFile)
if err != nil {
return
}
defer file.Close()
buf := make([]byte, 256*1024)
for !sl.isShutdown {
n, readErr := file.Read(buf)
if n > 0 {
if _, writeErr := writer.Write(buf[:n]); writeErr != nil {
return
}
if delayPerChunk > 0 {
time.Sleep(delayPerChunk)
}
}
if readErr != nil {
return
}
}
})
return mux
})
}
// StartTestExpiringRedirectServer creates a server that simulates expiring redirect URLs.
// The original URL redirects to a temporary URL that expires after a specified number of requests.
// When the temporary URL expires (returns 403), the client should retry with the original URL
+5 -1
View File
@@ -81,6 +81,10 @@ type nativeCookieJSON struct {
var providerSeq atomic.Uint64
// Keep native page creation aligned with the provider availability budget used
// by the integration contract. Cold WebView2 startup can exceed ten seconds.
const startupTimeout = time.Minute
func newPageWrapper(opts enginewebview.OpenOptions) *pageWrapper {
seq := providerSeq.Add(1)
return &pageWrapper{
@@ -142,7 +146,7 @@ func (p *pageWrapper) start() error {
case err := <-p.ready:
p.tracef("open %dms", time.Since(startedAt).Milliseconds())
return err
case <-time.After(10 * time.Second):
case <-time.After(startupTimeout):
p.tracef("open timeout %dms", time.Since(startedAt).Milliseconds())
return fmt.Errorf("webview startup timeout")
}
+5 -1
View File
@@ -14,6 +14,10 @@ import (
const TestUserAgent = "GopeedWebViewIntegration/1.0"
// Providers may need to initialize an external host or a native browser runtime
// before the first page can be created.
const defaultAvailabilityTimeout = time.Minute
type ContractOptions struct {
AvailabilityTimeout time.Duration
CookieDomainMode CookieDomainMode
@@ -32,7 +36,7 @@ func RunProviderContract(t *testing.T, provider enginewebview.Provider, opts Con
timeout := opts.AvailabilityTimeout
if timeout <= 0 {
timeout = 10 * time.Second
timeout = defaultAvailabilityTimeout
}
waitForProviderAvailable(t, provider, timeout)
@@ -7,7 +7,6 @@ import (
"os"
"path/filepath"
"testing"
"time"
"github.com/GopeedLab/gopeed/internal/webview/integrationtest"
enginewebview "github.com/GopeedLab/gopeed/pkg/download/engine/webview"
@@ -26,9 +25,8 @@ func TestProviderContract(t *testing.T) {
Token: *webViewRPCToken,
})
integrationtest.RunProviderContract(t, provider, integrationtest.ContractOptions{
AvailabilityTimeout: 5 * time.Minute,
CookieDomainMode: integrationtest.CookieDomainModeRequired,
CookieTestURL: "https://example.com/",
CookieDomainMode: integrationtest.CookieDomainModeRequired,
CookieTestURL: "https://example.com/",
})
}
+82
View File
@@ -0,0 +1,82 @@
package api
import (
"encoding/json"
"sync"
"github.com/GopeedLab/gopeed/pkg/download"
)
type TaskEventMask uint64
const (
TaskEventDone TaskEventMask = 1 << iota
TaskEventError
)
type TaskEvent struct {
Type string `json:"type"`
TaskID string `json:"taskId"`
Name string `json:"name,omitempty"`
Error string `json:"error,omitempty"`
}
type TaskEventListener func(payload string)
type taskEventSubscription struct {
mu sync.RWMutex
mask TaskEventMask
listener TaskEventListener
}
func (s *Service) SubscribeTaskEvents(mask TaskEventMask, listener TaskEventListener) {
s.taskEvents.mu.Lock()
defer s.taskEvents.mu.Unlock()
s.taskEvents.mask = mask
s.taskEvents.listener = listener
}
func (s *Service) emitTaskEvent(event *download.Event) {
if event == nil || event.Task == nil {
return
}
var mask TaskEventMask
switch event.Key {
case download.EventKeyDone:
mask = TaskEventDone
case download.EventKeyError:
mask = TaskEventError
default:
return
}
s.taskEvents.mu.RLock()
if s.taskEvents.mask&mask == 0 || s.taskEvents.listener == nil {
s.taskEvents.mu.RUnlock()
return
}
listener := s.taskEvents.listener
s.taskEvents.mu.RUnlock()
payload := TaskEvent{
Type: "task." + string(event.Key),
TaskID: event.Task.ID,
}
if event.Task.Meta != nil {
payload.Name = event.Task.Name()
}
if event.Err != nil {
payload.Error = event.Err.Error()
}
data, err := json.Marshal(payload)
if err != nil {
return
}
// A platform callback must never be able to crash a download worker.
func() {
defer func() { _ = recover() }()
listener(string(data))
}()
}
+37
View File
@@ -0,0 +1,37 @@
package api
import (
"encoding/json"
"testing"
"github.com/GopeedLab/gopeed/pkg/download"
)
func TestTaskEventSubscriptionFiltersMask(t *testing.T) {
service := &Service{}
var payloads []string
service.SubscribeTaskEvents(TaskEventDone, func(payload string) {
payloads = append(payloads, payload)
})
task := &download.Task{ID: "task-1"}
service.emitTaskEvent(&download.Event{Key: download.EventKeyError, Task: task})
service.emitTaskEvent(&download.Event{Key: download.EventKeyDone, Task: task})
if len(payloads) != 1 {
t.Fatalf("got %d callbacks, want 1", len(payloads))
}
var event TaskEvent
if err := json.Unmarshal([]byte(payloads[0]), &event); err != nil {
t.Fatal(err)
}
if event.Type != "task.done" || event.TaskID != task.ID {
t.Fatalf("unexpected event: %#v", event)
}
}
func TestTaskEventListenerPanicIsContained(t *testing.T) {
service := &Service{}
service.SubscribeTaskEvents(TaskEventDone, func(string) { panic("callback failed") })
service.emitTaskEvent(&download.Event{Key: download.EventKeyDone, Task: &download.Task{ID: "task-1"}})
}
+94
View File
@@ -0,0 +1,94 @@
package api
import (
"fmt"
pathpkg "path"
"strings"
)
type HandlerFunc func(*Context) *Response
type RouteSpec struct {
Method string
Pattern string
Handler HandlerFunc
parts []routePart
}
type routePart struct {
literal string
param string
}
func newRoute(method, pattern string, handler HandlerFunc) RouteSpec {
pattern = cleanPath(pattern)
return RouteSpec{
Method: strings.ToUpper(method),
Pattern: pattern,
Handler: handler,
parts: parseRouteParts(pattern),
}
}
func validateRoutes(routes []RouteSpec) error {
patterns := make(map[string]struct{}, len(routes))
for _, route := range routes {
if route.Method == "" || route.Pattern == "" || route.Handler == nil {
return fmt.Errorf("invalid API route: %+v", route)
}
key := route.Method + " " + route.Pattern
if _, exists := patterns[key]; exists {
return fmt.Errorf("duplicate API route: %s", key)
}
patterns[key] = struct{}{}
}
return nil
}
func parseRouteParts(pattern string) []routePart {
pattern = strings.Trim(pattern, "/")
if pattern == "" {
return nil
}
segments := strings.Split(pattern, "/")
parts := make([]routePart, 0, len(segments))
for _, segment := range segments {
if strings.HasPrefix(segment, "{") && strings.HasSuffix(segment, "}") {
name := strings.TrimSuffix(strings.TrimPrefix(segment, "{"), "}")
parts = append(parts, routePart{param: name})
continue
}
parts = append(parts, routePart{literal: segment})
}
return parts
}
func (r RouteSpec) Match(rawPath string) (map[string]string, bool) {
path := strings.Trim(cleanPath(rawPath), "/")
if path == "" && len(r.parts) == 0 {
return map[string]string{}, true
}
segments := strings.Split(path, "/")
if len(segments) != len(r.parts) {
return nil, false
}
params := make(map[string]string)
for index, part := range r.parts {
if part.param != "" {
params[part.param] = segments[index]
continue
}
if part.literal != segments[index] {
return nil, false
}
}
return params, true
}
func cleanPath(rawPath string) string {
clean := pathpkg.Clean("/" + strings.TrimSpace(rawPath))
if clean == "." {
return "/"
}
return clean
}
+457
View File
@@ -0,0 +1,457 @@
package api
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"runtime"
"strings"
"github.com/GopeedLab/gopeed/pkg/base"
"github.com/GopeedLab/gopeed/pkg/download"
restmodel "github.com/GopeedLab/gopeed/pkg/rest/model"
)
type Context struct {
Method string
Path string
Query url.Values
Body []byte
Headers http.Header
PathParams map[string]string
}
func (c *Context) PathParam(name string) string {
if c == nil || c.PathParams == nil {
return ""
}
return c.PathParams[name]
}
type Response struct {
StatusCode int
Body any
}
type Service struct {
Downloader *download.Downloader
routes []RouteSpec
taskEvents taskEventSubscription
}
func NewService(downloader *download.Downloader) (*Service, error) {
if downloader == nil {
return nil, fmt.Errorf("downloader is nil")
}
service := &Service{Downloader: downloader}
service.routes = []RouteSpec{
newRoute(http.MethodGet, "/api/v1/info", service.info),
newRoute(http.MethodPost, "/api/v1/resolve", service.resolve),
newRoute(http.MethodPost, "/api/v1/tasks", service.createTask),
newRoute(http.MethodPost, "/api/v1/tasks/batch", service.createTaskBatch),
newRoute(http.MethodPatch, "/api/v1/tasks/{id}", service.patchTask),
newRoute(http.MethodPut, "/api/v1/tasks/{id}/pause", service.pauseTask),
newRoute(http.MethodPut, "/api/v1/tasks/pause", service.pauseTasks),
newRoute(http.MethodPut, "/api/v1/tasks/{id}/continue", service.continueTask),
newRoute(http.MethodPut, "/api/v1/tasks/continue", service.continueTasks),
newRoute(http.MethodDelete, "/api/v1/tasks/{id}", service.deleteTask),
newRoute(http.MethodDelete, "/api/v1/tasks", service.deleteTasks),
newRoute(http.MethodGet, "/api/v1/tasks/{id}", service.getTask),
newRoute(http.MethodGet, "/api/v1/tasks/{id}/status", service.getTaskStatus),
newRoute(http.MethodGet, "/api/v1/tasks", service.getTasks),
newRoute(http.MethodGet, "/api/v1/tasks/{id}/stats", service.getStats),
newRoute(http.MethodGet, "/api/v1/config", service.getConfig),
newRoute(http.MethodPut, "/api/v1/config", service.putConfig),
newRoute(http.MethodPost, "/api/v1/extensions", service.installExtension),
newRoute(http.MethodGet, "/api/v1/extensions", service.getExtensions),
newRoute(http.MethodGet, "/api/v1/extensions/{identity}", service.getExtension),
newRoute(http.MethodPut, "/api/v1/extensions/{identity}/settings", service.updateExtensionSettings),
newRoute(http.MethodPut, "/api/v1/extensions/{identity}/switch", service.switchExtension),
newRoute(http.MethodDelete, "/api/v1/extensions/{identity}", service.deleteExtension),
newRoute(http.MethodGet, "/api/v1/extensions/{identity}/update", service.updateCheckExtension),
newRoute(http.MethodPost, "/api/v1/extensions/{identity}/update", service.updateExtension),
newRoute(http.MethodPost, "/api/v1/webhook/test", service.testWebhook),
}
if err := validateRoutes(service.routes); err != nil {
return nil, err
}
downloader.Listener(service.emitTaskEvent)
return service, nil
}
func (s *Service) RouteSpecs() []RouteSpec {
return append([]RouteSpec(nil), s.routes...)
}
func (s *Service) Dispatch(method, rawPath string, query url.Values, body []byte, headers http.Header) (response *Response) {
defer func() {
if recovered := recover(); recovered != nil {
response = newErrorResponse(fmt.Sprintf("%v", recovered))
}
}()
method = strings.ToUpper(strings.TrimSpace(method))
path := cleanPath(rawPath)
for _, route := range s.routes {
if route.Method != method {
continue
}
pathParams, matched := route.Match(path)
if !matched {
continue
}
return route.Handler(&Context{
Method: method,
Path: path,
Query: query,
Body: body,
Headers: headers,
PathParams: pathParams,
})
}
return newStatusResponse(http.StatusNotFound, restmodel.NewErrorResult("not found"))
}
func (s *Service) JSON(method, rawPath string, query url.Values, body []byte, headers http.Header) (int, []byte) {
response := s.Dispatch(method, rawPath, query, body, headers)
data, err := json.Marshal(response.Body)
if err != nil {
response = newErrorResponse(err.Error())
data, _ = json.Marshal(response.Body)
}
return response.StatusCode, data
}
func (s *Service) info(_ *Context) *Response {
return newOKResponse(map[string]any{
"version": base.Version,
"runtime": runtime.Version(),
"os": runtime.GOOS,
"arch": runtime.GOARCH,
"inDocker": base.InDocker == "true",
})
}
func (s *Service) resolve(ctx *Context) *Response {
var request restmodel.ResolveTask
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
result, err := s.Downloader.Resolve(request.Req, request.Opts)
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(result)
}
func (s *Service) createTask(ctx *Context) *Response {
var request restmodel.CreateTask
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
var (
taskID string
err error
)
if request.Rid != "" {
taskID, err = s.Downloader.Create(request.Rid)
} else if request.Req != nil {
taskID, err = s.Downloader.CreateDirect(request.Req, request.Opts)
} else {
return newErrorResponse("param invalid: rid or req", restmodel.CodeInvalidParam)
}
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(taskID)
}
func (s *Service) createTaskBatch(ctx *Context) *Response {
var request base.CreateTaskBatch
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
if len(request.Reqs) == 0 {
return newErrorResponse("param invalid: reqs", restmodel.CodeInvalidParam)
}
taskIDs, err := s.Downloader.CreateDirectBatch(&request)
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(taskIDs)
}
func (s *Service) patchTask(ctx *Context) *Response {
taskID := ctx.PathParam("id")
if taskID == "" {
return invalidIDResponse()
}
var request restmodel.ResolveTask
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
if err := s.Downloader.Patch(taskID, request.Req, request.Opts); err != nil {
if err == download.ErrTaskNotFound {
return taskNotFoundResponse()
}
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) pauseTask(ctx *Context) *Response {
return s.applyTaskAction(ctx, s.Downloader.Pause)
}
func (s *Service) pauseTasks(ctx *Context) *Response {
return applyFilterAction(taskFilterFromQuery(ctx.Query), s.Downloader.Pause)
}
func (s *Service) continueTask(ctx *Context) *Response {
return s.applyTaskAction(ctx, s.Downloader.Continue)
}
func (s *Service) continueTasks(ctx *Context) *Response {
return applyFilterAction(taskFilterFromQuery(ctx.Query), s.Downloader.Continue)
}
func (s *Service) applyTaskAction(ctx *Context, action func(*download.TaskFilter) error) *Response {
taskID := ctx.PathParam("id")
if taskID == "" {
return invalidIDResponse()
}
return applyFilterAction(&download.TaskFilter{IDs: []string{taskID}}, action)
}
func applyFilterAction(filter *download.TaskFilter, action func(*download.TaskFilter) error) *Response {
if err := action(filter); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) deleteTask(ctx *Context) *Response {
taskID := ctx.PathParam("id")
if taskID == "" {
return invalidIDResponse()
}
return deleteTasks(s.Downloader, &download.TaskFilter{IDs: []string{taskID}}, ctx.Query.Get("force") == "true")
}
func (s *Service) deleteTasks(ctx *Context) *Response {
return deleteTasks(s.Downloader, taskFilterFromQuery(ctx.Query), ctx.Query.Get("force") == "true")
}
func deleteTasks(downloader *download.Downloader, filter *download.TaskFilter, force bool) *Response {
if err := downloader.Delete(filter, force); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) getTask(ctx *Context) *Response {
taskID := ctx.PathParam("id")
if taskID == "" {
return invalidIDResponse()
}
task := s.Downloader.GetTask(taskID)
if task == nil {
return taskNotFoundResponse()
}
return newOKResponse(task)
}
func (s *Service) getTaskStatus(ctx *Context) *Response {
taskID := ctx.PathParam("id")
if taskID == "" {
return invalidIDResponse()
}
status, err := s.Downloader.RuntimeStatus(taskID)
if err != nil {
if err == download.ErrTaskNotFound {
return taskNotFoundResponse()
}
return newErrorResponse(err.Error())
}
return newOKResponse(status)
}
func (s *Service) getTasks(ctx *Context) *Response {
return newOKResponse(s.Downloader.GetTasksByFilter(taskFilterFromQuery(ctx.Query)))
}
func (s *Service) getStats(ctx *Context) *Response {
taskID := ctx.PathParam("id")
if taskID == "" {
return invalidIDResponse()
}
stats, err := s.Downloader.Stats(taskID)
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(stats)
}
func (s *Service) getConfig(_ *Context) *Response {
config, err := s.Downloader.GetConfig()
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(config)
}
func (s *Service) putConfig(ctx *Context) *Response {
var config base.DownloaderStoreConfig
if response := decodeRequest(ctx.Body, &config); response != nil {
return response
}
if err := s.Downloader.PutConfig(&config); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) installExtension(ctx *Context) *Response {
var request restmodel.InstallExtension
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
var (
extension *download.Extension
err error
)
if request.DevMode {
extension, err = s.Downloader.InstallExtensionByFolder(request.URL, true)
} else {
extension, err = s.Downloader.InstallExtensionByGit(request.URL)
}
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(extension.Identity)
}
func (s *Service) getExtensions(_ *Context) *Response {
return newOKResponse(s.Downloader.GetExtensions())
}
func (s *Service) getExtension(ctx *Context) *Response {
identity := ctx.PathParam("identity")
if identity == "" {
return newErrorResponse("param invalid: identity", restmodel.CodeInvalidParam)
}
extension, err := s.Downloader.GetExtension(identity)
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(extension)
}
func (s *Service) updateExtensionSettings(ctx *Context) *Response {
identity := ctx.PathParam("identity")
var request restmodel.UpdateExtensionSettings
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
if err := s.Downloader.UpdateExtensionSettings(identity, request.Settings); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) switchExtension(ctx *Context) *Response {
identity := ctx.PathParam("identity")
var request restmodel.SwitchExtension
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
if err := s.Downloader.SwitchExtension(identity, request.Status); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) deleteExtension(ctx *Context) *Response {
if err := s.Downloader.DeleteExtension(ctx.PathParam("identity")); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) updateCheckExtension(ctx *Context) *Response {
version, err := s.Downloader.UpgradeCheckExtension(ctx.PathParam("identity"))
if err != nil {
return newErrorResponse(err.Error())
}
return newOKResponse(&restmodel.UpdateCheckExtensionResp{NewVersion: version})
}
func (s *Service) updateExtension(ctx *Context) *Response {
if err := s.Downloader.UpgradeExtension(ctx.PathParam("identity")); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func (s *Service) testWebhook(ctx *Context) *Response {
var request restmodel.TestWebhookReq
if response := decodeRequest(ctx.Body, &request); response != nil {
return response
}
if err := s.Downloader.TestWebhookUrl(request.URL); err != nil {
return newErrorResponse(err.Error())
}
return newNilResponse()
}
func decodeRequest(body []byte, target any) *Response {
if err := json.NewDecoder(bytes.NewReader(body)).Decode(target); err != nil {
return newErrorResponse(err.Error())
}
return nil
}
func taskFilterFromQuery(query url.Values) *download.TaskFilter {
if query == nil {
query = url.Values{}
}
return &download.TaskFilter{
IDs: query["id"],
Statuses: convertStatuses(query["status"]),
NotStatuses: convertStatuses(query["notStatus"]),
}
}
func convertStatuses(values []string) []base.Status {
statuses := make([]base.Status, 0, len(values))
for _, value := range values {
statuses = append(statuses, base.Status(value))
}
return statuses
}
func invalidIDResponse() *Response {
return newErrorResponse("param invalid: id", restmodel.CodeInvalidParam)
}
func taskNotFoundResponse() *Response {
return newErrorResponse("task not found", restmodel.CodeTaskNotFound)
}
func newOKResponse(data any) *Response {
return &Response{StatusCode: http.StatusOK, Body: restmodel.NewOkResult(data)}
}
func newNilResponse() *Response {
return &Response{StatusCode: http.StatusOK, Body: restmodel.NewNilResult()}
}
func newErrorResponse(message string, code ...restmodel.RespCode) *Response {
return &Response{StatusCode: http.StatusOK, Body: restmodel.NewErrorResult(message, code...)}
}
func newStatusResponse(statusCode int, body any) *Response {
return &Response{StatusCode: statusCode, Body: body}
}
+2
View File
@@ -23,6 +23,8 @@ const (
HttpHeaderContentDisposition = "Content-Disposition"
HttpHeaderUserAgent = "User-Agent"
HttpHeaderLastModified = "Last-Modified"
HttpHeaderETag = "ETag"
HttpHeaderIfRange = "If-Range"
HttpHeaderBytes = "bytes"
HttpHeaderRangeFormat = "bytes=%d-%d"
+25
View File
@@ -133,6 +133,8 @@ type Options struct {
Name string `json:"name"`
// Download file path
Path string `json:"path"`
// Use this path as the default download directory after creation succeeds
AsDefaultPath bool `json:"asDefaultPath,omitempty"`
// Select file indexes to download
SelectFiles []int `json:"selectFiles"`
// Extra info for specific fetcher
@@ -206,6 +208,8 @@ type DownloaderStoreConfig struct {
Script *ScriptConfig `json:"script"` // Script is the script execution configuration
AutoTorrent *AutoTorrentConfig `json:"autoTorrent"` // AutoTorrent is the auto torrent task creation configuration
Archive *ArchiveConfig `json:"archive"` // Archive is the archive extraction configuration
API *APIServerConfig `json:"api"` // API is the optional REST server configuration
AutoStartTasks bool `json:"autoStartTasks"` // AutoStartTasks continues all unfinished tasks when the backend starts
AutoDeleteMissingFileTasks bool `json:"autoDeleteMissingFileTasks"` // AutoDeleteMissingFileTasks enables automatic deletion of tasks with missing files
}
@@ -271,6 +275,27 @@ func (cfg *DownloaderStoreConfig) Merge(beforeCfg *DownloaderStoreConfig) *Downl
if cfg.Archive == nil {
cfg.Archive = beforeCfg.Archive
}
if cfg.API == nil {
cfg.API = beforeCfg.API
}
return cfg
}
type APIServerConfig struct {
Enable bool `json:"enable"`
MCPEnable bool `json:"mcpEnable"`
Network string `json:"network"`
Address string `json:"address"`
Token string `json:"token"`
}
func (cfg *APIServerConfig) Init() *APIServerConfig {
if cfg.Network == "" {
cfg.Network = "tcp"
}
if cfg.Address == "" {
cfg.Address = "127.0.0.1:9999"
}
return cfg
}
+198
View File
@@ -0,0 +1,198 @@
package base
import (
"encoding/json"
"errors"
"fmt"
"math/bits"
)
const (
// PieceMapEncoding identifies the one-bit wire format used by PieceMap.
// One byte stores eight ordered pieces, least-significant bit first: piece
// 0 uses bit 0, piece 1 uses bit 1, and so on. A set bit means the piece is
// locally complete and verified; a clear bit means it is not complete.
PieceMapEncoding = "bitset-v1"
piecesPerByte = 8
)
var ErrPieceIndexOutOfRange = errors.New("piece index out of range")
// PieceMap stores the verified completion state of ordered pieces as a bitset.
// It deliberately excludes scheduler states such as downloading, hashing and
// failed: those states are transient and are not stable across pause/restart.
//
// Fields are private so PieceCount, CompletedPieces and packed bytes remain
// consistent. Use Add, Delete, Update and Get for mutation, and Bytes when a
// binary copy is required. JSON serializes Data as Base64.
type PieceMap struct {
pieceCount int
pieceSize int64
completedPieces int
data []byte
}
// NewPieceMap creates a map containing pieceCount incomplete pieces.
func NewPieceMap(pieceCount int, pieceSize int64) *PieceMap {
if pieceCount < 0 {
pieceCount = 0
}
return &PieceMap{
pieceCount: pieceCount,
pieceSize: pieceSize,
data: make([]byte, packedPieceByteCount(pieceCount)),
}
}
// NewPieceMapFromBytes restores a bitset-v1 map. Input bytes are copied and
// unused high bits in the last byte are cleared.
func NewPieceMapFromBytes(pieceCount int, pieceSize int64, data []byte) (*PieceMap, error) {
if pieceCount < 0 {
return nil, fmt.Errorf("%w: negative piece count", ErrPieceIndexOutOfRange)
}
expectedBytes := packedPieceByteCount(pieceCount)
if len(data) != expectedBytes {
return nil, fmt.Errorf("invalid piece data length: got %d, want %d", len(data), expectedBytes)
}
pieceMap := &PieceMap{
pieceCount: pieceCount,
pieceSize: pieceSize,
data: append([]byte(nil), data...),
}
pieceMap.clearUnusedBits()
for _, value := range pieceMap.data {
pieceMap.completedPieces += bits.OnesCount8(value)
}
return pieceMap, nil
}
// Clone returns an independent ordered snapshot.
func (m *PieceMap) Clone() *PieceMap {
if m == nil {
return nil
}
return &PieceMap{
pieceCount: m.pieceCount,
pieceSize: m.pieceSize,
completedPieces: m.completedPieces,
data: append([]byte(nil), m.data...),
}
}
// Add appends a piece while preserving all existing indexes.
func (m *PieceMap) Add(completed bool) {
if m.pieceCount%piecesPerByte == 0 {
m.data = append(m.data, 0)
}
m.pieceCount++
if completed {
m.setCompleted(m.pieceCount-1, true)
m.completedPieces++
}
}
// Delete removes a piece and shifts every following piece one index left.
func (m *PieceMap) Delete(index int) error {
if !m.validIndex(index) {
return ErrPieceIndexOutOfRange
}
if m.completedAt(index) {
m.completedPieces--
}
for current := index; current < m.pieceCount-1; current++ {
m.setCompleted(current, m.completedAt(current+1))
}
m.pieceCount--
m.data = m.data[:packedPieceByteCount(m.pieceCount)]
m.clearUnusedBits()
return nil
}
// Update changes whether the piece at index is complete and verified.
func (m *PieceMap) Update(index int, completed bool) error {
if !m.validIndex(index) {
return ErrPieceIndexOutOfRange
}
previous := m.completedAt(index)
if previous == completed {
return nil
}
if completed {
m.completedPieces++
} else {
m.completedPieces--
}
m.setCompleted(index, completed)
return nil
}
// Get reports whether the exact piece index is complete and verified.
func (m *PieceMap) Get(index int) (bool, error) {
if !m.validIndex(index) {
return false, ErrPieceIndexOutOfRange
}
return m.completedAt(index), nil
}
// Bytes returns an independent copy of the packed bitset-v1 bytes.
func (m *PieceMap) Bytes() []byte {
return append([]byte(nil), m.data...)
}
func (m *PieceMap) PieceCount() int { return m.pieceCount }
func (m *PieceMap) PieceSize() int64 { return m.pieceSize }
func (m *PieceMap) CompletedPieces() int { return m.completedPieces }
// MarshalJSON publishes the compact bytes without exposing mutable storage.
func (m PieceMap) MarshalJSON() ([]byte, error) {
type pieceMapJSON struct {
Encoding string `json:"encoding"`
PieceCount int `json:"pieceCount"`
PieceSize int64 `json:"pieceSize"`
CompletedPieces int `json:"completedPieces"`
Data []byte `json:"data"`
}
return json.Marshal(pieceMapJSON{
Encoding: PieceMapEncoding,
PieceCount: m.pieceCount,
PieceSize: m.pieceSize,
CompletedPieces: m.completedPieces,
Data: m.data,
})
}
func (m *PieceMap) validIndex(index int) bool {
return m != nil && index >= 0 && index < m.pieceCount
}
func (m *PieceMap) completedAt(index int) bool {
byteIndex, mask := piecePosition(index)
return m.data[byteIndex]&mask != 0
}
func (m *PieceMap) setCompleted(index int, completed bool) {
byteIndex, mask := piecePosition(index)
if completed {
m.data[byteIndex] |= mask
} else {
m.data[byteIndex] &^= mask
}
}
func (m *PieceMap) clearUnusedBits() {
if m.pieceCount == 0 || m.pieceCount%piecesPerByte == 0 {
return
}
usedBits := uint(m.pieceCount % piecesPerByte)
m.data[len(m.data)-1] &= byte(1<<usedBits) - 1
}
func piecePosition(index int) (byteIndex int, mask byte) {
return index / piecesPerByte, byte(1 << uint(index%piecesPerByte))
}
func packedPieceByteCount(pieceCount int) int {
return (pieceCount + piecesPerByte - 1) / piecesPerByte
}
+104
View File
@@ -0,0 +1,104 @@
package base
import (
"encoding/json"
"errors"
"testing"
)
func TestPieceMapCRUDAndBytes(t *testing.T) {
pieceMap := NewPieceMap(4, 16*1024)
_ = pieceMap.Update(0, true)
_ = pieceMap.Update(2, true)
if got, want := pieceMap.Bytes(), []byte{0b00000101}; len(got) != 1 || got[0] != want[0] {
t.Fatalf("Bytes() = %08b, want %08b", got, want)
}
if got := pieceMap.CompletedPieces(); got != 2 {
t.Fatalf("CompletedPieces() = %d, want 2", got)
}
pieceMap.Add(true)
if got := pieceMap.PieceCount(); got != 5 {
t.Fatalf("PieceCount() = %d, want 5", got)
}
if err := pieceMap.Delete(1); err != nil {
t.Fatalf("Delete: %v", err)
}
wantAfterDelete := []bool{true, true, false, true}
for index, want := range wantAfterDelete {
got, err := pieceMap.Get(index)
if err != nil || got != want {
t.Fatalf("Get(%d) = %v, %v; want %v", index, got, err, want)
}
}
if got := pieceMap.CompletedPieces(); got != 3 {
t.Fatalf("CompletedPieces() after delete = %d, want 3", got)
}
bytesCopy := pieceMap.Bytes()
bytesCopy[0] = 0
got, _ := pieceMap.Get(0)
if !got {
t.Fatal("Bytes returned mutable internal storage")
}
}
func TestPieceMapValidationAndRestore(t *testing.T) {
pieceMap, err := NewPieceMapFromBytes(10, 1024, []byte{0b10010001, 0xff})
if err != nil {
t.Fatalf("NewPieceMapFromBytes: %v", err)
}
// Only the low positions for pieces 8 and 9 belong to the map.
if got, want := pieceMap.Bytes()[1], byte(0b00000011); got != want {
t.Fatalf("last byte = %08b, want %08b", got, want)
}
if pieceMap.CompletedPieces() != 5 {
t.Fatalf("CompletedPieces() = %d, want 5", pieceMap.CompletedPieces())
}
if _, err := NewPieceMapFromBytes(10, 1024, []byte{0}); err == nil {
t.Fatal("expected invalid byte length error")
}
if err := pieceMap.Update(10, true); !errors.Is(err, ErrPieceIndexOutOfRange) {
t.Fatalf("Update out of range error = %v", err)
}
}
func TestPieceMapJSON(t *testing.T) {
pieceMap := NewPieceMap(4, 4096)
_ = pieceMap.Update(0, true)
_ = pieceMap.Update(2, true)
data, err := json.Marshal(pieceMap)
if err != nil {
t.Fatalf("Marshal: %v", err)
}
var got map[string]any
if err := json.Unmarshal(data, &got); err != nil {
t.Fatalf("Unmarshal JSON: %v", err)
}
if got["encoding"] != PieceMapEncoding || got["data"] != "BQ==" {
t.Fatalf("unexpected JSON: %s", data)
}
if got["pieceCount"] != float64(4) || got["pieceSize"] != float64(4096) || got["completedPieces"] != float64(2) {
t.Fatalf("unexpected metadata: %s", data)
}
}
func TestPieceMapCloneIsIndependent(t *testing.T) {
pieceMap := NewPieceMap(4, 4096)
_ = pieceMap.Update(0, true)
snapshot := pieceMap.Clone()
_ = snapshot.Update(1, true)
if got, _ := pieceMap.Get(1); got {
t.Fatal("Clone mutated the source map")
}
if snapshot.CompletedPieces() != 2 {
t.Fatalf("clone completed pieces = %d, want 2", snapshot.CompletedPieces())
}
if (*PieceMap)(nil).Clone() != nil {
t.Fatal("nil map clone must stay nil")
}
}
+21
View File
@@ -0,0 +1,21 @@
package base
// PeerStats is the common row returned by protocols that expose connected
// peers. Speeds contain payload bytes per second rather than protocol overhead.
type PeerStats struct {
Address string `json:"address"`
Client string `json:"client"`
DownloadSpeed int64 `json:"downloadSpeed"`
UploadSpeed int64 `json:"uploadSpeed"`
PieceCount int `json:"pieceCount"`
// Completion is the known remote data completion ratio in the range 0–1.
// It is omitted when a protocol cannot determine the remote total.
Completion *float64 `json:"completion,omitempty"`
// Relevance is the ratio of locally wanted, missing pieces that this peer
// claims to have. It is omitted when the local missing set is unavailable or empty.
Relevance *float64 `json:"relevance,omitempty"`
Source string `json:"source"`
// Transport is the active connection transport, for example tcp or utp.
// It is intentionally separate from Source, which describes peer discovery.
Transport string `json:"transport"`
}
+366 -31
View File
@@ -1,6 +1,8 @@
package download
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math"
@@ -28,10 +30,14 @@ import (
)
const (
uploadCheckpointInterval = 30 * time.Second
// task info bucket
bucketTask = "task"
// task download data bucket
bucketSave = "save"
// task statistics snapshot bucket
bucketTaskStats = "task_stats"
// protocol-level shared client state bucket
bucketProtocolState = "protocol_state"
// downloader config bucket
@@ -103,6 +109,7 @@ type Downloader struct {
listener Listener
lock *sync.Mutex
configLock *sync.RWMutex
fetcherMapLock *sync.RWMutex
checkDuplicateLock *sync.Mutex
closed atomic.Bool
@@ -128,6 +135,7 @@ func NewDownloader(cfg *DownloaderConfig) *Downloader {
storage: cfg.Storage,
lock: &sync.Mutex{},
configLock: &sync.RWMutex{},
fetcherMapLock: &sync.RWMutex{},
checkDuplicateLock: &sync.Mutex{},
@@ -147,7 +155,7 @@ func (d *Downloader) Setup() error {
d.blob = internalblob.NewRegistry("")
// setup storage
if err := d.storage.Setup([]string{bucketTask, bucketSave, bucketProtocolState, bucketConfig, bucketExtension, bucketExtensionStorage}); err != nil {
if err := d.storage.Setup([]string{bucketTask, bucketSave, bucketTaskStats, bucketProtocolState, bucketConfig, bucketExtension, bucketExtensionStorage}); err != nil {
return err
}
// load config from storage
@@ -222,7 +230,10 @@ func (d *Downloader) Setup() error {
// handle upload
go func() {
for _, task := range d.tasks {
d.lock.Lock()
tasks := append([]*Task(nil), d.tasks...)
d.lock.Unlock()
for _, task := range tasks {
if task.Status == base.DownloadStatusDone && task.Uploading {
if err := d.restoreTask(task); err != nil {
d.Logger.Error().Stack().Err(err).Msgf("task upload restore fetcher failed, task id: %s", task.ID)
@@ -238,9 +249,14 @@ func (d *Downloader) Setup() error {
// calculate download speed every tick
go func() {
lastUploadCheckpoint := time.Now()
for !d.closed.Load() {
if len(d.tasks) > 0 {
for _, task := range d.tasks {
uploadCheckpointDue := time.Since(lastUploadCheckpoint) >= uploadCheckpointInterval
d.lock.Lock()
tasks := append([]*Task(nil), d.tasks...)
d.lock.Unlock()
if len(tasks) > 0 {
for _, task := range tasks {
func() {
// Do not acquire d.lock (via GetTask) while holding
// statusLock; scheduling uses the opposite lock order.
@@ -260,6 +276,7 @@ func (d *Downloader) Setup() error {
current := task.fetcher.Progress().TotalDownloaded()
tick := float64(d.cfg.RefreshInterval) / 1000
downloadDataChanged := false
uploading := task.Uploading
if task.Status == base.DownloadStatusRunning {
downloadDataChanged = current != task.Progress.Downloaded
task.Progress.Used = task.timer.Used()
@@ -268,7 +285,7 @@ func (d *Downloader) Setup() error {
}
uploadDataChanged := false
if task.Uploading {
if uploading {
uploader := task.fetcher.(fetcher.Uploader)
currentUploaded := uploader.UploadedBytes()
uploadDataChanged = currentUploaded != task.Progress.Uploaded
@@ -276,23 +293,44 @@ func (d *Downloader) Setup() error {
task.Progress.Uploaded = currentUploaded
}
task.statusLock.Unlock()
// Stats are pulled on the same cadence as speed so fetchers stay
// storage-agnostic. Runtime is refreshed in memory every tick, while
// only a changed durable Snapshot reaches bucketTaskStats.
if err := d.captureTaskStats(task, true, false); err != nil {
d.Logger.Warn().Err(err).Msgf("persist task stats failed, task id: %s", task.ID)
}
// Listener callbacks may Pause/Continue and acquire statusLock.
d.emit(EventKeyProgress, task)
// store fetcher progress when download/upload data changed
if !downloadDataChanged && !uploadDataChanged {
// Store active upload state periodically even without traffic so
// protocol-owned values such as BT seed time remain durable.
if !shouldSaveTaskCheckpoint(
downloadDataChanged,
uploadDataChanged,
uploading,
uploadCheckpointDue,
) {
return
}
d.saveTask(task)
if err := d.saveTask(task); err != nil {
d.Logger.Warn().Err(err).Msgf("persist task checkpoint failed, task id: %s", task.ID)
}
}()
}
}
if uploadCheckpointDue {
lastUploadCheckpoint = time.Now()
}
time.Sleep(time.Millisecond * time.Duration(d.cfg.RefreshInterval))
}
}()
return nil
}
func shouldSaveTaskCheckpoint(downloadChanged, uploadChanged, uploading, uploadCheckpointDue bool) bool {
return downloadChanged || uploadChanged || uploading && uploadCheckpointDue
}
// cleanupNonExistingTasks checks for tasks whose files are missing on disk
// and removes them if the AutoCleanMissingFiles config is enabled.
func (d *Downloader) cleanupNonExistingTasks() {
@@ -426,9 +464,6 @@ func ensureResourceRequestRawURLs(parentReq *base.Request, res *base.Resource) {
}
func (d *Downloader) Resolve(req *base.Request, opts *base.Options) (rr *ResolveResult, err error) {
if req == nil {
return nil, errors.New("request cannot be nil")
}
rrId, err := gonanoid.New()
if err != nil {
return
@@ -496,6 +531,18 @@ func (d *Downloader) remainRunningCount() int {
}
func (d *Downloader) CreateDirect(req *base.Request, opts *base.Options) (taskId string, err error) {
defaultPath, err := d.prepareDefaultPath(opts)
if err != nil {
return "", err
}
taskId, err = d.createDirect(req, opts)
if err == nil {
d.persistDefaultPathBestEffort(defaultPath)
}
return
}
func (d *Downloader) createDirect(req *base.Request, opts *base.Options) (taskId string, err error) {
ensureRequestRawURL(req)
var fetcher fetcher.Fetcher
fetcher, err = d.buildFetcher(req.URL)
@@ -511,18 +558,26 @@ func (d *Downloader) CreateDirect(req *base.Request, opts *base.Options) (taskId
}
func (d *Downloader) CreateDirectBatch(req *base.CreateTaskBatch) (taskId []string, err error) {
defaultPath, err := d.prepareDefaultPath(req.Opts)
if err != nil {
return nil, err
}
taskIds := make([]string, 0)
for _, ir := range req.Reqs {
opts := ir.Opts
if opts == nil {
opts = req.Opts
}
taskId, err := d.CreateDirect(ir.Req, opts.Clone())
if opts != nil {
opts = opts.Clone()
}
taskId, err := d.createDirect(ir.Req, opts)
if err != nil {
return nil, err
}
taskIds = append(taskIds, taskId)
}
d.persistDefaultPathBestEffort(defaultPath)
return taskIds, nil
}
@@ -538,7 +593,15 @@ func (d *Downloader) Create(rrId string) (taskId string, err error) {
delete(d.fetcherCache, rrId)
d.fetcherMapLock.Unlock()
}()
return d.doCreate(fetcher, nil)
defaultPath, err := d.prepareDefaultPath(fetcher.Meta().Opts)
if err != nil {
return "", err
}
taskId, err = d.doCreate(fetcher, nil)
if err == nil {
d.persistDefaultPathBestEffort(defaultPath)
}
return
}
// Patch modifies task-specific data based on the protocol.
@@ -741,6 +804,16 @@ func (d *Downloader) ContinueBatch(filter *TaskFilter) (err error) {
return
}
// ContinueOnStartup applies the persisted startup policy after the backend is
// ready to accept connections. Continue(nil) intentionally preserves the same
// continue-all semantics exposed by the API, including retrying failed tasks.
func (d *Downloader) ContinueOnStartup() error {
if !d.cfg.DownloaderStoreConfig.AutoStartTasks {
return nil
}
return d.Continue(nil)
}
func (d *Downloader) Delete(filter *TaskFilter, force bool) (err error) {
if filter == nil || filter.IsEmpty() {
return d.deleteAll(force)
@@ -814,19 +887,189 @@ func (d *Downloader) Stats(id string) (sr any, err error) {
if task == nil {
return sr, ErrTaskNotFound
}
if task.fetcher == nil {
err = func() error {
task.statusLock.Lock()
defer task.statusLock.Unlock()
return d.restoreFetcher(task)
}()
if err != nil {
return
// A loaded fetcher is authoritative. Query it directly without restoring a
// paused fetcher from bucketSave: statistics reads must never consume or
// otherwise mutate download recovery state.
task.lock.Lock()
if task.fetcher != nil {
status := d.taskStatus(task)
live := status == base.DownloadStatusRunning || task.Uploading
if captureErr := d.captureTaskStats(task, live, false); captureErr != nil {
d.Logger.Warn().Err(captureErr).Msgf("capture task stats failed, task id: %s", task.ID)
}
}
sr = task.fetcher.Stats()
return
task.lock.Unlock()
stats, err := d.loadTaskStats(task)
if err != nil || stats == nil {
return nil, err
}
return stats, nil
}
type storedTaskStats struct {
Snapshot json.RawMessage `json:"snapshot"`
}
// captureTaskStats updates the task-level cache from a loaded fetcher and
// persists only the stable Snapshot payload. Runtime telemetry is deliberately
// discarded as soon as a task is no longer active.
func (d *Downloader) captureTaskStats(task *Task, live, force bool) error {
if task == nil || task.fetcher == nil {
return nil
}
stats := task.fetcher.Stats()
if stats == nil {
return nil
}
if !live {
stats = &fetcher.Stats{Snapshot: stats.Snapshot}
}
hasSnapshotUpdate := stats.Snapshot != nil
var snapshot json.RawMessage
if hasSnapshotUpdate {
encoded, err := json.Marshal(stats.Snapshot)
if err != nil {
return err
}
if !bytes.Equal(encoded, []byte("null")) {
snapshot = encoded
} else {
hasSnapshotUpdate = false
}
}
task.statsLock.Lock()
defer task.statsLock.Unlock()
if err := d.loadStoredTaskStatsLocked(task); err != nil {
return err
}
if !hasSnapshotUpdate {
// A nil Snapshot means the protocol is temporarily unable to provide a
// trustworthy stable view (for example while BT verifies restored
// storage). Keep the previous Snapshot and refresh Runtime only.
var previousSnapshot any
if task.stats != nil {
previousSnapshot = task.stats.Snapshot
}
if previousSnapshot == nil && len(task.statsSnapshot) > 0 {
previousSnapshot = append(json.RawMessage(nil), task.statsSnapshot...)
}
if previousSnapshot == nil && stats.Runtime == nil {
task.stats = nil
} else {
task.stats = &fetcher.Stats{Snapshot: previousSnapshot, Runtime: stats.Runtime}
}
return nil
}
task.stats = stats
if !force && bytes.Equal(snapshot, task.statsSnapshot) {
return nil
}
if err := d.storage.Put(bucketTaskStats, task.ID, &storedTaskStats{Snapshot: snapshot}); err != nil {
return err
}
task.statsSnapshot = append(task.statsSnapshot[:0], snapshot...)
return nil
}
// loadTaskStats lazily restores a task snapshot. The protocol payload stays as
// json.RawMessage so Downloader remains independent from HTTP, BT, and ED2K
// schemas and can return it without a second decode/encode cycle.
func (d *Downloader) loadTaskStats(task *Task) (*fetcher.Stats, error) {
task.statsLock.Lock()
defer task.statsLock.Unlock()
if err := d.loadStoredTaskStatsLocked(task); err != nil {
return nil, err
}
return task.stats, nil
}
// loadStoredTaskStatsLocked initializes the cache from storage once. Caller
// must hold statsLock. It is shared by reads and nil-Snapshot refreshes so the
// latter can retain a trusted snapshot after process restart.
func (d *Downloader) loadStoredTaskStatsLocked(task *Task) error {
if task.statsLoaded {
return nil
}
var stored storedTaskStats
exists, err := d.storage.Get(bucketTaskStats, task.ID, &stored)
if err != nil {
return err
}
task.statsLoaded = true
if !exists || len(stored.Snapshot) == 0 {
return nil
}
task.statsSnapshot = append(json.RawMessage(nil), stored.Snapshot...)
task.stats = &fetcher.Stats{
Snapshot: append(json.RawMessage(nil), stored.Snapshot...),
}
return nil
}
// RuntimeStatus returns the small task snapshot used by high-frequency detail
// polling. Reading task.lock before statusLock follows the same lock order as
// pause and patch operations, while also keeping fetcher and resource metadata
// stable while file progress is collected.
func (d *Downloader) RuntimeStatus(id string) (*TaskRuntimeStatus, error) {
task := d.GetTask(id)
if task == nil {
return nil, ErrTaskNotFound
}
task.lock.Lock()
defer task.lock.Unlock()
task.statusLock.Lock()
defer task.statusLock.Unlock()
result := &TaskRuntimeStatus{
Status: task.Status,
Files: make([]FileRuntimeStatus, 0),
}
if task.Progress != nil {
result.Used = task.Progress.Used
result.Speed = task.Progress.Speed
result.Downloaded = task.Progress.Downloaded
result.UploadSpeed = task.Progress.UploadSpeed
result.Uploaded = task.Progress.Uploaded
result.ExtractStatus = task.Progress.ExtractStatus
result.ExtractProgress = task.Progress.ExtractProgress
}
if task.Meta == nil || task.Meta.Res == nil {
return result, nil
}
result.Total = task.Meta.Res.Size
if task.fetcher == nil {
return result, nil
}
fileProgress := task.fetcher.Progress()
var selectedFiles []int
if task.Meta.Opts != nil {
selectedFiles = task.Meta.Opts.SelectFiles
}
resourceFiles := task.Meta.Res.Files
for progressIndex, downloaded := range fileProgress {
resourceIndex := progressIndex
if progressIndex < len(selectedFiles) {
resourceIndex = selectedFiles[progressIndex]
}
if resourceIndex < 0 || resourceIndex >= len(resourceFiles) {
continue
}
result.Files = append(result.Files, FileRuntimeStatus{
Index: resourceIndex,
Size: resourceFiles[resourceIndex].Size,
Downloaded: downloaded,
})
}
return result, nil
}
func (d *Downloader) doDelete(task *Task, force bool) (err error) {
@@ -838,6 +1081,9 @@ func (d *Downloader) doDelete(task *Task, force bool) (err error) {
if err := d.storage.Delete(bucketSave, task.ID); err != nil {
return err
}
if err := d.storage.Delete(bucketTaskStats, task.ID); err != nil {
return err
}
if task.fetcher != nil {
if err := task.fetcher.Close(); err != nil {
@@ -1015,12 +1261,60 @@ func (d *Downloader) GetTasksByFilter(filter *TaskFilter) []*Task {
}
func (d *Downloader) GetConfig() (*base.DownloaderStoreConfig, error) {
d.configLock.RLock()
defer d.configLock.RUnlock()
return d.cfg.DownloaderStoreConfig, nil
}
func (d *Downloader) PutConfig(v *base.DownloaderStoreConfig) error {
d.cfg.DownloaderStoreConfig = v
return d.storage.Put(bucketConfig, "config", v)
if v == nil {
return errors.New("config is nil")
}
next := util.DeepClone(v)
d.configLock.Lock()
defer d.configLock.Unlock()
if err := d.storage.Put(bucketConfig, "config", next); err != nil {
return err
}
d.cfg.DownloaderStoreConfig = next
return nil
}
func (d *Downloader) prepareDefaultPath(opts *base.Options) (string, error) {
if opts == nil || !opts.AsDefaultPath || strings.TrimSpace(opts.Path) == "" {
return "", nil
}
selectedPath := strings.TrimSpace(opts.Path)
selectedPath, err := d.initDownloadPath(selectedPath)
if err != nil {
return "", err
}
return selectedPath, nil
}
func (d *Downloader) persistDefaultPathBestEffort(defaultPath string) {
if defaultPath == "" {
return
}
if err := d.persistDefaultPath(defaultPath); err != nil {
d.Logger.Warn().Err(err).Msg("persist default download path failed")
}
}
func (d *Downloader) persistDefaultPath(defaultPath string) error {
d.configLock.Lock()
defer d.configLock.Unlock()
next := util.DeepClone(d.cfg.DownloaderStoreConfig)
if next.DownloadDir == defaultPath {
return nil
}
next.DownloadDir = defaultPath
if err := d.storage.Put(bucketConfig, "config", next); err != nil {
return err
}
d.cfg.DownloaderStoreConfig = next
return nil
}
func (d *Downloader) getProtocolConfig(name string, v any) bool {
@@ -1119,6 +1413,9 @@ func (d *Downloader) watch(task *Task) {
if !d.markTaskDone(task) {
return
}
if err := d.captureTaskStats(task, false, true); err != nil {
d.Logger.Error().Stack().Err(err).Msgf("persist completed task stats failed, task id: %s", task.ID)
}
d.storage.Put(bucketTask, task.ID, task.clone())
d.emit(EventKeyDone, task)
d.emit(EventKeyFinally, task, err)
@@ -1231,6 +1528,14 @@ func (d *Downloader) handleOnError(task *Task, err error, resetFetcher bool) {
d.Logger.Warn().Err(resetErr).Msgf("reset recovered task fetcher failed, task id: %s", task.ID)
}
}
if statsErr := d.captureTaskStats(task, false, true); statsErr != nil {
d.Logger.Warn().Err(statsErr).Msgf("persist failed task stats failed, task id: %s", task.ID)
}
if d.taskStatus(task) == base.DownloadStatusError {
if persistErr := d.storage.Put(bucketTask, task.ID, task.clone()); persistErr != nil {
d.Logger.Error().Stack().Err(persistErr).Msgf("persist failed task failed, task id: %s", task.ID)
}
}
task.lock.Unlock()
if d.taskStatus(task) == base.DownloadStatusError {
d.releaseBlobTask(task)
@@ -1269,6 +1574,14 @@ func (d *Downloader) resetTaskFetcher(task *Task) error {
task.Progress.Downloaded = 0
task.Progress.Speed = 0
}
task.statsLock.Lock()
task.statsLoaded = true
task.stats = nil
task.statsSnapshot = nil
task.statsLock.Unlock()
if err := d.storage.Delete(bucketTaskStats, task.ID); err != nil {
return err
}
return d.storage.Delete(bucketSave, task.ID)
}
@@ -1284,7 +1597,7 @@ func (d *Downloader) restoreTask(task *Task) error {
func (d *Downloader) restoreFetcher(task *Task) error {
v, f := task.fetcherManager.Restore()
if v != nil {
err := d.storage.Pop(bucketSave, task.ID, v)
_, err := d.storage.Get(bucketSave, task.ID, v)
if err != nil {
return err
}
@@ -1370,23 +1683,32 @@ func (d *Downloader) initOptions(opts *base.Options) (*base.Options, error) {
}
opts.Path = storeConfig.DownloadDir
}
path, err := d.initDownloadPath(opts.Path)
if err != nil {
return nil, err
}
opts.Path = path
return opts, nil
}
func (d *Downloader) initDownloadPath(path string) (string, error) {
// Replace placeholders in download path (e.g., %year%, %month%, %day%, %date%)
opts.Path = util.ReplacePathPlaceholders(opts.Path)
path = util.ReplacePathPlaceholders(path)
// if enable white download directory, check if the download directory is in the white list
if len(d.cfg.WhiteDownloadDirs) > 0 {
inWhiteList := false
for _, dir := range d.cfg.WhiteDownloadDirs {
if match, err := filepath.Match(dir, opts.Path); match && err == nil {
if match, err := filepath.Match(dir, path); match && err == nil {
inWhiteList = true
break
}
}
if !inWhiteList {
return nil, errors.New("download directory is not in white list")
return "", errors.New("download directory is not in white list")
}
}
return opts, nil
return path, nil
}
func (d *Downloader) statusMut(task *Task, fn func() (bool, error)) (bool, error) {
@@ -1495,6 +1817,11 @@ func (d *Downloader) doStart(task *Task) (err error) {
return err
}
started = true
if err := d.captureTaskStats(task, true, true); err != nil {
// Statistics are auxiliary. A storage or serialization failure must not
// turn an already-started download into a failed task.
d.Logger.Warn().Err(err).Msgf("persist started task stats failed, task id: %s", task.ID)
}
if err := d.saveTask(task); err != nil {
return err
}
@@ -1556,7 +1883,7 @@ func (d *Downloader) doPauseForScheduling(task *Task) (bool, error) {
func (d *Downloader) preparePause(task *Task) (generation uint64, isReturn bool, err error) {
isReturn, err = d.statusMut(task, func() (isReturn bool, err error) {
if task.Status == base.DownloadStatusPause || task.Status == base.DownloadStatusDone {
if task.Status == base.DownloadStatusPause || task.Status == base.DownloadStatusDone || task.Status == base.DownloadStatusError {
isReturn = true
return
}
@@ -1585,6 +1912,13 @@ func (d *Downloader) runPauseHandler(task *Task, generation uint64, pauseFetcher
return false, err
}
}
if task.fetcher != nil {
if err := d.captureTaskStats(task, false, true); err != nil {
// The fetcher is already paused at this point. Keep the task lifecycle
// successful even if its optional statistics snapshot cannot be stored.
d.Logger.Warn().Err(err).Msgf("persist paused task stats failed, task id: %s", task.ID)
}
}
if task.fetcherManager != nil && task.fetcher != nil {
if err := d.saveTask(task); err != nil {
return false, err
@@ -2066,6 +2400,7 @@ func initTask(task *Task) {
task.statusLock = &sync.Mutex{}
task.lock = &sync.Mutex{}
task.statsLock = &sync.Mutex{}
task.blobRefLock = &sync.Mutex{}
task.speedArr = make([]int64, 0)
task.uploadSpeedArr = make([]int64, 0)
+572 -3
View File
@@ -4,6 +4,7 @@ import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -102,6 +103,7 @@ func (m *generationTestManager) Close() error { return nil }
type generationTestFetcher struct {
manager *generationTestManager
meta *fetcher.FetcherMeta
stats *fetcher.Stats
done chan error
}
@@ -152,11 +154,48 @@ func (f *generationTestFetcher) Pause() error {
return nil
}
func (f *generationTestFetcher) Close() error { return nil }
func (f *generationTestFetcher) Stats() any { return nil }
func (f *generationTestFetcher) Stats() *fetcher.Stats { return f.stats }
func (f *generationTestFetcher) Meta() *fetcher.FetcherMeta { return f.meta }
func (f *generationTestFetcher) Progress() fetcher.Progress { return fetcher.Progress{1} }
func (f *generationTestFetcher) Wait() error { return <-f.done }
type recoveryTestData struct {
SeedBytes int64
}
type recoveryTestManager struct {
*generationTestManager
}
func newRecoveryTestManager() *recoveryTestManager {
return &recoveryTestManager{generationTestManager: &generationTestManager{}}
}
func (m *recoveryTestManager) Build() fetcher.Fetcher {
return &recoveryTestFetcher{
generationTestFetcher: &generationTestFetcher{manager: m.generationTestManager, meta: &fetcher.FetcherMeta{}},
data: &recoveryTestData{},
}
}
func (m *recoveryTestManager) Store(f fetcher.Fetcher) (any, error) {
return f.(*recoveryTestFetcher).data, nil
}
func (m *recoveryTestManager) Restore() (any, func(*fetcher.FetcherMeta, any) fetcher.Fetcher) {
return &recoveryTestData{}, func(meta *fetcher.FetcherMeta, value any) fetcher.Fetcher {
return &recoveryTestFetcher{
generationTestFetcher: &generationTestFetcher{manager: m.generationTestManager, meta: meta},
data: value.(*recoveryTestData),
}
}
}
type recoveryTestFetcher struct {
*generationTestFetcher
data *recoveryTestData
}
func newTestDownloadOpt(t *testing.T) *base.Options {
t.Helper()
return newTestDownloadOptAt(t.TempDir())
@@ -167,11 +206,13 @@ func newTestDownloadOptAt(path string) *base.Options {
Path: path,
Name: test.DownloadName,
Extra: http.OptsExtra{
Connections: 4,
Connections: testDownloadConnections,
},
}
}
const testDownloadConnections = 4
func TestDownloader_Resolve(t *testing.T) {
listener := test.StartTestFileServer()
defer listener.Close()
@@ -735,6 +776,74 @@ func TestDownloader_Create(t *testing.T) {
}
}
func TestDownloader_CreateDirectUsesPathAsDefault(t *testing.T) {
listener := test.StartTestFileServer()
defer listener.Close()
downloader := NewDownloader(nil)
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer func() {
downloader.Delete(nil, true)
downloader.Clear()
}()
initialDir := t.TempDir()
cfg, err := downloader.GetConfig()
if err != nil {
t.Fatal(err)
}
cfg.DownloadDir = initialDir
if err := downloader.PutConfig(cfg); err != nil {
t.Fatal(err)
}
createAndWait := func(opts *base.Options) {
t.Helper()
done := make(chan struct{}, 1)
downloader.Listener(func(event *Event) {
if event.Key == EventKeyDone {
done <- struct{}{}
}
})
req := &base.Request{URL: "http://" + listener.Addr().String() + "/" + test.BuildName}
if _, err := downloader.CreateDirect(req, opts); err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("task did not finish")
}
}
selectedRoot := t.TempDir()
defaultPathOpts := newTestDownloadOptAt(selectedRoot)
defaultPathOpts.AsDefaultPath = true
createAndWait(defaultPathOpts)
cfg, err = downloader.GetConfig()
if err != nil {
t.Fatal(err)
}
if cfg.DownloadDir != selectedRoot {
t.Fatalf("DownloadDir = %q, want selected root %q", cfg.DownloadDir, selectedRoot)
}
cfg.DownloadDir = initialDir
if err := downloader.PutConfig(cfg); err != nil {
t.Fatal(err)
}
createAndWait(newTestDownloadOpt(t))
cfg, err = downloader.GetConfig()
if err != nil {
t.Fatal(err)
}
if cfg.DownloadDir != initialDir {
t.Fatalf("DownloadDir = %q, want unchanged %q", cfg.DownloadDir, initialDir)
}
}
func TestDownloader_CreateNotInWhite(t *testing.T) {
listener := test.StartTestFileServer()
defer listener.Close()
@@ -1333,6 +1442,313 @@ func TestDownloader_Stats(t *testing.T) {
if stats == nil {
t.Error("Stats() returned nil stats")
}
statsFrame, ok := stats.(*fetcher.Stats)
if !ok {
t.Fatalf("Stats() type = %T, want *fetcher.Stats", stats)
}
httpStats, ok := statsFrame.Snapshot.(*http.Stats)
if !ok {
t.Fatalf("Stats().Snapshot type = %T, want *http.Stats", statsFrame.Snapshot)
}
for index, connection := range httpStats.Connections {
if !connection.Completed && !connection.Failed {
t.Fatalf("completed task connection %d was still active", index)
}
}
}
func TestDownloader_TaskStatsPersistsSnapshotWithoutRuntime(t *testing.T) {
downloader := NewDownloader(&DownloaderConfig{Storage: NewBoltStorage(t.TempDir())})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer downloader.Clear()
task := &Task{
ID: "stats-snapshot",
Status: base.DownloadStatusPause,
Progress: &Progress{},
fetcher: &generationTestFetcher{stats: &fetcher.Stats{
Snapshot: map[string]any{"downloaded": float64(42)},
Runtime: map[string]any{"activePeers": float64(7)},
}},
}
initTask(task)
if err := downloader.captureTaskStats(task, true, true); err != nil {
t.Fatal(err)
}
task.statsLock.Lock()
liveFrame := task.stats
task.statsLock.Unlock()
if liveFrame.Runtime == nil {
t.Fatal("running task lost runtime stats")
}
// Simulate a freshly restored protocol that is still verifying its local
// pieces. A nil Snapshot must keep the last trusted persisted value while
// allowing current Runtime telemetry to refresh.
task.statsLock.Lock()
task.statsLoaded = false
task.stats = nil
task.statsSnapshot = nil
task.statsLock.Unlock()
task.fetcher.(*generationTestFetcher).stats = &fetcher.Stats{
Runtime: map[string]any{"activePeers": float64(9)},
}
if err := downloader.captureTaskStats(task, true, true); err != nil {
t.Fatal(err)
}
task.statsLock.Lock()
verifyingFrame := task.stats
task.statsLock.Unlock()
if verifyingFrame == nil || verifyingFrame.Runtime.(map[string]any)["activePeers"] != float64(9) {
t.Fatalf("verifying runtime = %+v", verifyingFrame)
}
if _, ok := verifyingFrame.Snapshot.(json.RawMessage); !ok {
t.Fatalf("verifying snapshot type = %T, want persisted json.RawMessage", verifyingFrame.Snapshot)
}
// Simulate a fresh process: no fetcher and an empty task-level cache.
task.fetcher = nil
task.Status = base.DownloadStatusPause
task.statsLock.Lock()
task.statsLoaded = false
task.stats = nil
task.statsSnapshot = nil
task.statsLock.Unlock()
downloader.lock.Lock()
downloader.tasks = append(downloader.tasks, task)
downloader.lock.Unlock()
restored, err := downloader.Stats(task.ID)
if err != nil {
t.Fatal(err)
}
restoredFrame := restored.(*fetcher.Stats)
if restoredFrame.Runtime != nil {
t.Fatalf("persisted runtime = %+v, want nil", restoredFrame.Runtime)
}
raw, ok := restoredFrame.Snapshot.(json.RawMessage)
if !ok {
t.Fatalf("persisted snapshot type = %T", restoredFrame.Snapshot)
}
var snapshot map[string]any
if err := json.Unmarshal(raw, &snapshot); err != nil {
t.Fatal(err)
}
if snapshot["downloaded"] != float64(42) {
t.Fatalf("persisted snapshot = %+v", snapshot)
}
}
func TestDownloader_StatsDoesNotRestoreOrConsumeFetcherSave(t *testing.T) {
downloader := NewDownloader(&DownloaderConfig{Storage: NewBoltStorage(t.TempDir())})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer downloader.Clear()
task := &Task{ID: "stats-no-restore", Status: base.DownloadStatusPause, Progress: &Progress{}}
initTask(task)
downloader.lock.Lock()
downloader.tasks = append(downloader.tasks, task)
downloader.lock.Unlock()
if err := downloader.storage.Put(bucketSave, task.ID, map[string]any{"downloaded": 12}); err != nil {
t.Fatal(err)
}
stats, err := downloader.Stats(task.ID)
if err != nil {
t.Fatal(err)
}
if stats != nil {
t.Fatalf("missing task stats = %+v, want nil", stats)
}
var recovery map[string]any
exists, err := downloader.storage.Get(bucketSave, task.ID, &recovery)
if err != nil {
t.Fatal(err)
}
if !exists || recovery["downloaded"] != float64(12) {
t.Fatalf("fetcher recovery was consumed: exists=%v data=%+v", exists, recovery)
}
}
func TestDownloader_RestoreFetcherDoesNotConsumeSave(t *testing.T) {
storage := NewMemStorage()
if err := storage.Setup([]string{bucketSave, bucketConfig}); err != nil {
t.Fatal(err)
}
manager := newRecoveryTestManager()
downloader := NewDownloader(&DownloaderConfig{
Storage: storage,
FetchManagers: []fetcher.FetcherManager{manager},
DownloaderStoreConfig: (&base.DownloaderStoreConfig{}).Init(),
})
task := &Task{
ID: "restore-keeps-checkpoint",
Meta: &fetcher.FetcherMeta{Req: &base.Request{URL: "generation://restore"}},
Progress: &Progress{},
fetcherManager: manager,
}
initTask(task)
if err := storage.Put(bucketSave, task.ID, &recoveryTestData{SeedBytes: 42}); err != nil {
t.Fatal(err)
}
if err := downloader.restoreFetcher(task); err != nil {
t.Fatal(err)
}
restored := task.fetcher.(*recoveryTestFetcher).data
if restored.SeedBytes != 42 {
t.Fatalf("restored seed bytes = %d, want 42", restored.SeedBytes)
}
var checkpoint recoveryTestData
exists, err := storage.Get(bucketSave, task.ID, &checkpoint)
if err != nil {
t.Fatal(err)
}
if !exists || checkpoint.SeedBytes != 42 {
t.Fatalf("restore consumed checkpoint: exists=%v data=%+v", exists, checkpoint)
}
}
func TestShouldSaveTaskCheckpoint(t *testing.T) {
if uploadCheckpointInterval != 30*time.Second {
t.Fatalf("upload checkpoint interval = %s, want 30s", uploadCheckpointInterval)
}
tests := []struct {
name string
downloadChanged bool
uploadChanged bool
uploading bool
uploadCheckpointDue bool
want bool
}{
{name: "download changed", downloadChanged: true, want: true},
{name: "upload changed", uploadChanged: true, want: true},
{name: "active upload checkpoint due", uploading: true, uploadCheckpointDue: true, want: true},
{name: "active upload checkpoint not due", uploading: true, want: false},
{name: "inactive task checkpoint due", uploadCheckpointDue: true, want: false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := shouldSaveTaskCheckpoint(
tt.downloadChanged,
tt.uploadChanged,
tt.uploading,
tt.uploadCheckpointDue,
)
if got != tt.want {
t.Fatalf("shouldSaveTaskCheckpoint() = %v, want %v", got, tt.want)
}
})
}
}
func TestDownloader_CompletedHTTPStatsSurviveRestore(t *testing.T) {
listener := test.StartTestFileServer()
defer listener.Close()
storageDir := t.TempDir()
downloader := NewDownloader(&DownloaderConfig{Storage: NewBoltStorage(storageDir)})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
req := &base.Request{URL: "http://" + listener.Addr().String() + "/" + test.BuildName}
rr, err := downloader.Resolve(req, newTestDownloadOpt(t))
if err != nil {
t.Fatal(err)
}
done := make(chan struct{}, 1)
downloader.Listener(func(event *Event) {
if event.Key == EventKeyDone {
done <- struct{}{}
}
})
taskID, err := downloader.Create(rr.ID)
if err != nil {
t.Fatal(err)
}
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for HTTP task completion")
}
beforeRestoreValue, err := downloader.Stats(taskID)
if err != nil {
t.Fatal(err)
}
beforeRestore := decodeHTTPStatsSnapshot(t, beforeRestoreValue)
if err := downloader.Close(); err != nil {
t.Fatal(err)
}
downloader = NewDownloader(&DownloaderConfig{Storage: NewBoltStorage(storageDir)})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
statsValue, err := downloader.Stats(taskID)
if err != nil {
t.Fatal(err)
}
stats := decodeHTTPStatsSnapshot(t, statsValue)
if len(stats.Connections) == 0 {
t.Fatal("restored completed task has no HTTP connection stats")
}
if !reflect.DeepEqual(stats, beforeRestore) {
t.Fatalf("restored stats changed\nbefore: %+v\nafter: %+v", beforeRestore, stats)
}
var downloaded int64
for _, connection := range stats.Connections {
downloaded += connection.Downloaded
}
if downloaded != test.BuildSize {
t.Fatalf("restored connection downloads = %d, want %d", downloaded, test.BuildSize)
}
if err := downloader.Close(); err != nil {
t.Fatal(err)
}
// Restoring stats must not consume the persisted snapshot. Completed tasks
// do not write another checkpoint, so verify a second restart as well.
downloader = NewDownloader(&DownloaderConfig{Storage: NewBoltStorage(storageDir)})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer downloader.Clear()
statsValue, err = downloader.Stats(taskID)
if err != nil {
t.Fatal(err)
}
secondRestore := decodeHTTPStatsSnapshot(t, statsValue)
if !reflect.DeepEqual(secondRestore, beforeRestore) {
t.Fatalf("stats changed after second restart\nbefore: %+v\nafter: %+v", beforeRestore, secondRestore)
}
}
func decodeHTTPStatsSnapshot(t *testing.T, value any) *http.Stats {
t.Helper()
frame, ok := value.(*fetcher.Stats)
if !ok {
t.Fatalf("stats type = %T, want *fetcher.Stats", value)
}
switch snapshot := frame.Snapshot.(type) {
case *http.Stats:
return snapshot
case json.RawMessage:
var stats http.Stats
if err := json.Unmarshal(snapshot, &stats); err != nil {
t.Fatal(err)
}
return &stats
default:
t.Fatalf("HTTP snapshot type = %T", frame.Snapshot)
return nil
}
}
func TestDownloader_Delete(t *testing.T) {
@@ -1478,8 +1894,121 @@ func TestDownloader_PauseAndContinue(t *testing.T) {
downloader.Delete(nil, true)
}
func TestDownloader_FailedTaskSurvivesRestart(t *testing.T) {
storageDir := t.TempDir()
manager := &generationTestManager{holdOpen: true}
downloader := NewDownloader(&DownloaderConfig{
FetchManagers: []fetcher.FetcherManager{manager},
Storage: NewBoltStorage(storageDir),
})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
errorEvent := make(chan error, 1)
downloader.Listener(func(event *Event) {
if event.Key == EventKeyError {
errorEvent <- event.Err
}
})
taskID, err := downloader.CreateDirect(&base.Request{URL: "generation://restart-failure"}, &base.Options{
Path: t.TempDir(),
Name: "failed.bin",
})
if err != nil {
t.Fatal(err)
}
waitForTaskStatus(t, downloader, taskID, base.DownloadStatusRunning, 2*time.Second)
wantErr := errors.New("download failed before restart")
downloader.GetTask(taskID).fetcher.(*generationTestFetcher).done <- wantErr
select {
case got := <-errorEvent:
if !errors.Is(got, wantErr) {
t.Fatalf("error event = %v, want %v", got, wantErr)
}
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for task failure")
}
waitForTaskStatus(t, downloader, taskID, base.DownloadStatusError, 2*time.Second)
var stored Task
exists, err := downloader.storage.Get(bucketTask, taskID, &stored)
if err != nil {
t.Fatal(err)
}
if !exists || stored.Status != base.DownloadStatusError {
t.Fatalf("persisted task status = %s, exists = %t; want error", stored.Status, exists)
}
if err := downloader.Close(); err != nil {
t.Fatal(err)
}
downloader = NewDownloader(&DownloaderConfig{
FetchManagers: []fetcher.FetcherManager{manager},
Storage: NewBoltStorage(storageDir),
})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer downloader.Clear()
if got := downloader.GetTask(taskID).Status; got != base.DownloadStatusError {
t.Fatalf("restored task status = %s, want error", got)
}
}
func TestDownloader_ContinueOnStartupUsesContinueAllSemantics(t *testing.T) {
manager := &generationTestManager{holdOpen: true}
downloader := NewDownloader(&DownloaderConfig{FetchManagers: []fetcher.FetcherManager{manager}})
if err := downloader.Setup(); err != nil {
t.Fatal(err)
}
defer downloader.Clear()
taskID, err := downloader.CreateDirect(&base.Request{URL: "generation://auto-start"}, &base.Options{
Path: t.TempDir(),
Name: "auto-start.bin",
})
if err != nil {
t.Fatal(err)
}
waitForTaskStatus(t, downloader, taskID, base.DownloadStatusRunning, 2*time.Second)
if err := downloader.Pause(&TaskFilter{IDs: []string{taskID}}); err != nil {
t.Fatal(err)
}
cfg, err := downloader.GetConfig()
if err != nil {
t.Fatal(err)
}
cfg.Extra = map[string]any{"autoStartTasks": true}
if err := downloader.ContinueOnStartup(); err != nil {
t.Fatal(err)
}
if got := downloader.taskStatus(downloader.GetTask(taskID)); got != base.DownloadStatusPause {
t.Fatalf("task status with auto-start disabled = %s, want pause", got)
}
cfg.AutoStartTasks = true
if err := downloader.ContinueOnStartup(); err != nil {
t.Fatal(err)
}
waitForTaskStatus(t, downloader, taskID, base.DownloadStatusRunning, 2*time.Second)
downloader.GetTask(taskID).fetcher.(*generationTestFetcher).done <- errors.New("retry on next startup")
waitForTaskStatus(t, downloader, taskID, base.DownloadStatusError, 2*time.Second)
if err := downloader.ContinueOnStartup(); err != nil {
t.Fatal(err)
}
waitForTaskStatus(t, downloader, taskID, base.DownloadStatusRunning, 2*time.Second)
}
func TestDownloader_PauseAllAndContinueAll(t *testing.T) {
listener := test.StartTestSlowFileServer(time.Millisecond * 2000)
const targetDownloadDuration = time.Second
// Scale the per-byte delay with the configured connection count so a full
// ranged transfer stays near one second and is still running at Pause.
delayPerByte := targetDownloadDuration * testDownloadConnections / test.BuildSize
listener := test.StartTestLowSpeedServer(delayPerByte)
defer listener.Close()
downloader := NewDownloader(nil)
@@ -1577,6 +2106,46 @@ func TestDownloader_GetTask(t *testing.T) {
}
}
func TestDownloader_RuntimeStatus(t *testing.T) {
meta := &fetcher.FetcherMeta{
Res: &base.Resource{
Size: 20,
Files: []*base.FileInfo{
{Name: "skipped.bin", Size: 10},
{Name: "selected.bin", Size: 20},
},
},
Opts: &base.Options{SelectFiles: []int{1}},
}
task := &Task{
ID: "runtime-status",
Status: base.DownloadStatusRunning,
Meta: meta,
Progress: &Progress{Used: 11, Speed: 12, Downloaded: 13, UploadSpeed: 14, Uploaded: 15},
fetcher: &generationTestFetcher{manager: &generationTestManager{}, meta: meta},
}
initTask(task)
downloader := &Downloader{lock: &sync.Mutex{}, tasks: []*Task{task}}
status, err := downloader.RuntimeStatus(task.ID)
if err != nil {
t.Fatal(err)
}
if status.Status != base.DownloadStatusRunning || status.Total != 20 || status.Downloaded != 13 {
t.Fatalf("unexpected runtime status: %+v", status)
}
if len(status.Files) != 1 {
t.Fatalf("len(status.Files) = %d, want 1", len(status.Files))
}
file := status.Files[0]
if file.Index != 1 || file.Size != 20 || file.Downloaded != 1 {
t.Fatalf("unexpected file runtime status: %+v", file)
}
if _, err := downloader.RuntimeStatus("missing"); !errors.Is(err, ErrTaskNotFound) {
t.Fatalf("missing task error = %v, want ErrTaskNotFound", err)
}
}
func TestDownloader_Emit(t *testing.T) {
downloader := NewDownloader(nil)
if err := downloader.Setup(); err != nil {
+33 -8
View File
@@ -8,8 +8,8 @@ import (
"github.com/GopeedLab/gopeed/pkg/base"
gojaerror "github.com/GopeedLab/gopeed/pkg/download/engine/inject/error"
fetchapi "github.com/GopeedLab/gopeed/pkg/download/engine/inject/fetch"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/stream"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/vm"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/xhr"
@@ -24,6 +24,10 @@ var polyfillScript string
type Engine struct {
loop *eventloop.EventLoop
closeOnce sync.Once
cleanupMu sync.Mutex
cleanups []func()
Runtime *goja.Runtime
}
@@ -133,7 +137,25 @@ func (e *Engine) runOnLoop(fn func(runtime *goja.Runtime) (goja.Value, error)) (
}
func (e *Engine) Close() {
e.loop.Terminate()
e.closeOnce.Do(func() {
e.cleanupMu.Lock()
cleanups := e.cleanups
e.cleanups = nil
e.cleanupMu.Unlock()
for _, cleanup := range cleanups {
cleanup()
}
e.loop.Terminate()
})
}
func (e *Engine) addCleanup(cleanup func()) {
if cleanup == nil {
return
}
e.cleanupMu.Lock()
e.cleanups = append(e.cleanups, cleanup)
e.cleanupMu.Unlock()
}
type Config struct {
@@ -163,12 +185,6 @@ func NewEngine(cfg *Config) *Engine {
if err := file.Enable(runtime); err != nil {
return
}
if err := formdata.Enable(runtime); err != nil {
return
}
if err := xhr.Enable(runtime, cfg.ProxyConfig.ToHandler()); err != nil {
return
}
if _, err := runtime.RunString(polyfillScript); err != nil {
return
}
@@ -187,6 +203,15 @@ func NewEngine(cfg *Config) *Engine {
if err := stream.Enable(runtime, loop, cfg.StreamConfig); err != nil {
return
}
if err := fetchapi.Enable(runtime, loop, &fetchapi.Config{
ProxyHandler: cfg.ProxyConfig.ToHandler(),
RegisterCleanup: engine.addCleanup,
}); err != nil {
return
}
if err := xhr.Enable(runtime); err != nil {
return
}
return
})
<-done
@@ -0,0 +1,168 @@
package engine_test
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"github.com/GopeedLab/gopeed/pkg/download/engine"
)
func TestFetchDoesNotDependOnXMLHttpRequest(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/target", func(w http.ResponseWriter, request *http.Request) {
w.Header().Set("X-Method", request.Method)
_, _ = w.Write([]byte("ok"))
})
mux.HandleFunc("/redirect", func(w http.ResponseWriter, request *http.Request) {
http.Redirect(w, request, "/target", http.StatusFound)
})
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
runtime := engine.NewEngine(nil)
t.Cleanup(runtime.Close)
value, err := runtime.RunString(fmt.Sprintf(`
(async () => {
globalThis.XMLHttpRequest = function () {
throw new Error("fetch used XMLHttpRequest");
};
const get = await fetch(%q);
const head = await fetch(%q, { method: "HEAD" });
const manual = await fetch(%q, { redirect: "manual" });
let redirectError = false;
try {
await fetch(%q, { redirect: "error" });
} catch (_) {
redirectError = true;
}
return JSON.stringify({
get: await get.text(),
headStatus: head.status,
headMethod: head.headers.get("x-method"),
manualStatus: manual.status,
manualLocation: manual.headers.get("location"),
redirectError,
});
})()
`, server.URL+"/target", server.URL+"/target", server.URL+"/redirect", server.URL+"/redirect"))
if err != nil {
t.Fatal(err)
}
const want = `{"get":"ok","headStatus":200,"headMethod":"HEAD","manualStatus":302,"manualLocation":"/target","redirectError":true}`
if value != want {
t.Fatalf("unexpected fetch result: got %#v want %s", value, want)
}
}
func TestXMLHttpRequestUsesFetch(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("X-Test", "value")
_, _ = w.Write([]byte("payload"))
}))
t.Cleanup(server.Close)
runtime := engine.NewEngine(nil)
t.Cleanup(runtime.Close)
value, err := runtime.RunString(fmt.Sprintf(`
(async () => {
const originalFetch = globalThis.fetch;
let fetchCalls = 0;
globalThis.fetch = function (...args) {
fetchCalls++;
return originalFetch(...args);
};
const result = await new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
const states = [];
xhr.onreadystatechange = () => states.push(xhr.readyState);
xhr.onerror = () => reject(new Error("XHR failed"));
xhr.onload = () => resolve({
status: xhr.status,
text: xhr.responseText,
header: xhr.getResponseHeader("x-test"),
states,
});
xhr.open("GET", %q);
xhr.send();
});
result.fetchCalls = fetchCalls;
return JSON.stringify(result);
})()
`, server.URL))
if err != nil {
t.Fatal(err)
}
const want = `{"status":200,"text":"payload","header":"value","states":[1,2,3,4],"fetchCalls":1}`
if value != want {
t.Fatalf("unexpected XMLHttpRequest result: got %#v want %s", value, want)
}
}
func TestFetchResponseAndRequestCloneHaveIndependentBodies(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if request.Method == http.MethodPost {
_, _ = response.Write([]byte("posted"))
return
}
_, _ = response.Write([]byte("payload"))
}))
t.Cleanup(server.Close)
runtime := engine.NewEngine(nil)
t.Cleanup(runtime.Close)
value, err := runtime.RunString(fmt.Sprintf(`
(async () => {
const response = await fetch(%q);
const responseClone = response.clone();
const responseBodies = await Promise.all([response.text(), responseClone.text()]);
const request = new Request(%q, { method: "POST", body: "request-body" });
const requestClone = request.clone();
const requestBodies = await Promise.all([request.text(), requestClone.text()]);
return JSON.stringify({ responseBodies, requestBodies });
})()
`, server.URL, server.URL))
if err != nil {
t.Fatal(err)
}
const want = `{"responseBodies":["payload","payload"],"requestBodies":["request-body","request-body"]}`
if value != want {
t.Fatalf("unexpected clone result: got %#v want %s", value, want)
}
}
func TestFetchFormDataUsesWebEntryListSemantics(t *testing.T) {
runtime := engine.NewEngine(nil)
t.Cleanup(runtime.Close)
value, err := runtime.RunString(`
(() => {
const data = new FormData();
data.append("a", "one");
data.append("a", 2);
data.append("b", "three");
const beforeSet = Array.from(data.entries());
data.set("a", "four");
const afterSet = Array.from(data);
const all = data.getAll("a");
data.delete("b");
return JSON.stringify({ beforeSet, afterSet, all, hasB: data.has("b") });
})()
`)
if err != nil {
t.Fatal(err)
}
const want = `{"beforeSet":[["a","one"],["a","2"],["b","three"]],"afterSet":[["a","four"],["b","three"]],"all":["four"],"hasB":false}`
if value != want {
t.Fatalf("unexpected FormData result: got %#v want %s", value, want)
}
}
+898
View File
@@ -0,0 +1,898 @@
(function () {
const fetchOpen = globalThis.__gopeed_fetch_open;
const fetchRead = globalThis.__gopeed_fetch_read;
const fetchClose = globalThis.__gopeed_fetch_close;
const fetchAbort = globalThis.__gopeed_fetch_abort;
class FormData {
constructor(form) {
if (form !== undefined) throw new TypeError("FormData HTML form construction is not available in an extension worker");
this._entries = [];
}
_normalizeValue(value) {
if (typeof Blob !== "undefined" && value instanceof Blob) return value;
if (value && typeof value === "object" && "name" in value && "size" in value) return value;
return String(value);
}
append(name, value) {
this._entries.push([String(name), this._normalizeValue(value)]);
}
delete(name) {
name = String(name);
this._entries = this._entries.filter((entry) => entry[0] !== name);
}
get(name) {
name = String(name);
const entry = this._entries.find((item) => item[0] === name);
return entry ? entry[1] : null;
}
getAll(name) {
name = String(name);
return this._entries.filter((entry) => entry[0] === name).map((entry) => entry[1]);
}
has(name) {
name = String(name);
return this._entries.some((entry) => entry[0] === name);
}
set(name, value) {
name = String(name);
value = this._normalizeValue(value);
const first = this._entries.findIndex((entry) => entry[0] === name);
if (first < 0) {
this._entries.push([name, value]);
return;
}
this._entries[first] = [name, value];
this._entries = this._entries.filter((entry, index) => index === first || entry[0] !== name);
}
_iterator(kind) {
const data = this;
let index = 0;
return {
next() {
if (index >= data._entries.length) return { value: undefined, done: true };
const entry = data._entries[index++];
if (kind === "key") return { value: entry[0], done: false };
if (kind === "value") return { value: entry[1], done: false };
return { value: [entry[0], entry[1]], done: false };
},
[Symbol.iterator]() { return this; },
};
}
entries() { return this._iterator("entry"); }
keys() { return this._iterator("key"); }
values() { return this._iterator("value"); }
[Symbol.iterator]() { return this.entries(); }
forEach(callback, thisArg) {
for (const [name, value] of this) callback.call(thisArg, value, name, this);
}
}
Object.defineProperty(FormData.prototype, Symbol.toStringTag, { configurable: true, value: "FormData" });
globalThis.FormData = FormData;
const headerNamePattern = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
const headersIteratorBase = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
const headersIteratorPrototype = Object.create(headersIteratorBase);
function normalizeHeaderName(name) {
if (typeof name === "symbol") throw new TypeError("HTTP header names must be ByteStrings");
name = String(name);
for (let index = 0; index < name.length; index++) {
if (name.charCodeAt(index) > 0xFF) throw new TypeError("HTTP header names must be ByteStrings");
}
if (!headerNamePattern.test(name)) throw new TypeError("Invalid HTTP header name");
return name.toLowerCase();
}
function normalizeHeaderValue(value) {
value = String(value);
for (let index = 0; index < value.length; index++) {
if (value.charCodeAt(index) > 0xFF) throw new TypeError("HTTP header values must be ByteStrings");
}
value = value.replace(/^[\t\n\r ]+|[\t\n\r ]+$/g, "");
if (/[\0\n\r]/.test(value)) throw new TypeError("Invalid HTTP header value");
return value;
}
function normalizeStatusText(value) {
value = String(value);
for (let index = 0; index < value.length; index++) {
const code = value.charCodeAt(index);
if (code > 0xFF || (code !== 0x09 && (code < 0x20 || code === 0x7F))) {
throw new TypeError("Invalid response status text");
}
}
return value;
}
function sortedHeaderEntries(headers) {
const result = [];
for (const name of Array.from(headers._values.keys()).sort()) {
const values = headers._values.get(name);
if (name === "set-cookie") {
for (const value of values) result.push([name, value]);
} else {
result.push([name, values.join(", ")]);
}
}
return result;
}
Object.defineProperty(headersIteratorPrototype, "next", {
configurable: true,
enumerable: true,
writable: true,
value: function () {
const entries = sortedHeaderEntries(this._headers);
if (this._index >= entries.length) return { value: undefined, done: true };
const entry = entries[this._index++];
if (this._kind === "key") return { value: entry[0], done: false };
if (this._kind === "value") return { value: entry[1], done: false };
return { value: entry, done: false };
},
});
Object.defineProperty(headersIteratorPrototype, Symbol.iterator, {
configurable: true,
enumerable: false,
writable: true,
value: function () { return this; },
});
function createHeadersIterator(headers, kind) {
const iterator = Object.create(headersIteratorPrototype);
Object.defineProperties(iterator, {
_headers: { value: headers },
_kind: { value: kind },
_index: { value: 0, writable: true },
});
return iterator;
}
function forbiddenRequestHeader(name, value) {
if (name.startsWith("proxy-") || name.startsWith("sec-")) return true;
if ([
"accept-charset", "accept-encoding", "access-control-request-headers",
"access-control-request-method", "connection", "content-length", "cookie",
"cookie2", "date", "dnt", "expect", "host", "keep-alive", "origin",
"permissions-policy", "referer", "te", "trailer", "transfer-encoding",
"set-cookie", "upgrade", "via",
].includes(name)) return true;
if (["x-http-method", "x-http-method-override", "x-method-override"].includes(name)) {
return String(value).split(",").some((method) => {
method = method.trim().toUpperCase();
return method === "CONNECT" || method === "TRACE" || method === "TRACK";
});
}
return false;
}
function noCORSSafelistedRequestHeader(name, value) {
if (value.length > 128) return false;
const hasUnsafeByte = /[\x00-\x08\x0A-\x1F\x7F"():<>?@\[\\\]{}]/.test(value);
if (name === "accept") return !hasUnsafeByte;
if (name === "accept-language" || name === "content-language") {
return /^[0-9A-Za-z *,\-.;=]*$/.test(value);
}
if (name === "content-type") {
if (hasUnsafeByte) return false;
const essence = value.split(";", 1)[0].trim().toLowerCase();
return essence === "application/x-www-form-urlencoded" ||
essence === "multipart/form-data" || essence === "text/plain";
}
if (name === "range") return /^bytes=[0-9]+-[0-9]*$/.test(value);
return false;
}
function blockedByGuard(headers, name, value) {
if (headers._guard === "immutable") throw new TypeError("Headers are immutable");
if (headers._guard === "request") return forbiddenRequestHeader(name, value);
if (headers._guard === "request-no-cors") {
return forbiddenRequestHeader(name, value) || !noCORSSafelistedRequestHeader(name, value);
}
if (headers._guard === "response") return name === "set-cookie" || name === "set-cookie2";
return false;
}
class Headers {
constructor(init, guard) {
this._values = new Map();
this._guard = guard || "none";
if (init === undefined) return;
if (init === null || (typeof init !== "object" && typeof init !== "function")) {
throw new TypeError("Headers init must be a sequence or record");
}
const iterator = init[Symbol.iterator];
if (typeof iterator === "function") {
for (const pair of init) {
if (pair == null || typeof pair[Symbol.iterator] !== "function") {
throw new TypeError("Header pair must be iterable");
}
const values = Array.from(pair);
if (values.length !== 2) throw new TypeError("Header pair must contain exactly two items");
this.append(values[0], values[1]);
}
return;
}
for (const name of Reflect.ownKeys(init)) {
const descriptor = Reflect.getOwnPropertyDescriptor(init, name);
if (!descriptor || !descriptor.enumerable) continue;
const normalizedName = normalizeHeaderName(name);
this.append(normalizedName, init[name]);
}
}
append(name, value) {
name = normalizeHeaderName(name);
value = normalizeHeaderValue(value);
const values = this._values.get(name);
const combinedValue = values && name !== "set-cookie" ? values.join(", ") + ", " + value : value;
if (blockedByGuard(this, name, combinedValue)) return;
if (values) values.push(value);
else this._values.set(name, [value]);
}
delete(name) {
name = normalizeHeaderName(name);
if (this._guard === "immutable") throw new TypeError("Headers are immutable");
if (this._guard === "request-no-cors") {
if (forbiddenRequestHeader(name, "") || !["accept", "accept-language", "content-language", "content-type", "range"].includes(name)) return;
this._values.delete(name);
return;
}
if (blockedByGuard(this, name, "")) return;
this._values.delete(name);
}
get(name) {
const values = this._values.get(normalizeHeaderName(name));
return values ? values.join(", ") : null;
}
getSetCookie() {
const values = this._values.get("set-cookie");
return values ? values.slice() : [];
}
has(name) {
return this._values.has(normalizeHeaderName(name));
}
set(name, value) {
name = normalizeHeaderName(name);
value = normalizeHeaderValue(value);
if (blockedByGuard(this, name, value)) return;
this._values.set(name, [value]);
}
keys() { return createHeadersIterator(this, "key"); }
values() { return createHeadersIterator(this, "value"); }
entries() { return createHeadersIterator(this, "entry"); }
[Symbol.iterator]() { return this.entries(); }
forEach(callback, thisArg) {
for (const [name, value] of this) callback.call(thisArg, value, name, this);
}
}
globalThis.Headers = Headers;
const forbiddenMethods = new Set(["CONNECT", "TRACE", "TRACK"]);
function normalizeMethod(method) {
method = String(method);
if (!headerNamePattern.test(method)) throw new TypeError("Invalid HTTP method");
method = method.toUpperCase();
if (forbiddenMethods.has(method)) throw new TypeError("Forbidden HTTP method");
return method;
}
function resolveURL(value) {
const base = globalThis.location && globalThis.location.href ? globalThis.location.href : "http://localhost/";
const parsed = new URL(String(value), base);
if (parsed.username || parsed.password) throw new TypeError("Request URLs cannot contain credentials");
return parsed.href;
}
function normalizeEnum(value, allowed, name) {
value = String(value);
if (!allowed.includes(value)) throw new TypeError("Invalid Request " + name);
return value;
}
function normalizeReferrer(value) {
value = String(value);
if (value === "") return "no-referrer";
if (value === "about:client") return value;
return resolveURL(value);
}
function copyArrayBuffer(value) {
if (value instanceof ArrayBuffer) return value.slice(0);
return value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength);
}
function initializeBody(owner, body) {
owner._bodyInit = body == null ? null : body;
owner._bodyText = null;
owner._bodyArrayBuffer = null;
owner._bodyBlob = null;
owner._bodyFormData = null;
owner._bodyFormDataBoundary = "";
owner._bodyStream = null;
owner._bodyUsed = false;
if (body == null) return;
if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream) {
owner._bodyStream = body;
body.__gopeedMarkBodyUsed = () => { owner._bodyUsed = true; };
} else if (typeof body === "string") {
owner._bodyText = body;
} else if (typeof Blob !== "undefined" && body instanceof Blob) {
owner._bodyBlob = body;
} else if (typeof FormData !== "undefined" && body instanceof FormData) {
owner._bodyFormData = body;
const suffix = crypto.randomUUID ? crypto.randomUUID() : String(Date.now()) + String(Math.random()).slice(2);
owner._bodyFormDataBoundary = "----gopeed-" + suffix;
} else if (body instanceof ArrayBuffer || (ArrayBuffer.isView && ArrayBuffer.isView(body))) {
owner._bodyArrayBuffer = copyArrayBuffer(body);
} else if (typeof URLSearchParams !== "undefined" && body instanceof URLSearchParams) {
owner._bodyText = body.toString();
} else {
owner._bodyText = String(body);
}
}
function bodyContentType(owner) {
if (owner._bodyText != null) {
if (typeof URLSearchParams !== "undefined" && owner._bodyInit instanceof URLSearchParams) {
return "application/x-www-form-urlencoded;charset=UTF-8";
}
return "text/plain;charset=UTF-8";
}
if (owner._bodyBlob && owner._bodyBlob.type) return owner._bodyBlob.type;
if (owner._bodyFormData) return "multipart/form-data; boundary=" + owner._bodyFormDataBoundary;
return "";
}
function decodeFormComponent(value) {
return decodeURIComponent(String(value).replace(/\+/g, " "));
}
function installBodyMethods(prototype) {
Object.defineProperties(prototype, {
body: {
configurable: true,
enumerable: true,
get() {
if (this._bodyInit == null && !this.__gopeedBodyStream) return null;
if (this.__gopeedBodyStream) return this.__gopeedBodyStream;
if (!this._bodyStream) this._bodyStream = createBodyReadableStream(this);
return this._bodyStream;
},
},
bodyUsed: {
configurable: true,
enumerable: true,
get() { return Boolean(this._bodyUsed || this.__gopeedBodyConsumed); },
},
});
prototype.text = async function () {
if (this.bodyUsed) throw new TypeError("Already read");
if (this.body == null) return "";
return readAllFromStream(this.body, true);
};
prototype.arrayBuffer = async function () {
if (this.bodyUsed) throw new TypeError("Already read");
if (this.body == null) return new ArrayBuffer(0);
const bytes = await readAllFromStream(this.body, false);
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
};
prototype.bytes = async function () {
if (this.bodyUsed) throw new TypeError("Already read");
if (this.body == null) return new Uint8Array(0);
return readAllFromStream(this.body, false);
};
prototype.blob = async function () {
const data = await this.arrayBuffer();
return new Blob([data], { type: this.headers.get("content-type") || "" });
};
prototype.json = async function () { return JSON.parse(await this.text()); };
prototype.formData = async function () {
const contentType = this.headers.get("content-type") || "";
const essence = contentType.split(";", 1)[0].trim().toLowerCase();
if (essence === "multipart/form-data" && this._bodyFormData) {
if (this.bodyUsed) throw new TypeError("Already read");
await readAllFromStream(this.body, false);
const result = new FormData();
for (const entry of Array.from(this._bodyFormData.entries())) result.append(entry[0], entry[1]);
return result;
}
if (essence !== "application/x-www-form-urlencoded") {
throw new TypeError("Body is not URL-encoded form data");
}
if (this.body == null) return new FormData();
const text = await this.text();
const result = new FormData();
for (const entry of text.split("&")) {
if (!entry) continue;
const parts = entry.split("=");
const name = parts.shift();
result.append(decodeFormComponent(name), decodeFormComponent(parts.join("=")));
}
return result;
};
}
function transferReadableStream(stream) {
let reader = null;
return new ReadableStream({
async pull(controller) {
if (!reader) reader = stream.getReader();
const result = await reader.read();
if (result.done) {
reader.releaseLock();
controller.close();
} else {
controller.enqueue(result.value);
}
},
cancel(reason) {
if (!reader) reader = stream.getReader();
return reader.cancel(reason);
},
});
}
class Request {
constructor(input, init) {
if (arguments.length < 1) throw new TypeError("Request requires an input");
init = init || {};
if (init.window !== undefined && init.window !== null) throw new TypeError("Request window must be null");
const source = input instanceof Request ? input : null;
const bodyWasOverridden = Object.prototype.hasOwnProperty.call(init, "body");
if (source && source.bodyUsed && !bodyWasOverridden) throw new TypeError("Request body is already used");
this._url = source ? source.url : resolveURL(input);
this._method = normalizeMethod(init.method !== undefined ? init.method : (source ? source.method : "GET"));
this._destination = "";
this._referrer = init.referrer !== undefined ? normalizeReferrer(init.referrer) : (source ? source.referrer : "about:client");
this._referrerPolicy = normalizeEnum(init.referrerPolicy !== undefined ? init.referrerPolicy : (source ? source.referrerPolicy : ""), ["", "no-referrer", "no-referrer-when-downgrade", "origin", "origin-when-cross-origin", "same-origin", "strict-origin", "strict-origin-when-cross-origin", "unsafe-url"], "referrerPolicy");
this._mode = normalizeEnum(init.mode !== undefined ? init.mode : (source ? source.mode : "cors"), ["same-origin", "no-cors", "cors"], "mode");
this._credentials = normalizeEnum(init.credentials !== undefined ? init.credentials : (source ? source.credentials : "same-origin"), ["omit", "same-origin", "include"], "credentials");
this._cache = normalizeEnum(init.cache !== undefined ? init.cache : (source ? source.cache : "default"), ["default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached"], "cache");
this._redirect = normalizeEnum(init.redirect !== undefined ? init.redirect : (source ? source.redirect : "follow"), ["follow", "error", "manual"], "redirect");
if (this._mode === "no-cors" && !["GET", "HEAD", "POST"].includes(this._method)) {
throw new TypeError("no-cors requests require a CORS-safelisted method");
}
if (this._cache === "only-if-cached" && this._mode !== "same-origin") {
throw new TypeError("only-if-cached requires same-origin mode");
}
this._integrity = init.integrity !== undefined ? String(init.integrity) : (source ? source.integrity : "");
this._keepalive = init.keepalive !== undefined ? Boolean(init.keepalive) : (source ? source.keepalive : false);
this._priority = normalizeEnum(init.priority !== undefined ? init.priority : (source ? source._priority : "auto"), ["high", "low", "auto"], "priority");
this._signal = init.signal || (source && source.signal) || new AbortController().signal;
if (init.duplex !== undefined && String(init.duplex) !== "half") {
throw new TypeError("Request duplex must be 'half'");
}
this._duplex = "half";
const headerInit = init.headers !== undefined ? init.headers : (source ? source.headers : undefined);
this._headers = new Headers(headerInit, this._mode === "no-cors" ? "request-no-cors" : "request");
let body = init.body !== undefined ? init.body : (source ? source._bodyInit : null);
if (source && !bodyWasOverridden && source.body) body = transferReadableStream(source.body);
const bodyIsStream = typeof ReadableStream !== "undefined" && body instanceof ReadableStream;
if (bodyIsStream && (body.locked || body._disturbed)) {
throw new TypeError("ReadableStream body is locked or disturbed");
}
if (bodyIsStream && init.body !== undefined && init.duplex === undefined) {
throw new TypeError("ReadableStream request bodies require duplex: 'half'");
}
if (bodyIsStream && this._keepalive) {
throw new TypeError("keepalive requests cannot have a ReadableStream body");
}
if (source && !bodyWasOverridden && source.body && (source.body.locked || source.body._disturbed)) {
throw new TypeError("Request body is locked or disturbed");
}
if ((this._method === "GET" || this._method === "HEAD") && body != null) {
throw new TypeError("Body not allowed for GET or HEAD requests");
}
initializeBody(this, body);
const contentType = bodyContentType(this);
if (contentType && !this._headers.has("content-type")) this._headers.set("content-type", contentType);
if (source && source.body) source._bodyUsed = true;
}
get method() { return this._method; }
get url() { return this._url; }
get headers() { return this._headers; }
get destination() { return this._destination; }
get referrer() { return this._referrer; }
get referrerPolicy() { return this._referrerPolicy; }
get mode() { return this._mode; }
get credentials() { return this._credentials; }
get cache() { return this._cache; }
get redirect() { return this._redirect; }
get integrity() { return this._integrity; }
get keepalive() { return this._keepalive; }
get signal() { return this._signal; }
get isReloadNavigation() { return false; }
get isHistoryNavigation() { return false; }
get duplex() { return this._duplex; }
clone() {
if (this.bodyUsed) throw new TypeError("Request body is already used");
let body = null;
if (this.body) {
const branches = this.body.tee();
this._bodyInit = branches[0];
this._bodyStream = branches[0];
if (this.__gopeedBodyStream) this.__gopeedBodyStream = branches[0];
branches[0].__gopeedMarkBodyUsed = () => { this._bodyUsed = true; };
body = branches[1];
}
return new Request(this.url, {
method: this.method,
headers: this.headers,
body,
mode: this.mode,
credentials: this.credentials,
cache: this.cache,
redirect: this.redirect,
referrer: this.referrer,
referrerPolicy: this.referrerPolicy,
integrity: this.integrity,
keepalive: this.keepalive,
signal: this.signal,
duplex: "half",
});
}
}
installBodyMethods(Request.prototype);
const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);
class Response {
constructor(body, init) {
init = init || {};
const status = init.status === undefined ? 200 : Number(init.status);
if (!Number.isInteger(status) || status < 200 || status > 599) {
throw new RangeError("Invalid response status");
}
if (body != null && nullBodyStatuses.has(status)) {
throw new TypeError("Response with null-body status cannot have a body");
}
const statusText = init.statusText === undefined ? "" : normalizeStatusText(init.statusText);
this._type = "default";
this._url = init.url ? String(init.url) : "";
this._redirected = Boolean(init.redirected);
this._status = status;
this._statusText = statusText;
this._headers = new Headers(init.headers, "response");
if (typeof ReadableStream !== "undefined" && body instanceof ReadableStream && (body.locked || body._disturbed)) {
throw new TypeError("ReadableStream body is locked or disturbed");
}
initializeBody(this, body == null ? null : body);
const contentType = bodyContentType(this);
if (contentType && !this._headers.has("content-type")) this._headers.set("content-type", contentType);
}
get type() { return this._type; }
get url() { return this._url; }
get redirected() { return this._redirected; }
get status() { return this._status; }
get ok() { return this._status >= 200 && this._status <= 299; }
get statusText() { return this._statusText; }
get headers() { return this._headers; }
clone() {
if (this.bodyUsed) throw new TypeError("Response body is already used");
let body = null;
if (this.body) {
const branches = this.body.tee();
this._bodyInit = branches[0];
this._bodyStream = branches[0];
if (this.__gopeedBodyStream) this.__gopeedBodyStream = branches[0];
branches[0].__gopeedMarkBodyUsed = () => { this._bodyUsed = true; };
body = branches[1];
}
return new Response(body, {
status: this.status,
statusText: this.statusText,
headers: this.headers,
url: this.url,
redirected: this.redirected,
});
}
static error() {
const response = Object.create(Response.prototype);
response._type = "error";
response._url = "";
response._redirected = false;
response._status = 0;
response._statusText = "";
response._headers = new Headers(undefined, "immutable");
initializeBody(response, null);
return response;
}
static redirect(url, status) {
status = status === undefined ? 302 : Number(status);
if (![301, 302, 303, 307, 308].includes(status)) throw new RangeError("Invalid redirect status");
return new Response(null, { status, headers: { location: resolveURL(url) } });
}
static json(data, init) {
const body = JSON.stringify(data);
if (body === undefined) throw new TypeError("Value is not JSON serializable");
init = Object.assign({}, init || {});
const headers = new Headers(init.headers);
if (!headers.has("content-type")) headers.set("content-type", "application/json");
init.headers = headers;
return new Response(body, init);
}
}
installBodyMethods(Response.prototype);
globalThis.Request = Request;
globalThis.Response = Response;
function toUint8Array(chunk) {
if (chunk == null) return new Uint8Array(0);
if (chunk instanceof Uint8Array) return chunk;
if (typeof chunk === "string") return new TextEncoder().encode(chunk);
if (chunk instanceof ArrayBuffer) return new Uint8Array(chunk);
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(chunk)) {
return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
}
if (typeof Blob !== "undefined" && chunk instanceof Blob && chunk._buffer instanceof Uint8Array) {
return chunk._buffer;
}
return new Uint8Array(0);
}
function createBodyReadableStream(owner) {
const stream = new ReadableStream({
start(controller) {
Promise.resolve().then(async () => {
if (owner._noBody) {
controller.close();
return;
}
if (owner._bodyArrayBuffer) {
controller.enqueue(toUint8Array(owner._bodyArrayBuffer));
controller.close();
return;
}
if (owner._bodyBlob) {
const data = await owner._bodyBlob.arrayBuffer();
controller.enqueue(new Uint8Array(data));
controller.close();
return;
}
if (owner._bodyFormData) {
const boundary = owner._bodyFormDataBoundary;
const entries = Array.from(owner._bodyFormData.entries());
if (entries.length === 0) {
controller.close();
return;
}
let serialized = "";
for (const entry of entries) {
const name = String(entry[0]).replace(/\r|\n|"/g, (character) =>
character === "\r" ? "%0D" : character === "\n" ? "%0A" : "%22");
serialized += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n";
serialized += String(entry[1]) + "\r\n";
}
serialized += "--" + boundary + "--\r\n";
controller.enqueue(toUint8Array(serialized));
controller.close();
return;
}
if (owner._bodyText != null) {
controller.enqueue(toUint8Array(owner._bodyText));
controller.close();
return;
}
if (owner._bodyInit != null) controller.enqueue(toUint8Array(owner._bodyInit));
controller.close();
}).catch((error) => controller.error(error));
},
});
stream.__gopeedMarkBodyUsed = () => { owner._bodyUsed = true; };
return stream;
}
async function readAllFromStream(stream, asText) {
if (!stream) return asText ? "" : new Uint8Array(0);
const reader = stream.getReader();
const chunks = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!(value instanceof Uint8Array)) {
throw new TypeError("Fetch body stream chunks must be Uint8Array values");
}
const chunk = value;
chunks.push(chunk);
total += chunk.byteLength;
}
} finally {
reader.releaseLock();
}
const merged = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
offset += chunk.byteLength;
}
return asText ? new TextDecoder().decode(merged) : merged;
}
function attachResponseStreaming(response, stream) {
response.__gopeedBodyStream = stream;
response.__gopeedBodyConsumed = false;
const ensureUnused = () => {
if (response.__gopeedBodyConsumed) throw new TypeError("Already read");
};
const markBodyUsed = () => {
ensureUnused();
response.__gopeedBodyConsumed = true;
response.bodyUsed = true;
};
if (stream) {
stream.__gopeedMarkBodyUsed = () => {
if (!response.__gopeedBodyConsumed) {
response.__gopeedBodyConsumed = true;
response.bodyUsed = true;
}
};
}
response.text = async function () {
markBodyUsed();
return readAllFromStream(this.body, true);
};
response.arrayBuffer = async function () {
markBodyUsed();
const bytes = await readAllFromStream(this.body, false);
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
};
response.bytes = async function () {
markBodyUsed();
return readAllFromStream(this.body, false);
};
response.blob = async function () {
markBodyUsed();
const contentType = this.headers && this.headers.get ? (this.headers.get("content-type") || "") : "";
const bytes = await readAllFromStream(this.body, false);
return new Blob([bytes], { type: contentType });
};
response.json = async function () {
return JSON.parse(await this.text());
};
return response;
}
if (typeof globalThis.Response === "function") {
const responseProto = globalThis.Response.prototype;
const bodyDescriptor = Object.getOwnPropertyDescriptor(responseProto, "body");
if (!bodyDescriptor || typeof bodyDescriptor.get !== "function") {
Object.defineProperty(responseProto, "body", {
configurable: true,
enumerable: true,
get() {
if (!this.__gopeedBodyStream) this.__gopeedBodyStream = createBodyReadableStream(this);
return this.__gopeedBodyStream;
},
});
}
}
if (typeof fetchOpen !== "function") return;
globalThis.fetch = async function (input, init) {
const request = new Request(input, init);
const requestID = crypto.randomUUID ? crypto.randomUUID() : String(Date.now()) + "-" + String(Math.random());
const signal = request.signal;
let abortHandler = null;
const cleanupAbort = () => {
if (signal && abortHandler && typeof signal.removeEventListener === "function") {
signal.removeEventListener("abort", abortHandler);
}
abortHandler = null;
};
if (signal) {
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
abortHandler = () => fetchAbort(requestID, signal.reason == null ? "" : String(signal.reason));
signal.addEventListener("abort", abortHandler, { once: true });
}
let body = null;
if (request._bodyStream && !request._bodyFormData) {
const bytes = await readAllFromStream(request._bodyStream, false);
body = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
} else if (request._bodyFormData) {
body = request._bodyFormData._entries;
} else if (request._bodyArrayBuffer) {
body = request._bodyArrayBuffer;
} else if (request._bodyBlob) {
body = await request._bodyBlob.arrayBuffer();
} else if (request._bodyInit != null && typeof request._bodyInit === "object") {
body = request._bodyInit;
} else if (request._bodyText != null) {
body = request._bodyText;
} else if (request._bodyInit != null) {
body = request._bodyInit;
}
const headers = [];
request.headers.forEach((value, key) => headers.push([key, value]));
let metadata;
try {
metadata = await fetchOpen({
id: requestID,
url: request.url,
method: request.method,
headers,
body,
bodyType: request._bodyFormData ? "formdata" : "",
bodyBoundary: request._bodyFormDataBoundary,
redirect: request.redirect,
credentials: request.credentials,
});
} catch (error) {
cleanupAbort();
if (signal && signal.aborted) throw new DOMException("Aborted", "AbortError");
throw error instanceof Error ? error : new TypeError(String(error));
}
const stream = new ReadableStream({
async pull(controller) {
let chunk;
try {
chunk = await fetchRead(metadata.id, 64 * 1024);
} catch (error) {
fetchClose(metadata.id);
cleanupAbort();
controller.error(error instanceof Error ? error : new TypeError(String(error)));
return;
}
if (chunk == null) {
fetchClose(metadata.id);
cleanupAbort();
controller.close();
return;
}
const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
if (bytes.byteLength === 0) {
fetchClose(metadata.id);
cleanupAbort();
controller.close();
return;
}
controller.enqueue(bytes);
},
cancel(reason) {
cleanupAbort();
fetchAbort(metadata.id, reason == null ? "" : String(reason));
},
});
const response = new Response(null, {
status: metadata.status,
statusText: metadata.statusText,
headers: metadata.headers,
url: metadata.url,
redirected: metadata.redirected,
});
response._type = "basic";
response._headers._guard = "immutable";
return attachResponseStreaming(response, stream);
};
})();
+619
View File
@@ -0,0 +1,619 @@
package fetch
import (
"bytes"
"context"
_ "embed"
"errors"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"sync"
"github.com/GopeedLab/gopeed/internal/httpclient"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
"github.com/GopeedLab/gopeed/pkg/download/engine/util"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/eventloop"
"golang.org/x/net/publicsuffix"
)
const FingerprintMagicKey = "__gopeed_fetch_fingerprint"
//go:embed fetch.js
var script string
type Config struct {
ProxyHandler func(*http.Request) (*url.URL, error)
RegisterCleanup func(func())
}
func Enable(runtime *goja.Runtime, loop *eventloop.EventLoop, cfg *Config) error {
if cfg == nil {
cfg = &Config{}
}
registry := newRegistry()
if cfg.RegisterCleanup != nil {
cfg.RegisterCleanup(registry.CloseAll)
}
if err := runtime.Set("__gopeed_setFingerprint", func(fingerprint string) {
_ = runtime.Set(FingerprintMagicKey, fingerprint)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_open", func(call goja.FunctionCall) goja.Value {
request, err := exportRequest(runtime, call.Argument(0))
if err != nil {
panic(runtime.NewGoError(err))
}
fingerprint := util.SafeGet[string](runtime, FingerprintMagicKey)
promise, resolve, reject := runtime.NewPromise()
go func() {
metadata, err := registry.Open(fingerprint, cfg.ProxyHandler, request)
ok := loop.RunOnLoop(func(runtime *goja.Runtime) {
if err != nil {
reject(runtime.NewGoError(err))
return
}
resolve(runtime.ToValue(metadata))
})
if !ok && metadata != nil {
registry.Close(metadata.ID)
}
}()
return runtime.ToValue(promise)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_read", func(call goja.FunctionCall) goja.Value {
id := call.Argument(0).String()
chunkSize := int(call.Argument(1).ToInteger())
promise, resolve, reject := runtime.NewPromise()
go func() {
chunk, done, err := registry.Read(id, chunkSize)
ok := loop.RunOnLoop(func(runtime *goja.Runtime) {
if err != nil {
reject(runtime.NewGoError(err))
return
}
if done {
resolve(goja.Null())
return
}
resolve(runtime.ToValue(runtime.NewArrayBuffer(chunk)))
})
if !ok {
registry.Close(id)
}
}()
return runtime.ToValue(promise)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_close", func(id string) {
registry.Close(id)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_abort", func(id, reason string) {
registry.Abort(id, reason)
}); err != nil {
return err
}
_, err := runtime.RunString(script)
return err
}
type request struct {
ID string
URL string
Method string
Headers [][2]string
Body any
Redirect string
Credentials string
}
type responseMetadata struct {
ID string `json:"id"`
Status int `json:"status"`
StatusText string `json:"statusText"`
URL string `json:"url"`
Redirected bool `json:"redirected"`
Headers [][2]string `json:"headers"`
}
type formDataEntry struct {
name string
value any
}
type formDataSnapshot struct {
entries []formDataEntry
boundary string
}
func exportRequest(runtime *goja.Runtime, value goja.Value) (*request, error) {
obj := value.ToObject(runtime)
if obj == nil {
return nil, fmt.Errorf("invalid fetch request")
}
result := &request{
ID: obj.Get("id").String(),
URL: obj.Get("url").String(),
Method: obj.Get("method").String(),
Redirect: obj.Get("redirect").String(),
Credentials: obj.Get("credentials").String(),
}
if result.Method == "" {
result.Method = http.MethodGet
}
if headersValue := obj.Get("headers"); headersValue != nil && !goja.IsUndefined(headersValue) && !goja.IsNull(headersValue) {
if exported, ok := headersValue.Export().([]any); ok {
for _, item := range exported {
pair, ok := item.([]any)
if !ok || len(pair) != 2 {
continue
}
result.Headers = append(result.Headers, [2]string{fmt.Sprint(pair[0]), fmt.Sprint(pair[1])})
}
}
}
bodyValue := obj.Get("body")
if bodyValue != nil && !goja.IsUndefined(bodyValue) && !goja.IsNull(bodyValue) {
var body any
var err error
if obj.Get("bodyType").String() == "formdata" {
body, err = snapshotFormData(bodyValue.Export())
} else {
body, err = snapshotBody(bodyValue.Export())
}
if err != nil {
return nil, err
}
if snapshot, ok := body.(*formDataSnapshot); ok {
snapshot.boundary = obj.Get("bodyBoundary").String()
}
result.Body = body
}
return result, nil
}
// snapshotBody runs on the JavaScript event loop. Go request goroutines must
// not retain mutable ArrayBuffer or FormData storage owned by goja.
func snapshotBody(body any) (any, error) {
switch value := body.(type) {
case nil, string:
return value, nil
case []byte:
return append([]byte(nil), value...), nil
case goja.ArrayBuffer:
return append([]byte(nil), value.Bytes()...), nil
case *file.File:
return snapshotFile(value), nil
default:
if bytesValue, ok := value.(interface{ Bytes() []byte }); ok {
return append([]byte(nil), bytesValue.Bytes()...), nil
}
return value, nil
}
}
func snapshotFormData(body any) (*formDataSnapshot, error) {
entries, ok := body.([]any)
if !ok {
return nil, fmt.Errorf("invalid FormData entry list %T", body)
}
snapshot := &formDataSnapshot{entries: make([]formDataEntry, 0, len(entries))}
for _, item := range entries {
pair, ok := item.([]any)
if !ok || len(pair) != 2 {
return nil, fmt.Errorf("invalid FormData entry %T", item)
}
name, ok := pair[0].(string)
if !ok {
return nil, fmt.Errorf("invalid FormData field name %T", pair[0])
}
value := pair[1]
if formFile, ok := value.(*file.File); ok {
value = snapshotFile(formFile)
}
snapshot.entries = append(snapshot.entries, formDataEntry{name: name, value: value})
}
return snapshot, nil
}
func snapshotFile(source *file.File) *file.File {
if source == nil {
return nil
}
return &file.File{
Reader: source.Reader,
Closer: source.Closer,
Name: source.Name,
Size: source.Size,
}
}
type registry struct {
mu sync.Mutex
operations map[string]*operation
ctx context.Context
cancel context.CancelFunc
jar http.CookieJar
closed bool
}
type operation struct {
ctx context.Context
cancel context.CancelFunc
readMu sync.Mutex
stateMu sync.Mutex
body io.ReadCloser
pending error
closed bool
closeOnce sync.Once
}
func newRegistry() *registry {
ctx, cancel := context.WithCancel(context.Background())
jar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
return &registry{
operations: make(map[string]*operation),
ctx: ctx,
cancel: cancel,
jar: jar,
}
}
func (r *registry) Open(fingerprint string, proxyHandler func(*http.Request) (*url.URL, error), metadata *request) (*responseMetadata, error) {
ctx, cancel := context.WithCancel(r.ctx)
op := &operation{ctx: ctx, cancel: cancel}
if err := r.add(metadata.ID, op); err != nil {
cancel()
return nil, err
}
keepOperation := false
defer func() {
if !keepOperation {
r.Close(metadata.ID)
}
}()
contentType, body, contentLength, err := buildBody(metadata.Body)
if err != nil {
return nil, err
}
if metadata.Method == http.MethodGet || metadata.Method == http.MethodHead {
body = nil
contentLength = 0
}
httpRequest, err := http.NewRequestWithContext(ctx, metadata.Method, metadata.URL, body)
if err != nil {
return nil, err
}
for _, header := range metadata.Headers {
httpRequest.Header.Add(header[0], header[1])
}
if host := httpRequest.Header.Get("Host"); host != "" {
httpRequest.Host = host
}
if body != nil {
if contentType != "" && !hasHeader(metadata.Headers, "Content-Type") {
httpRequest.Header.Set("Content-Type", contentType)
}
httpRequest.ContentLength = contentLength
}
var jar http.CookieJar
if metadata.Credentials != "omit" {
jar = r.jar
}
redirected := false
client, err := httpclient.NewClient(httpclient.Options{
Client: httpclient.ClientOptions{
Jar: jar,
CheckRedirect: func(_ *http.Request, via []*http.Request) error {
switch metadata.Redirect {
case "manual":
return http.ErrUseLastResponse
case "error":
return fmt.Errorf("redirect failed")
default:
redirected = len(via) > 0
if len(via) > 20 {
return fmt.Errorf("too many redirects")
}
return nil
}
},
},
Transport: httpclient.TransportOptions{Proxy: proxyHandler},
Impersonation: impersonationOptions(fingerprint),
})
if err != nil {
return nil, err
}
response, err := client.Do(httpRequest)
if err != nil {
var networkError net.Error
if errors.As(err, &networkError) && networkError.Timeout() {
return nil, fmt.Errorf("Network request timed out")
}
return nil, fmt.Errorf("Network request failed: %w", err)
}
if !op.setBody(response.Body) {
return nil, context.Canceled
}
keepOperation = true
result := &responseMetadata{
ID: metadata.ID,
Status: response.StatusCode,
StatusText: http.StatusText(response.StatusCode),
URL: metadata.URL,
}
if response.Request != nil && response.Request.URL != nil {
responseURL := *response.Request.URL
responseURL.Fragment = ""
result.URL = responseURL.String()
}
result.Redirected = redirected
for key, values := range response.Header {
for _, value := range values {
result.Headers = append(result.Headers, [2]string{key, value})
}
}
return result, nil
}
func (r *registry) add(id string, op *operation) error {
if id == "" {
return fmt.Errorf("fetch request ID is required")
}
r.mu.Lock()
defer r.mu.Unlock()
if r.closed {
return context.Canceled
}
if _, exists := r.operations[id]; exists {
return fmt.Errorf("duplicate fetch request ID %q", id)
}
r.operations[id] = op
return nil
}
func (r *registry) Read(id string, chunkSize int) ([]byte, bool, error) {
op := r.get(id)
if op == nil {
return nil, true, nil
}
chunk, done, err := op.read(chunkSize)
if done || err != nil {
r.Close(id)
}
return chunk, done, err
}
func (r *registry) Close(id string) {
r.mu.Lock()
op := r.operations[id]
delete(r.operations, id)
r.mu.Unlock()
if op != nil {
op.close()
}
}
func (r *registry) Abort(id, _ string) {
r.Close(id)
}
func (r *registry) CloseAll() {
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return
}
r.closed = true
operations := r.operations
r.operations = make(map[string]*operation)
r.mu.Unlock()
r.cancel()
for _, op := range operations {
op.close()
}
}
func (r *registry) get(id string) *operation {
r.mu.Lock()
defer r.mu.Unlock()
return r.operations[id]
}
func (o *operation) setBody(body io.ReadCloser) bool {
o.stateMu.Lock()
defer o.stateMu.Unlock()
if o.closed {
_ = body.Close()
return false
}
o.body = body
return true
}
func (o *operation) read(chunkSize int) ([]byte, bool, error) {
o.readMu.Lock()
defer o.readMu.Unlock()
o.stateMu.Lock()
body := o.body
pending := o.pending
o.pending = nil
closed := o.closed
o.stateMu.Unlock()
if pending != nil {
if errors.Is(pending, io.EOF) {
return nil, true, nil
}
return nil, false, pending
}
if closed || body == nil {
return nil, true, nil
}
if chunkSize <= 0 {
chunkSize = 64 * 1024
}
buffer := make([]byte, chunkSize)
n, err := body.Read(buffer)
if n > 0 {
if err != nil {
o.stateMu.Lock()
o.pending = err
o.stateMu.Unlock()
}
return buffer[:n], false, nil
}
if errors.Is(err, io.EOF) {
return nil, true, nil
}
if err != nil {
return nil, false, err
}
return []byte{}, false, nil
}
func (o *operation) close() {
o.closeOnce.Do(func() {
o.cancel()
o.stateMu.Lock()
o.closed = true
body := o.body
o.stateMu.Unlock()
if body != nil {
_ = body.Close()
}
})
}
func buildBody(body any) (string, io.Reader, int64, error) {
switch value := body.(type) {
case nil:
return "", nil, 0, nil
case string:
return "text/plain;charset=UTF-8", strings.NewReader(value), int64(len(value)), nil
case []byte:
return "", bytes.NewReader(value), int64(len(value)), nil
case goja.ArrayBuffer:
data := value.Bytes()
return "", bytes.NewReader(data), int64(len(data)), nil
case *file.File:
return "application/octet-stream", value.Reader, value.Size, nil
case *formDataSnapshot:
return buildMultipartBody(value)
default:
if bytesValue, ok := value.(interface{ Bytes() []byte }); ok {
data := bytesValue.Bytes()
return "", bytes.NewReader(data), int64(len(data)), nil
}
data := fmt.Sprint(value)
return "", strings.NewReader(data), int64(len(data)), nil
}
}
type countingWriter struct {
n int64
}
func (w *countingWriter) Write(data []byte) (int, error) {
w.n += int64(len(data))
return len(data), nil
}
func buildMultipartBody(snapshot *formDataSnapshot) (string, io.Reader, int64, error) {
boundary := snapshot.boundary
if boundary == "" {
boundaryWriter := multipart.NewWriter(io.Discard)
boundary = boundaryWriter.Boundary()
_ = boundaryWriter.Close()
}
counter := &countingWriter{}
statWriter := multipart.NewWriter(counter)
if err := statWriter.SetBoundary(boundary); err != nil {
return "", nil, 0, err
}
for _, entry := range snapshot.entries {
switch value := entry.value.(type) {
case string:
if err := statWriter.WriteField(entry.name, value); err != nil {
return "", nil, 0, err
}
case *file.File:
if _, err := statWriter.CreateFormFile(entry.name, value.Name); err != nil {
return "", nil, 0, err
}
counter.n += value.Size
}
}
if err := statWriter.Close(); err != nil {
return "", nil, 0, err
}
reader, writer := io.Pipe()
multipartWriter := multipart.NewWriter(writer)
if err := multipartWriter.SetBoundary(boundary); err != nil {
_ = reader.Close()
_ = writer.CloseWithError(err)
return "", nil, 0, err
}
go func() {
for _, entry := range snapshot.entries {
var err error
switch value := entry.value.(type) {
case string:
err = multipartWriter.WriteField(entry.name, value)
case *file.File:
var part io.Writer
part, err = multipartWriter.CreateFormFile(entry.name, value.Name)
if err == nil {
_, err = io.Copy(part, value)
}
}
if err != nil {
_ = writer.CloseWithError(err)
return
}
}
if err := multipartWriter.Close(); err != nil {
_ = writer.CloseWithError(err)
return
}
_ = writer.Close()
}()
return multipartWriter.FormDataContentType(), reader, counter.n, nil
}
func hasHeader(headers [][2]string, key string) bool {
for _, header := range headers {
if strings.EqualFold(header[0], key) {
return true
}
}
return false
}
func impersonationOptions(fingerprint string) httpclient.ImpersonationOptions {
switch fingerprint {
case "chrome":
return httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationFixed, Browser: httpclient.BrowserChrome}
case "firefox":
return httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationFixed, Browser: httpclient.BrowserFirefox}
case "safari":
return httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationFixed, Browser: httpclient.BrowserSafari}
default:
return httpclient.ImpersonationOptions{Mode: httpclient.ImpersonationNative}
}
}
@@ -1,68 +0,0 @@
package formdata
import "github.com/dop251/goja"
type FormData struct {
data map[string]any
}
func (fd *FormData) Append(name string, value any) {
fd.data[name] = value
}
func (fd *FormData) Delete(name string) {
delete(fd.data, name)
}
func (fd *FormData) Entries() []any {
var entries []any
for k, v := range fd.data {
entries = append(entries, []any{k, v})
}
return entries
}
func (fd *FormData) Get(name string) any {
return fd.data[name]
}
func (fd *FormData) GetAll(name string) []any {
return []any{fd.data[name]}
}
func (fd *FormData) Has(name string) bool {
_, ok := fd.data[name]
return ok
}
func (fd *FormData) Keys() []string {
var keys []string
for k := range fd.data {
keys = append(keys, k)
}
return keys
}
func (fd *FormData) Set(name string, value any) {
fd.data[name] = value
}
func (fd *FormData) Values() []any {
var values []any
for _, v := range fd.data {
values = append(values, v)
}
return values
}
func Enable(runtime *goja.Runtime) error {
file := runtime.ToValue(func(call goja.ConstructorCall) *goja.Object {
instance := &FormData{
data: make(map[string]any),
}
instanceValue := runtime.ToValue(instance).(*goja.Object)
instanceValue.SetPrototype(call.This.Prototype())
return instanceValue
})
return runtime.Set("FormData", file)
}
-513
View File
@@ -6,21 +6,11 @@ import (
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/xhr"
"github.com/GopeedLab/gopeed/pkg/download/engine/util"
"github.com/dop251/goja"
"github.com/dop251/goja_nodejs/eventloop"
"github.com/imroc/req/v3"
)
//go:embed stream.js
@@ -29,8 +19,6 @@ var script string
type Config struct {
CreateObjectURL func(opts *ObjectURLOptions, open ObjectURLOpener) (string, error)
RevokeObjectURL func(url string) error
ProxyHandler func(r *http.Request) (*url.URL, error)
RegisterCleanup func(cleanup func())
}
type ObjectURLOptions struct {
@@ -96,69 +84,6 @@ func Enable(runtime *goja.Runtime, loop *eventloop.EventLoop, cfg *Config) error
}); err != nil {
return err
}
fetchRegistry := newFetchRegistry()
if cfg.RegisterCleanup != nil {
cfg.RegisterCleanup(fetchRegistry.CloseAll)
}
if err := runtime.Set("__gopeed_fetch_open", func(call goja.FunctionCall) goja.Value {
reqMeta, err := exportFetchRequest(runtime, call.Argument(0))
if err != nil {
panic(runtime.NewGoError(err))
}
fingerprint := util.SafeGet[string](runtime, xhr.FingerprintMagicKey)
promise, resolve, reject := runtime.NewPromise()
go func() {
meta, err := fetchRegistry.Open(fingerprint, cfg.ProxyHandler, reqMeta)
ok := loop.RunOnLoop(func(runtime *goja.Runtime) {
if err != nil {
reject(runtime.NewGoError(err))
return
}
resolve(runtime.ToValue(meta))
})
if !ok && meta != nil {
fetchRegistry.Close(meta.ID)
}
}()
return runtime.ToValue(promise)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_read", func(call goja.FunctionCall) goja.Value {
id := call.Argument(0).String()
chunkSize := int(call.Argument(1).ToInteger())
promise, resolve, reject := runtime.NewPromise()
go func() {
chunk, done, err := fetchRegistry.Read(id, chunkSize)
ok := loop.RunOnLoop(func(runtime *goja.Runtime) {
if err != nil {
reject(runtime.NewGoError(err))
return
}
if done {
resolve(goja.Null())
return
}
resolve(runtime.ToValue(runtime.NewArrayBuffer(chunk)))
})
if !ok {
fetchRegistry.Close(id)
}
}()
return runtime.ToValue(promise)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_close", func(id string) {
fetchRegistry.Close(id)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_fetch_abort", func(id string, reason string) {
fetchRegistry.Abort(id, reason)
}); err != nil {
return err
}
if err := runtime.Set("__gopeed_blob_pipe_chunk", func(call goja.FunctionCall) goja.Value {
id := call.Argument(0).String()
ok := blobPipes.Push(id, exportBytes(call.Argument(1)))
@@ -550,441 +475,3 @@ func exportJSError(value goja.Value) error {
}
return errors.New(stack)
}
type fetchRegistry struct {
mu sync.Mutex
streams map[string]*fetchStream
ctx context.Context
cancel context.CancelFunc
closed bool
}
type fetchStream struct {
body io.ReadCloser
cancel context.CancelFunc
closeOnce sync.Once
ctx context.Context
ch chan fetchChunk
readMu sync.Mutex
pending []byte
}
type fetchChunk struct {
data []byte
err error
}
type fetchRequest struct {
URL string
Method string
Headers [][2]string
Body any
Redirect string
Credentials string
}
type fetchFormDataEntry struct {
name string
value any
}
type fetchFormDataSnapshot struct {
entries []fetchFormDataEntry
}
type fetchOpenMeta struct {
ID string `json:"id"`
Status int `json:"status"`
StatusText string `json:"statusText"`
URL string `json:"url"`
Headers [][2]string `json:"headers"`
}
func newFetchRegistry() *fetchRegistry {
ctx, cancel := context.WithCancel(context.Background())
return &fetchRegistry{
streams: make(map[string]*fetchStream),
ctx: ctx,
cancel: cancel,
}
}
func exportFetchRequest(runtime *goja.Runtime, value goja.Value) (*fetchRequest, error) {
obj := value.ToObject(runtime)
if obj == nil {
return nil, fmt.Errorf("invalid fetch request")
}
meta := &fetchRequest{
URL: obj.Get("url").String(),
Method: obj.Get("method").String(),
Redirect: obj.Get("redirect").String(),
Credentials: obj.Get("credentials").String(),
}
if meta.Method == "" {
meta.Method = http.MethodGet
}
if headersVal := obj.Get("headers"); headersVal != nil && !goja.IsUndefined(headersVal) && !goja.IsNull(headersVal) {
if exported, ok := headersVal.Export().([]any); ok {
for _, item := range exported {
pair, ok := item.([]any)
if !ok || len(pair) != 2 {
continue
}
meta.Headers = append(meta.Headers, [2]string{fmt.Sprint(pair[0]), fmt.Sprint(pair[1])})
}
}
}
bodyVal := obj.Get("body")
if bodyVal != nil && !goja.IsUndefined(bodyVal) && !goja.IsNull(bodyVal) {
body, err := snapshotFetchBody(bodyVal.Export())
if err != nil {
return nil, err
}
meta.Body = body
}
return meta, nil
}
// snapshotFetchBody runs on the JavaScript event loop before fetch work is
// handed to a background goroutine. Values exported by goja may still share
// mutable storage with JavaScript (notably ArrayBuffer and FormData), so the
// background request must only retain immutable Go-owned data.
func snapshotFetchBody(body any) (any, error) {
switch v := body.(type) {
case nil, string:
return v, nil
case []byte:
return append([]byte(nil), v...), nil
case goja.ArrayBuffer:
return append([]byte(nil), v.Bytes()...), nil
case *file.File:
return snapshotFetchFile(v), nil
case *formdata.FormData:
entries := v.Entries()
snapshot := &fetchFormDataSnapshot{
entries: make([]fetchFormDataEntry, 0, len(entries)),
}
for _, entry := range entries {
pair, ok := entry.([]any)
if !ok || len(pair) != 2 {
return nil, fmt.Errorf("invalid FormData entry %T", entry)
}
name, ok := pair[0].(string)
if !ok {
return nil, fmt.Errorf("invalid FormData field name %T", pair[0])
}
value := pair[1]
if formFile, ok := value.(*file.File); ok {
value = snapshotFetchFile(formFile)
}
snapshot.entries = append(snapshot.entries, fetchFormDataEntry{
name: name,
value: value,
})
}
return snapshot, nil
default:
if typed, ok := v.(interface{ Bytes() []byte }); ok {
return append([]byte(nil), typed.Bytes()...), nil
}
return v, nil
}
}
func snapshotFetchFile(src *file.File) *file.File {
if src == nil {
return nil
}
return &file.File{
Reader: src.Reader,
Closer: src.Closer,
Name: src.Name,
Size: src.Size,
}
}
func (r *fetchRegistry) Open(fingerprint string, proxyHandler func(r *http.Request) (*url.URL, error), reqMeta *fetchRequest) (*fetchOpenMeta, error) {
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return nil, context.Canceled
}
registryCtx := r.ctx
r.mu.Unlock()
client := req.C()
if proxyHandler != nil {
client.SetProxy(proxyHandler)
}
setFetchFingerprint(client, fingerprint)
contentType, body, err := buildFetchBody(reqMeta.Body)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(registryCtx)
keepCancel := false
defer func() {
if !keepCancel {
cancel()
}
}()
reqBuilder := client.R()
reqBuilder.SetContext(ctx)
reqBuilder.DisableAutoReadResponse()
for _, header := range reqMeta.Headers {
reqBuilder.SetHeader(header[0], header[1])
}
if body != nil && reqMeta.Method != http.MethodGet && reqMeta.Method != http.MethodHead {
reqBuilder.SetBody(body)
if contentType != "" && !hasHeader(reqMeta.Headers, "Content-Type") {
reqBuilder.SetHeader("Content-Type", contentType)
}
}
client.SetRedirectPolicy(func(req *http.Request, via []*http.Request) error {
switch reqMeta.Redirect {
case "manual":
return http.ErrUseLastResponse
case "error":
return fmt.Errorf("redirect failed")
default:
if len(via) > 20 {
return fmt.Errorf("too many redirects")
}
return nil
}
})
resp, err := reqBuilder.Send(reqMeta.Method, reqMeta.URL)
if err != nil {
var ne net.Error
if errorsAsTimeout(err, &ne) {
return nil, fmt.Errorf("Network request timed out")
}
return nil, fmt.Errorf("Network request failed: %w", err)
}
id := fmt.Sprintf("%d", time.Now().UnixNano())
meta := &fetchOpenMeta{
ID: id,
Status: resp.StatusCode,
StatusText: resp.Status,
URL: reqMeta.URL,
}
if resp.Response != nil && resp.Response.Request != nil && resp.Response.Request.URL != nil {
responseURL := *resp.Response.Request.URL
responseURL.Fragment = ""
meta.URL = responseURL.String()
}
for key, values := range resp.Header {
meta.Headers = append(meta.Headers, [2]string{key, strings.Join(values, ", ")})
}
bodyCloser := io.NopCloser(strings.NewReader(""))
if resp.Response != nil && resp.Response.Body != nil {
bodyCloser = resp.Response.Body
}
stream := &fetchStream{
body: bodyCloser,
cancel: cancel,
ctx: ctx,
ch: make(chan fetchChunk, 8),
}
r.mu.Lock()
if r.closed {
r.mu.Unlock()
closeFetchStream(stream)
return nil, context.Canceled
}
r.streams[id] = stream
r.mu.Unlock()
keepCancel = true
go stream.readLoop()
return meta, nil
}
func (r *fetchRegistry) Read(id string, chunkSize int) ([]byte, bool, error) {
stream := r.get(id)
if stream == nil {
return nil, true, nil
}
stream.readMu.Lock()
defer stream.readMu.Unlock()
if len(stream.pending) > 0 {
n := len(stream.pending)
if chunkSize > 0 && n > chunkSize {
n = chunkSize
}
chunk := append([]byte(nil), stream.pending[:n]...)
stream.pending = stream.pending[n:]
return chunk, false, nil
}
select {
case item, ok := <-stream.ch:
if !ok {
r.Close(id)
return nil, true, nil
}
if item.err != nil {
r.Close(id)
return nil, false, item.err
}
if chunkSize > 0 && len(item.data) > chunkSize {
head := append([]byte(nil), item.data[:chunkSize]...)
stream.pending = append(stream.pending[:0], item.data[chunkSize:]...)
return head, false, nil
}
return item.data, false, nil
case <-stream.ctx.Done():
return nil, false, stream.ctx.Err()
}
}
func (s *fetchStream) readLoop() {
defer close(s.ch)
buf := make([]byte, 64*1024)
for {
n, err := s.body.Read(buf)
if n > 0 {
chunk := append([]byte(nil), buf[:n]...)
select {
case s.ch <- fetchChunk{data: chunk}:
case <-s.ctx.Done():
return
}
}
if err == io.EOF {
return
}
if err != nil {
select {
case s.ch <- fetchChunk{err: err}:
case <-s.ctx.Done():
}
return
}
}
}
func (r *fetchRegistry) Close(id string) {
r.mu.Lock()
stream := r.streams[id]
delete(r.streams, id)
r.mu.Unlock()
closeFetchStream(stream)
}
// CloseAll permanently closes the registry and cancels both active and
// in-flight fetches. It is safe to call more than once.
func (r *fetchRegistry) CloseAll() {
if r == nil {
return
}
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return
}
r.closed = true
if r.cancel != nil {
r.cancel()
}
streams := r.streams
r.streams = make(map[string]*fetchStream)
r.mu.Unlock()
for _, stream := range streams {
closeFetchStream(stream)
}
}
func closeFetchStream(stream *fetchStream) {
if stream == nil {
return
}
stream.closeOnce.Do(func() {
if stream.cancel != nil {
stream.cancel()
}
_ = stream.body.Close()
})
}
func (r *fetchRegistry) Abort(id string, _ string) {
r.Close(id)
}
func (r *fetchRegistry) get(id string) *fetchStream {
r.mu.Lock()
defer r.mu.Unlock()
return r.streams[id]
}
func buildFetchBody(body any) (string, any, error) {
switch v := body.(type) {
case nil:
return "", nil, nil
case string:
return "text/plain;charset=UTF-8", v, nil
case []byte:
return "application/octet-stream", v, nil
case goja.ArrayBuffer:
return "application/octet-stream", v.Bytes(), nil
case *file.File:
return "application/octet-stream", v.Reader, nil
case *fetchFormDataSnapshot:
pr, pw := io.Pipe()
mw := xhr.NewMultipart(pw)
for _, entry := range v.entries {
switch vv := entry.value.(type) {
case string:
if err := mw.WriteField(entry.name, vv); err != nil {
_ = pw.CloseWithError(err)
return "", nil, err
}
case *file.File:
if err := mw.WriteFile(entry.name, vv); err != nil {
_ = pw.CloseWithError(err)
return "", nil, err
}
}
}
go func() {
if err := mw.Send(); err != nil {
_ = pw.CloseWithError(err)
return
}
if err := mw.Close(); err != nil {
_ = pw.CloseWithError(err)
return
}
_ = pw.Close()
}()
return mw.FormDataContentType(), pr, nil
default:
if typed, ok := v.(interface{ Bytes() []byte }); ok {
return "application/octet-stream", typed.Bytes(), nil
}
return "", fmt.Sprint(v), nil
}
}
func hasHeader(headers [][2]string, key string) bool {
for _, header := range headers {
if strings.EqualFold(header[0], key) {
return true
}
}
return false
}
func setFetchFingerprint(client *req.Client, fingerprint string) {
switch fingerprint {
case "chrome":
client.ImpersonateChrome()
case "firefox":
client.ImpersonateFirefox()
case "safari":
client.ImpersonateSafari()
}
}
func errorsAsTimeout(err error, target *net.Error) bool {
return errors.As(err, target) && (*target).Timeout()
}
@@ -258,7 +258,6 @@ func waitForJSValue(t *testing.T, engine *engine.Engine, expression, want string
func newStreamTestEngine(t *testing.T, created chan<- createdObjectURL) (*engine.Engine, func()) {
t.Helper()
var next atomic.Int64
var cleanup func()
e := engine.NewEngine(&engine.Config{
StreamConfig: &stream.Config{
CreateObjectURL: func(opts *stream.ObjectURLOptions, open stream.ObjectURLOpener) (string, error) {
@@ -266,13 +265,7 @@ func newStreamTestEngine(t *testing.T, created chan<- createdObjectURL) (*engine
return fmt.Sprintf("blob:test-%d", next.Add(1)), nil
},
RevokeObjectURL: func(string) error { return nil },
RegisterCleanup: func(fn func()) {
cleanup = fn
},
},
})
if cleanup == nil {
t.Fatal("stream cleanup was not registered")
}
return e, cleanup
return e, e.Close
}
@@ -1,191 +0,0 @@
package stream
import (
"context"
"io"
"strings"
"sync/atomic"
"testing"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/file"
"github.com/GopeedLab/gopeed/pkg/download/engine/inject/formdata"
"github.com/dop251/goja"
)
func TestExportFetchRequestSnapshotsArrayBuffer(t *testing.T) {
runtime := goja.New()
buffer := runtime.NewArrayBuffer([]byte("before"))
request := runtime.NewObject()
setFetchRequestDefaults(t, request)
if err := request.Set("body", buffer); err != nil {
t.Fatal(err)
}
meta, err := exportFetchRequest(runtime, request)
if err != nil {
t.Fatal(err)
}
buffer.Bytes()[0] = 'X'
body, ok := meta.Body.([]byte)
if !ok {
t.Fatalf("expected byte snapshot, got %T", meta.Body)
}
if got := string(body); got != "before" {
t.Fatalf("ArrayBuffer snapshot changed after export: %q", got)
}
}
func TestExportFetchRequestSnapshotsFormData(t *testing.T) {
runtime := goja.New()
runtime.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
if err := formdata.Enable(runtime); err != nil {
t.Fatal(err)
}
value, err := runtime.RunString(`
globalThis.form = new FormData();
form.append("field", "before");
form;
`)
if err != nil {
t.Fatal(err)
}
request := runtime.NewObject()
setFetchRequestDefaults(t, request)
if err := request.Set("body", value); err != nil {
t.Fatal(err)
}
meta, err := exportFetchRequest(runtime, request)
if err != nil {
t.Fatal(err)
}
if _, err := runtime.RunString(`form.set("field", "after")`); err != nil {
t.Fatal(err)
}
body, ok := meta.Body.(*fetchFormDataSnapshot)
if !ok {
t.Fatalf("expected FormData snapshot, got %T", meta.Body)
}
if len(body.entries) != 1 {
t.Fatalf("expected one FormData entry, got %d", len(body.entries))
}
if got := body.entries[0]; got.name != "field" || got.value != "before" {
t.Fatalf("unexpected FormData snapshot: %#v", got)
}
}
func setFetchRequestDefaults(t *testing.T, request *goja.Object) {
t.Helper()
for key, value := range map[string]any{
"url": "https://example.test",
"method": "POST",
"redirect": "follow",
"credentials": "same-origin",
} {
if err := request.Set(key, value); err != nil {
t.Fatal(err)
}
}
}
func TestSnapshotFetchBodyCopiesFileMetadata(t *testing.T) {
source := &file.File{
Reader: strings.NewReader("payload"),
Name: "before.txt",
Size: 7,
}
value, err := snapshotFetchBody(source)
if err != nil {
t.Fatal(err)
}
snapshot, ok := value.(*file.File)
if !ok {
t.Fatalf("expected file snapshot, got %T", value)
}
source.Name = "after.txt"
source.Size = 99
if snapshot.Name != "before.txt" || snapshot.Size != 7 {
t.Fatalf("file metadata was not snapshotted: %#v", snapshot)
}
}
func TestFetchRegistryCloseAll(t *testing.T) {
registry := newFetchRegistry()
streamCtx, cancel := context.WithCancel(context.Background())
body := &trackingReadCloser{}
registry.streams["active"] = &fetchStream{
body: body,
cancel: cancel,
ctx: streamCtx,
ch: make(chan fetchChunk),
}
registry.CloseAll()
registry.CloseAll()
select {
case <-streamCtx.Done():
default:
t.Fatal("active fetch context was not canceled")
}
if got := body.closeCalls.Load(); got != 1 {
t.Fatalf("expected body to close once, got %d", got)
}
registry.mu.Lock()
closed := registry.closed
remaining := len(registry.streams)
registry.mu.Unlock()
if !closed || remaining != 0 {
t.Fatalf("registry not fully closed: closed=%v remaining=%d", closed, remaining)
}
if _, err := registry.Open("", nil, &fetchRequest{URL: "https://example.test"}); err == nil {
t.Fatal("expected a closed registry to reject new fetches")
}
}
func TestFetchRegistryReadPreservesChunkOrder(t *testing.T) {
registry := newFetchRegistry()
ctx, cancel := context.WithCancel(context.Background())
stream := &fetchStream{
body: io.NopCloser(strings.NewReader("")),
cancel: cancel,
ctx: ctx,
ch: make(chan fetchChunk, 2),
}
stream.ch <- fetchChunk{data: []byte("abc")}
stream.ch <- fetchChunk{data: []byte("def")}
registry.streams["ordered"] = stream
defer registry.CloseAll()
var got strings.Builder
for range 4 {
chunk, done, err := registry.Read("ordered", 2)
if err != nil {
t.Fatal(err)
}
if done {
t.Fatal("stream ended before buffered chunks were read")
}
got.Write(chunk)
}
if got.String() != "abcdef" {
t.Fatalf("fetch chunks were reordered: %q", got.String())
}
}
type trackingReadCloser struct {
closeCalls atomic.Int32
}
func (r *trackingReadCloser) Read([]byte) (int, error) {
return 0, io.EOF
}
func (r *trackingReadCloser) Close() error {
r.closeCalls.Add(1)
return nil
}
+90 -244
View File
@@ -1,10 +1,6 @@
(function () {
const createBlobObjectURL = globalThis.__gopeed_create_blob_object_url;
const revokeObjectURL = globalThis.__gopeed_revoke_object_url;
const fetchOpen = globalThis.__gopeed_fetch_open;
const fetchRead = globalThis.__gopeed_fetch_read;
const fetchClose = globalThis.__gopeed_fetch_close;
const fetchAbort = globalThis.__gopeed_fetch_abort;
if (typeof globalThis.ReadableStream === "undefined") {
class ReadableStreamDefaultController {
@@ -30,7 +26,10 @@
this._stream = stream;
}
read() {
read(view) {
if (view !== undefined) {
return this._stream._readInto(view);
}
return this._stream._read();
}
@@ -59,6 +58,7 @@
this._errored = null;
this._reader = null;
this._pulling = false;
this._disturbed = false;
this.locked = false;
this._controller = new ReadableStreamDefaultController(this);
if (typeof source.start === "function") {
@@ -96,6 +96,7 @@
if (this._errored) {
return Promise.reject(this._errored);
}
this._disturbed = true;
this._markBodyUsed();
if (this._queue.length > 0) {
return Promise.resolve({ done: false, value: this._queue.shift() });
@@ -116,6 +117,26 @@
});
}
async _readInto(view) {
if (!ArrayBuffer.isView(view) || view.byteLength === 0) {
throw new TypeError("BYOB reads require a non-empty ArrayBufferView");
}
const result = await this._read();
if (result.done) {
return { done: true, value: new Uint8Array(view.buffer, view.byteOffset, 0) };
}
if (!(result.value instanceof Uint8Array)) {
throw new TypeError("Byte streams require Uint8Array chunks");
}
const length = Math.min(view.byteLength, result.value.byteLength);
const target = new Uint8Array(view.buffer, view.byteOffset, length);
target.set(result.value.subarray(0, length));
if (length < result.value.byteLength) {
this._queue.unshift(result.value.subarray(length));
}
return { done: false, value: target };
}
_maybePull() {
if (this._closed || this._errored || this._pulling) {
return;
@@ -155,6 +176,7 @@
}
cancel(reason) {
this._disturbed = true;
this._markBodyUsed();
if (this._source && typeof this._source.cancel === "function") {
return Promise.resolve(this._source.cancel(reason)).then(() => {
@@ -185,6 +207,69 @@
writer.releaseLock();
}
}
tee() {
const reader = this.getReader();
let reading = false;
let currentRead = null;
let finished = false;
const waiting = [[], []];
const queues = [[], []];
const cloneChunk = (chunk) => {
if (chunk instanceof ArrayBuffer) return chunk.slice(0);
if (ArrayBuffer.isView(chunk)) {
const buffer = chunk.buffer.slice(0);
if (chunk instanceof DataView) return new DataView(buffer, chunk.byteOffset, chunk.byteLength);
return new chunk.constructor(buffer, chunk.byteOffset, chunk.length);
}
return chunk;
};
const flush = (index) => {
while (waiting[index].length && queues[index].length) {
waiting[index].shift().enqueue(queues[index].shift());
}
if (finished && queues[index].length === 0) {
while (waiting[index].length) waiting[index].shift().close();
}
};
const pump = () => {
if (reading) return currentRead;
if (finished) return Promise.resolve();
reading = true;
currentRead = (async () => {
try {
const result = await reader.read();
if (result.done) {
finished = true;
} else {
queues[0].push(result.value);
queues[1].push(cloneChunk(result.value));
}
} catch (error) {
finished = true;
for (const branches of waiting) {
while (branches.length) branches.shift().error(error);
}
throw error;
} finally {
reading = false;
currentRead = null;
flush(0);
flush(1);
}
})();
return currentRead;
};
const branch = (index) => new ReadableStream({
pull(controller) {
waiting[index].push(controller);
flush(index);
return pump();
},
});
return [branch(0), branch(1)];
}
}
globalThis.ReadableStream = ReadableStream;
@@ -351,167 +436,6 @@
};
}
function toUint8Array(chunk) {
if (chunk == null) {
return new Uint8Array(0);
}
if (chunk instanceof Uint8Array) {
return chunk;
}
if (typeof chunk === "string") {
return new TextEncoder().encode(chunk);
}
if (chunk instanceof ArrayBuffer) {
return new Uint8Array(chunk);
}
if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView && ArrayBuffer.isView(chunk)) {
return new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
}
if (typeof Blob !== "undefined" && chunk instanceof Blob) {
if (chunk._buffer instanceof Uint8Array) {
return chunk._buffer;
}
}
return new Uint8Array(0);
}
function createBodyReadableStream(owner) {
return new ReadableStream({
start(controller) {
Promise.resolve().then(async () => {
owner.bodyUsed = true;
if (owner._noBody) {
controller.close();
return;
}
if (owner._bodyArrayBuffer) {
controller.enqueue(toUint8Array(owner._bodyArrayBuffer));
controller.close();
return;
}
if (owner._bodyBlob) {
const data = await owner._bodyBlob.arrayBuffer();
controller.enqueue(new Uint8Array(data));
controller.close();
return;
}
if (owner._bodyText != null) {
controller.enqueue(toUint8Array(owner._bodyText));
controller.close();
return;
}
if (owner._bodyInit != null) {
controller.enqueue(toUint8Array(owner._bodyInit));
}
controller.close();
}).catch((err) => {
controller.error(err);
});
}
});
}
async function readAllFromStream(stream, asText) {
if (!stream) {
return asText ? "" : new Uint8Array(0);
}
const reader = stream.getReader();
const chunks = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const chunk = toUint8Array(value);
chunks.push(chunk);
total += chunk.byteLength;
}
} finally {
reader.releaseLock();
}
const merged = new Uint8Array(total);
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
offset += chunk.byteLength;
}
if (asText) {
return new TextDecoder().decode(merged);
}
return merged;
}
function attachResponseStreaming(response, stream) {
response.__gopeedBodyStream = stream;
response.__gopeedBodyConsumed = false;
const ensureUnused = () => {
if (response.__gopeedBodyConsumed) {
throw new TypeError("Already read");
}
};
const markBodyUsed = () => {
ensureUnused();
response.__gopeedBodyConsumed = true;
response.bodyUsed = true;
};
if (stream) {
stream.__gopeedMarkBodyUsed = () => {
if (!response.__gopeedBodyConsumed) {
response.__gopeedBodyConsumed = true;
response.bodyUsed = true;
}
};
}
response.text = async function () {
ensureUnused();
markBodyUsed();
return readAllFromStream(stream, true);
};
response.arrayBuffer = async function () {
ensureUnused();
markBodyUsed();
const bytes = await readAllFromStream(stream, false);
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
};
response.blob = async function () {
ensureUnused();
markBodyUsed();
const contentType = this.headers && this.headers.get ? (this.headers.get("content-type") || "") : "";
// Response.blob() is a materializing body consumer. Keeping the live
// response stream behind an empty one-shot Blob makes retry, range and a
// second object-URL reader silently produce an empty file.
const bytes = await readAllFromStream(stream, false);
return new Blob([bytes], { type: contentType });
};
response.json = async function () {
const text = await this.text();
return JSON.parse(text);
};
return response;
}
if (typeof globalThis.Response === "function") {
const responseProto = globalThis.Response.prototype;
const bodyDescriptor = Object.getOwnPropertyDescriptor(responseProto, "body");
if (!bodyDescriptor || typeof bodyDescriptor.get !== "function") {
Object.defineProperty(responseProto, "body", {
configurable: true,
enumerable: true,
get() {
if (this.__gopeedBodyStream) {
return this.__gopeedBodyStream;
}
if (!this.__gopeedBodyStream) {
this.__gopeedBodyStream = createBodyReadableStream(this);
}
return this.__gopeedBodyStream;
}
});
}
}
const blobReaders = new Map();
function getValueTypeName(value) {
@@ -883,82 +807,4 @@
}
};
const originalFetch = typeof globalThis.fetch === "function"
? globalThis.fetch.bind(globalThis)
: null;
if (typeof fetchOpen === "function") {
globalThis.fetch = async function (input, init) {
const request = new Request(input, init);
if (originalFetch && (request.method === "HEAD" || request.redirect === "manual" || request.redirect === "error")) {
return originalFetch(input, init);
}
let body = null;
if (request._bodyFormData) {
body = request._bodyFormData;
} else if (request._bodyArrayBuffer) {
body = request._bodyArrayBuffer;
} else if (request._bodyBlob) {
body = await request._bodyBlob.arrayBuffer();
} else if (request._bodyInit != null && typeof request._bodyInit === "object") {
body = request._bodyInit;
} else if (request._bodyText != null) {
body = request._bodyText;
} else if (request._bodyInit != null) {
body = request._bodyInit;
}
const headers = [];
request.headers.forEach((value, key) => {
headers.push([key, value]);
});
let meta;
try {
meta = await fetchOpen({
url: request.url,
method: request.method,
headers,
body,
redirect: request.redirect,
credentials: request.credentials
});
} catch (error) {
throw error instanceof Error ? error : new TypeError(String(error));
}
const stream = new ReadableStream({
async pull(controller) {
let chunk;
try {
chunk = await fetchRead(meta.id, 64 * 1024);
} catch (error) {
fetchClose(meta.id);
controller.error(error instanceof Error ? error : new TypeError(String(error)));
return;
}
if (chunk == null) {
fetchClose(meta.id);
controller.close();
return;
}
const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
if (bytes.byteLength === 0) {
fetchClose(meta.id);
controller.close();
return;
}
controller.enqueue(bytes);
},
cancel(reason) {
fetchAbort(meta.id, reason == null ? "" : String(reason));
}
});
const response = new Response(null, {
status: meta.status,
statusText: meta.statusText,
headers: meta.headers,
url: meta.url
});
return attachResponseStreaming(response, stream);
};
globalThis.fetch.__gopeedOriginalFetch = originalFetch;
}
})();
Loaded 100 of 874 files, more files were not shown because too many files have changed in this diff. Show more