接入一个音乐平台
搜索、专辑、歌单、播放地址、歌词、播放上报、一起听。实现 describe
和用得到的操作,平台就会出现在「添加平台」里,界面跟内置平台一样。
LZR / LUA PLUGIN MANIFEST · SANDBOX · HOST API
Lazer 不带内置的流媒体网关。音乐平台用什么接口、怎么签名、返回的 JSON 怎么解析、 账号规则怎么定,都写在插件的 Lua 里;客户端只负责显示和播放。
插件就是一个 ZIP。解压后真正起作用的文件有两类:清单说明它需要什么,Lua 说明它做什么。
客户端不执行包里的 JavaScript,也不会把 Flutter Widget 交给 Lua,
能做的事都得经过 host 提供的接口。
搜索、专辑、歌单、播放地址、歌词、播放上报、一起听。实现 describe
和用得到的操作,平台就会出现在「添加平台」里,界面跟内置平台一样。
host.http 按清单里的白名单发请求,host.crypto 负责签名,
host.storage_* 存会话。也可以开 TCP 或 WebSocket 连接,
甚至在本机监听端口,给外部前端用。
可以加设置项、插件页面、正在播放页的菜单项,也能提供主题和布局规则。 控件都由宿主绘制,插件只交数据。
插件拿不到 Dart 对象、Flutter Widget、宿主的文件路径、进程和动态库,
也读不到别的插件的数据。这一点没法用配置放开:
Lua 里能看见的只有 host 和你自己返回的 table。
插件以 ZIP 形式安装。manifest.json 必须放在 ZIP 根目录,
entry 指向的 Lua 文件也要在包里。其余 Lua 文件用 require 加载。
my-plugin.zip
├── manifest.json # 必需,唯一的清单来源
├── main.lua # 必需,entry 指向它
├── api.lua # 可选,require("api") 加载
├── sign.lua # 可选,require("sign")
├── data/keys.json # 可选,host.resource("data/keys.json") 读取
├── frontend/ # 可选,随包携带的只读 HTML/CSS/JS
│ └── index.html
├── README.md # 可选
└── LICENSE # 可选
| 限制 | 数值 | 说明 |
|---|---|---|
| ZIP 大小 | 16 MB | 超过直接拒绝安装 |
| 解压后总量 | 8 MB | 所有文件累计 |
| 单文件 | 2 MB | 任意一个文件 |
| 文件个数 | 256 | 压缩包内有效条目 |
| 路径长度 | 200 | 相对路径字符数 |
允许的文件类型只有:manifest.json、*.lua、
.json / .md / .txt / .html / .css / .js / .svg
文本资源,以及根目录的 LICENSE。出现别的扩展名时整包拒绝,不会只装能认出来的那部分。
所有路径必须是安全的相对路径:不含反斜杠、盘符或开头的 /,
不允许 . 与 .. 段,不允许以点或空格结尾的段,
也不允许 < > " | ? * 与控制字符。路径按小写去重,所以
Api.lua 和 api.lua 属于冲突。
打包工具留下的杂物直接忽略,不算错误:__MACOSX/、.DS_Store、Thumbs.db。
Windows 资源管理器写出的反斜杠路径会被规范化。打包时多裹了一层目录、
所有文件都在同一个顶层目录下的,客户端会把这一层提升为根。
自动提升只对「所有文件共用一个顶层目录」有效。ZIP 里既有 my-plugin/manifest.json
又有根目录的 README.md 时不会提升,安装会报「ZIP 根目录缺少 manifest.json」。
manifest.json 是插件唯一的声明来源,决定插件叫什么、入口在哪、能访问哪些网络、
在客户端里显示成什么样。字段不合法时整包被拒,而报错不会告诉你是哪个字段,
所以下面这些规则需要逐条对。
^[a-z][a-z0-9_.-]{2,79}$:小写字母开头,3–80 位。
建议用反写域名,例如 community.bilibili.music。
1.4.2 或 2.0.0-beta.1。与市场清单里的 version 必须完全一致。1。写成别的值(包括遗漏时的默认 0)一律拒绝。gateway(音乐平台)、theme(主题)或 other(其他)。省略或填入未知名称时按 gateway 处理。gateway 必填;其他类型可省略。非空时须符合 ^[a-z][a-z0-9_-]{1,39}$,且不得为 local。
多平台网关以各自的 describe.providers[].id 作为 args.platform。
main.lua。必须是安全相对路径且以 .lua 结尾。- / _。订阅播放广播时,
请按事件回调中的拼写列出 player_events 或 player-events。
qr、sms、password、cookie;同一数组中的 exportCookie 打开导出入口。{
"id": "community.example.music",
"name": "Example Music",
"version": "1.0.0",
"description": "把 Example Music 接进 Lazer",
"author": "YOUR NAME",
"entry": "main.lua",
"apiVersion": 1,
"type": "gateway",
"provider": "example",
"capabilities": ["search", "playlists", "lyrics", "scrobble", "player_events"],
"auth": ["qr", "cookie"],
"permissions": {
"network": ["api.example.com", "*.example-cdn.com"],
"storage": true,
"data": ["library", "profile"]
}
}
permissions.network 是 HTTPS 主机的白名单,最多 32 条。每条是一个主机名,
可带端口,也可以用 *. 前缀通配子域。
| 写法 | 允许 | 不允许 |
|---|---|---|
api.example.com | 恰好这个主机 | 任何子域、任何其他主机 |
*.example.com | example.com 及其所有子域 | example.org |
api.example.com:8443 | 同主机且端口为 8443 | 443 或其他端口 |
*.com | 拒绝安装:通配必须落在可注册域名上 | |
通配符后面必须是一个可注册域名。客户端内置了一小张公共后缀表(co.uk、
com.cn、co.jp 等),把 *.co.uk 这类写法判为无效;
想覆盖国别域名下的子域,请写完整的 *.example.co.uk。
请求必须使用 HTTPS,且 URL 中不能带用户名或密码。
*.example.com 额外允许裸域 example.com 本身。
端口不写时要求目标端口为默认 443;写了端口就要求精确相等。
最小的插件只需要一个入口文件和一个 call 函数。
下面这份能登录、能搜索、能取歌词,够出现在平台列表里了。
-- main.lua
local api = require("api")
return {
call = function(operation, args)
if operation == "describe" then
return { providers = {
{ id = "example", name = "Example Music",
auth = { "cookie" },
capabilities = { "search", "lyrics" } },
} }
end
if operation == "session" then
local cookie = host.storage_get("cookie")
if not cookie then return nil end
return { id = "me", name = "Example User" }
end
if operation == "loginCookie" then
host.storage_set("cookie", args.cookie)
return { id = "me", name = "Example User" }
end
if operation == "search" then
return api.search(args.query, args.limit or 30, args.offset or 0)
end
if operation == "lyrics" then
return api.lyrics(args.id)
end
error("unsupported operation: " .. tostring(operation))
end,
}
-- api.lua
local M = {}
local BASE = "https://api.example.com"
-- 参数既可以直接给查询串,也可以给 table;table 会被编码成 a=1&b=2
local function encode(params)
if params == nil then return nil end
if type(params) == "string" then return params end
local parts = {}
for key, value in pairs(params) do
parts[#parts + 1] = host.url_encode(tostring(key))
.. "=" .. host.url_encode(tostring(value))
end
return table.concat(parts, "&")
end
-- host.http 返回 {status, headers, body},状态码由插件自己解释
local function send(method, path, query, payload)
local url = BASE .. path
local params = encode(query)
if params and params ~= "" then url = url .. "?" .. params end
local body, contentType = nil, nil
if type(payload) == "table" then
body, contentType = host.json_encode(payload), "application/json"
elseif type(payload) == "string" then
body, contentType = payload, "application/x-www-form-urlencoded"
end
local response = host.http({
url = url,
method = method,
headers = {
["Cookie"] = host.storage_get("cookie") or "",
["Content-Type"] = contentType or "application/json",
},
body = body,
})
if response.status < 200 or response.status >= 300 then
return { error = { httpStatus = response.status } }
end
if response.body == "" then return {} end
return host.json_decode(response.body)
end
function M.get(path, query) return send("GET", path, query) end
function M.post(path, payload) return send("POST", path, nil, payload) end
function M.search(query, limit, offset)
local body = M.get("/search", { q = query, limit = limit, offset = offset })
if body.error then return body end
local songs = {}
for _, item in ipairs(body.songs or {}) do
songs[#songs + 1] = {
id = tostring(item.id),
title = item.name,
artists = { { id = tostring(item.artist.id), name = item.artist.name } },
albumId = tostring(item.album.id),
albumName = item.album.name,
coverUrl = item.album.picUrl,
durationMs = item.duration,
}
end
return { songs = songs }
end
function M.lyrics(id)
local body = M.get("/lyric", { id = id })
if body.error then return body end
-- 返回候选数组;客户端解析 LRC 后就得到时间轴
return { { synced = true, lrc = body.lrc } }
end
return M
把 manifest.json、main.lua、api.lua 放在同一个目录里压成 ZIP。
用 PowerShell 打包时别把父目录一起装进去,按文件逐个压:
Compress-Archive -Path .\manifest.json, .\main.lua, .\api.lua `
-DestinationPath .\community.example.music.zip -Force
安装时客户端先把包解压到临时目录,校验清单和入口,再用一个临时 VM 跑一遍入口。 全部通过才替换旧版本;中途失败就保留原版本,正在用的插件不受影响。
打开客户端的「设置 → 插件管理」,选择安装并挑中你的 ZIP。
启动失败时只会显示「插件启动失败,请检查插件版本或重新导入」。
具体原因在 host.log 写出的诊断日志里,或者在开发者控制台的 Lua 输出里。
用 host.log("debug", "payload", { status = 200 }) 记结构化信息。
日志会经过脱敏并截断长度,别把 Cookie 或令牌写进去:被抹掉之后反而查不出问题。
改完重新打包,再装一次就覆盖了。更新会重置这个插件已获得的授权, 数据权限要重新同意一次,免得旧授权被新代码直接拿走。
| 现象 | 原因 |
|---|---|
| ZIP 根目录缺少 manifest.json | 压缩时多包了一层目录,且没有满足自动提升条件 |
| 清单无效 | 某个字段不满足规则:常见是 apiVersion 没写、provider 用了大写或在 id 里混入大写 |
| 缺少插件入口 | entry 指向的文件不在包里,或路径大小写与 ZIP 内不一致 |
| 插件仅支持 Lua 源码与说明文件 | 包里混入了 .png、.exe 等不被允许的类型 |
| Entry must return a table | 入口文件没有 return { call = ... },或 require 失败 |
| 插件缺少 call 入口 | 入口返回的 table 里没有 call 字段 |
入口文件只执行一次,必须 return 一个 table,call 是其中唯一的入口函数。
此后宿主的所有调用都走它:平台操作、事件回调、计时器。
return {
call = function(operation, args)
-- operation: string
-- args: table(普通平台操作一定带平台 ID)
return nil
end,
}
| 位置 | 内容 |
|---|---|
operation | 操作名,字符串。大小写敏感,按文档写成驼峰或全小写。 |
args |
参数表。由客户端发起的调用会额外带上 args.platform(即清单里的
provider);事件回调带各自的字段,见 事件回调。
|
| 返回值 | 须符合该操作的结果类型。session 可以用 nil 表示未登录;stream 等要求对象的操作不接受 nil。 |
Lua 与宿主之间只能传 nil、布尔值、数字、字符串、数组和字符串键表。
函数、协程、userdata 跨边界会直接报错 Only data can cross the plugin boundary。
| 规则 | 限制 |
|---|---|
| 嵌套深度 | 48 层 |
| 单表键数 | 100000 |
| 表的键类型 | 只能是字符串或整数;其它类型报 Invalid table key |
| 数组语义 | 整数键恰好覆盖 1..n 时按数组处理,否则按字符串键表处理 |
| 数字 | 整数保持整数,浮点保持浮点;NaN 与无穷不可传递 |
返回值里不要放函数或循环引用。序列化会失败,整次调用报错, 界面上只会说「插件请求失败」,你的错误信息到不了用户。
两三个操作用 if 就够了。多起来之后可以按表分发,少一层缩进,
未实现的操作也能一起兜住:
local handlers = {}
handlers.describe = function(args) ... end
handlers.search = function(args) return search(args.query) end
handlers.lyrics = function(args) return lyrics(args.id) end
return {
call = function(operation, args)
local handler = handlers[operation]
if not handler then
error("unsupported operation: " .. tostring(operation))
end
return handler(args or {})
end,
}
未实现的操作直接 error 报出来,别静默返回 nil。
客户端解析失败只会说「插件返回了无效数据」,出错的位置只有你自己的错误信息能说明。
从 ZIP 到能用,中间是串行的几步。任何一步失败,已经装好的旧版本都不受影响: 客户端只在临时目录里验证通过之后才替换。
检查 ZIP 体积、文件类型、路径安全性、清单字段,并确认 entry 指向的文件存在。
这一步不执行任何 Lua。
在隔离环境里加载入口、跑一遍 bootstrap。入口必须返回 table 且带 call 字段。
启动有 40 秒上限。
启动成功才替换旧版本。停用、更新或卸载前,客户端会先停掉该插件的请求和关联播放会话。
插件启用后客户端调用 describe,据此得到平台列表、名称、登录方式与能力。
旧式单平台网关可在返回值中省略 providers,沿用清单里的 provider / capabilities / auth。
设置项、插件页面、播放器菜单项在入口执行时注册。注册是幂等的:
同一个插件里用相同的 id 再注册一次,更新原项,不会多出一条。
session 返回已登录账号或 nil。之后每次搜索、取流、取歌词都是一次
call,同一个插件的调用串行执行。
键值存储、设置值与文件沙箱按插件隔离。多平台插件应自行把 args.platform 放进会话键名,
不要用一个全局 Cookie 覆盖所有平台的账号。
选择本地音乐不会触发 logout,切换平台也不会清空其他平台的会话。
logout 只清除当前 args.platform 的凭据。要清空整个插件的数据,
用 host.storage_clear(),或让用户在插件管理里卸载。
每个插件跑在独立的 VM 和独立的 isolate 里,有自己的调用队列和时间预算。 标准库里涉及文件系统、进程和动态加载的部分全部移除了。
| 被移除 | 后果 |
|---|---|
io、os | 没有文件、环境变量、时钟和进程接口 |
package、debug | 不能加载 C 模块,也不能操作调用栈 |
dofile、loadfile、load、loadstring | 不能执行动态生成的代码 |
print | 普通插件里为 nil;用 host.log |
require | 被重新实现为「从 ZIP 内加载 .lua」,见下 |
require 只能加载 ZIP 里的 Lua 文件。模块名就是文件路径去掉末尾
.lua,再把 / 换成 .:
| ZIP 内路径 | 写法 |
|---|---|
api.lua | require("api") |
lib/util.lua | require("lib.util") |
vendor/sign/rsa.lua | require("vendor.sign.rsa") |
同一个模块只会执行一次,结果会被缓存。加载不存在的模块报
unknown module: <name>;模块文件没有返回值时按 true 处理。
入口文件本身不能被 require,它由宿主单独加载。
| 项目 | 数值 | 超限之后 |
|---|---|---|
| 单次调用指令数 | 250000 | 按超时处理(code 408),VM 重建 |
| 单次调用墙钟 | 40 秒 | 按超时处理(code 408),VM 重建 |
| 启动握手 | 40 秒 | 插件启动失败 |
host.http 单次 | 30 秒 | 调用失败 |
host.sleep | 0–60000 ms | 按 60000 处理 |
| socket / websocket 接收 | 0–30000 ms | 返回 nil,不报错 |
后台操作有更紧的预算:scrobble、playStats、lyrics、
song 各 10 秒。这样一次卡住的上报不会堵住下一条取流请求。
stream 是用户在等的那一次调用,用默认预算,并且超时后客户端会在新 VM 上重试一次。
指令预算比看起来容易用完。不要在 call 里对几千条数据逐条拼字符串或做嵌套排序,
批量数据交给 host.json_decode,由宿主完成。
死循环会以「插件响应超时,已自动重启插件」结束:会话还在,这次调用丢了。
错误分两层:Lua 抛出的错误会让当前调用失败;返回一张
{ error = { ... } } 表则是「预期内的失败」,客户端会据此提示用户重试或重新登录。
| 写法 | 客户端行为 |
|---|---|
error("boom") |
调用失败,界面提示「插件请求失败」。错误文本不会直接展示给用户。 |
return { error = { code = 40 } } |
识别为登录态失效,提示重新登录。 |
return { error = { code = 40, httpStatus = 401 } } |
同上;httpStatus 优先于 code 里的状态码。 |
return nil |
取决于操作:session 表示未登录;stream 须返回对象,nil 是无效负载,不等于业务码 70。 |
local response = host.http({ url = url, headers = headers })
if response.status ~= 200 then
-- 401 表示需要登录,403 本身不等于会话失效,429 表示限流
return { error = { httpStatus = response.status } }
end
code 落在 400–599 之间时会被当作 HTTP 状态解释。业务错误码请用范围外的数值,
例如 code = 70 表示当前歌曲不可用。
网络、文件和私有数据接口在缺少所需权限时会抛错;有些接口会返回错误表,见原生能力。
可能失败的调用包在 pcall 里,沙箱的 pcall 是异步版本,
能包住会挂起的 host.http。
local ok, result = pcall(host.http, { url = "https://api.example.com/ping" })
if not ok then
host.log("warn", "request failed", { reason = tostring(result) })
return nil
end
return result
| 错误文本 | 含义 |
|---|---|
Network permission required | 清单声明了域名,但用户还没同意网络授权 |
Network permission denied | 目标域名不在 permissions.network 里,或不是 HTTPS |
Plugin data permission denied | 数据权限被拒绝(code 403) |
Plugin data permission revoked | 调用过程中权限被用户撤销 |
Storage permission required | 清单没有 permissions.storage |
Filesystem permission required | 没有文件权限,或用户拒绝 |
Storage full / Filesystem storage full | 持久化空间或文件配额已满 |
插件响应超时,已自动重启插件。 | 墙钟或指令预算耗尽(code 408) |
插件启用后客户端调的第一个操作,返回这个插件提供哪些平台。
一个插件可以带多个平台,后续调用里的 args.platform 就是这里列的 id。
不提供音乐平台的主题或工具插件应显式返回 providers = {};网关省略 providers 时回退到清单中的平台信息。
if operation == "describe" then
return {
providers = {
{
id = "example",
name = "Example Music",
auth = { "qr", "cookie" },
capabilities = { "search", "playlists", "lyrics", "scrobble" },
loginHint = "使用 Example Music App 扫码登录",
cookieHint = "从浏览器开发者工具复制 Cookie",
forgotPasswordUrl = "https://example.com/forgot",
},
},
}
end
| 字段 | 说明 |
|---|---|
id | 平台 ID,^[a-z][a-z0-9_-]{1,39}$,不能是 local,同一插件内不可重复 |
name | 显示名称,非空 |
auth | 登录方式及可选的 exportCookie 标志;省略时沿用清单 |
capabilities | 该平台的能力数组。省略或传 Lua 空表时沿用清单 |
loginHint | 登录页上的提示文案 |
cookieHint | Cookie 登录页上的提示文案 |
forgotPasswordUrl | 忘记密码链接 |
experimental | 原生端读取这个布尔标志;Web 端当前不读取 |
Lua 空表 {} 跨边界后是对象,不是数组,因此不会清空清单中已有的能力。
要为某个平台缩小能力集,请返回非空数组,只列出它实际支持的能力。
| 能力 | 需要实现的操作 | 影响 |
|---|---|---|
search | search | 搜索页 |
browseAlbums | albums、album、albumSongs | 专辑浏览与详情 |
savedAlbums | savedAlbums | 收藏的专辑 |
playlists | playlists、playlist、playlistSongs | 歌单列表与详情 |
editPlaylists | createPlaylist、addToPlaylist、removeFromPlaylist | 新建歌单、增删曲目 |
favorites | favorites、setFavorite | 喜欢歌单与收藏按钮 |
lyrics | lyrics | 歌词页 |
scrobble | scrobble、playStats | 播放上报与统计 |
recommendations | recommendations | 猜你喜欢 |
comments | comments、setCommentLiked | 歌曲评论 |
listenTogether | listenTogether | 一起听入口 |
radio | radio | 私人漫游、心动模式、歌手电台 |
charts | charts、playlistSongs | 插件榜单(与客户端外部榜单合并) |
homeFeed | homeFeed | 每日推荐、精选、新发行 |
能力名不区分大小写,_ 和 - 会被折叠掉:
listenTogether、listen_together、listen-together
是同一个能力。无法识别的名字会被忽略,不会导致整个平台描述失败。
皮肤由 describe 顶层的 theme(别名 skin)声明;
exportCookie 属于 auth,不是平台能力。播放事件则只认清单中的订阅标志。
封面、头像这类公共素材常常要带特定 Referer 或缩图参数。
在 describe 顶层用 media 声明规则,客户端按规则发请求,它不认识任何平台的域名。
media = {
{
host = "*.images.example-cdn.com",
headers = { ["Referer"] = "https://example.com/" },
artworkResize = { parameter = "size", value = "{size}x{size}" },
fallbackHosts = { "images2.example-cdn.com" },
},
}
顶层 media 按插件注册,不写在单个 providers[] 内。host 超出 permissions.network 范围时整条规则被忽略;fallbackHosts 逐项检查,只保留范围内的主机。
公共规则只保留字符串头值,头名转为小写;Cookie、Authorization、Proxy-Authorization、Host、Content-Length、Connection、Transfer-Encoding 会被丢弃。音频来源专用的头见 stream。
登录拆成了若干小操作,客户端只显示你在 auth 里声明过的方式。
凭据由插件自己保存,客户端不接触 Cookie、密码和令牌。
| 操作 | 参数 | 返回 |
|---|---|---|
session | — | 已登录返回账号对象,未登录返回 nil |
loginCookie | cookie | 账号对象 |
loginPassword | account、password | 账号对象 |
sendCaptcha | phone | 任意值 |
loginCaptcha | phone、captcha | 账号对象 |
qrKey | — | 二维码 key |
qrUrl | key、web(bool)、rich(bool) | URL 字符串,或 {url, code, hint, actionUrl} |
qrCheck | key | 800 过期,801 等待扫码,802 已扫码,8821 待手机验证,803 已确认;此时宿主再查 session,账号尚未就绪会继续等待 |
logout | — | 任意值 |
return {
id = "12345678", -- 平台原始账号 ID,字符串
name = "Example User", -- 昵称
avatarUrl = "https://...", -- 头像
signature = "签名", -- 可选
membership = "VIP", -- 可选,会员名称
}
session 在客户端启动、切换平台、刷新时都会被调用,所以它必须只读、快速、无副作用。
不要在这里发登录请求,否则「未登录」状态每次刷新都要多走一次网络往返。
if operation == "qrKey" then
local body = api.post("/login/qr/key")
host.storage_set("qr.key", body.key)
return body.key
end
if operation == "qrUrl" then
-- 设备授权码流:返回 code 与跳转链接,界面会显示验证码
local body = api.post("/login/qr/create", { key = args.key })
return {
url = body.qrUrl,
code = body.userCode,
hint = "在手机上打开 App,输入下面的验证码",
actionUrl = body.browserUrl,
}
end
if operation == "qrCheck" then
local body = api.get("/login/qr/check", { key = args.key })
if body.code == 803 then
host.storage_set("cookie", body.cookie)
end
return body.code
end
宿主传入 rich = true,web 表示是否在浏览器中。返回表时,code、hint、actionUrl 也分别接受 userCode、instructions、browserUrl。
也可直接返回 URL 字符串。兼容旧插件时,宿主按顺序查找查询参数 user_code、userCode、code;取到非空验证码后,以原 URL 作为跳转链接。
host.storage_*,不要写进日志、错误文本或长期缓存。args.platform 分开存,否则两个账号会互相覆盖。logout 只清除当前平台的凭据。| 操作 | 参数 | 返回 |
|---|---|---|
search | query、limit、offset | {songs, albums, artists, playlists},四个数组 |
song | id | 歌曲对象 |
album | id | 专辑对象 |
albums | sort、limit、offset | 专辑数组 |
albumSongs | id、limit、offset | 歌曲数组 |
artist | id | 歌手对象 |
artistSongs | id、limit、offset | 歌曲数组 |
artistAlbums | id、limit、offset | 专辑数组 |
limit 与 offset 由客户端给出,插件只返回当前页。客户端会按
limit 截断,并用「返回条数是否够 limit」判断还有没有下一页。
if operation == "playlistSongs" then
local body = api.get("/playlist/track/all", {
id = args.id,
limit = args.limit,
offset = args.offset,
})
local out = {}
for _, row in ipairs(body.songs or {}) do
out[#out + 1] = toSong(row)
end
return out
end
返回满 limit 条就代表可能还有下一页。实际只有 30 条却返回了 30 条,
客户端会再请求第 2 页,拿到空页才停。按实际条数返回,不要为了结束翻页丢掉最后一条。
Lua 的空表跨边界之后是一张空 map {} 而不是 []。
客户端把「空 map」视为「没有数据」,这不算错误;但非空的 map 或标量回来会被判为无效负载。
args.sort 只会是 newest(默认,最新)或 random(随机)。
| 操作 | 参数 | 返回 |
|---|---|---|
playlists | limit、offset | 当前账号的歌单数组 |
playlist | id | 歌单对象 |
playlistSongs | id、limit、offset | 歌曲数组 |
createPlaylist | name、isPublic | 新建的歌单对象 |
addToPlaylist | playlist、songs(歌曲 ID 数组) | 任意值 |
removeFromPlaylist | playlist、indexes(从 0 开始) | 任意值 |
favorites | limit、offset | 喜欢歌单的歌曲数组 |
setFavorite | id、favorite(bool) | 任意值 |
当前账号自己的喜欢歌单要在 playlists 里标 isFavorites = true,
同时满足 writable = true 或 owner 等于当前账号 ID,客户端才会认定它;
认不出时它会用固定键造一个本地收藏歌单,你的服务端收藏就变成两套了。
保留服务端返回的名称(例如「用户名喜欢的音乐」),客户端不会再生成一份同内容的歌单。
{
id = "501",
name = "Example User喜欢的音乐",
description = "",
coverUrl = "https://...",
songCount = 512,
owner = "12345678",
writable = true,
isFavorites = true,
}
removeFromPlaylist 的 indexes 是「歌曲在当前页里的位置」,
从 0 开始,按降序删除更安全。需要服务端歌曲 ID 时请二次查询,别把页内下标当 ID 用。
if operation == "stream" then
local body = api.get("/song/url", { id = args.id, level = args.quality })
local item = body.data[1]
if not item or not item.url then
return { error = { code = 70 } } -- 当前歌曲或音质不可用
end
return {
url = item.url, -- 必须是 http(s)
contentType = "audio/mpeg",
suffix = "mp3",
bitRate = item.br,
size = item.size,
headers = { ["Referer"] = "https://example.com/" },
}
end
| 键 | 说明 |
|---|---|
url | 播放地址,必填 |
contentType | MIME 类型,例如 audio/flac |
suffix | 文件后缀,用于缓存命名 |
bitRate | 码率 |
size | 字节数 |
transcoded | 是否转码流 |
headers | 该 URL 专用的字符串键值表,例如 User-Agent、Origin、Referer。同名头不分大小写,优先级为单次取流、公共媒体规则、宿主默认值 |
args.quality 取 original、high、medium 或 low。提供不了这一档时可返回低一档的流,并如实填写 bitRate。
播放器转发播放请求时去掉预设的 Range,由解码器按需请求字节段;下载请求可保留来源的范围提示。
队列快照只存曲目标识与元数据,不保存取流 URL 或请求头。
if operation == "scrobble" then
-- submission=false 表示只上报进度,不计入播放次数
api.post("/scrobble", {
id = args.id,
time = args.playedMs,
submit = args.submission and "true" or "false",
})
return true
end
if operation == "playStats" then
local body = api.get("/user/play/records", { limit = args.limit, offset = args.offset })
local records = {}
for _, row in ipairs(body.records or {}) do
records[#records + 1] = { song = toSong(row.song), playCount = row.count }
end
return { records = records }
end
| 操作 | 参数 | 返回 |
|---|---|---|
scrobble | id、playedMs、submission、time(ISO 8601) | 任意值 |
playStats | limit、offset | {records = [{song, playCount}]};每条只读取这两项,缺省次数为 0 |
这两个操作只有 10 秒预算,因为它们跑在后台。一次卡住的上报会挤掉下一条取流请求,
所以不要在 scrobble 里做额外查询。
lyrics 返回一个歌词候选数组。客户端选第一个 synced = true 的候选;没有同步候选时选数组首项。
原文、翻译、罗马音是三条独立的轨道,可以只给其中一条。
| 键 | 类型 | 说明 |
|---|---|---|
synced | bool | 是否有时间轴 |
lines | 数组 | 逐行歌词,见下 |
lrc | string | LRC 原文 |
translation / tlyric | string | 逐行翻译 |
wordTranslation / ytlrc | string | 逐字翻译 |
romanization / romanLyric / romaji / rlyric | string | 逐行音译 |
wordRomanization / yromalrc | string | 逐字音译 |
wordByWord / yrc | string | 逐字歌词(YRC) |
ttml | string | AMLL TTML,带 x-roman / x-translation 角色 |
pureMusic | bool | 纯音乐标记 |
offsetMs | number | 整体时间偏移 |
return {
{
synced = true,
lines = {
{ text = "君へ", startMs = 1000,
translation = "给你",
romanization = "kimi e" },
{ text = "届け", startMs = 3200,
translation = "传达给你",
romanization = "todoke" },
},
},
}
每行的 text 必填,startMs 可选(缺省表示无时间的纯文本行)。
翻译与音译分别支持 translation / translatedLyric 和
romanization / romanLyric / romaji 两组别名。
普通 LRC 没有明确音译标记时,客户端不会凭语言或重复时间戳去猜音译。
要提供音译就给 romanization 轨道或 TTML 的 ttm:role="x-roman"。
用户关闭罗马音显示后,正在播放、桌面歌词和导出都会隐藏音译,原文和翻译保留。
歌词会被客户端下载并缓存,插件不需要管理本地文件。没有音译的行不会占额外空间,所以按行提供 romanization 比整段返回一个可能对不齐的字符串更稳。
这些接口都是可选的,声明了对应能力才会被调用。返回空数组合法: 客户端不会因为接口在就摆一个空模块出来。
| 操作 | 参数 | 返回 |
|---|---|---|
homeFeed | — | {featured, featuredSongs, quick, daily, recommended, playlists, albums, editorialPlaylists} |
recommendations | limit | 歌曲数组 |
savedAlbums | limit、offset | 专辑数组 |
charts | — | 歌单数组;歌曲用 playlistSongs 分页取 |
radio | kind、seed、playlist、limit | 歌曲数组 |
comments | id、limit、offset | {hot, latest, total, hasMore} |
setCommentLiked | id、commentId、liked | 任意值 |
listenTogether | operation + 其它字段 | {roomId, inviterId, members} |
exportCookie | — | 当前平台的 Cookie 字符串 |
theme | — | {theme = {...}, layout = {...}} |
kind = "personal"(私人漫游)不传种子;"artist" 的 seed 是歌手 ID。
"heart"(心动模式)传入喜欢歌单的 playlist ID,seed 若有值则为歌曲 ID。ID 均为平台的原始标识。
{
hot = { { id = "9001", content = "好听", author = "某人",
authorId = "42", avatarUrl = "https://...",
time = 1730000000000, location = "上海",
liked = false, likedCount = 12,
replies = { { author = "另一个人", content = "+1" } } } },
latest = { ... },
total = 2048,
hasMore = true,
}
评论 ID 用字符串,时间用 Unix 毫秒。所有远端 ID 都应视作不透明字符串, 不要假设它是数字。
| operation | 参数 | 说明 |
|---|---|---|
create | — | 建房,返回 roomId、inviterId |
createMulti | songId、playedTime、nextSongIds | 有当前曲目时,宿主以此操作建房;没有曲目时调用 create |
join | roomId、inviterId | 接受邀请 |
status | roomId | 房间状态与成员;不带 roomId 时取当前账号仍在的房间 |
leave | roomId | 退出或结束 |
heartbeat | roomId、songId、playStatus、progress、playlistVersion | 每 5 秒一次 |
command | roomId、command | 播放指令,见下 |
syncPlaylist | roomId | 可选,读房间队列 |
syncList | roomId、playlistVersion、playlist | 可选,上报队列与版本 |
建房与加入要求当前平台已登录并声明 listenTogether 能力。接收指令时,宿主读取 heartbeat / status 返回的房间对象中的 command,不再单独请求指令列表。
队列版本变化可触发 syncPlaylist;指令按序号去重,按 userId 忽略自己发出的指令。
建房或加入的返回值可以不带 code(缺失视为成功)。状态或心跳未带成员列表时,客户端保留上一次的成员列表。
所有模型都是普通 table。ID 在插件内部使用,客户端会把 provider、连接和实体类型编码进
MusicId,所以你只需要保证「同一个实体总是返回同一个 ID」。
| 键 | 类型 | 说明 |
|---|---|---|
id | string / number | 平台歌曲 ID,必填 |
title | string | 标题 |
artists | 数组 | 歌手对象数组,见下 |
albumId | string / number | 可空 |
albumName | string | |
coverUrl | string | 封面地址 |
durationMs | number | 时长,毫秒 |
starred | bool | 是否已喜欢 |
contentType、suffix、bitRate | — | 可选的格式信息 |
translatedTitle | string | 翻译标题 |
-- 专辑
{ id = "301", title = "Example Album", artists = { artist },
coverUrl = "https://...", year = 2024, songCount = 12,
description = "" }
-- 歌手
{ id = "42", name = "Example Artist", coverUrl = "https://...",
description = "", albumCount = 8 }
{ id = "501", name = "歌单名", description = "",
coverUrl = "https://...", songCount = 88, owner = "12345678",
writable = true, isPublic = true, isFavorites = false }
writable 决定界面是否给出编辑入口,isFavorites 决定它是不是「喜欢歌单」。
两个字段都只认 true,缺省即 false。
id 必须非空。空 ID 在第一次被当作请求参数使用时才炸,报错位置离原因很远。durationMs 缺省按 0 处理,界面会显示 0:00,尽量填上。artists 里的每一项同样按歌手模型解析,至少要有 id 和 name。"true" 字符串会被当成 false。coverUrl、owner、contentType 这类可空字段只接受字符串或
nil。传数字会直接解析失败,整次调用按无效负载处理。
trackNumber、discNumber 不会被读取,歌词的 language 同理,填了也没用。
预期内的失败返回 { error = { code, httpStatus } },客户端据此决定提示用户重新登录、
保留重试机会,还是降一档音质再试。
| 码 | 含义 | 客户端行为 |
|---|---|---|
| 40 | 未登录或登录已失效 | 提示重新登录 |
| 41 | 同上(兼容旧值) | 提示重新登录 |
| 44 | 同上(兼容旧值) | 提示重新登录 |
| 401 | HTTP 未授权 | 提示重新登录 |
| 403 | HTTP 禁止访问 | 单凭此状态不判定登录失效 |
| 429 | HTTP 限流 | 停止尝试其他远端音质,稍后重试 |
| 70 | 当前歌曲或音质不可用 | 只有这个业务码触发尝试下一档远端音质 |
| 408 | 插件调用超时(由宿主产生) | 网关对 stream 最多重试一次;不等于上游 HTTP 408 |
code 落在 400–599 会被当成 HTTP 状态解释。业务错误码请用范围外的数字,
否则一个自定义的 code = 500 会被显示成服务端故障。
业务失败应返回结构化错误表,不依赖宿主解析 Lua 异常文本。实际认证失败的判断是业务码 40、41、44,或 httpStatus = 401。
错误对象里不要放服务端响应正文或凭据,它可能出现在界面上。需要排查细节时写
host.log,日志会被脱敏。
local response = host.http({
url = "https://api.example.com/search",
method = "POST",
headers = { ["Content-Type"] = "application/json", ["Cookie"] = cookie },
body = host.json_encode({ keyword = "Miku", limit = 30 }),
})
-- response = { status = 200, headers = {...}, body = "..." }
| 项目 | 规则 |
|---|---|
| 协议 | 只允许 https,URL 不能带用户名或密码 |
| 主机 | 必须命中 permissions.network,否则 Network permission denied |
| 方法 | GET / POST / PUT / DELETE / PATCH / HEAD |
| 请求头 | host、content-length、connection 会被丢弃 |
| 重定向 | 不自动跟随,3xx 原样返回给你处理 |
| 请求体 | UTF-8 文本最多 2 MiB。默认 Web 中继不向上游发送 GET / HEAD 请求体 |
| 响应体 | 原生最多 8 MiB;默认 Web 中继最多读取 3 MiB 上游响应,封装为 JSON 后最多 4 MiB |
| 超时 | 原生连接 20 秒,整次调用 30 秒;默认 Web 中继向上游请求 25 秒,浏览器等中继最多 30 秒 |
| 返回 | {status, headers, body};多个同名响应头用换行合并 |
host.http_json 参数相同,直接把响应体解析成 table。响应体为空时返回
nil;解析失败会抛错。
第一次访问清单里的域名时,客户端会向用户申请网络授权,被拒绝的话请求根本不会发出去。
这一步在 call 内部,所以 host.http 报错时先看是不是权限问题,再怀疑网络。
host.crypto 用一张 spec 表描述运算。输入统一取 text
(也接受 input),除特别说明外返回字符串。
| operation | 额外参数 | 输出 |
|---|---|---|
md5 | — | 小写十六进制摘要 |
sha1 | — | 小写十六进制 |
sha256 | — | 小写十六进制 |
hmac | key;algorithm = sha1 / md5 / 其它(默认 sha256) | 十六进制 HMAC |
base64 | — | Base64 |
base64_decode | — | 原文 |
xor | key;encoding = hex / 其它(按 Base64 解析输入);outputEncoding = hex / utf8 / 其它(Base64) | 按 outputEncoding |
zlib_inflate | — | 输入按 Base64 解码后解压 |
zlib_deflate | — | 压缩后 Base64 |
krc_decode | — | KRC 歌词解码 |
rsa_modpow | modulus(十六进制)、exponent(默认 65537)、width(默认 256)、reverse、inputEncoding | 定宽小写十六进制 |
aes | key;mode = cbc / 其它;iv(CBC 必填);decrypt;encoding = hex / base64 | 密文或明文 |
-- 网易云式的 weapi 参数:两次 AES + 一次 RSA
local first = host.crypto({ operation = "aes", mode = "cbc",
key = presetKey, iv = presetKey, text = text })
local second = host.crypto({ operation = "aes", mode = "cbc",
key = randomKey, iv = randomIv, text = first,
encoding = "hex" })
local secret = host.crypto({ operation = "rsa_modpow",
text = second, modulus = modulus, exponent = 65537, reverse = true })
-- MD5 签名
local sign = host.crypto({ operation = "md5", text = payload .. salt })
host.crypto 面向文本签名,默认会处理编码与 PKCS7。媒体解密需要保留原始字节,
因此使用独立的 host.drm,输入可以是 base64、带 hex: 前缀的十六进制
或字节数组,输出默认是 base64。单次调用最多 8 MB。
| operation | 参数 | 返回 |
|---|---|---|
aes_block | key、mode(ecb/cbc/ctr)、iv、data、encoding | 解密后的字符串、十六进制或 base64 |
aes_samples | key、mode、iv、samples 数组、encoding | 按顺序返回解密样本数组 |
cenc_sample | key、iv、data、可选 subsamples | {data, encryptedBytes} |
rsa_decrypt | data、十六进制 modulus、privateExponent、scheme | 原始或 PKCS#1 解密结果 |
aes_cmac | key、data | 固定返回 Base64 标签 |
constant_time_equals | a、b | 布尔值 |
-- 一个 CENC 样本:16 字节明文、32 字节密文、16 字节明文
local result = host.drm({
operation = "cenc_sample",
key = "hex:2b7e151628aed2a6abf7158809cf4f3c",
iv = "hex:000102030405060708090a0b0c0d0e0f",
data = sampleBase64,
subsamples = { { 16, 32 } },
})
if result.error then
host.log("warn", "CENC decrypt failed", { reason = result.error })
return nil
end
local plainBase64 = result.data
CBC 和 ECB 要求密文长度是 16 字节的整数倍,CTR 接受任意长度。CENC 的
subsamples 按 {clearBytes, encryptedBytes} 交替描述样本,
加密区尾部不足一个块时由 CTR 处理。输入校验失败会返回 {error="..."},
当前原生与 Web 宿主均报告 drm 特性,没有单独的清单权限或运行时授权项。
xor 的 key 为空时原样返回输入,不做任何解码,
这是给线上格式随账号变化的接口留的退路,不要拿它当加密。
zlib_* 与 krc_decode 失败返回空字符串,不抛错。
| 函数 | 说明 |
|---|---|
host.json_encode(value) | 编码为 JSON 字符串 |
host.json_decode(text) | 解析 JSON |
host.url_encode(text) / host.url_decode(text) | URL 百分号编码与解码 |
host.now() | Unix 毫秒时间戳(整数) |
host.random_hex(count) | 安全随机十六进制,count 1–1024,默认 16,输出长度 2×count |
host.sleep(ms) | 异步挂起 0–60000 毫秒,适合轮询与限流 |
host.log(level, message, data) | 写入宿主诊断日志;level 默认 info,消息截断到 2048 字符 |
host.info() / host.plugin_info() | 清单、运行时类型与可用特性 |
这三个函数只做字符串处理,不发请求。客户端用它把散落的
Set-Cookie 拼成一条能直接塞进请求头的 Cookie。
| 函数 | 行为 |
|---|---|
host.cookie_compact(text) | 丢掉 domain、path、expires、httponly、secure、samesite 等属性,只留 名=值 |
host.cookie_field(text, name) | 取出某个字段的值,没有则返回 nil |
host.cookie_merge(previous, updates) | 合并响应里的新 Cookie,保留没被覆盖的旧字段 |
local response = host.http({ url = url, method = "POST", body = form })
local merged = host.cookie_merge(
host.storage_get("cookie") or "",
response.headers["set-cookie"]
)
host.storage_set("cookie", merged)
{
runtime = "native", -- 或 "web"
plugin = "community.example.music",
name = "Example Music",
version = "1.0.0",
apiVersion = 1,
provider = "example",
capabilities = { ... },
auth = { ... },
permissions = { network = {...}, data = {...}, storage = true, ... },
features = { "http", "crypto", "drm", "storage", "resources", "player",
"player_lyrics", "player_recent", "frontend_library", "frontend_user",
"data_permissions", "native_host_v1", "websocket", "sleep", "pages",
"page_edit", "timer", "filesystem", "appearance", "socket" }, -- Web 无 socket
}
features 是字符串数组,用 ipairs 检查成员;它不是按名称索引的表,也不是用户的授权清单。
两端都报告 websocket,都没有单独的 websocket_server 标志;只有原生报告 socket。
音频引擎、桌面歌词等操作的支持状态请查 host.native()。
清单声明 "storage": true 即可使用,无需单独授权。值按 JSON 序列化;原生端将其存入插件自己的文件,
Web 端使用浏览器存储,受浏览器配额限制。
| 函数 | 说明 |
|---|---|
host.storage_get(key) | 取值;不存在返回 nil |
host.storage_set(key, value) | 写入;value 为 nil 即删除该键 |
host.storage_keys() | 返回已排序的键数组 |
host.storage_clear() | 清空本插件的所有键 |
local key = "session." .. args.platform
host.storage_set(key, { cookie = cookie, uid = uid, expiresAt = host.now() + 86400000 })
local session = host.storage_get(key)
if session and session.expiresAt < host.now() then
host.storage_set(key, nil) -- 过期即删除
session = nil
end
没有声明 storage 时,storage_get 与 storage_keys
静默返回 nil / 空表,而 storage_set 与 storage_clear
会抛错。原生端全部键值序列化后的 UTF-8 数据超过 1 MiB 时,写入报 Storage full。
host.file(spec) 与 host.files(spec) 是同一接口。声明 "filesystem": true 并获用户授权后,可读写本插件的文件。
根目录固定为插件的 files 目录,所有路径都是相对路径,越界与符号链接一律拒绝。
| operation | 参数 | 返回 |
|---|---|---|
read | path、encoding | 字符串 / 字节数组 / Base64 |
write | path、data、encoding | {path, size} |
append | 同上 | {path, size} |
exists | path | 布尔 |
stat | path | {path, type, size, modifiedMs} 或 nil |
list | path(可为空表示根) | [{name, path, type, size}] |
mkdir | path | true |
delete | path、recursive | 删除成功 true,目标不存在 false |
| encoding | 读 | 写 |
|---|---|---|
"binary" | 字节数组(0–255 的整数表) | 按默认文本处理 |
"base64" | Base64 字符串 | 先解码再写入 |
| 缺省 | UTF-8 文本 | UTF-8 文本,或 0–255 整数数组 |
host.file({ operation = "mkdir", path = "cache" })
host.file({ operation = "write", path = "cache/state.json",
data = host.json_encode({ version = 2 }) })
local state = host.json_decode(
host.file({ operation = "read", path = "cache/state.json" }))
for _, entry in ipairs(host.file({ operation = "list", path = "cache" })) do
host.log("debug", "cached", { path = entry.path, size = entry.size })
end
单文件 4 MB、插件总量 16 MB、目录项最多 2048 个。delete
默认只删除空目录,要删目录连同内容必须显式传 recursive = true。
Web 端的 stat.modifiedMs 恒为 0,别用它判断文件新旧。
随包携带的文本文件可以直接读出来,不需要文件权限。只读、只在本包内、安装时已载入内存。
| 函数 | 说明 |
|---|---|
host.resource(path) | 读取资源文本;不存在返回 nil |
host.read_resource(path) | 同上(别名) |
host.resource_keys() | 列出所有资源路径,升序 |
-- data/keys.json 随包携带,用来放公钥或固定表
local keys = host.json_decode(host.resource("data/keys.json") or "{}")
-- frontend/ 里的 HTML/CSS/JS 也是资源
local page = host.resource("frontend/index.html")
可读的类型是 .json、.md、.txt、.html、
.css、.js、.svg。路径必须是安全相对路径,
且大小写要与 ZIP 内一致。
宿主不会执行这些 JavaScript,也不会因此获得宿主文件系统访问权限。 把前端页面放进包里只是让插件把它读出来发给外部浏览器或 WebSocket 客户端。
host.timer({ id = "poll", intervalMs = 200 }) -- 注册,返回 true
host.timer({ operation = "list" }) -- 当前 id 数组
host.timer({ operation = "cancel", id = "poll" }) -- 取消
-- 周期回调以 call 的形式回到插件
if operation == "timer" and args.id == "poll" then
drainSocket()
return true
end
| 规则 | 数值 |
|---|---|
| 周期 | 100–60000 ms |
| 每个插件上限 | 4 个 |
| 同时在途的回调 | 4 个 |
| 回调堆积 | 同一个 id 已有回调在跑时,本次 tick 直接丢弃,不排队 |
tick 会被合并丢弃,所以不要指望「每秒恰好一次」。需要累积计数就用
host.now() 计算真实间隔。不要在回调里写死循环,它和普通调用共享同一份指令预算。
host.player_control({ command = "play" })
host.player_control({ command = "seek", positionMs = 30000 })
host.player_control({ command = "volume", volume = 0.8 })
host.player_control({ command = "repeat", mode = "all" })
host.player_control({ command = "shuffle", enabled = true })
local state = host.player_state() -- 播放状态
local queue = host.player_queue() -- 队列
local track = host.player_track() -- 当前歌曲,可能为 nil
local lyrics = host.player_lyrics() -- 当前歌词
local recent = host.player_recent() -- 最近播放(需要 history 权限)
| command | 参数 | 返回 |
|---|---|---|
play / pause / stop / toggle / next / prev | — | true |
seek | positionMs 或 fraction(0–1) | true / false |
volume | volume(限制在 0–1) | true / false |
play_index | index | true / false(越界) |
shuffle | enabled | {shuffle, repeat} |
repeat | mode = off / all / one | {shuffle, repeat} |
status | — | 播放状态表 |
queue | — | {index, currentIndex, length, revision, shuffle, repeat, tracks} |
track | — | 当前歌曲表。通用 host.player_control 会把空结果转成 true;判断有无当前曲目请用 host.player_track() |
lyrics | — | {loading, pureMusic, imported, lines = [{text, time, startTime, ...}]} |
recent | — | 最近播放数组(最多 100 条) |
播放状态表包含 state、positionMs、durationMs、
volume、bufferedPositionMs、audioReady、
queueIndex、queueLength、shuffle、repeat
与 track。
host.player_status() 等同于 host.player_state();host.now_playing() 等同于 host.player_track()。
当前没有曲目时,后两种取曲目写法均返回 nil;先用 if track then 判断再读字段。
这些接口通过客户端访问资料库、账号和本机统计,使用前须声明相应的数据权限并取得用户同意。 搜索、歌单和专辑可能查询当前音乐平台;网关处理自己的目录时应直接调用插件内部函数,避免递归请求自己的网关。
| 函数 | 权限 | operation |
|---|---|---|
host.library(spec) | library | playlists(默认) |
tracks:id 指定的歌单曲目 | ||
album:id 指定的专辑曲目 | ||
local:本地音乐条目 | ||
play:kind = song / album / playlist,id、index | ||
search:等同于 host.search(spec) | ||
host.search(spec) | library | query(非空白,最多 256 字符);tracks、playlists、albums、artists 各自是一页,例如 result.tracks.items |
host.user(spec) | profile | profile(默认)、platforms |
history | statistics:range = today / last7Days / last30Days / allTime | |
host.permissions() | — | {declared, granted}:已声明和已获准的数据权限名称数组,不含网络、文件等授权 |
host.request_permission(scope) | — | 返回布尔值;未声明的 scope 直接 false |
-- 在用户点击按钮之后申请,不要在启动阶段申请
if not host.request_permission("library") then
return { error = { code = 403 } }
end
local lists = host.library({ operation = "playlists", limit = 50, offset = 0 })
for _, item in ipairs(lists.items) do
host.log("debug", "playlist", { name = item.name, count = item.trackCount })
end
local result = host.library({ operation = "search", query = "Miku", limit = 10 })
local tracks = result.tracks.items
if host.request_permission("history") then
local stats = host.user({ operation = "statistics", range = "last7Days" })
-- stats.skipCount 和 stats.durationMs 来自本机统计,而非平台的 playStats
end
分页结果统一是 {items, offset, limit, total, hasMore},offset
从 0 开始,limit 默认 50、上限 200。数据权限被拒绝时抛
Plugin data permission denied(code 403)。
账号 Cookie、密码、令牌、可播放音源 URL 和本地文件路径都不会通过这些接口导出。 本地文件封面也不会暴露绝对路径。
local caps = host.native() -- 等同 host.native({ operation = "capabilities" })
if caps.operations["audio.status"].supported then
local ok, result = pcall(host.native, { operation = "audio.status" })
if ok and result.ok then
-- result.data.source / result.data.output / result.data.metrics
end
end
| operation | 数据权限 | 成功时的返回值 |
|---|---|---|
capabilities(默认) | — | 顶层 {ok, supported, version, platform, operations, desktopLyrics};每个操作列出 supported 和 permission |
audio.status | native_audio | data 含引擎、流状态及 source、output、metrics |
audio.devices | native_audio | data.items 为缓存设备摘要,最多 64 项;index 从 0 开始,仅对本次快照有效 |
lyrics.status | native_control | data 含 mode、locked、lines、desktopSupported;表示请求的设置,不代表歌词窗口已打开 |
lyrics.configure | native_control | 至少给一项:mode(off / floating / desktop)、布尔 locked 或整数 lines(1–5)。成功后 data 同 lyrics.status |
能力探测不申请数据权限。其他操作成功时读 result.data;平台、引擎或操作不支持时返回 ok = false、supported = false 和 error.code,参数不合法时可返回 invalid_argument。
权限检查在操作执行前进行:未声明、用户未同意、授权被撤销或插件已停用,都会抛出异常(403),不是 supported = false。用 pcall 区分这两条路径。
除了 HTTP,插件还能开 TCP socket、WebSocket 连接,甚至在本机监听端口。 自建服务、外部前端、本地桥都走这条路。
| 接口 | 清单权限 | 运行时授权 |
|---|---|---|
host.socket(spec) | permissions.socket(为空时回退 network) | socket |
host.socket_server(spec) | permissions.socketServer(为空时回退 websocketServer) | socketServer |
host.websocket(spec) | permissions.websocket(ws / wss) | websocket |
host.websocket_server(spec) | permissions.websocketServer | websocketServer |
主动连接用 id 区分,省略时为 "default"。TCP 的 connect(默认,别名 open)接收 host、port 和可选 timeoutMs,返回 {id, host, port};WebSocket 的 open(默认)接收 url,成功返回 true。
打开后,两者都通过同一 id 调 send(data 为文本或字节数组)、receive(可选 timeoutMs)与 close。成功发送、关闭均返回 true。
TCP 每次接收一个数据块:format = "binary" 返回字节数组,"text" 返回 UTF-8 文本;省略时优先解码 UTF-8,失败则返回字节数组。WebSocket 按消息帧返回文本或字节数组。
-- manifest: "permissions": { "websocketServer": ["127.0.0.1:11444"] }
local listener = host.websocket_server({
operation = "listen", id = "lyrics", host = "127.0.0.1",
port = 11444, path = "/lyrics",
})
local client = host.websocket_server({ operation = "accept", id = "lyrics", timeoutMs = 0 })
if client then
host.websocket_server({ operation = "send", id = "lyrics",
clientId = client.clientId, data = host.json_encode({ type = "hello" }) })
end
| 服务端 operation | 说明 |
|---|---|
listen(默认) | host 默认 127.0.0.1,port 默认 0(系统分配);返回 {id, host, port},其中 port 为实际端口。TCP 也接受 bind;只有 WebSocket 可用 path 限定握手路径 |
accept | TCP 返回 {clientId, remoteAddress, remotePort},WebSocket 返回 {clientId, address};超时返回 nil |
clients | 当前客户端 ID 数组 |
send / receive | 用 clientId 指定连接 |
broadcast | 发送 data,返回本次发送的连接数,不表示对端已确认接收 |
close_client / close | 关闭单个连接 / 关闭服务端 |
| 限制 | 数值 |
|---|---|
| 每个插件的 TCP / WebSocket 服务端 | 各 4 个 |
| 每个服务端的客户端 | 32 个 |
| 主动连接(TCP / WebSocket) | 各 16 个 |
| 单条消息 | 1 MB |
| 单连接接收队列 | 128 条 / 4 MB |
接收超时 timeoutMs | 0–30000 ms,默认 30000 |
timeoutMs = 0 只检查已到达的数据,立即返回,在计时器里轮询时用它,
免得长时间占住串行队列。accept 与 receive 超时返回 nil,
不抛错,也不会关闭连接。
Web 端可用 host.websocket 主动连接;host.websocket_server 虽已注册,调用会报不支持。
TCP 的 host.socket 与 host.socket_server 在 Web 上均为 nil。
插件可以在设置页里加自己的控件。提交的是数据,控件由宿主创建; 它拿不到 Widget,也接管不了输入、焦点和无障碍树。
local quality = host.add_setting({
id = "quality", -- [a-zA-Z0-9_.-]{1,64}
type = "select", -- toggle / select / text / number / action
title = "音质", -- ≤ 120,必填
subtitle = "选择播放音质", -- ≤ 240
default = "standard",
options = {
{ value = "standard", label = "标准" },
{ value = "high", label = "高" },
{ value = "lossless", label = "无损" },
},
})
-- quality 是宿主持久化后的当前值
| type | 别名 | 专属字段 | 值类型 |
|---|---|---|---|
toggle | switch、boolean | — | 布尔,默认 false |
select | choice | options(1–32 项,value ≤128 且唯一,label ≤120) | 必须是某个 option 的 value |
text | string | — | 字符串,≤ 2048 字符 |
number | slider | min、max、step(需满足 max > min、0 < step ≤ max − min) | 区间内的数字 |
action | button | — | 不保存值 |
每个插件最多 64 个设置项,重复的 id 会更新已有项而不是新增。
add_setting 的返回值就是当前值,宿主已经把用户上次的选择读回来了,
你不需要自己再存一份。
if operation == "setting_changed" then
-- args.id / args.value;action 类型的 value 为 nil
if args.id == "quality" then
currentQuality = args.value
end
return true
end
设置值由宿主持久化,你也拿不到「尚未保存」的中间态。
action 类设置不保存任何值,它的变化同样以
setting_changed 送达,value 为 nil。
host.add_page({
id = "tools",
title = "工具",
subtitle = "插件工具页",
icon = "settings",
elements = {
{ type = "section", title = "常用操作" },
{ type = "text", text = "这段说明由宿主渲染。" },
{ type = "toggle", id = "enabled", title = "启用功能", value = true },
{ type = "select", id = "mode", title = "模式", value = "a",
options = { { value = "a", label = "模式 A" }, { value = "b", label = "模式 B" } } },
{ type = "slider", id = "volume", title = "强度", min = 0, max = 100, step = 5, value = 50 },
{ type = "text_field", id = "query", title = "关键词", placeholder = "输入关键词" },
{ type = "button", id = "refresh", title = "刷新", icon = "refresh" },
},
})
| type | 别名 | 需要 id | 说明 |
|---|---|---|---|
text | label | 否 | 纯文本,text ≤ 4000 字符 |
section | heading | 否 | 分组标题 |
divider | — | 否 | 分隔线 |
spacer | — | 否 | 空白间距 |
button | action | 是 | 点击后送回 page_event |
toggle | switch、boolean | 是 | 布尔值 |
select | choice | 是 | 1–32 个选项 |
slider | number | 是 | min / max / step |
text_field | textfield、input | 是 | maxLines 1–12,默认 4 |
| 元素字段 | 限制 |
|---|---|
id | ^[a-zA-Z0-9_.-]{1,64}$,同一页内不能重复 |
title / label | ≤ 120;交互型元素必填 |
subtitle / description | ≤ 240 |
text / content | ≤ 4000 |
icon | ≤ 40 |
placeholder | ≤ 120 |
value | toggle 为布尔值,select 须命中选项,slider 须在区间内。页面 text_field 最多 16384 字符;设置项的 text 上限为 2048 字符。 |
| 上限 | 数值 |
|---|---|
| 每个插件的页面 | 16 |
| 每页的控件 | 128 |
if operation == "page_event" then
-- args.page / args.id / args.value
if args.page == "tools" and args.id == "refresh" then
reload()
end
return true
end
页面注册之后仍然可以在运行时改写:换标题、调间距、插入或删除控件。 所有编辑都提交纯数据,由宿主校验后写入界面,且只作用于该插件自己的页面。
| 接口 | 用途 |
|---|---|
host.page(id) | 读取页面当前描述 {id, title, subtitle, icon, layout, elements} |
host.pages() | 列出本插件页面的概要,elements 是控件数量 |
host.update_page(spec) | 改写标题、副标题、图标与布局 |
host.set_page_elements(spec) | 整体替换控件列表;elements = {} 清空页面 |
host.add_page_element(spec) | 新建控件;用 at、before、after 定位,缺省追加 |
host.update_page_element(spec) | 按 element / id / index 局部改写;未提交的字段保持原样 |
host.remove_page_element(spec) | 删除控件 |
host.move_page_element(spec) | 调整顺序;to 是目标位置(从 1 起)或目标控件 ID |
host.update_page({
page = "tools",
title = "工具箱",
gap = 18, -- 控件之间的间隙,0–96
inset = 14, -- 页面左右内边距,0–96
maxWidth = 720, -- 内容宽度上限,0 表示跟随应用布局,上限 2400
align = "center", -- start / center / end / stretch
direction = "grid", -- vertical / horizontal / grid
columns = 2, -- grid 列数 1–4
card = true, -- 是否保留分组卡片外观
header = true, -- 是否保留标题与副标题
})
host.add_page_element({ page = "tools", before = "refresh", type = "toggle",
id = "auto_sync", title = "自动同步", value = true })
host.update_page_element({ page = "tools", id = "auto_sync", title = "自动同步收藏" })
host.move_page_element({ page = "tools", element = "auto_sync", to = 1 })
host.remove_page_element({ page = "tools", element = "auto_sync" })
-- 读取宿主侧的真实状态,再决定下一次编辑
local page = host.page("tools")
local count = #page.elements
布局键既可以平铺在 spec 顶层,也可以写成嵌套的 layout = { ... }。
数值会被限制在允许范围内,无法识别的 align、direction
或控件字段会直接报错,不会被静默忽略。
update_page_element 只覆盖你传入的字段。用户已经拨好的开关和滑块值
不会因为你改了一句文案就丢失。
插件能换皮,换的只是一组数值和字重,没有 Widget 树。 页面、焦点、语义树和输入始终归宿主;未知字段忽略,越界数值回退到允许范围。
if operation == "describe" then
return { providers = { ... }, theme = true } -- 声明后再实现 theme 操作
end
if operation == "theme" then
return {
theme = {
id = "example.dark",
name = "Example Dark",
elements = {
groupedCardRadius = 18,
cornerScale = 0.5,
railWidth = 232,
listTileMinHeight = 52,
pageTitleCompactSize = 36,
displayWeight = 800,
titleWeight = 700,
lyricWeight = 500,
lyricLineHeight = 1.55,
lyricTranslationGap = 6,
lyricSpringStiffnessScale = 1.1,
lyricStaggerDelay = 0.04,
},
},
layout = {
id = "example.compact",
name = "Example Compact",
compactInset = 18,
regularInset = 28,
maxContentWidth = 1080,
},
}
end
| 令牌 | 默认 | 范围 |
|---|---|---|
groupedCardRadius | 14 | 0–40 |
cornerScale | 1 | 0–2(组件类表面的系数;卡片圆角见 groupedCardRadius) |
capsuleRadius / navBarRadius | 0 | 0–64(插件令牌;胶囊与导航栏圆角) |
pageTitleWeight / playerBarArtistWeight | 0 | 0–900;0 沿用原字重 |
pageTitleSubtitleGap / playerBarArtistSize | 0 / 0 | 0–96 / 0–48;歌手字号为 0 时沿用原字号 |
railWidth | 0(自适应 216–264) | 0–420 |
playerBarHeight / compactPlayerBarHeight | 0 / 0 | 0–200 / 0–160 |
listTileMinHeight | 50 | 0–160 |
listTileVerticalPadding | 11 | 0–48 |
trackHoverDurationMs | 120 | 40–1000(歌曲行悬浮遮罩的过渡时长,0 会被抬到这个下限) |
pageTitleCompactSize / pageTitleRegularSize | 34 / 32 | 0–72 |
sectionHeaderSize | 20 | 0–48 |
controlRadius | 12 | 0–40 |
glassBlurSigma | 16 | 0–48 |
displayWeight / headingWeight | 700 | 100–900 |
titleWeight / labelWeight | 600 / 500 | 100–900 |
bodyWeight | 400 | 100–900 |
lyricWeight / lyricTranslationWeight | 跟随主题 | 100–900 |
lyricFontScale | 1 | 0.5–2 |
lyricTranslationScale | 0.73 | 0.4–1.5 |
lyricLineHeight / lyricTranslationLineHeight | 1.5 / 1.45 | 0.8–3 |
lyricTranslationGap | 5 | 0–48 |
lyricDimAlpha / lyricTranslationAlpha | 0.48 / 0.58 | 0–1 |
lyricTextAlign | start | start / center / end / justify |
lyricSpringMassScale、lyricSpringStiffnessScale、lyricSpringDampingScale | 1 | 0.25–4 |
lyricStaggerDelay | 0.05 | 0–0.5 |
lyricStaggerDecay | 1.05 | 1–2 |
lyricFocusScaleDelta | 3 | 0.5–20 |
| 令牌 | 默认 | 范围 |
|---|---|---|
compactInset | 16 | 0–80 |
regularInset | 24 | 0–120 |
tvInsetFactor | 0.043 | 0–0.25 |
maxContentWidth | 1180 | 0–3000 |
tvMaxContentWidth | 1560 | 0–4000 |
tabletBreakpoint | 700 | 320–1600 |
皮肤出错只会被忽略,不会让音乐平台启动失败,也就是说令牌名写错时不会有报错,只是没有效果。 改完对着上表核一遍拼写。皮肤同样接管不了焦点、语义树、输入或权限。
elements.colors 与 elements.darkColors 覆盖宿主的语义颜色,
宿主仍然掌管对比度、焦点、语义树和所有 Widget。槽位名与内置 Apple 调色板一致,
也接受 canvas、ink、hairline、clay、
playerSurface 这类别名;值写 #rgb、#rrggbb、
#aarrggbb、0xAARRGGBB 或 32 位无符号 ARGB 整数都行。这些写法适用于皮肤槽位,不适用于 host.set_colors 的 accent。
darkColors 不写就沿用 colors,只做浅色的皮肤不用写两遍。
| 槽位 | 用途 |
|---|---|
background / groupedBackground | 页面画布、分组列表底 |
secondaryBackground / tertiaryBackground | 画布上浮的两层 |
secondaryGroupedBackground / tertiaryGroupedBackground | 卡片、列表行 |
label / secondaryLabel / tertiaryLabel / quaternaryLabel | 主文字 → 最弱文字 |
fill / secondaryFill / tertiaryFill | 高亮底、主打卡片底、未激活轨道(开关关闭态、滑块底、进度条底) |
separator / opaqueSeparator | 发丝线与不透明分隔 |
accent / accentSoft | 唯一强调色与它的低透明度版本(浅色约 9%,深色约 15%) |
glass / glassStrong | 玻璃材质与播放条表面 |
elements = {
colors = {
canvas = "#F0EEE6", -- 别名 → background
surface = "#FAF9F5", -- 别名 → secondaryGroupedBackground
ink = "#141413", -- 别名 → label
muted = "#87867F", -- 别名 → secondaryLabel
hairline = "#CCCBC8", -- 别名 → separator
clay = "#D97757", -- 别名 → accent
playerSurface = "#141413", -- 别名 → glassStrong
},
darkColors = { background = "#191918", label = "#F0EEE6" },
}
监听画布可以整块交给皮肤排版:左栏封面、间距、一条竖发丝线、右栏阅读面。
这些值全为 0 时沿用内置的等比两栏,给了才走皮肤的版心。
| 令牌 | 默认 | 范围 | 作用 |
|---|---|---|---|
nowPlayingArtworkFraction | 0 | 0–0.9 | 左栏宽 = clamp(宽 × 系数, min, max);0 关闭皮肤版心 |
nowPlayingArtworkMin / nowPlayingArtworkMax | 0 / 0 | 0–1200 | 上面那条 clamp 的下限与上限 |
nowPlayingSidePadding | 0 | 0–200 | 画布左右留白;0 跟随 4% clamp 28–80。同族的 nowPlayingSidePaddingMax 目前只做校验与序列化,还没接进排版 |
nowPlayingTitleSize / nowPlayingSubtitleSize / nowPlayingMetaSize | 0 / 0 / 0 | 0–96 / 0–72 / 0–72 | 曲名、翻译行、歌手字号;0 跟随内置档位 |
nowPlayingCoverRadius / nowPlayingDockHeight | 0 / 0 | 0–64 / 0–240 | 封面圆角(> 0 才覆盖全局圆角设置)、底部传输 dock 高度 |
backgroundPlayMode | "" | off / nowPlayingStatic / nowPlayingDynamic | 分别接受别名 none、static、dynamic。依次为关闭、静态和动态专辑色流;空串或未知值沿用用户设置 |
backgroundOpacity / backgroundBlurSigma / backgroundVeilAlpha | 1 / -1 / -1 | 0–1 / -1–96 / -1–1 | 背景层不透明度、模糊、遮罩;-1 = 沿用用户设置 |
令牌是默认值,不是强制值。两处用户设置能压过皮肤, 因为它们是用户自己调出来的:
| 用户设置 | 相关令牌 | 谁生效 |
|---|---|---|
| 设置 → 外观 → 圆角设置 | 卡片:groupedCardRadius;按钮/胶囊:cornerScale |
「跟随主题设置」时卡片用皮肤的 groupedCardRadius、组件用 cornerScale;
「自行调节」时用户的 px 直接压过 groupedCardRadius,组件按 px / 16 缩放
|
| 字体自定义 → 某分类字重 / 歌词字重 | displayWeight、titleWeight、bodyWeight、labelWeight、lyricWeight |
用户动过就用户说了算,没动过才用皮肤 |
| 字体自定义 → 字体族 / 字号缩放 | — | 皮肤不能指定字体族,也不参与缩放 |
圆角设置的单位是 px,滑块一直都在:
groupedCardRadius,
设置页显示的也是这个数(例如皮肤写 groupedCardRadius = 0,
设置里就写「0 px(主题)」,看着是直角就是直角)。
0 px 全直角、
16 px 等于组件原本的圆角、32 px 加倍。
这个值直接替换卡片的圆角,而不是乘在皮肤的 0 上 ——
否则皮肤只要写 0,滑块就永远调不动。往里一拖会自动切到「自行调节」。
常规组件跟随主题的 cornerScale,自行调节时按 px / 16 缩放。
胶囊和底部导航栏各有独立的圆角来源:跟随主题时分别读 capsuleRadius 和 navBarRadius,也可跟随全局值或由用户手动设置。
封面也走这一套:歌单/专辑封面、「最近播放」里的小卡片都用同一个卡片圆角,
客户端里就是 AppCover 与 AppArtistTrackCard 读
AppleShape.cardRadiusOf。
AppCover 自带一个「短边四分之一」的上限:44 px 的列表缩略图在 24 px 设置下
收到 11 px,不会变成圆形;大封面(160、190、270+)碰不到这个上限,完全跟着设置走。
首页那张 330 px 的推荐封面自己传的是 followCornerSetting: false,
圆角由外层 ClipRRect 按卡片圆角裁出来。
播放队列另外走 AppleShape.thumbnailRadiusOf。
头像(ClipOval)、圆形播放指示、被外层裁过的拼贴小块显式关闭
(followCornerSetting: false),保持固定形状。
两端都在插件启动时加载皮肤。原生端还会在 setting_changed / page_event 之后重读 describe 及其声明的主题;失败时保留上一份皮肤。
Web 端没有这步热重读。需要根据设置调整的令牌请在宿主读取主题时计算。
皮肤令牌是插件自己的皮,强调色是应用本身的颜色。清单里声明
permissions.appearance 之后,host.colors()
读当前设置,host.set_colors 改它。改的就是设置页里那个强调色,
用户随手再改一次也会覆盖插件的结果,两边不各存一份。
local current = host.colors()
-- { ok = true, mode = "custom", accent = "#FF3B30" }
host.set_colors({ accent = "#0A84FF" }) -- accent 自带 mode = "custom"
host.set_colors({ mode = "nowPlaying" }) -- 跟随封面取色
host.set_colors({ mode = "fixed" }) -- 回到默认配色,保留用户存过的自定义色
mode 取 fixed、nowPlaying、
custom;accent 只认 #RRGGBB,
短写和 0x 前缀会被拒绝,免得插件和取色器对「同一个颜色」有不同理解。
只给 accent 等同于 mode = "custom";显式指定 custom 也可给颜色,与 fixed 或 nowPlaying 同传则报错。未知键、未知模式也报错。
host.colors() 返回 {ok, mode};有自定义色值时才附带 accent。
宿主主动触发的调用同样走 call,只是 args 的形状不同。
它们不带 args.platform,需要区分平台时自己从会话里取。
| operation | args | 触发时机 |
|---|---|---|
setting_changed | id、value | 用户改了设置项 |
page_event | page、id、value | 用户操作了插件页面上的控件 |
player_menu | id、track | 用户点了正在播放页的菜单项 |
player_event | type、data;data 的各字段也出现在 args 顶层 | track:曲目 ID 改变;queue:队列修订号改变;lyric:歌词更新;status:播放状态或进度 |
timer | id | 计时器周期到达 |
if operation == "player_event" then
if args.type == "track" then
pushNowPlaying(host.player_track())
elseif args.type == "status" then
pushStatus(host.player_state())
end
return true
end
player_events 要在清单的 capabilities 里声明,
且按精确字符串匹配(player_events 或 player-events),写进 describe 不算数。
拖动进度条不会单独触发 track。播放中的 status 约每秒更新,状态变化时也会广播;lyric 含 lyric 行数组(text、毫秒 startTime / endTime)及 pureMusic。
每次 player_event 预算 1500 毫秒,与播放请求共用串行队列。
storage 和 appearance 只需在清单声明,不另行弹窗。网络、连接、文件沙箱和私有数据除了声明范围,还须取得对应的运行时授权。
host.permissions() 只列出 permissions.data 的声明与授权;host.info().permissions 列出清单声明,不代表实际授权状态。
| 键 | 类型 | 上限 | 用途 |
|---|---|---|---|
network | 字符串数组 | 32 | host.http 的目标主机 |
socket | 字符串数组 | 32 | TCP 连接目标;为空时回退 network |
socketServer | host:port 数组 | 16 | TCP 监听地址 |
websocket | 字符串数组 | 32 | WebSocket 连接目标 |
websocketServer | host:port 数组 | 16 | WebSocket 监听地址 |
storage | 布尔 | — | 键值存储 |
appearance | 布尔 | — | 读取和修改全局强调色,见 全局强调色 |
filesystem | 布尔 | — | 文件沙箱;也接受 files / file 别名 |
data | 字符串数组 | 5 | 本地资料权限,见下 |
| scope | 可读取的内容 | 界面文案 |
|---|---|---|
library | 歌单、指定歌单/专辑曲目、本地音乐条目、搜索、按目录 ID 播放 | 歌单与音乐库 |
profile | 已连接平台与能力、当前平台、账号原始 ID、昵称、头像 | 平台与账号资料 |
history | 最近播放、播放次数、跳过次数、收听时长 | 播放记录与统计 |
native_audio | 原生音频格式、输出条件、缓冲与欠载指标、设备名称摘要 | 原生音频诊断与设备摘要 |
native_control | 桌面/悬浮歌词的开关、锁定与显示行数 | 桌面与悬浮歌词控制 |
"permissions": {
"network": ["api.example.com", "*.example-cdn.com"],
"socket": ["127.0.0.1:9000"],
"socketServer": ["127.0.0.1:0"],
"websocket": ["socket.example.com"],
"websocketServer": ["127.0.0.1:11444"],
"storage": true,
"filesystem": true,
"data": ["library", "profile"]
}
监听地址必须是明确的 IP 或 localhost,不支持通配域名。
调用时传 port = 0 由系统分配端口。WebSocket 监听必须与声明端口精确匹配;TCP 声明端口为 0 时也允许在同一主机指定端口。
socketServer 为空时回退到 websocketServer 的绑定声明,运行时仍申请 TCP 服务端授权。
授权按插件存储,用户在插件详情里可以逐项撤销。撤销不需要重启插件, 正在加载但尚未返回 Lua 的私密数据也会被丢弃。
| 时机 | 行为 |
|---|---|
| 插件更新 | 重新申请全部权限 |
| 首次使用网络 | 对清单允许的目标,按插件申请 network 授权,不逐域名弹窗;每个请求仍校验目标地址 |
| 首次调用数据接口 | 触发对应的数据权限申请;拒绝则抛错 |
| 用户撤销 | 下一次调用立即失败;进行中的请求结果被丢弃 |
| 停用或卸载 | 关闭该插件所有的连接与监听端口 |
-- 主动申请:用户拒绝时返回 false,不抛错
if not host.request_permission("library") then
return { error = { code = 403 } }
end
-- 查看当前状态
local state = host.permissions()
-- state.declared = { "library", "profile" }
-- state.granted = { "library" }
不要在插件启动或 describe 阶段申请数据权限:安装探测阶段没有宿主资料接口,
而且一装好就弹窗的用户体验很差。等到用户点了按钮、菜单项或外部前端发来明确请求时再申请。
客户端不内置插件目录,它直接读市场清单:https://lazer.naominet.dev/plugin/plugins.json。
加一个插件就是往里的 plugins 数组追加一项。
{
"id": "community.example.music",
"name": { "zh-CN": "示例音乐", "en": "Example Music" },
"summary": { "zh-CN": "把示例音乐接进播放器" },
"author": "YOUR NAME",
"type": "open-source",
"version": "1.0.0",
"license": "MIT",
"repo": "https://github.com/OWNER/REPO",
"download": "https://lazer.naominet.dev/plugin/YOUR_NAME/community.example.music/1.0.0/community.example.music.zip",
"homepage": "https://github.com/OWNER/REPO",
"platforms": ["windows", "macos", "linux", "android"],
"tags": ["music", "streaming"],
"minAppVersion": "2.0.0",
"updatedAt": "2026-11-23"
}
| 字段 | 必填 | 校验 |
|---|---|---|
id | 是 | ^[a-z][a-z0-9_.-]{2,79}$,全局唯一,必须与 ZIP 内清单一致 |
name / summary | 是 | 字符串,或 { "zh-CN": "...", "en": "..." } 映射 |
author | 是 | 作者或团队名 |
type | 是 | open-source 或 closed-source |
version | 是 | 语义化版本,必须等于 ZIP 内清单的 version |
updatedAt | 是 | YYYY-MM-DD |
platforms | 是 | 非空数组,取值 windows / macos / linux / android / ios / web |
download | 视类型 | 公开 HTTPS 地址,不能带用户名密码 |
sha256 | 是 | 64 位十六进制,必须与包字节一致 |
license / repo | 开源必填 | 许可证标识与公开仓库 |
tags | 否 | 小写标签,最多 8 个 |
minAppVersion | 否 | 最低客户端版本 |
download 不能指向 releases/latest/。客户端会同时校验
sha256 和包内 version,上游一发新版本,清单里的两个值立刻失配,
用户侧看到的就是「插件校验失败」。请用打了版本号的 release 资源,或把 ZIP 托管到市场。
打包之后算 SHA-256,把它填进清单的 sha256。
在 lazer-web 仓库里跑
npm run check:plugins。它会检查字段、市场托管 ZIP 是否存在、哈希是否对得上;
加 -- --remote 还会把外部 download 抓下来对一遍。
改 public/plugin/plugins.json,按
上架模板
写清插件类型与版本。没有自动上架通道,所有变更都要经过一次合并的 PR。
Vercel 会重新构建站点,/plugin/plugins.json 随即更新。
npm run build 会先跑一遍校验,清单写错时构建直接失败,坏条目不会被发布。
# 打包
Compress-Archive -Path .\manifest.json, .\main.lua, .\api.lua `
-DestinationPath .\community.example.music.zip -Force
# 算哈希
(Get-FileHash .\community.example.music.zip -Algorithm SHA256).Hash.ToLower()
# 校验市场清单
npm run check:plugins
npm run check:plugins -- --remote
市场托管 ZIP 放在 public/plugin/<作者>/<插件 id>/<版本>/<插件 id>.zip,
随 PR 一起提交,不需要额外文件服务器。开源插件的新版本可以直接发 Release,
只有元数据变化时才需要改清单;闭源插件每次发版都要提 PR。
把 describe、密码登录、搜索、首页、歌单、歌词、电台和榜单全实现一遍,
播放地址指向本机 127.0.0.1 上的 Range HTTP 服务,音源是现合成的 WAV,
全程不联网。
只用 describe 加 theme 两个操作,交一组字号、字重、圆角与
歌词动效令牌,不返回任何 Widget,也没有网络、存储和文件权限。
市场里的网易云、酷狗、YouTube 与 B 站插件都是真实工程, 可以直接下载 ZIP 解开看清单与模块划分。
示例代码在客户端仓库的 examples/ 目录下:gateway-mock 与
theme-plugin。跑 build.bat(Windows)或
./build.sh(macOS / Linux)就能打出可以直接导入的 ZIP。
同一份插件可用于原生客户端和 Web 版。host.info().features 报告本端已注册的特性;
实际可用性还取决于运行平台、引擎以及用户授权。
| 项目 | 原生 | Web |
|---|---|---|
host.info().runtime | native | web |
host.socket / host.socket_server | 有 socket 特性;获授权后可用 | 未注册(字段为 nil) |
host.websocket_server | 可用 | 恒定报不支持 |
host.websocket | 可用 | 可用 |
host.http | 原生 HTTP 客户端 | 转同源中继 /api/plugin-http;响应大小和超时与原生不同 |
| 键值存储 | UTF-8 JSON 总量 1 MiB | 浏览器存储与配额 |
host.file | 真实文件系统 | 浏览器存储,stat.modifiedMs 恒为 0 |
| 超时处理 | 重建 isolate | 不重建 VM |
apiVersion 目前只有 1。不认识的版本整包拒绝,不会「尽量兼容」。home_feed 这样的写法。describe 没返回 providers,或平台 id
不符合 ^[a-z][a-z0-9_-]{1,39}$、与别的平台重复、或者用了保留字
local。任何一条不满足都会让整个插件启动失败。
permissions.network,或者用了 http://。
注意重定向也是不跟随的:跳到另一个域名会原样返回 3xx,那个域名同样要声明。
capabilities 的问题。
synced = true 和带 startMs 的 lines。
只给 lrc 字符串也能解析,但逐行数组更可靠。
limit 条,客户端以为还有下一页。少返回一条,或如实按分页切片。
call 里串了几十个 HTTP 请求。
socket 系列不存在、
websocket_server 报不支持。用 host.info().features 判断后再降级。
return 一个带
call 的 table,且 require 的模块路径要与 ZIP 内的层级一致。