bili

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"

DefaultUserAgent is a realistic desktop Chrome UA. Bilibili rejects unusual or empty agents with code -412.

View Source
const Referer = "https://www.bilibili.com"

Referer is required on most endpoints to avoid interception.

Variables

This section is empty.

Functions

func CacheStats

func CacheStats(dir string) (files int, bytes int64)

CacheStats returns the number of cached files and total bytes.

func ClearCache

func ClearCache(dir string) (int, error)

Clear removes every cached entry and returns the count removed.

func ConfigDir

func ConfigDir() string

ConfigDir returns the directory for the config file.

func DataDir

func DataDir() string

DataDir returns the directory for the local database default.

func EdgeHelp added in v0.2.0

func EdgeHelp() string

EdgeHelp is a one-line catalogue of presets and edges for flag help and error messages.

Types

type APIError

type APIError struct {
	Code    int
	Message string // upstream message (often Chinese)
	Hint    string // English hint
	Kind    ErrKind
}

APIError is a non-zero bilibili envelope code mapped to a clean message.

func (*APIError) Error

func (e *APIError) Error() string

type Article

type Article struct {
	CVID          int64  `json:"cvid"`
	Title         string `json:"title"`
	AuthorMid     int64  `json:"author_mid"`
	AuthorName    string `json:"author_name"`
	Summary       string `json:"summary"`
	BannerURL     string `json:"banner_url"`
	CategoryName  string `json:"category_name"`
	Words         int    `json:"words"`
	ViewCount     int64  `json:"view_count"`
	LikeCount     int64  `json:"like_count"`
	ReplyCount    int64  `json:"reply_count"`
	FavoriteCount int64  `json:"favorite_count"`
	CoinCount     int64  `json:"coin_count"`
	PublishTime   int64  `json:"publish_time"`
	ContentText   string `json:"content_text,omitempty"`
	FetchedAt     string `json:"fetched_at"`
}

Article is a column post.

type Audio

type Audio struct {
	SID           int64  `json:"sid"`
	Title         string `json:"title"`
	Author        string `json:"author"`
	Uname         string `json:"uname"`
	UID           int64  `json:"uid"`
	CoverURL      string `json:"cover_url"`
	Intro         string `json:"intro"`
	Duration      int    `json:"duration_seconds"`
	PlayCount     int64  `json:"play_count"`
	ReplyCount    int64  `json:"reply_count"`
	FavoriteCount int64  `json:"favorite_count"`
	ShareCount    int64  `json:"share_count"`
	Ctime         int64  `json:"ctime"`
	FetchedAt     string `json:"fetched_at"`
}

Audio is a music track.

type Bangumi

type Bangumi struct {
	SeasonID      int64     `json:"season_id"`
	MediaID       int64     `json:"media_id"`
	SeasonTitle   string    `json:"season_title"`
	Title         string    `json:"title"`
	TypeName      string    `json:"type_name"`
	TotalEp       int       `json:"total_ep"`
	Status        int       `json:"status"`
	CoverURL      string    `json:"cover_url"`
	Evaluate      string    `json:"evaluate"`
	RatingScore   float64   `json:"rating_score"`
	RatingCount   int64     `json:"rating_count"`
	Area          string    `json:"area"`
	Styles        []string  `json:"styles,omitempty"`
	PublishText   string    `json:"publish_text"`
	StatViews     int64     `json:"stat_views"`
	StatFavorites int64     `json:"stat_favorites"`
	StatDanmakus  int64     `json:"stat_danmakus"`
	Episodes      []Episode `json:"episodes,omitempty"`
	FetchedAt     string    `json:"fetched_at"`
}

Bangumi is an anime/film season with its episodes.

type Client

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

Client is a typed, signed, rate-limited bilibili web API client.

func NewClient

func NewClient(cfg Config) *Client

NewClient builds a client from cfg, filling defaults for zero fields.

func (*Client) Article

func (c *Client) Article(ctx context.Context, idOrURL string, withText bool) (*Article, error)

Article fetches a column article. When withText is set the plain-text body is extracted and attached.

func (*Client) Audio

func (c *Client) Audio(ctx context.Context, idOrURL string) (*Audio, error)

