tmdb

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 22 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

Package tmdb 是 TMDB v3 接口的客户端:搜索电影与剧集、按 IMDb 编号查找、取详情。 API Key 用用户自己填的(v3 的 API Key 或 v4 的读取令牌都可以),没填时用构建时内置的(BuiltinKey); 默认中文,中文简介为空时取英文的。 走设置里的代理,没有时用环境变量里的代理;响应缓存在 SQLite 里;自己限速。错误里不带请求地址(API Key 在地址里)。

Index

Constants

View Source
const (
	EpisodeGroupAirDate    = 1
	EpisodeGroupAbsolute   = 2
	EpisodeGroupDVD        = 3
	EpisodeGroupDigital    = 4
	EpisodeGroupStoryArc   = 5
	EpisodeGroupProduction = 6
	EpisodeGroupTV         = 7
)

剧集组的类型(type)。

View Source
const (
	// ListTrending 是本周趋势
	ListTrending = "trending"
	// ListPopular 是热门
	ListPopular = "popular"
	// ListTopRated 是高分
	ListTopRated = "top_rated"
	// ListNowPlaying、ListUpcoming 是电影的正在上映、即将上映
	ListNowPlaying = "now_playing"
	ListUpcoming   = "upcoming"
	// ListOnTheAir、ListAiringToday 是剧集的正在播出(最近一周有新的一集)、今天播出
	ListOnTheAir    = "on_the_air"
	ListAiringToday = "airing_today"
	// ListTTL 是列表的缓存时间
	ListTTL = 6 * time.Hour
)

探索页用的列表。

View Source
const (
	SizePoster   = "w780"
	SizeBackdrop = "w1280"
	SizeStill    = "w300"
)

图片的尺寸(TMDB 图片地址里的一段)。

View Source
const (
	DefaultBaseURL = "https://api.themoviedb.org/3"
	ImageBaseURL   = "https://image.tmdb.org/t/p/"
)

DefaultBaseURL 是 TMDB v3 接口地址;ImageBaseURL 是图片地址。

View Source
const (
	KindMovie = "movie"
	KindTV    = "tv"
)

Kind 是条目类型。

View Source
const (
	SearchTTL  = 24 * time.Hour
	DetailsTTL = 7 * 24 * time.Hour
)

缓存时长:搜索结果一天,查找与详情一周。

View Source
const DefaultMaxCacheRows = 5000

DefaultMaxCacheRows 是缓存条数的默认上限。

View Source
const DefaultRatePerSecond = 8

DefaultRatePerSecond 是默认限速(每秒请求数)。

View Source
const EpisodeGroupTTL = 24 * time.Hour

EpisodeGroupTTL 是剧集组的缓存时间。

View Source
const FindTVDBTTL = 30 * 24 * time.Hour

FindTVDBTTL 是按 TVDB 编号找到的剧集的缓存时间:一部剧的 TVDB 编号与 TMDB 编号对应好以后不会变。

View Source
const GenreAnimation = 16

GenreAnimation 是 TMDB 的「动画」类型编号(电影与剧集相同)。

View Source
const PersonTTL = 30 * 24 * time.Hour

PersonTTL 是演员译名的缓存时间。

View Source
const SeasonsTTL = 24 * time.Hour

SeasonsTTL 是剧集各季列表的缓存时间:新的一季宣布了要能看到,比详情的一周短。

Variables

View Source
var (
	ErrNoKey        = errors.New("没有填写 TMDB API Key")
	ErrUnauthorized = errors.New("TMDB API Key 无效")
	ErrNotFound     = errors.New("TMDB 上没有这个条目")
	ErrRateLimited  = errors.New("TMDB 请求太频繁,稍后再试")
	// ErrUnavailable 表示连不上 TMDB,或 TMDB 回了其它错误(网络、代理、5xx)。
	ErrUnavailable = errors.New("TMDB 暂时不能访问")
)
View Source
var BuiltinKey = ""

BuiltinKey 是构建时用 -ldflags 注入的 TMDB API Key(发布流程从仓库 secret PT_TOOLS_TMDB_KEY 来,源码里没有): 用户没填自己的 Key 时用它,像 Jellyfin、tinyMediaManager 那样装好就能识别。为空(从源码编译)时要自己填。

View Source
var (

	// ErrNotImage 表示图片地址回的不是图片。
	ErrNotImage = errors.New("TMDB 图片地址返回的不是图片")
)

Functions

func Builtin

func Builtin() string

Builtin 是能用的内置 Key:去掉首尾空白;格式不对(不到 16 个字符、超过 512 个、中间有空白)时当作没有。

func HasList

func HasList(kind, list string) bool

HasList 报告电影或剧集有没有这个列表。

func IsOfficialAPIBase

func IsOfficialAPIBase(base string) bool

IsOfficialAPIBase 报告接口地址是不是 TMDB 官方的(https 加官方域名,不带端口)。内置 Key 是所有用户共用的, 不发给镜像与自建的中转,免得被人收集了去滥用、连累大家。

func NewHTTPClient

func NewHTTPClient(proxyURL string) (*http.Client, error)

NewHTTPClient 建一个访问 TMDB 的 http.Client:走 proxyURL,为空时用环境变量里的代理。

func NewLimiter

func NewLimiter(perSec float64) *rate.Limiter

NewLimiter 建一个限速器(perSec 为 0 时用 DefaultRatePerSecond)。

func NormalizeAPIBaseURL

func NormalizeAPIBaseURL(raw string) (string, error)

NormalizeAPIBaseURL 规整用户填的 TMDB 接口地址:只写域名时补上 https:// 与 /3,去掉末尾的 /。 空串表示用官方地址(DefaultBaseURL)。可以是镜像或自建的中转,带不带子路径都行。

func NormalizeImageBaseURL

func NormalizeImageBaseURL(raw string) (string, error)

NormalizeImageBaseURL 规整用户填的 TMDB 图片地址(到尺寸之前为止,例如 https://image.tmdb.org/t/p/): 只写域名时补上 https:// 与 /t/p/,末尾总是带 /。空串表示用官方地址(ImageBaseURL)。

func ParseProxyURL

func ParseProxyURL(s string) (*url.URL, error)

ParseProxyURL 校验代理地址:http、https、socks5 或 socks5h,不能带路径以外的多余部分。

func PosterURL

func PosterURL(path, size string) string

PosterURL 是海报图片地址(size 为空时用 w342)。

func ValidEpisodeGroupID

func ValidEpisodeGroupID(id string) bool

ValidEpisodeGroupID 报告 id 是不是剧集组编号的写法。

func ValidKey

func ValidKey(key string) bool

ValidKey 报告 key 像不像 TMDB 的 Key(v3 的 API Key 或 v4 的读取令牌):16 到 512 个字符,中间没有空白。

Types

type Cache

type Cache interface {
	Get(key string) ([]byte, bool)
	Set(key string, value []byte, ttl time.Duration)
}

Cache 是响应缓存。

type CastMember

type CastMember struct {
	ID          int    `json:"id,omitempty"`
	Name        string `json:"name"`
	Character   string `json:"character,omitempty"`
	Order       int    `json:"order"`
	ProfilePath string `json:"profile_path,omitempty"`
}

CastMember 是一位演员。ID 是 TMDB 上这个人的编号(取中文译名用),ProfilePath 是头像图片的路径(/xxx.jpg),没有时为空。

type Client

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

Client 是 TMDB 客户端。

func New

func New(o Options) (*Client, error)

New 建一个客户端。没有 API Key 时返回 ErrNoKey。

func (*Client) Details

func (c *Client) Details(ctx context.Context, kind string, id int) (*Result, error)

Details 取一个条目的详情(带 IMDb 编号)。中文简介为空时取英文的。

func (*Client) Discover

func (c *Client) Discover(ctx context.Context, kind string, f DiscoverFilter, page int) (*ListPage, error)

Discover 按出品国家与类型发现电影或剧集(按热度排,不含成人内容)。page 从 1 开始,最多到第 20 页。

func (*Client) EpisodeGroup

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

EpisodeGroup 取一个剧集组的详情(缓存 24 小时):组按 order 排、组里的集按 order 排(order 一样时按原来的先后)。 编号不是剧集组编号的写法时是 ErrNotFound(不发请求)。

func (*Client) EpisodeGroups

func (c *Client) EpisodeGroups(ctx context.Context, tvID int) ([]EpisodeGroupSummary, error)

EpisodeGroups 列出一部剧的剧集组(缓存 24 小时);没有时是空的。

func (*Client) Extras

func (c *Client) Extras(ctx context.Context, kind string, id int) (*Extras, error)

Extras 取一个条目的 Extras(见 Extras 类型)。

func (*Client) Find

func (c *Client) Find(ctx context.Context, imdb string) ([]Result, error)

Find 按 IMDb 编号查找(链接也可以),电影在前、剧集在后。

func (*Client) FindByTVDB

func (c *Client) FindByTVDB(ctx context.Context, tvdbID int) (*Result, error)

FindByTVDB 按 TVDB 编号找 TMDB 上的剧集(GET /find/{tvdb}?external_source=tvdb_id,缓存 30 天)。Servarr 兼容入口用: Seerr 请求剧集时只给 TVDB 编号。找不到或编号不对时是 ErrNotFound。

func (*Client) Image

func (c *Client) Image(ctx context.Context, path, size string) ([]byte, error)

Image 下载一张 TMDB 图片(path 是条目里的 poster_path 一类,size 如 w780)。 只接受 image/* 响应,最多 10 MiB;图片走图片服务器,不占接口的限速额度。

func (*Client) Images

func (c *Client) Images(ctx context.Context, kind string, id int) (*Images, error)

Images 取条目的图片列表(刮削按语言挑海报、找 Logo 时用),缓存一周。

func (*Client) Language

func (c *Client) Language() string

Language 是客户端取详情用的语言(例如 zh-CN)。

func (*Client) List

func (c *Client) List(ctx context.Context, kind, list string, page int) (*ListPage, error)

List 取电影或剧集的一个列表(见 HasList)。page 从 1 开始,最多到第 20 页。今天播出按服务器的时区算 (TZ 写了时区名时;没写时是 TMDB 默认的时区)。

func (*Client) PersonChineseName

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

PersonChineseName 是演员在 TMDB 上的中文译名(/person/{id}/translations,缓存 30 天):按 zh-CN、zh-SG、zh-TW、zh-HK 的顺序取, 都没有时回空串。TMDB 上没有这个人时也回空串。

func (*Client) PosterURL

func (c *Client) PosterURL(path, size string) string

PosterURL 是这个客户端的图片地址下的海报地址(size 为空时用 w342):用户换了图片地址时,通知里的海报也用它。

func (*Client) ProfileURL

func (c *Client) ProfileURL(path string) string

ProfileURL 是演员头像的地址(w185):用这个客户端的图片地址。路径格式不对时为空。

func (*Client) Recommendations

func (c *Client) Recommendations(ctx context.Context, kind string, id int) ([]Result, error)

Recommendations 取 TMDB 按这个条目推荐的电影或剧集(第 1 页,同类),缓存 ListTTL。

func (*Client) Search

func (c *Client) Search(ctx context.Context, kind, query string, year int) ([]Result, error)

Search 按名字搜索电影或剧集。电影带上年份过滤;剧集不带(首播年份过滤会漏掉后面几季)。

func (*Client) Season

func (c *Client) Season(ctx context.Context, tvID, number int) (*Season, error)

Season 取剧集一季的详情:各集的标题、简介、播出日期与截图。

func (*Client) Seasons

func (c *Client) Seasons(ctx context.Context, tvID int) ([]SeasonSummary, error)

Seasons 取剧集的各季(按 TMDB 给的顺序),缓存 SeasonsTTL。格式不对的海报路径去掉。

func (*Client) ServerTime

func (c *Client) ServerTime(ctx context.Context) (time.Time, error)

ServerTime 同 Validate,另返回 TMDB 那边现在的时间(响应头的 Date 加上 Age,CDN 缓存的响应 Date 是生成时的): 系统体检拿它比本机的时钟。响应里没有 Date 时返回零值。

func (*Client) Titles

func (c *Client) Titles(ctx context.Context, kind string, id int) ([]string, error)

Titles 是条目的英文名、别名(罗马音、各地译名)与各语言的译名:种子名常用这些名字,中文搜索结果里只有中文名与原名。 英文名与别名有时都带着副标题(龙族的英文名是「Dragon Raja -The Blazing Dawn-」),种子名用的「Dragon Raja」 只在法语、德语等的译名里,所以译名也要比。用 en-US 取详情并带上 alternative_titles 与 translations,一次请求; 去掉重复与空的。

func (*Client) Validate

func (c *Client) Validate(ctx context.Context) error

Validate 用 /configuration 检查 API Key 是否可用。

type Collection

type Collection struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

Collection 是电影所属的系列。

type DBCache

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

DBCache 把缓存放在 SQLite 的 media_cache 表里。读写失败时当作没有缓存,不影响请求。 条数有上限(MaxRows):超出时按到期时间删掉最早的。

func NewDBCache

func NewDBCache(db *gorm.DB) *DBCache

NewDBCache 建一个数据库缓存。

func (*DBCache) Get

func (c *DBCache) Get(key string) ([]byte, bool)

Get 读一条没过期的缓存。

func (*DBCache) Purge

func (c *DBCache) Purge() error

Purge 删除过期的缓存;条数仍超过上限时,按到期时间删掉最早的那些。

func (*DBCache) Set

func (c *DBCache) Set(key string, value []byte, ttl time.Duration)

Set 写一条缓存;隔一段时间顺便清掉过期的。

type DiscoverFilter

type DiscoverFilter struct {
	Country string
	Genres  string
}

DiscoverFilter 是按条件发现的筛选:Country 是出品国家或地区(ISO 3166-1 的两个大写字母,例如 CN),Genres 是 TMDB 的类型编号(几个用 | 隔开时是其中任意一个,例如综艺的 10764|10767)。空的不限。

type Episode

type Episode struct {
	ID          int      `json:"id,omitempty"`
	Number      int      `json:"episode_number"`
	Name        string   `json:"name,omitempty"`
	Overview    string   `json:"overview,omitempty"`
	AirDate     string   `json:"air_date,omitempty"`
	StillPath   string   `json:"still_path,omitempty"`
	Runtime     int      `json:"runtime,omitempty"`
	VoteAverage float64  `json:"vote_average,omitempty"`
	VoteCount   int      `json:"vote_count,omitempty"`
	Directors   []string `json:"directors,omitempty"`
	Writers     []string `json:"writers,omitempty"`
}

Episode 是剧集一季里的一集。Directors 与 Writers 是这一集的导演与编剧。

type EpisodeGroup

type EpisodeGroup struct {
	EpisodeGroupSummary
	Groups []EpisodeGroupPart `json:"groups"`
}

EpisodeGroup 是剧集组的详情:Groups 按 Order 排好。

type EpisodeGroupEpisode

type EpisodeGroupEpisode struct {
	Season  int    `json:"season_number"`
	Episode int    `json:"episode_number"`
	Order   int    `json:"order"`
	Name    string `json:"name,omitempty"`
	AirDate string `json:"air_date,omitempty"`
}

EpisodeGroupEpisode 是剧集组里的一集:Season、Episode 是它在默认排法里的季与集。

type EpisodeGroupPart

type EpisodeGroupPart struct {
	ID       string                `json:"id"`
	Name     string                `json:"name"`
	Order    int                   `json:"order"`
	Episodes []EpisodeGroupEpisode `json:"episodes"`
}

EpisodeGroupPart 是剧集组里的一组(相当于一季):Episodes 按 Order 排好。

type EpisodeGroupSummary

type EpisodeGroupSummary struct {
	ID           string `json:"id"`
	Name         string `json:"name"`
	Type         int    `json:"type"`
	Description  string `json:"description,omitempty"`
	GroupCount   int    `json:"group_count"`
	EpisodeCount int    `json:"episode_count"`
	Network      string `json:"network,omitempty"`
}

EpisodeGroupSummary 是一部剧的一个剧集组(列表里的一项)。Network 是这种排法所属的电视台或平台(没有时为空)。

type Extras

type Extras struct {
	Tagline string `json:"tagline,omitempty"`
	// Status 是 TMDB 的状态原文(剧集:Returning Series、Ended、Canceled……)
	Status    string `json:"status,omitempty"`
	VoteCount int    `json:"vote_count,omitempty"`
	IMDbID    string `json:"imdb_id,omitempty"`
	TVDBID    int    `json:"tvdb_id,omitempty"`
	// Studios 是电影的出品公司、剧集的电视网
	Studios []string `json:"studios,omitempty"`
	// Certifications 是各国家或地区的分级(ISO 3166-1 → 分级,例如 US → PG-13)
	Certifications map[string]string `json:"certifications,omitempty"`
	Collection     *Collection       `json:"collection,omitempty"`
	Directors      []string          `json:"directors,omitempty"`
	Writers        []string          `json:"writers,omitempty"`
	Cast           []CastMember      `json:"cast,omitempty"`
}

Extras 是刮削写 NFO 用的、详情里没有的那些:演职员、分级、出品公司(剧集是电视网)、所属系列、剧集的状态、 宣传语、评分人数与 TVDB 编号。用一次带 append_to_response 的详情请求取到,缓存一周。

func (*Extras) TVDBIDString

func (x *Extras) TVDBIDString() string

TVDBIDString 是 TVDB 编号的字符串(没有时为空)。

type Image

type Image struct {
	Path  string  `json:"path"`
	Lang  string  `json:"lang,omitempty"`
	Vote  float64 `json:"vote,omitempty"`
	Votes int     `json:"votes,omitempty"`
}

Image 是条目的一张图片。Lang 是图上文字的语言(ISO 639-1),空串是没有文字。

type ImageClient

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

ImageClient 只取图片:图片服务器不用 API Key,没填 Key 时 App 的海报也能经 pt-tools 取。

func NewImageClient

func NewImageClient(imageBaseURL string, hc *http.Client) *ImageClient

NewImageClient 建图片客户端:imageBaseURL 为空时用官方地址,hc 是发请求用的客户端(带代理)。

func (*ImageClient) Image

func (c *ImageClient) Image(ctx context.Context, path, size string) ([]byte, error)

Image 同 Client.Image。

type Images

type Images struct {
	Posters   []Image `json:"posters,omitempty"`
	Backdrops []Image `json:"backdrops,omitempty"`
	Logos     []Image `json:"logos,omitempty"`
}

Images 是条目的海报、背景与 Logo,每类都按评分从高到低排好。 只取中文、英文、日文与没有文字的,每种语言最多 maxImagesPerLang 张;SVG 一类不能直接用的格式不要。

type ListPage

type ListPage struct {
	Results    []Result `json:"results"`
	Page       int      `json:"page"`
	TotalPages int      `json:"total_pages"`
}

ListPage 是列表的一页。

type Options

type Options struct {
	APIKey  string
	BaseURL string // 为空时用 DefaultBaseURL
	// ImageBaseURL 是图片地址(到 /t/p/ 为止);为空时用 ImageBaseURL
	ImageBaseURL string
	Language     string // 为空时用 zh-CN
	ProxyURL     string // 为空时用环境变量里的代理
	Cache        Cache  // 为空时不缓存
	// RatePerSecond 是每秒最多几个请求(为 0 时 8 个);读缓存不算。Limiter 不为空时不用它。
	RatePerSecond float64
	// Limiter 不为空时用它限速:同一个服务建的多个客户端共用一份额度。
	Limiter *rate.Limiter
	// HTTPClient 不为空时用它发请求(ProxyURL 不再生效):同一个代理的客户端共用连接池。
	HTTPClient *http.Client
}

Options 是客户端的选项。

type Result

type Result struct {
	ID               int     `json:"id"`
	MediaType        string  `json:"media_type"`
	Title            string  `json:"title"`
	OriginalTitle    string  `json:"original_title"`
	Year             int     `json:"year,omitempty"`
	Date             string  `json:"date,omitempty"`
	Overview         string  `json:"overview,omitempty"`
	PosterPath       string  `json:"poster_path,omitempty"`
	Popularity       float64 `json:"popularity,omitempty"`
	VoteAverage      float64 `json:"vote_average,omitempty"`
	OriginalLanguage string  `json:"original_language,omitempty"`
	IMDbID           string  `json:"imdb_id,omitempty"`
	Seasons          int     `json:"seasons,omitempty"`
	BackdropPath     string  `json:"backdrop_path,omitempty"`
	// GenreIDs 是 TMDB 的类型编号(16 是动画);Genres 是类型名称,只有详情里有
	GenreIDs []int    `json:"genre_ids,omitempty"`
	Genres   []string `json:"genres,omitempty"`
	// Runtime 是片长(分钟):电影是整部,剧集是一集,只有详情里有
	Runtime int `json:"runtime,omitempty"`
	// Countries 是出品国家或地区(ISO 3166-1,例如 CN、US):origin_country 与电影的 production_countries 合在一起;
	// 详情里有,剧集的搜索结果里也有
	Countries []string `json:"countries,omitempty"`
}

Result 是一个电影或剧集条目(搜索、查找与详情共用)。

func (Result) IsAnimation

func (r Result) IsAnimation() bool

IsAnimation 报告条目是不是动画。

type Season

type Season struct {
	Number     int       `json:"season_number"`
	Name       string    `json:"name,omitempty"`
	Overview   string    `json:"overview,omitempty"`
	AirDate    string    `json:"air_date,omitempty"`
	PosterPath string    `json:"poster_path,omitempty"`
	Episodes   []Episode `json:"episodes,omitempty"`
}

Season 是剧集的一季(含各集)。

func (*Season) Episode

func (s *Season) Episode(n int) *Episode

Episode 返回第 n 集;没有时返回 nil。

type SeasonSummary

type SeasonSummary struct {
	Number       int    `json:"season_number"`
	Name         string `json:"name,omitempty"`
	EpisodeCount int    `json:"episode_count"`
	AirDate      string `json:"air_date,omitempty"`
	PosterPath   string `json:"poster_path,omitempty"`
}

SeasonSummary 是剧集详情里列的一季:季号(0 是特别篇)、名字、集数、首播日期与季海报。

Jump to

Keyboard shortcuts

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