connector-spotify

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spotify with
spotify-client

通过
spotify-client
接入 Spotify

Motoko 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 (
mo:ic/Types
for the management-canister interface), so it pulls
ic
as a dependency and pins PocketIC in
[toolchain]
.
基于 Spotify 官方 OpenAPI spec 生成的 Spotify Web API Motoko 绑定:包含 15 个 API 模块、270 个操作。该包以 icp-cli mode 构建(针对 management-canister interface 使用
mo:ic/Types
),因此会引入
ic
作为依赖,并在
[toolchain]
中固定 PocketIC 版本。

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:
  1. Client Credentials — server-to-server, no user. Reads public catalog only:
    search
    ,
    getTrack
    ,
    getAnAlbum
    ,
    getAnArtist
    ,
    getNewReleases
    ,
    getCategories
    ,
    getAvailableMarkets
    , public playlists, public shows. It cannot touch any
    /me/*
    endpoint, the library, or the player.
  2. Authorization Code with PKCE — user-facing. Required for every
    /me/*
    call, playlist mutation, library write and player command, each gated by its own scope (
    user-read-playback-state
    ,
    user-modify-playback-state
    ,
    playlist-modify-public
    ,
    user-library-read
    , …). Scopes absent from the token surface as 403, not as a validation error.
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 在链下签发后传入。有两种重要流程:
  1. Client Credentials——server-to-server,无用户上下文。只能读取公共目录数据:
    search
    、
    getTrack
    、
    getAnAlbum
    、
    getAnArtist
    、
    getNewReleases
    、
    getCategories
    、
    getAvailableMarkets
    、公共播放列表和公共节目。它无法访问任何
    /me/*
    endpoint、曲库或播放器
    。
  2. Authorization Code with PKCE——面向用户。所有
    /me/*
    调用、播放列表修改、曲库写入和播放器命令都必须采用此流程;每项操作还分别受各自 scope 限制(
    user-read-playback-state
    、
    user-modify-playback-state
    、
    playlist-modify-public
    、
    user-library-read
    等)。token 中缺少的 scope 会表现为 403,而不是校验错误。
token 的有效期为 一小时,刷新同样在链下完成。遇到 401 时,应将其视为“要求客户端刷新并重试”,绝不能视为永久性失败;同时,绝不要在 canister 中存储 client secret。

Calls are non-replicated by default

默认情况下,调用采用非复制模式

The package ships
is_replicated = ?false
in
defaultConfig
, and 91 of the 135 operations depend on it. The generator already pins non-replication per request for the 27
PUT
and 17
DELETE
operations, because the IC requires it there — so playlist edits and library saves were never at risk. The default is what covers the rest:
  • the 7
    POST
    s
    , which include
    addToQueue
    and both skip endpoints. These are not idempotent, so replicated they would queue a track ~13 times and skip ~13 tracks;
  • all 84
    GET
    s
    , which are non-deterministic for the player — currently-playing carries
    timestamp
    and
    progress_ms
    , differing per node — and would cost ~13x the cycles even where they agree.
You don't set the flag yourself; the default is correct. Override with
is_replicated = ?true
only together with a
transform
that strips the volatile fields.
Upgrading from 0.2.x — the old advice was backwards. That skill told callers to keep
is_replicated = null
for mutations "because consensus matters", and showed
let userCfg = { cfg with is_replicated = null }
. Carrying that forward is now actively harmful:
null
means replicated, so every
addToQueue
and skip would fire once per replica. Delete any such override and take
defaultConfig
as it comes.
该包在
defaultConfig
中提供
is_replicated = ?false
,且 135 个操作中有 91 个依赖此配置。生成器已经为 27 个
PUT
和 17 个
DELETE
操作
逐请求固定为非复制模式,因为 IC 对这些操作有此要求——因此播放列表编辑和曲库保存从来不存在这方面的风险。默认配置则覆盖其余操作:
  • 7 个
    POST
    ,其中包括
    addToQueue
    和两个 skip endpoint。这些操作并非幂等,因此在复制模式下执行时,一首曲目会被加入队列约 13 次,并跳过约 13 首曲目;
  • 全部 84 个
    GET
    。这些调用对播放器而言是非确定性的——当前播放状态包含
    timestamp
    和
    progress_ms
    ,不同节点上的值不同——即使结果一致,也会消耗约 13 倍 cycles。
你不需要自行设置该标志;默认值是正确的。只有在同时提供一个用于去除易变字段的
transform
时,才应将
is_replicated
覆盖为
?true
。
从 0.2.x 升级——旧建议恰好相反。 当时的 skill 要求调用方对 mutation 保持
is_replicated = null
,理由是“共识很重要”,并给出
let userCfg = { cfg with is_replicated = null }
。现在继续沿用这种做法会直接造成危害:
null
表示采用复制模式,因此每次
addToQueue
和 skip 都会在每个 replica 上分别执行一次。请删除所有此类覆盖配置,直接使用
defaultConfig
。

Everything in a response is optional

响应中的所有内容都是可选的

Spotify marks almost no response field required, so the models are all-optional:
TrackObject.name : ?Text
,
.artists : ?[SimplifiedArtistObject]
,
CurrentlyPlayingContextObject.is_playing : ?Bool
. Reach through with a
do ?
block rather than nested
switch
es, and decide what absence means for your caller — Spotify omits fields your token's scopes don't cover.
Spotify 几乎没有将任何响应字段标记为必需,因此所有 model 的字段都是可选的:
TrackObject.name : ?Text
、
.artists : ?[SimplifiedArtistObject]
、
CurrentlyPlayingContextObject.is_playing : ?Bool
。请使用
do ?
块向下取值,而不要嵌套
switch
,并由调用方决定字段缺失的含义——对于 token scope 未覆盖的字段,Spotify 会将其省略。

IDs, not URIs

使用 ID,而不是 URI

Endpoint parameters take Spotify's base-62 IDs (
11dFghVXANMlKmJXsNCbNl
), not URIs (
spotify:track:11dFghVXANMlKmJXsNCbNl
) and not URLs. When a user pastes a Spotify link, extract the segment after the last
/
and before any
?
. The
uris
parameters on playlist operations are the exception — those do take full
spotify:track:…
URIs.
endpoint 参数接受 Spotify 的 base-62 ID(
11dFghVXANMlKmJXsNCbNl
),而不是 URI(
spotify:track:11dFghVXANMlKmJXsNCbNl
)或 URL。当用户粘贴 Spotify 链接时,应提取最后一个
/
之后、任何
?
之前的部分。播放列表操作中的
uris
参数是例外——该参数确实接受完整的
spotify:track:…
URI。

Starting playback

开始播放

PlayerApi.startAUsersPlayback
takes the four fields as scalars —
context_uri : ?Text
,
uris : ?[Text]
,
position_ms : ?Int
— and
transferAUsersPlayback
takes
play : ?Bool
. Pick one of
uris
(explicit tracks) or
context_uri
(an album, artist or playlist), never both.
offset
is the exception: it is a free-form object in the spec, so the generator maps it to
?Map<Text, Text>
and serialises every value as a string.
{"uri": "spotify:track:…"}
therefore works, while Spotify's other documented form
{"position": 5}
goes out as
{"position": "5"}
and is rejected. Offset into a context by URI, not by index.
PlayerApi.startAUsersPlayback
以标量形式接收四个字段——
context_uri : ?Text
、
uris : ?[Text]
、
position_ms : ?Int
——而
transferAUsersPlayback
接收
play : ?Bool
。在
uris
(明确指定曲目)与
context_uri
(专辑、艺人或播放列表)中选择其一,绝不能同时使用。
offset
是例外:它在 spec 中是自由形式对象,因此生成器将其映射为
?Map<Text, Text>
,并将每个值都序列化为字符串。因此
{"uri": "spotify:track:…"}
可以正常工作,而 Spotify 记录的另一种形式
{"position": 5}
会作为
{"position": "5"}
发出并被拒绝。要按 URI 偏移到 context 中,而不是按索引。

One operation does not work

一个操作无法使用

PlaylistsApi.uploadCustomPlaylistCover
— the spec declares the body as
image/jpeg
(
format: byte
), but the generator only ever emits JSON request bodies, so the call sends
Content-Type: application/json
with the base64 wrapped in JSON quotes. Spotify rejects it. This is not new in 0.3.0: 0.2.2 JSON-wrapped the raw
Blob
instead, equally wrong on the wire. Do not offer custom playlist cover upload, and do not hand-roll it with
ic.http_request
; raise it on
caffeinelabs/skills-internal
.
Everything else in the surface is sound — unlike some connectors, there are no stubbed
oneOf
converters, no operation silently dropping its request body, and no endpoint returning a non-JSON body through the JSON decoder.
PlaylistsApi.uploadCustomPlaylistCover
——spec 将 body 声明为
image/jpeg
(
format: byte
),但生成器始终只会发出 JSON request body,因此该调用会发送
Content-Type: application/json
,并将 base64 包在 JSON 引号中。Spotify 会拒绝该请求。这并非 0.3.0 才出现的问题:0.2.2 也会将原始
Blob
包在 JSON 中,在 wire 上同样错误。不要提供自定义播放列表封面上传功能,也不要使用
ic.http_request
手工实现;请在
caffeinelabs/skills-internal
上反馈该问题。
除此之外,其余 API surface 均正常可靠——与某些 connector 不同,这里没有被 stub 的
oneOf
converter,没有 operation 会静默丢弃 request body,也没有 endpoint 会让非 JSON body 通过 JSON decoder 返回。

The idle player rejects instead of returning "nothing playing"

空闲播放器会 reject,而不是返回“当前没有播放内容”

PlayerApi.getInformationAboutTheUsersCurrentPlayback
and
getTheUsersCurrentlyPlayingTrack
answer 204 with an empty body when playback is not active. The generated code treats every 2xx as the 200 schema and runs the JSON decoder over it, so an idle player produces
Error.reject(… Failed to parse JSON …)
rather than an absent value. Wrap both in
try
/
catch
and read a rejection as "nothing playing", as the §Backend sample does.
This is a codegen gap, not a Spotify quirk: the spec declares
'204': Playback not available or active
for the first operation (the generator ignores no-content 2xx responses and has no
?T
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
?CurrentlyPlayingContextObject
, so it belongs in the plugin as its own change.
当未处于播放状态时,
PlayerApi.getInformationAboutTheUsersCurrentPlayback
和
getTheUsersCurrentlyPlayingTrack
会以 204 和空 body 作出响应。生成代码会把所有 2xx 都当作 200 schema 处理,并对其运行 JSON decoder,因此播放器空闲时产生的是
Error.reject(… Failed to parse JSON …)
,而不是一个缺失值。应将这两个调用都包在
try
/
catch
中,并将 rejection 解读为“当前没有播放内容”,正如 §后端 示例所示。
这是 codegen 缺口,而不是 Spotify 特性异常:第一个操作的 spec 声明了
'204': Playback not available or active
(生成器会忽略 no-content 2xx 响应,并且没有为它们提供
?T
返回类型),而第二个操作在实践中会由 Spotify 返回 204,但 spec 完全没有声明。对已声明的 no-content 响应进行建模,会将 generated signature 改为
?CurrentlyPlayingContextObject
,因此应在 plugin 中作为一项独立变更处理。

Every write now reports its status

现在每次写入都会报告其状态

Until 0.3.0 the 43 operations returning
async* ()
—
skip
,
pause
,
addToQueue
, 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
try
/
catch
around writes to actually fire: a missing scope surfaces as 403 where it previously looked like a successful no-op.
在 0.3.0 之前,43 个返回
async* ()
的操作——
skip
、
pause
、
addToQueue
、所有曲库和播放列表 mutation——会完全丢弃 HTTP response,因此无法将 401、403 或 429 与成功区分开来。现在它们会对任何非 2xx status 执行 reject。写入操作外围的
try
/
catch
现在确实会触发:缺少 scope 会明确表现为 403,而此前看起来只是一次成功的 no-op。

Cycles and response sizes

Cycles 与响应大小

defaultConfig.cycles = 30_000_000_000
suits a typical single-object read. Large pages need more:
search
with
limit=50
,
getAnAlbum
on a long tracklist, or
getAudioAnalysis
(which returns a very large object) want
cycles = 100_000_000_000
and an explicit
max_response_bytes = ?2_000_000
.
defaultConfig.cycles = 30_000_000_000
适合典型的单对象读取。大型分页需要更多 cycles:
search
(
limit=50
)、包含较长 tracklist 的
getAnAlbum
,或返回极大对象的
getAudioAnalysis
,应将
cycles
设置为
100_000_000_000
,并显式设置
max_response_bytes = ?2_000_000
。

Errors

错误

Non-2xx responses and decode failures
throw Error.reject(…)
. The client is generated with
diagnostics
, so the message is
HTTP <status> body[<n>B]=<first 100 chars>: <reason>
— enough to separate a 401 (expired token) from a 403 (missing scope) from a 404 (bad ID) without extra logging. Catch with
try
/
catch
and surface
Error.message(err)
.
非 2xx 响应和解码失败会
throw Error.reject(…)
。客户端以
diagnostics
生成,因此错误消息格式为
HTTP <status> body[<n>B]=<first 100 chars>: <reason>
——无需额外日志,就足以区分 401(token 过期)、403(缺少 scope)和 404(ID 无效)。请通过
try
/
catch
捕获,并对外提供
Error.message(err)
。