Audio fetches a music track's metadata and stat.

func (*Client) Bangumi

func (c *Client) Bangumi(ctx context.Context, idOrURL string) (*Bangumi, error)

Bangumi fetches a season (by ss/ep/md) with all episodes.

func (*Client) BrowseLive

func (c *Client) BrowseLive(ctx context.Context, areaID int, opt ListOptions) iter.Seq2[LiveRoom, error]

BrowseLive streams live rooms in an area.

func (*Client) Comments

func (c *Client) Comments(ctx context.Context, idOrURL string, opt CommentOptions) iter.Seq2[Comment, error]

Comments streams top-level comments for an object.

func (*Client) Danmaku

func (c *Client) Danmaku(ctx context.Context, idOrURL string, part int) iter.Seq2[Danmaku, error]

Danmaku streams every bullet-chat line for a video part (protobuf segments).

func (*Client) DanmakuXML

func (c *Client) DanmakuXML(ctx context.Context, idOrURL string, part int) ([]Danmaku, error)

DanmakuXML fetches the legacy XML danmaku snapshot for a video part.

func (*Client) Dynamic

func (c *Client) Dynamic(ctx context.Context, id string) (*Dynamic, error)

Dynamic fetches one dynamic post.

func (*Client) Dynamics

func (c *Client) Dynamics(ctx context.Context, mid string, opt ListOptions) iter.Seq2[Dynamic, error]

Dynamics streams a user's dynamics feed.

func (*Client) FavoriteItems

func (c *Client) FavoriteItems(ctx context.Context, idOrURL string, opt ListOptions) iter.Seq2[Video, error]

FavoriteItems streams the videos in a favorite folder.

func (*Client) Favorites

func (c *Client) Favorites(ctx context.Context, mid string) ([]Favorite, error)

Favorites lists a user's created favorite folders.

func (*Client) Live

func (c *Client) Live(ctx context.Context, roomOrUID string, byUID bool) (*LiveRoom, error)

Live fetches a live room by room id, or by uid when byUID is set.

func (*Client) Nav

func (c *Client) Nav(ctx context.Context) (*Nav, error)

Nav returns login state and the current WBI keys. The nav endpoint returns code -101 when anonymous but still carries the WBI keys in data, so this decodes data regardless of code.

func (*Client) Pages

func (c *Client) Pages(ctx context.Context, idOrURL string) ([]Page, error)

Pages returns the part list of a video.

func (*Client) Popular

func (c *Client) Popular(ctx context.Context, opt ListOptions) iter.Seq2[Video, error]

Popular streams the "popular" feed.

func (*Client) Ranking

func (c *Client) Ranking(ctx context.Context, tid int) ([]Video, error)

Ranking returns the leaderboard, optionally for one partition (tid/rid).

func (*Client) Raw

func (c *Client) Raw(ctx context.Context, base string, params url.Values, sign bool) ([]byte, error)

Raw fetches base+params and returns the untouched response body (the full envelope). Used by --raw.

func (*Client) Related

func (c *Client) Related(ctx context.Context, idOrURL string) ([]Video, error)

Related returns related videos for a video.

func (*Client) Resolve

func (c *Client) Resolve(ctx context.Context, s string) (*Identity, error)

Resolve classifies and normalizes an arbitrary id or URL. It performs at most one network call (to follow b23.tv short links).

func (*Client) Search

Search streams search results of the requested type (default video).

func (*Client) SetNow

func (c *Client) SetNow(f func() time.Time)

SetNow overrides the clock (testing).

func (*Client) Streams

func (c *Client) Streams(ctx context.Context, idOrURL string, part, qn int) ([]Stream, error)

Streams returns the available playable qualities for a video part. fnval 4048 requests the DASH set (video+audio streams). Anonymous callers get up to 480/720p; SESSDATA raises the ceiling to the account entitlement.

func (*Client) Suggest

func (c *Client) Suggest(ctx context.Context, term string) ([]string, error)

Suggest returns autosuggest terms for a query.

func (*Client) Trending

func (c *Client) Trending(ctx context.Context, limit int) ([]string, error)

Trending returns the current hot search terms.

func (*Client) User

func (c *Client) User(ctx context.Context, mid string) (*User, error)

User fetches a creator's profile and stat.

func (*Client) UserVideos

func (c *Client) UserVideos(ctx context.Context, mid string, opt ListOptions) iter.Seq2[Video, error]

UserVideos streams a creator's uploaded videos.

func (*Client) Video

func (c *Client) Video(ctx context.Context, idOrURL string, opt VideoOptions) (*VideoResult, error)

Video resolves an id/url to a full video record.

It uses the plain /x/web-interface/view endpoint for the core record (the combined .../view/detail endpoint is risk-controlled for anonymous callers and returns HTTP 412), then enriches with tags and, when asked, related videos via their own endpoints.

func (*Client) Walk added in v0.2.0

func (c *Client) Walk(ctx context.Context, seeds []Seed, opts WalkOptions, emit func(*Node) error) error

Walk runs a breadth-first walk from a client, streaming each node to emit.

func (*Client) Weekly

func (c *Client) Weekly(ctx context.Context, number int) ([]Video, error)

Weekly returns one issue of the "每周必看" weekly selection.

type Comment

type Comment struct {
	RpID       int64     `json:"rpid"`
	OID        int64     `json:"oid"`
	Type       int       `json:"type"`
	Parent     int64     `json:"parent"`
	Root       int64     `json:"root"`
	Mid        int64     `json:"mid"`
	Uname      string    `json:"uname"`
	AvatarURL  string    `json:"avatar_url"`
	Level      int       `json:"level"`
	Content    string    `json:"content"`
	LikeCount  int       `json:"like_count"`
	ReplyCount int       `json:"reply_count"`
	Ctime      int64     `json:"ctime"`
	CtimeText  string    `json:"ctime_text"`
	Location   string    `json:"location"`
	IsTop      bool      `json:"is_top"`
	Replies    []Comment `json:"replies,omitempty"`
	FetchedAt  string    `json:"fetched_at"`
}

Comment is one comment, with nested replies when expanded.

type CommentOptions

type CommentOptions struct {
	Order   string // hot | time
	Replies bool
	Limit   int
}

CommentOptions controls the comments command.

type Config

type Config struct {
	Cookie    string
	UserAgent string
	Proxy     string
	Lang      string

	Rate    time.Duration
	Retries int
	Timeout time.Duration

	CacheDir string
	CacheTTL time.Duration
	NoCache  bool

	// DryRun makes every request print its method and URL to DryRunWriter
	// (default os.Stdout) and return an empty success envelope instead of
	// hitting the network.
	DryRun bool
}

Config holds everything the client needs. The zero value is usable after passing through DefaultConfig.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns sane, polite defaults.

type Danmaku

type Danmaku struct {
	DmID       int64  `json:"dmid"`
	ProgressMs int32  `json:"progress_ms"`
	Mode       int32  `json:"mode"`
	Fontsize   int32  `json:"fontsize"`
	Color      uint32 `json:"color"`
	Ctime      int64  `json:"ctime"`
	Pool       int32  `json:"pool"`
	SenderHash string `json:"sender_hash"`
	Content    string `json:"content"`
}

Danmaku is one bullet-chat line.

type Dynamic

type Dynamic struct {
	ID          string   `json:"id"`
	Type        string   `json:"type"`
	AuthorMid   int64    `json:"author_mid"`
	AuthorName  string   `json:"author_name"`
	PubTs       int64    `json:"pub_ts"`
	PubText     string   `json:"pub_text"`
	Text        string   `json:"text"`
	Pics        []string `json:"pics,omitempty"`
	OrigID      string   `json:"orig_id,omitempty"`
	VideoBVID   string   `json:"video_bvid,omitempty"`
	StatLike    int64    `json:"stat_like"`
	StatReply   int64    `json:"stat_reply"`
	StatForward int64    `json:"stat_forward"`
	FetchedAt   string   `json:"fetched_at"`
}

Dynamic is one post in a user's feed.

type Edge added in v0.2.0

type Edge string

Edge is one relationship the walker can follow. Each edge has a fixed source and target node kind (see source/Target).

const (
	// EdgeRelated is the recommendation edge: a video to the videos bilibili
	// suggests alongside it. video -> video.
	EdgeRelated Edge = "related"
	// EdgeUploader is the authorship edge: a video to the creator who posted
	// it. video -> user.
	EdgeUploader Edge = "uploader"
	// EdgeUploads is the catalogue edge: a creator to the videos they have
	// uploaded. user -> video.
	EdgeUploads Edge = "uploads"
)

func (Edge) Target added in v0.2.0

func (e Edge) Target() NodeKind

Target reports the node kind an edge arrives at. The walker uses it to tag a neighbor with the right kind as it is enqueued, so a node's kind is decided by the edge that found it.

type EdgeSet added in v0.2.0

type EdgeSet map[Edge]bool

EdgeSet is a set of edges to follow.

func DefaultEdges added in v0.2.0

func DefaultEdges() EdgeSet

DefaultEdges is the edge set used when --follow is empty: the content preset.

func ParseEdges added in v0.2.0

func ParseEdges(spec string) (EdgeSet, error)

ParseEdges turns a --follow spec into an edge set. The spec is empty (the default), a preset name, or a comma-separated list mixing presets and edge names. Each token resolves as a preset first and an edge name second; an unrecognized token is an error that names the catalogue.

func (EdgeSet) Has added in v0.2.0

func (s EdgeSet) Has(e Edge) bool

Has reports whether the set contains an edge.

func (EdgeSet) List added in v0.2.0

func (s EdgeSet) List() []Edge

List returns the edges in the set in canonical (catalogue) order.

func (EdgeSet) String added in v0.2.0

func (s EdgeSet) String() string

String renders the set as a comma-separated list in canonical order.

type Episode

type Episode struct {
	EpID      int64  `json:"ep_id"`
	AID       int64  `json:"aid"`
	BVID      string `json:"bvid"`
	CID       int64  `json:"cid"`
	Title     string `json:"title"`
	LongTitle string `json:"long_title"`
	CoverURL  string `json:"cover_url"`
	Duration  int    `json:"duration_seconds"`
	PubText   string `json:"pub_text"`
	Badge     string `json:"badge"`
}

Episode is one episode of a bangumi season.

type ErrKind

type ErrKind int

ErrKind groups API errors so the CLI can map them to exit codes.

const (
	ErrGeneric ErrKind = iota
	ErrNotFound
	ErrAccess
	ErrRate
	ErrNetwork
)

func Kind

func Kind(err error) ErrKind

Kind reports the ErrKind of an error if it is an APIError.

type Favorite

type Favorite struct {
	MediaID    int64  `json:"media_id"`
	FID        int64  `json:"fid"`
	Title      string `json:"title"`
	CoverURL   string `json:"cover_url"`
	Intro      string `json:"intro"`
	MediaCount int    `json:"media_count"`
	OwnerMid   int64  `json:"owner_mid"`
	OwnerName  string `json:"owner_name"`
	Ctime      int64  `json:"ctime"`
	FetchedAt  string `json:"fetched_at"`
}

Favorite is a favorite folder.

type IDKind

type IDKind string

IDKind classifies an identifier.

const (
	KindVideo    IDKind = "video"
	KindUser     IDKind = "user"
	KindBangumi  IDKind = "bangumi"
	KindEpisode  IDKind = "episode"
	KindMedia    IDKind = "media"
	KindLive     IDKind = "live"
	KindAudio    IDKind = "audio"
	KindArticle  IDKind = "article"
	KindFavorite IDKind = "favorite"
	KindDynamic  IDKind = "dynamic"
	KindUnknown  IDKind = "unknown"
)

type Identity

type Identity struct {
	Kind     IDKind `json:"kind"`
	BVID     string `json:"bvid,omitempty"`
	AID      int64  `json:"aid,omitempty"`
	Mid      int64  `json:"mid,omitempty"`
	SeasonID int64  `json:"season_id,omitempty"`
	EpID     int64  `json:"ep_id,omitempty"`
	MediaID  int64  `json:"media_id,omitempty"`
	RoomID   int64  `json:"room_id,omitempty"`
	SID      int64  `json:"sid,omitempty"`
	CVID     int64  `json:"cvid,omitempty"`
	FavID    int64  `json:"fav_id,omitempty"`
	Dynamic  string `json:"dynamic,omitempty"`
	Input    string `json:"input"`
}

