songdl

package
v0.4.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

单曲下载核心:从拿到的 SongURL + Song 完成落盘,返回结构化 Outcome。 命令层(song runDownload / playlist worker)负责拿 URL/Song,调 DownloadOne, 然后按各自需要渲染(单曲渲染结果 / 批量汇总)。

Package songdl 是单曲下载的核心逻辑(文件名构造 / 元数据写入 / 下载 / 冲突处理), 供 song 与 playlist 命令共享。它是叶子包:不依赖任何 cli feature 包, 只依赖 kit(渲染/进度)、endpoint 协议类型、外部音频库。

设计动机(issue #23 / PRD-0013):song download 与 playlist download 都要消费 同一套「拿直链 → 文件名 → mkdir → 冲突 → 流式下载 → 元数据」链路。把它下沉到 独立包避免 feature 包互相导出(参考 cobra enterprise guide + DoltHub 循环依赖策略: 共享逻辑放叶子包,feature 包保持薄)。命令层只做 flag 编排 + 结果渲染。

元数据写入:mp3 用 bogem/id3v2,flac 用 go-flac 三件套。 从 internal/cli/song 包迁入(原 metadata.go),逻辑不变,仅包名 + 导出。

Index

Constants

View Source
const DefaultFilenameTemplate = "{artist} - {title}"

DefaultFilenameTemplate 默认文件名模板:{首艺人} - {歌名}。 SongFilename(无 --filename 时)用此模板。冲突回退在此基础追加 ({id})。

Variables

This section is empty.

Functions

func DownloadToFile

func DownloadToFile(ctx context.Context, k *kit.Kit, url string, total int64, path, label string) (int64, error)

DownloadToFile 流式下载 URL 到 path,带进度条(TTY 时渲染 stderr)。 返回写入字节数(本次下载量;不含续传的已存在部分)。

.part 续传(PRD-0013 issue #24):

  • 下载中写到 path+".part";成功后 rename 到 path(原子完成)
  • 重跑时若 .part 已存在:发 HTTP Range 头从当前字节续传(206 Partial Content)
  • 服务端忽略 Range(返 200):truncate .part 从头重下
  • 网络中断:保留 .part,返回带续传提示的错误(调用方 Warnf)

func FallbackFilename

func FallbackFilename(s *mmpb.Song, ext string) string

FallbackFilename 构造冲突回退文件名:默认模板 + ({id}) 后缀。 用稳定的 id 做后缀,可重跑幂等(不自动加 (2)/(3),避免破坏断点续传语义)。 导出供批量下载做 size 预检时遍历候选名(默认名 + 回退名)。

func FetchCover

func FetchCover(picURL string, client *http.Client) []byte

FetchCover HTTP GET 取封面字节,失败返回 nil(不阻塞主流程)。 封面 CDN 通常无 Referer 检查,用普通请求即可。client 为 nil 时用 DefaultClient; 显式代理时调用方传 k.HTTPClient()——封面也是直连 HTTP 路径,须与音频下载 同一代理决策(PRD-0018 双路径不变式)。

func FormatFallbackFilename

func FormatFallbackFilename(tmpl string, s *mmpb.Song, ext string) string

FormatFallbackFilename 给定自定义模板,构造冲突回退文件名:模板 + ({id})。 用于 --filename 自定义模板时的冲突回退(同 FallbackFilename 的自定义版)。

func FormatFilename

func FormatFilename(tmpl string, s *mmpb.Song, ext string) string

FormatFilename 应用 {artist}/{title}/{album}/{id} 占位符模板,过滤路径不安全字符, 附加 .{ext} 扩展名。未知占位符(如 {foo})字面保留(PRD:非法占位符 → 字面字符串)。

用 strings.ReplaceAll 而非 text/template:① 仅 4 个固定占位符,无需通用引擎; ② 避免 template 注入(用户输入 {{printf}} 会被 text/template 执行); ③ 「未知保留字面」是 ReplaceAll 的自然行为(ReplaceAll 找不到的串原样留下)。

注意:本函数不处理空值兜底。默认模板的「艺人/歌名空 → id 替代」是 SongFilename 的专属行为(见 applyDefaultEmptyFallback),自定义模板按 PRD 保留空串字面。

func FormatSizeLabel

func FormatSizeLabel(bytes int64) string

FormatSizeLabel 字节 → 人类可读大小(PRD 显示 "3.4 MB")。

func ResolveConflictPath

func ResolveConflictPath(s *mmpb.Song, ext, dir, filenameTmpl string, force bool) (path string, skipped bool)

ResolveConflictPath 决定单曲落盘的最终路径,实现 PRD-0013 文件名冲突处理:

  1. 默认/自定义名;不存在 → 用它(返回 skipped=false)
  2. 存在但 force=true → 用它覆盖(返回 skipped=false)
  3. 存在且非 force → 尝试名 + ({id}) 回退;不存在 → 用它
  4. 两个都存在且非 force → 跳过(返回 skipped=true,path 指向首名供提示)

filenameTmpl 空串时用默认模板(SongFilename/FallbackFilename);非空时按自定义模板。 不自动加 (2)/(3):不可重跑,破坏「重跑即续传」的幂等语义。

func SongFilename

func SongFilename(s *mmpb.Song, ext string) string

SongFilename 构造单曲下载的默认文件名:{首艺人} - {歌名}.{ext}。 多艺人取首个;过滤路径不安全字符;艺人/歌名空时用 id 兜底。 不处理冲突回退(那是命令层策略,见 ResolveConflictPath)。

func WriteMetadata

func WriteMetadata(path string, info Metadata) error

WriteMetadata 把 Metadata 写入 path 指向的音频文件。 按扩展名分派:mp3 用 bogem/id3v2,flac 用 go-flac 三件套。 调用方必须保证文件已落盘(本函数只读写元数据,不动音频流)。 写入失败返回 error,但调用方应按 PRD-0013 约定当作非阻塞警告处理。

func WriteSongMetadata

func WriteSongMetadata(path string, song *mmpb.Song, client *http.Client) error

WriteSongMetadata 构造 Metadata 并写入。失败返回 error(调用方按非阻塞 Warnf 处理)。

Types

type Deps

type Deps struct {
	// contains filtered or unexported fields
}

Deps 是下载过程的可注入依赖(网络 + 文件 IO + 元数据)。

抽成结构是为了错误路径单测:注入 mock fetchURL/download/writeMeta, 覆盖 VIP 无音源、下载失败、元数据失败等确定性场景;真实网络行为留集成测试。

用法:

  • 单曲命令(song runDownload):fetchURL + fetchDetail 在命令层先调, 再把结果传给 DownloadOne;download/writeMeta 由 Deps 提供。
  • 批量命令(playlist worker):同上,但 fetchURL 在 worker 内 per-song 调。

func NewDeps

func NewDeps(k *kit.Kit, opts ...DepsOption) Deps

NewDeps 构造生产 Deps:真实 HTTP 下载 + 真实元数据写入。 downloadURL 是单曲/批量共用的流式下载器(签名见 DownloadToFile)。 opts 用于测试覆盖个别字段(WithDownload/WithWriteMeta),保留其余默认。

type DepsOption

type DepsOption func(*Deps)

DepsOption 用于测试注入个别字段(保留默认其余)。

func WithDownload

func WithDownload(fn func(ctx context.Context, url string, total int64, path, label string) (int64, error)) DepsOption

WithDownload 覆盖 download 字段(测试用)。

func WithWriteMeta

func WithWriteMeta(fn func(path string, song *mmpb.Song) error) DepsOption

WithWriteMeta 覆盖 writeMeta 字段(测试用)。

type Metadata

type Metadata struct {
	Title  string
	Artist string
	Album  string
	Cover  []byte // 可为 nil
}

Metadata 是要写入音频文件的元数据。 Cover 为 nil 表示无封面(其他字段照写)。

type Options

type Options struct {
	Out          string
	Force        bool
	FilenameTmpl string
	SkipMeta     bool
}

Options 是 DownloadOne 的落盘选项(位置参数过多时改 struct,便于扩展且调用点可读)。

字段语义:

  • Out:下载目录(自动 mkdir -p)
  • Force:true 覆盖已存在文件;false 走 ResolveConflictPath 冲突策略
  • FilenameTmpl:自定义文件名模板(空 = 默认 {artist} - {title});见 FormatFilename
  • SkipMeta:true 跳过元数据写入(--no-metadata,纯流式落盘更快)

type Outcome

type Outcome struct {
	Status Status
	// SongID 歌曲 ID(汇总失败列表用)。
	SongID int64
	// Reason skipped/failed 时的原因(success 时为空)。
	Reason string
	// Network 标记 failed 是否源于网络/HTTP 错误(而非 VIP 无音源、size 不符等
	// 逻辑跳过)。批量风控只对 Network=true 计连续失败,避免 VIP 歌曲误触发限流。
	Network bool

	// 以下字段仅 Status == StatusSuccess 时有意义。
	Path        string // 绝对路径
	Filename    string // 文件名(不含目录)
	Dir         string // 目录(绝对)
	Bytes       int64
	Format      string
	Bitrate     int64
	MetaWritten bool
}

Outcome 单曲下载结果。命令层收集后做汇总渲染。

func DownloadOne

func DownloadOne(ctx context.Context, song *mmpb.Song, songURL *mmpb.SongURL, opts Options, deps Deps) Outcome

DownloadOne 完成单曲落盘的核心链路,返回结构化 Outcome(不渲染)。

调用方负责:① 拿到 songURL(含 Url/Format/Size/Bitrate);② 拿到 song(歌名/艺人/封面)。 空音源(songURL==nil 或 Url=="")→ 调用方应在调本函数前拦截(单曲/批量各自的处理不同, 不在此强加)。本函数只处理「拿到合法 songURL/song 之后」的落盘流程。

流程:ResolveConflictPath → mkdir → download → writeMeta(失败非阻塞,SkipMeta 时跳过)。 Outcome.Status 三态:Success / Skipped(冲突且非 force)/ Failed(下载或 IO 错误)。

type Status

type Status int

Status 单曲下载结果状态。

const (
	StatusSuccess Status = iota
	StatusSkipped
	StatusFailed
)

func (Status) String

func (s Status) String() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL