connector-spotify
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpotify with spotify-client
spotify-client通过 spotify-client
接入 Spotify
spotify-clientMotoko bindings for the
Spotify Web API,
generated from Spotify's official OpenAPI spec: 15 API modules, 270
operations. The package is built in icp-cli mode ( for the
management-canister interface), so it pulls as a dependency and pins
PocketIC in .
mo:ic/Typesic[toolchain]基于 Spotify 官方 OpenAPI spec 生成的 Spotify Web API Motoko 绑定:包含 15 个 API 模块、270 个操作。该包以 icp-cli mode 构建(针对 management-canister interface 使用 ),因此会引入 作为依赖,并在 中固定 PocketIC 版本。
mo:ic/Typesic[toolchain]Backend
后端
Reading catalog data and driving the player. The token always comes from the
caller — the canister never holds a Spotify client secret:
motoko
import { getTrack } "mo:spotify-client/Apis/TracksApi";
import { getInformationAboutTheUsersCurrentPlayback; skipUsersPlaybackToNextTrack } "mo:spotify-client/Apis/PlayerApi";
import { type Config; defaultConfig } "mo:spotify-client/Config";
persistent actor {
func config(accessToken : Text) : Config = { defaultConfig with auth = ?#bearer accessToken };
// Catalog read — a client-credentials token suffices. `market = ""` omits the
// parameter; empty strings and zeroes are how optional query params are
// dropped, there is no `?Text` to leave null.
public func trackName(accessToken : Text, id : Text) : async ?Text {
let track = await* getTrack(config accessToken, id, "");
track.name;
};
// User read — needs a user token with `user-read-playback-state`. An idle
// player answers 204 with an empty body, which the generated decoder cannot
// parse, so it rejects; treat that as "nothing playing", not as an error.
public func nowPlaying(accessToken : Text) : async ?Bool {
try {
let state = await* getInformationAboutTheUsersCurrentPlayback(config accessToken, "", "");
state.is_playing;
} catch (_err) {
null;
};
};
// User write — needs `user-modify-playback-state`. Returns `()`, and since
// 0.3.0 a non-2xx status rejects, so a missing scope or an expired token
// surfaces here instead of looking like success.
public func skip(accessToken : Text) : async () {
await* skipUsersPlaybackToNextTrack(config accessToken, "");
};
}读取目录数据并控制播放器。token 始终由调用方传入——canister 绝不保存 Spotify client secret:
motoko
import { getTrack } "mo:spotify-client/Apis/TracksApi";
import { getInformationAboutTheUsersCurrentPlayback; skipUsersPlaybackToNextTrack } "mo:spotify-client/Apis/PlayerApi";
import { type Config; defaultConfig } "mo:spotify-client/Config";
persistent actor {
func config(accessToken : Text) : Config = { defaultConfig with auth = ?#bearer accessToken };
// Catalog read — a client-credentials token suffices. `market = ""` omits the
// parameter; empty strings and zeroes are how optional query params are
// dropped, there is no `?Text` to leave null.
public func trackName(accessToken : Text, id : Text) : async ?Text {
let track = await* getTrack(config accessToken, id, "");
track.name;
};
// User read — needs a user token with `user-read-playback-state`. An idle
// player answers 204 with an empty body, which the generated decoder cannot
// parse, so it rejects; treat that as "nothing playing", not as an error.
public func nowPlaying(accessToken : Text) : async ?Bool {
try {
let state = await* getInformationAboutTheUsersCurrentPlayback(config accessToken, "", "");
state.is_playing;
} catch (_err) {
null;
};
};
// User write — needs `user-modify-playback-state`. Returns `()`, and since
// 0.3.0 a non-2xx status rejects, so a missing scope or an expired token
// surfaces here instead of looking like success.
public func skip(accessToken : Text) : async () {
await* skipUsersPlaybackToNextTrack(config accessToken, "");
};
}Auth: the canister never sees a client secret
认证:canister 绝不接触 client secret
Every call needs an OAuth 2.0 bearer access token, minted off-chain and
passed in. Two flows matter:
- Client Credentials — server-to-server, no user. Reads public catalog
only: ,
search,getTrack,getAnAlbum,getAnArtist,getNewReleases,getCategories, public playlists, public shows. It cannot touch anygetAvailableMarketsendpoint, the library, or the player./me/* - Authorization Code with PKCE — user-facing. Required for every call, playlist mutation, library write and player command, each gated by its own scope (
/me/*,user-read-playback-state,user-modify-playback-state,playlist-modify-public, …). Scopes absent from the token surface as 403, not as a validation error.user-library-read
Tokens expire after one hour and refresh is off-chain too. Treat a 401 as
"ask the client to refresh and retry", never as a permanent failure, and never
store a client secret in the canister.
每次调用都需要一个 OAuth 2.0 bearer access token,该 token 在链下签发后传入。有两种重要流程:
- Client Credentials——server-to-server,无用户上下文。只能读取公共目录数据:、
search、getTrack、getAnAlbum、getAnArtist、getNewReleases、getCategories、公共播放列表和公共节目。它无法访问任何getAvailableMarketsendpoint、曲库或播放器。/me/* - Authorization Code with PKCE——面向用户。所有 调用、播放列表修改、曲库写入和播放器命令都必须采用此流程;每项操作还分别受各自 scope 限制(
/me/*、user-read-playback-state、user-modify-playback-state、playlist-modify-public等)。token 中缺少的 scope 会表现为 403,而不是校验错误。user-library-read
token 的有效期为 一小时,刷新同样在链下完成。遇到 401 时,应将其视为“要求客户端刷新并重试”,绝不能视为永久性失败;同时,绝不要在 canister 中存储 client secret。
Calls are non-replicated by default
默认情况下,调用采用非复制模式
The package ships in , and 91 of the
135 operations depend on it. The generator already pins non-replication per
request for the 27 and 17 operations, because the IC requires it
there — so playlist edits and library saves were never at risk. The default is
what covers the rest:
is_replicated = ?falsedefaultConfigPUTDELETE- the 7 s, which include
POSTand both skip endpoints. These are not idempotent, so replicated they would queue a track ~13 times and skip ~13 tracks;addToQueue - all 84 s, which are non-deterministic for the player — currently-playing carries
GETandtimestamp, differing per node — and would cost ~13x the cycles even where they agree.progress_ms
You don't set the flag yourself; the default is correct. Override with
only together with a that strips the
volatile fields.
is_replicated = ?truetransformUpgrading from 0.2.x — the old advice was backwards. That skill told callers
to keep for mutations "because consensus matters", and
showed . Carrying that forward
is now actively harmful: means replicated, so every and
skip would fire once per replica. Delete any such override and take
as it comes.
is_replicated = nulllet userCfg = { cfg with is_replicated = null }nulladdToQueuedefaultConfig该包在 中提供 ,且 135 个操作中有 91 个依赖此配置。生成器已经为 27 个 和 17 个 操作逐请求固定为非复制模式,因为 IC 对这些操作有此要求——因此播放列表编辑和曲库保存从来不存在这方面的风险。默认配置则覆盖其余操作:
defaultConfigis_replicated = ?falsePUTDELETE- 7 个 ,其中包括
POST和两个 skip endpoint。这些操作并非幂等,因此在复制模式下执行时,一首曲目会被加入队列约 13 次,并跳过约 13 首曲目;addToQueue - 全部 84 个 。这些调用对播放器而言是非确定性的——当前播放状态包含
GET和timestamp,不同节点上的值不同——即使结果一致,也会消耗约 13 倍 cycles。progress_ms
你不需要自行设置该标志;默认值是正确的。只有在同时提供一个用于去除易变字段的 时,才应将 覆盖为 。
transformis_replicated?true从 0.2.x 升级——旧建议恰好相反。 当时的 skill 要求调用方对 mutation 保持 ,理由是“共识很重要”,并给出 。现在继续沿用这种做法会直接造成危害: 表示采用复制模式,因此每次 和 skip 都会在每个 replica 上分别执行一次。请删除所有此类覆盖配置,直接使用 。
is_replicated = nulllet userCfg = { cfg with is_replicated = null }nulladdToQueuedefaultConfigEverything in a response is optional
响应中的所有内容都是可选的
Spotify marks almost no response field required, so the models are all-optional:
, ,
. Reach through with a
block rather than nested es, and decide what absence means for your
caller — Spotify omits fields your token's scopes don't cover.
TrackObject.name : ?Text.artists : ?[SimplifiedArtistObject]CurrentlyPlayingContextObject.is_playing : ?Booldo ?switchSpotify 几乎没有将任何响应字段标记为必需,因此所有 model 的字段都是可选的:、、。请使用 块向下取值,而不要嵌套 ,并由调用方决定字段缺失的含义——对于 token scope 未覆盖的字段,Spotify 会将其省略。
TrackObject.name : ?Text.artists : ?[SimplifiedArtistObject]CurrentlyPlayingContextObject.is_playing : ?Booldo ?switchIDs, not URIs
使用 ID,而不是 URI
Endpoint parameters take Spotify's base-62 IDs
(), not URIs ()
and not URLs. When a user pastes a Spotify link, extract the segment after the
last and before any . The parameters on playlist operations are
the exception — those do take full URIs.
11dFghVXANMlKmJXsNCbNlspotify:track:11dFghVXANMlKmJXsNCbNl/?urisspotify:track:…endpoint 参数接受 Spotify 的 base-62 ID(),而不是 URI()或 URL。当用户粘贴 Spotify 链接时,应提取最后一个 之后、任何 之前的部分。播放列表操作中的 参数是例外——该参数确实接受完整的 URI。
11dFghVXANMlKmJXsNCbNlspotify:track:11dFghVXANMlKmJXsNCbNl/?urisspotify:track:…Starting playback
开始播放
PlayerApi.startAUsersPlaybackcontext_uri : ?Texturis : ?[Text]position_ms : ?InttransferAUsersPlaybackplay : ?Booluriscontext_urioffset?Map<Text, Text>{"uri": "spotify:track:…"}{"position": 5}{"position": "5"}PlayerApi.startAUsersPlaybackcontext_uri : ?Texturis : ?[Text]position_ms : ?InttransferAUsersPlaybackplay : ?Booluriscontext_urioffset?Map<Text, Text>{"uri": "spotify:track:…"}{"position": 5}{"position": "5"}One operation does not work
一个操作无法使用
PlaylistsApi.uploadCustomPlaylistCoverimage/jpegformat: byteContent-Type: application/jsonBlobic.http_requestcaffeinelabs/skills-internalEverything else in the surface is sound — unlike some connectors, there are no
stubbed converters, no operation silently dropping its request body, and
no endpoint returning a non-JSON body through the JSON decoder.
oneOfPlaylistsApi.uploadCustomPlaylistCoverimage/jpegformat: byteContent-Type: application/jsonBlobic.http_requestcaffeinelabs/skills-internal除此之外,其余 API surface 均正常可靠——与某些 connector 不同,这里没有被 stub 的 converter,没有 operation 会静默丢弃 request body,也没有 endpoint 会让非 JSON body 通过 JSON decoder 返回。
oneOfThe idle player rejects instead of returning "nothing playing"
空闲播放器会 reject,而不是返回“当前没有播放内容”
PlayerApi.getInformationAboutTheUsersCurrentPlaybackgetTheUsersCurrentlyPlayingTrackError.reject(… Failed to parse JSON …)trycatchThis is a codegen gap, not a Spotify quirk: the spec declares
for the first operation (the generator
ignores no-content 2xx responses and has no return shape for them), while
for the second Spotify returns 204 in practice without declaring it at all.
Modelling declared no-content responses would change the generated signature to
, so it belongs in the plugin as its own
change.
'204': Playback not available or active?T?CurrentlyPlayingContextObject当未处于播放状态时, 和 会以 204 和空 body 作出响应。生成代码会把所有 2xx 都当作 200 schema 处理,并对其运行 JSON decoder,因此播放器空闲时产生的是 ,而不是一个缺失值。应将这两个调用都包在 / 中,并将 rejection 解读为“当前没有播放内容”,正如 §后端 示例所示。
PlayerApi.getInformationAboutTheUsersCurrentPlaybackgetTheUsersCurrentlyPlayingTrackError.reject(… Failed to parse JSON …)trycatch这是 codegen 缺口,而不是 Spotify 特性异常:第一个操作的 spec 声明了 (生成器会忽略 no-content 2xx 响应,并且没有为它们提供 返回类型),而第二个操作在实践中会由 Spotify 返回 204,但 spec 完全没有声明。对已声明的 no-content 响应进行建模,会将 generated signature 改为 ,因此应在 plugin 中作为一项独立变更处理。
'204': Playback not available or active?T?CurrentlyPlayingContextObjectEvery write now reports its status
现在每次写入都会报告其状态
Until 0.3.0 the 43 operations returning — , ,
, every library and playlist mutation — discarded the HTTP response
entirely, so a 401, 403 or 429 was indistinguishable from success. They now
reject on any non-2xx status. Expect / around writes to actually
fire: a missing scope surfaces as 403 where it previously looked like a
successful no-op.
async* ()skippauseaddToQueuetrycatch在 0.3.0 之前,43 个返回 的操作——、、、所有曲库和播放列表 mutation——会完全丢弃 HTTP response,因此无法将 401、403 或 429 与成功区分开来。现在它们会对任何非 2xx status 执行 reject。写入操作外围的 / 现在确实会触发:缺少 scope 会明确表现为 403,而此前看起来只是一次成功的 no-op。
async* ()skippauseaddToQueuetrycatchCycles and response sizes
Cycles 与响应大小
defaultConfig.cycles = 30_000_000_000searchlimit=50getAnAlbumgetAudioAnalysiscycles = 100_000_000_000max_response_bytes = ?2_000_000defaultConfig.cycles = 30_000_000_000searchlimit=50getAnAlbumgetAudioAnalysiscycles100_000_000_000max_response_bytes = ?2_000_000Errors
错误
Non-2xx responses and decode failures . The client is
generated with , so the message is
— enough to separate a
401 (expired token) from a 403 (missing scope) from a 404 (bad ID) without extra
logging. Catch with / and surface .
throw Error.reject(…)diagnosticsHTTP <status> body[<n>B]=<first 100 chars>: <reason>trycatchError.message(err)非 2xx 响应和解码失败会 。客户端以 生成,因此错误消息格式为 ——无需额外日志,就足以区分 401(token 过期)、403(缺少 scope)和 404(ID 无效)。请通过 / 捕获,并对外提供 。
throw Error.reject(…)diagnosticsHTTP <status> body[<n>B]=<first 100 chars>: <reason>trycatchError.message(err)