Identity is the normalized form of any pasted identifier.

type ListOptions

type ListOptions struct {
	Page     int
	PageSize int
	Order    string
	Keyword  string
	Limit    int
}

ListOptions controls paged list endpoints.

type LiveRoom

type LiveRoom struct {
	RoomID         int64  `json:"room_id"`
	ShortID        int64  `json:"short_id"`
	UID            int64  `json:"uid"`
	Uname          string `json:"uname"`
	Title          string `json:"title"`
	AreaName       string `json:"area_name"`
	ParentAreaName string `json:"parent_area_name"`
	LiveStatus     int    `json:"live_status"`
	Online         int64  `json:"online"`
	Attention      int64  `json:"attention"`
	Tags           string `json:"tags"`
	CoverURL       string `json:"cover_url"`
	KeyframeURL    string `json:"keyframe_url"`
	LiveStartText  string `json:"live_start_text"`
	FetchedAt      string `json:"fetched_at"`
}

LiveRoom is a live streaming room.

type Nav struct {
	IsLogin bool   `json:"isLogin"`
	Uname   string `json:"uname"`
	Mid     int64  `json:"mid"`
	WbiImg  struct {
		ImgURL string `json:"img_url"`
		SubURL string `json:"sub_url"`
	} `json:"wbi_img"`
}

Nav is the bootstrap response: login state plus the current WBI keys.

type Node added in v0.2.0

type Node struct {
	Kind   NodeKind `json:"kind"`
	Depth  int      `json:"depth"`
	Via    Edge     `json:"via,omitempty"`
	Parent string   `json:"parent,omitempty"`
	Video  *Video   `json:"video,omitempty"`
	User   *User    `json:"user,omitempty"`
}

Node is one object reached by a walk, tagged with how it was reached. Exactly one of Video or User is set, per Kind.

func (*Node) Endpoint added in v0.2.0

func (n *Node) Endpoint() string

Endpoint returns the node's identity: a BVID for a video, a mid for a user.

type NodeKind added in v0.2.0

type NodeKind string

NodeKind is the kind of object a walk node represents. The graph has two kinds: videos and the creators who upload them.

const (
	NodeVideo NodeKind = "video"
	NodeUser  NodeKind = "user"
)

type Page

type Page struct {
	CID        int64  `json:"cid"`
	Page       int    `json:"page"`
	PartTitle  string `json:"part_title"`
	Duration   int    `json:"duration_seconds"`
	Width      int    `json:"dimension_width"`
	Height     int    `json:"dimension_height"`
	FirstFrame string `json:"first_frame_url"`
}

Page is one part of a multi-part video.

type SearchOptions

type SearchOptions struct {
	Type     string
	Order    string
	Duration int
	Tid      int
	Page     int
	PageSize int
	Limit    int
}

SearchOptions controls search.

type SearchResult

type SearchResult struct {
	ResultType string    `json:"result_type"`
	Video      *Video    `json:"video,omitempty"`
	User       *User     `json:"user,omitempty"`
	Bangumi    *Bangumi  `json:"bangumi,omitempty"`
	LiveRoom   *LiveRoom `json:"live_room,omitempty"`
	Article    *Article  `json:"article,omitempty"`
}

SearchResult is a discriminated search hit.

func (SearchResult) Payload

func (r SearchResult) Payload() any

Payload returns the concrete record the result wraps (a *Video, *User, etc.), so output formats can render real columns instead of the wrapper. It falls back to the wrapper itself if nothing is set.

type Seed added in v0.2.0

type Seed struct {
	Raw string
}

Seed is a starting point for a walk: any id or URL the client can resolve to a video or a user.

type Stream

type Stream struct {
	Quality     int      `json:"quality"`
	QualityText string   `json:"quality_text"`
	Codecs      string   `json:"codecs"`
	MIME        string   `json:"mime"`
	Bandwidth   int64    `json:"bandwidth"`
	Width       int      `json:"width"`
	Height      int      `json:"height"`
	FrameRate   string   `json:"frame_rate"`
	URL         string   `json:"url"`
	BackupURLs  []string `json:"backup_urls,omitempty"`
	DurationMs  int64    `json:"duration_ms"`
}

Stream is one playable quality of a video part.

type Suggestion

type Suggestion struct {
	Term string `json:"term"`
}

Suggestion is one autosuggest term.

type User

type User struct {
	Mid            int64  `json:"mid"`
	Name           string `json:"name"`
	Sex            string `json:"sex"`
	FaceURL        string `json:"face_url"`
	Sign           string `json:"sign"`
	Level          int    `json:"level"`
	TopPhotoURL    string `json:"top_photo_url"`
	OfficialRole   int    `json:"official_role"`
	OfficialTitle  string `json:"official_title"`
	VipType        int    `json:"vip_type"`
	VipStatus      int    `json:"vip_status"`
	Birthday       string `json:"birthday"`
	School         string `json:"school"`
	FollowerCount  int64  `json:"follower_count"`
	FollowingCount int64  `json:"following_count"`
	VideoCount     int64  `json:"video_count"`
	TotalView      int64  `json:"total_view"`
	TotalLike      int64  `json:"total_like"`
	FetchedAt      string `json:"fetched_at"`
}

User is a creator's profile and stat.

type Video

type Video struct {
	BVID          string   `json:"bvid"`
	AID           int64    `json:"aid"`
	CID           int64    `json:"cid"`
	Title         string   `json:"title"`
	Description   string   `json:"description"`
	OwnerMid      int64    `json:"owner_mid"`
	OwnerName     string   `json:"owner_name"`
	TypeID        int      `json:"type_id"`
	TypeName      string   `json:"type_name"`
	Duration      int      `json:"duration_seconds"`
	ViewCount     int64    `json:"view_count"`
	DanmakuCount  int64    `json:"danmaku_count"`
	ReplyCount    int64    `json:"reply_count"`
	FavoriteCount int64    `json:"favorite_count"`
	CoinCount     int64    `json:"coin_count"`
	ShareCount    int64    `json:"share_count"`
	LikeCount     int64    `json:"like_count"`
	NowRank       int      `json:"now_rank"`
	HisRank       int      `json:"his_rank"`
	Pubdate       int64    `json:"pubdate"`
	PubdateText   string   `json:"pubdate_text"`
	Ctime         int64    `json:"ctime"`
	Parts         int      `json:"parts"`
	Width         int      `json:"dimension_width"`
	Height        int      `json:"dimension_height"`
	Copyright     int      `json:"copyright"`
	CoverURL      string   `json:"cover_url"`
	ShortLink     string   `json:"short_link"`
	URL           string   `json:"url"`
	Tags          []string `json:"tags,omitempty"`
	Honor         []string `json:"honor,omitempty"`
	Pages         []Page   `json:"pages,omitempty"`
	State         int      `json:"state"`
	FetchedAt     string   `json:"fetched_at"`
}

Video is the central record.

type VideoOptions

type VideoOptions struct {
	Detail  bool
	Related bool
	Tags    bool
}

VideoOptions controls the video command.

type VideoResult

type VideoResult struct {
	Video   Video
	Related []Video
}

VideoResult bundles a video with optional related videos.

type WalkOptions added in v0.2.0

type WalkOptions struct {
	Depth  int
	Max    int
	Fanout int
	Edges  EdgeSet
	Note   func(string)
}

WalkOptions bounds a walk. Depth is the number of hops from each seed; Max caps the total nodes streamed; Fanout caps neighbors followed per edge. Note, when set, receives a one-line message for each non-fatal failure deeper in the walk.

type Walker added in v0.2.0

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

Walker performs a breadth-first walk of the graph over a grapher.

func NewWalker added in v0.2.0

func NewWalker(g grapher) *Walker

NewWalker returns a walker backed by g.

func (*Walker) Walk added in v0.2.0

func (w *Walker) Walk(ctx context.Context, seeds []Seed, opts WalkOptions, emit func(*Node) error) error

Walk runs a breadth-first walk from the seeds, streaming each node to emit as it is reached. A seed that cannot be fetched is fatal; a failure deeper in the walk is reported through opts.Note and the walk continues.

Jump to

Keyboard shortcuts

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