diff --git a/entry_desktop.go b/entry_desktop.go
new file mode 100644
index 00000000..cb992dbf
--- /dev/null
+++ b/entry_desktop.go
@@ -0,0 +1,9 @@
+//go:build !ios && !android
+
+package main
+
+import "github.com/ShellMonster/PudMusic/internal/bootstrap"
+
+func platformDependencies() bootstrap.Dependencies {
+ return bootstrap.DefaultDependencies()
+}
diff --git a/entry_mobile.go b/entry_mobile.go
new file mode 100644
index 00000000..9c6836ae
--- /dev/null
+++ b/entry_mobile.go
@@ -0,0 +1,12 @@
+//go:build ios || android
+
+package main
+
+import (
+ "github.com/ShellMonster/PudMusic/internal/bootstrap"
+ "github.com/ShellMonster/PudMusic/internal/mobileui"
+)
+
+func platformDependencies() bootstrap.Dependencies {
+ return bootstrap.MobileDependencies(mobileui.Run)
+}
diff --git a/go.mod b/go.mod
index ed95127e..bc99ead6 100644
--- a/go.mod
+++ b/go.mod
@@ -5,7 +5,7 @@ go 1.27.3
require (
github.com/Eyevinn/mp4ff v0.62.0
github.com/ebitengine/purego v0.11.3
- github.com/egoist/mygo v0.9.1
+ github.com/egoist/mygo v0.10.0
github.com/mewkiz/flac v1.0.14
github.com/tphakala/go-m4a v0.8.0
golang.org/x/image v0.47.0
diff --git a/go.sum b/go.sum
index 9412bb83..6db2db50 100644
--- a/go.sum
+++ b/go.sum
@@ -8,8 +8,8 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg=
github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ=
-github.com/egoist/mygo v0.9.1 h1:vzMjSyahUjSk62+n+qmNXt8Bamyx1UNz359OyEDo/kg=
-github.com/egoist/mygo v0.9.1/go.mod h1:Hw9sxdSQ4tHuehHw5Q6alR1qTS8kgv3oSFxEejg+7qo=
+github.com/egoist/mygo v0.10.0 h1:HpLUrlh6WES+4VYbz5K0TvUSw/v8PSdjT/ttiUYrBFM=
+github.com/egoist/mygo v0.10.0/go.mod h1:Hw9sxdSQ4tHuehHw5Q6alR1qTS8kgv3oSFxEejg+7qo=
github.com/go-test/deep v1.1.0 h1:WOcxcdHcvdgThNXjw0t76K42FXTU7HpNQWHpA2HHNlg=
github.com/go-test/deep v1.1.0/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE=
github.com/go-text/typesetting v0.3.5 h1:XZPUooClHY0Vf/rFyUyuPRNEkawARaFzLMQcXLSEyPk=
diff --git a/internal/app/account.go b/internal/app/account.go
index 0105c290..4e217c0f 100644
--- a/internal/app/account.go
+++ b/internal/app/account.go
@@ -28,6 +28,7 @@ import (
"fmt"
"log"
"net/http"
+ "net/url"
"strings"
"sync"
"time"
@@ -86,6 +87,7 @@ type LoginState struct {
Err string
// LoggedIn 是此刻有没有登录态。登录成功后为 true。
LoggedIn bool
+ qrURL string
}
// Busy 报登录流程是不是还在跑。
@@ -93,6 +95,17 @@ func (s LoginState) Busy() bool {
return s.Phase == LoginWaiting || s.Phase == LoginScanned
}
+func (s LoginState) ConfirmationURL() string {
+ if !s.Busy() || s.QR == nil {
+ return ""
+ }
+ link, err := url.Parse(s.qrURL)
+ if err != nil || link.Scheme != "https" || !strings.EqualFold(link.Host, "passport.bilibili.com") || link.User != nil {
+ return ""
+ }
+ return s.qrURL
+}
+
// pollInterval 是轮询二维码状态的间隔。
//
// B 站建议 2 秒。太快会被限速(-412 风控),太慢用户会干等。
@@ -109,7 +122,8 @@ type Account struct {
mu sync.Mutex
state LoginState
// stop 是当前那一轮登录的取消函数。再开一轮之前先调它。
- stop context.CancelFunc
+ stop context.CancelFunc
+ loginLease *Lease
// runID 是「当前是第几轮登录」。每次开始或取消都 +1。
//
// 它的用处是让**上一轮的 goroutine 闭嘴**:取消只是把 ctx 掐掉,
@@ -265,6 +279,9 @@ func (a *App) onLoginSucceeded() {
// 账号的收藏夹,直到下一件别的事把它画出来。
func (a *App) onAccountChanged() {
a.FavoritesOf().forgetAccount()
+ a.commentsMu.Lock()
+ a.resetCommentsLocked("")
+ a.commentsMu.Unlock()
// 喜欢状态也属于上一个账号:换人之后旧答案一条都不能留。已经发出去的
// 写请求靠 `favEpoch` 拦(见 `SetBoundFavorite`)。
a.clearFavorites()
@@ -320,12 +337,8 @@ func (a *Account) restore(cli *bili.Client) error {
// 那个 goroutine 会一直等在 ctx 上。
func (a *Account) Close() {
a.mu.Lock()
- stop := a.stop
- a.stop = nil
+ a.stopLoginLocked()
a.mu.Unlock()
- if stop != nil {
- stop()
- }
}
// httpCookiesOf 把落盘的 cookie 变成 net/http 认的形式。
@@ -354,9 +367,7 @@ func (a *App) BeginLogin() {
func (a *Account) beginLogin() {
a.mu.Lock()
- if a.stop != nil {
- a.stop()
- }
+ a.stopLoginLocked()
ctx, cancel := context.WithCancel(context.Background())
a.stop = cancel
a.runID++
@@ -365,6 +376,7 @@ func (a *Account) beginLogin() {
// **代次在这时候拿**。它记的是「用户按下登录那一刻」的登录态版本。
// 扫码成功要写回时对不上(最常见的是中间退了登),Lease 会挡住。
lease := a.mgr.BeginRenew()
+ a.loginLease = lease
a.state = LoginState{Phase: LoginWaiting, Hint: "正在向 B 站申请二维码…"}
a.mu.Unlock()
a.wakeUp()
@@ -389,18 +401,22 @@ func (a *App) CancelLogin() {
func (a *Account) cancel() {
a.mu.Lock()
- stop := a.stop
- a.stop = nil
+ a.stopLoginLocked()
// +1 让在途的那一轮闭嘴:它回来之后写的任何状态都会被挡掉。
a.runID++
a.state = LoginState{Phase: LoginIdle}
a.mu.Unlock()
- if stop != nil {
- stop()
- }
a.wakeUp()
}
+func (a *Account) stopLoginLocked() {
+ if a.stop != nil {
+ a.loginLease.settled.Store(true)
+ a.stop()
+ a.stop, a.loginLease = nil, nil
+ }
+}
+
// wakeUp 叫醒界面。回调可能在 setWake 之前还没装上,所以判空。
func (a *Account) wakeUp() {
a.mu.Lock()
@@ -413,9 +429,10 @@ func (a *Account) wakeUp() {
// run 是那一轮登录的完整流程:申请 → 画 → 循环轮询 → 落盘。
func (a *Account) run(ctx context.Context, lease *Lease, id uint64) {
- defer lease.Discard() // 没走到 Commit 的路径一律作废代次
+ defer lease.settled.Store(true)
- qr, err := a.cli.NewQRCode(ctx)
+ login := a.cli.NewLoginClient()
+ qr, err := login.NewQRCode(ctx)
if err != nil {
if ctx.Err() != nil {
return // 用户取消了,这不是错误
@@ -434,7 +451,7 @@ func (a *Account) run(ctx context.Context, lease *Lease, id uint64) {
a.mu.Unlock() // 已经被取消了
return
}
- a.state = LoginState{Phase: LoginWaiting, QR: code, Hint: bili.ScanWaiting.String()}
+ a.state = LoginState{Phase: LoginWaiting, QR: code, Hint: bili.ScanWaiting.String(), qrURL: qr.URL}
interval := a.interval
a.mu.Unlock()
a.wakeUp()
@@ -446,7 +463,7 @@ func (a *Account) run(ctx context.Context, lease *Lease, id uint64) {
case <-ctx.Done():
return
case <-ticker.C:
- res, err := a.cli.PollScan(ctx, qr.Key)
+ res, err := login.PollScan(ctx, qr.Key)
switch {
case ctx.Err() != nil:
return
@@ -467,7 +484,7 @@ func (a *Account) run(ctx context.Context, lease *Lease, id uint64) {
a.hint(id, LoginExpired, bili.ScanExpired.String())
return
case bili.ScanConfirmed:
- a.finish(ctx, lease, res, id)
+ a.finish(ctx, lease, res, login.IssuedCookies(), id)
return
}
}
@@ -475,7 +492,7 @@ func (a *Account) run(ctx context.Context, lease *Lease, id uint64) {
}
// finish 把扫成功的凭据存进去。
-func (a *Account) finish(ctx context.Context, lease *Lease, res bili.ScanResult, id uint64) {
+func (a *Account) finish(ctx context.Context, lease *Lease, res bili.ScanResult, cookies []*http.Cookie, id uint64) {
sess := Session{RefreshToken: res.RefreshToken}
if !res.LoggedInAt.IsZero() {
sess.SavedAt = res.LoggedInAt
@@ -484,7 +501,7 @@ func (a *Account) finish(ctx context.Context, lease *Lease, res bili.ScanResult,
// session.go 里 isOwnHost 的注释:按 cookie 自己的域过滤会把登录凭据滤掉)。
// 这里全都收下——SESSDATA / bili_jct / DedeUserID 三个都在里面,
// 少一个都会让「登录成功之后第一个要用的接口」失败。
- for _, c := range a.cli.IssuedCookies() {
+ for _, c := range cookies {
sess.Cookies = append(sess.Cookies, CookieFromHTTP(c))
}
sess.Normalize(sess.SavedAt)
@@ -503,10 +520,10 @@ func (a *Account) finish(ctx context.Context, lease *Lease, res bili.ScanResult,
// 得在拉新账号的那一趟**之前**作废掉(见 `App.onAccountChanged`)。
prev := a.mgr.Current()
- err := lease.Commit(ctx, func(cur *Session) error {
+ err := lease.commit(ctx, func(cur *Session) error {
*cur = sess
return nil
- })
+ }, true, func() { _ = a.cli.SeedCookies(cookies) })
switch {
case errors.Is(err, ErrStaleGeneration):
// 用户在这中间退了登。**什么都不写**,安静收工——
@@ -520,7 +537,6 @@ func (a *Account) finish(ctx context.Context, lease *Lease, res bili.ScanResult,
// 还是同样的结果。正确的做法是让他登进去用着,同时**明说**存不住:
// 界面上那一行「凭据后端不可用,登录态关掉应用就没了」就是干这个的。
log.Printf("pudmusic: 这次登录没能存下来,先只在内存里用着:%v", err)
- a.mgr.Adopt(sess)
a.notifyAccountChanged(prev, sess)
a.setStateFor(id, LoginState{
Phase: LoginDone,
@@ -626,14 +642,10 @@ func (a *App) Logout() error {
func (a *Account) logout() error {
a.mu.Lock()
- stop := a.stop
- a.stop = nil
+ a.stopLoginLocked()
a.runID++
a.state = LoginState{Phase: LoginIdle}
a.mu.Unlock()
- if stop != nil {
- stop()
- }
// 先让 B 站那边把这个会话也作废,**然后**再清本地的。
//
@@ -657,8 +669,7 @@ func (a *Account) logout() error {
// 然后清 jar:Manager.Logout 可能失败(后端解不开、写不了),
// 但**内存里的 cookie 无论如何都得清掉**——
// 宁可不彻底,也不能让用户退不出去。
- _ = a.cli.SeedCookies(nil)
- err := a.mgr.Logout(context.Background())
+ err := a.mgr.logout(context.Background(), func() { _ = a.cli.SeedCookies(nil) })
a.wakeUp()
return err
}
diff --git a/internal/app/app.go b/internal/app/app.go
index 7dfb0e5b..f81b4dca 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -986,6 +986,8 @@ type App struct {
// ⚠️ **它让进度条不必靠整树重建来走**:没有这一栏时,界面只能从 `State`
// 里拿到建树那一刻的位置,于是「让那根线往前走」只能靠每 50ms 重建整棵树。
playPositionNS atomic.Int64
+ playbackIntent atomic.Uint64
+ beforePlayback func() bool
// danmakuSeq 是**在途序号**。每发起一趟取弹幕就加一(**不管是哪一集**)。
//
// 🔴 **它挡的是「同一个 key 上慢的那一趟把新的盖掉」**:代次
@@ -1507,7 +1509,10 @@ func (a *App) setCover(url string) {
}
// Open 打开一个本地音频文件并开始播放,上一首连同它的文件句柄一起关掉。
-func (a *App) Open(path string) error { return a.openLocal(path, 0, openPlay) }
+func (a *App) Open(path string) error {
+ a.playbackIntent.Add(1)
+ return a.openLocal(path, 0, openPlay)
+}
// openMode 是「打开一个本地文件」时的那一档。
//
@@ -1730,7 +1735,7 @@ func (a *App) openLocal(path string, at time.Duration, mode openMode) error {
if pos > 0 {
p.Seek(pos)
}
- p.Play()
+ a.startPlayer(p)
}
a.publishMedia()
// 歌词跟着换歌一起换:先重置成默认值,再从缓存恢复(见 lyrics.go)。
@@ -1747,6 +1752,7 @@ func (a *App) openLocal(path string, at time.Duration, mode openMode) error {
// Toggle 在播放和暂停之间切换。播放到头之后按它是重头播。
func (a *App) Toggle() {
+ a.playbackIntent.Add(1)
a.mu.Lock()
p, wake := a.player, a.wake
a.mu.Unlock()
@@ -1756,7 +1762,7 @@ func (a *App) Toggle() {
if p.Playing() {
p.Pause()
} else {
- p.Play()
+ a.startPlayer(p)
}
a.mu.Lock()
@@ -1906,6 +1912,7 @@ func (a *App) SetRate(r float64) {
p.SetRate(r)
}
_, _ = a.UpdateSettings(func(s *Settings) { s.PlaybackRate = r })
+ a.publishMedia()
if wake != nil {
wake()
}
@@ -1929,7 +1936,7 @@ func (a *App) ScrubEnd(fraction float64) {
t := min(time.Duration(fraction*float64(dur)), dur)
p.Seek(t)
if wantPlay {
- p.Play()
+ a.startPlayer(p)
}
// 立刻把位置改过来:暂停状态下 tick 不跑,界面下一帧读的就是这里写的值。
diff --git a/internal/app/collection.go b/internal/app/collection.go
index 09e4e444..f07624a0 100644
--- a/internal/app/collection.go
+++ b/internal/app/collection.go
@@ -89,6 +89,8 @@ type CollectionRef struct {
ID int64
// Type 是哪一类容器。
Type bili.CollectionType
+ // OwnerMid 是来源已知的合集或系列创建者。
+ OwnerMid int64
}
// Key 是这一份状态属于哪个容器。界面拿它认出「换容器了,该重建了」。
@@ -521,6 +523,9 @@ func (a *App) fetchCollection(ref CollectionRef) (CollectionInfo, error) {
// ⚠️ **它只看缓存、不问网络**:`fetchCollection` 自己就在拉元信息,再在这儿问
// 一次就是自己叫自己(`collectionOwnerMid` 的「当场问一次」会绕回来)。
func (a *App) collectionMidHint(ref CollectionRef) int64 {
+ if ref.OwnerMid > 0 {
+ return ref.OwnerMid
+ }
return a.Collection(ref).OwnerMid
}
@@ -772,10 +777,8 @@ func DownloaderMissing(err error) bool { return errors.Is(err, errDownloaderMiss
// 列表(或者一句 -400)——界面上是**一页空白,一个错都没有**。用户看到的是
// 「点进合集,里面什么都没有」。
//
-// ⚠️ **合集 / 系列要 `mid`**,而 `CollectionRef` 只有 ID 和 Type——mid 从
-// 元信息缓存里拿(`CollectionInfo.OwnerMid`,见 `fetchCollection`)。**没拉到
-// 元信息时 mid 是 0**:文档说这个参数「也可以是任意的非负整数」,所以 0 是
-// 能发的(真网验证不了,但发 0 比不发强——不发的话 B 站回 -400)。
+// ⚠️ **合集 / 系列要 `mid`**。从来源传入的创建者 ID 优先,否则读取或查询
+// 容器元信息。两处都拿不到时发送 0。
//
// ⚠️ **keyword 只对收藏夹有意义**:那两个接口没有 `keyword` 参数。合集 / 系列
// 里按歌名找是把这一页筛掉吗?不——**本地筛不能筛没拉下来的页**(理由见
@@ -866,7 +869,7 @@ var errCollectionSearchUnsupported = errors.New("pudmusic: 合集和系列里还
// ⚠️ **问不到也照发 0**:不发的话 B 站回 -400,界面上是「这个合集打不开」,
// 而发 0 至少还有「B 站接受任意 mid」那一半的机会。两害相权,发。
func (a *App) collectionOwnerMid(ref CollectionRef) int64 {
- if mid := a.Collection(ref).OwnerMid; mid > 0 {
+ if mid := a.collectionMidHint(ref); mid > 0 {
return mid
}
info, err := a.fetchCollection(ref)
diff --git a/internal/app/comment_write.go b/internal/app/comment_write.go
new file mode 100644
index 00000000..6e1c0676
--- /dev/null
+++ b/internal/app/comment_write.go
@@ -0,0 +1,59 @@
+package app
+
+import (
+ "context"
+ "errors"
+
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+)
+
+func (a *App) AddComment(ctx context.Context, account AccountSnapshot, item Item, root, parent int64, message string) error {
+ err := a.writeComment(ctx, account, item, func(client *bili.Client, kind, object int64) error {
+ return client.AddComment(ctx, kind, object, root, parent, message)
+ })
+ if err == nil {
+ slot := commentSlotKey(item)
+ a.commentsMu.Lock()
+ if a.commentsSlot == slot && root > 0 {
+ delete(a.commentsReplies, root)
+ }
+ a.commentsMu.Unlock()
+ if a.CommentsSlot() == slot {
+ a.RefreshComments()
+ }
+ }
+ return err
+}
+
+func (a *App) LikeComment(ctx context.Context, account AccountSnapshot, item Item, reply int64, liked bool) error {
+ return a.writeComment(ctx, account, item, func(client *bili.Client, kind, object int64) error {
+ return client.LikeComment(ctx, kind, object, reply, liked)
+ })
+}
+
+func (a *App) writeComment(ctx context.Context, account AccountSnapshot, item Item, send func(*bili.Client, int64, int64) error) error {
+ client := a.commentsClient()
+ if client == nil || account.SelfMid <= 0 || !a.LoggedIn() {
+ return errors.New("登录后才能操作评论")
+ }
+ a.commentsMu.Lock()
+ fetch := a.commentsArchiveFetch
+ a.commentsMu.Unlock()
+ kind, object, supported, err := a.resolveCommentTarget(ctx, item, fetch)
+ if err != nil {
+ return err
+ }
+ if !supported {
+ return errCommentsUnavailable
+ }
+ if !a.accountSnapshotCurrent(account) {
+ return ErrStaleGeneration
+ }
+ if err := send(client, kind, object); err != nil {
+ return err
+ }
+ if !a.accountSnapshotCurrent(account) {
+ return ErrStaleGeneration
+ }
+ return nil
+}
diff --git a/internal/app/credentials.go b/internal/app/credentials.go
index 103b1aa8..6793905f 100644
--- a/internal/app/credentials.go
+++ b/internal/app/credentials.go
@@ -46,6 +46,7 @@ import (
"sort"
"strings"
"sync"
+ "sync/atomic"
"time"
)
@@ -457,9 +458,16 @@ func StoreUnavailable(err error) bool {
//
// 后端清不掉时内存也会清(返回错误),宁可不彻底也不能让用户退不出去。
func (m *Manager) Logout(ctx context.Context) error {
+ return m.logout(ctx, nil)
+}
+
+func (m *Manager) logout(ctx context.Context, clearClient func()) error {
m.mu.Lock()
+ defer m.mu.Unlock()
m.cur, m.gen = Session{}, m.gen+1
- m.mu.Unlock()
+ if clearClient != nil {
+ clearClient()
+ }
if err := m.store.Clear(ctx); err != nil {
return fmt.Errorf("app: 退出登录: %w", err)
}
@@ -473,8 +481,9 @@ func (m *Manager) Logout(ctx context.Context) error {
//
// 一次操作一个 Lease,不复用。忘了 Discard 只是代次白涨一次,没有别的后果。
type Lease struct {
- m *Manager
- gen uint64
+ m *Manager
+ gen uint64
+ settled atomic.Bool
}
// BeginRenew 拿一张租约,声明「我要在后台动登录态了」。
@@ -487,25 +496,40 @@ func (m *Manager) BeginRenew() *Lease {
// Commit 把续期结果写回去。登录态在这期间变过就返回 ErrStaleGeneration,
// **不写**。调用方看到这个错误就直接收工,不要重试。
func (l *Lease) Commit(ctx context.Context, fn func(*Session) error) error {
+ return l.commit(ctx, fn, false, nil)
+}
+
+func (l *Lease) commit(ctx context.Context, fn func(*Session) error, acceptMemoryOnly bool, publishClient func()) error {
l.m.mu.Lock()
- if l.m.gen != l.gen {
- l.m.mu.Unlock()
+ defer l.m.mu.Unlock()
+ if l.settled.Load() || l.m.gen != l.gen || ctx.Err() != nil {
return ErrStaleGeneration
}
next := l.m.cur
err := fn(&next)
if err != nil {
- l.m.mu.Unlock()
return err
}
next.Normalize(time.Now())
- if err := l.m.store.Save(ctx, next); err != nil {
- l.m.mu.Unlock()
+ err = l.m.store.Save(ctx, next)
+ if !l.settled.CompareAndSwap(false, true) || ctx.Err() != nil {
+ if err != nil {
+ return ErrStaleGeneration
+ }
+ restoreCtx := context.WithoutCancel(ctx)
+ if l.m.cur.LoggedIn() {
+ return errors.Join(ErrStaleGeneration, l.m.store.Save(restoreCtx, l.m.cur))
+ }
+ return errors.Join(ErrStaleGeneration, l.m.store.Clear(restoreCtx))
+ }
+ if err != nil && !(acceptMemoryOnly && StoreUnavailable(err)) {
return fmt.Errorf("app: 保存续期结果: %w", err)
}
l.m.cur, l.m.gen = next, l.m.gen+1
- l.m.mu.Unlock()
- return nil
+ if publishClient != nil {
+ publishClient()
+ }
+ return err
}
// Discard 放弃这次操作。什么都写不了,只把代次退回去——
diff --git a/internal/app/credentials_file_darwin.go b/internal/app/credentials_file_darwin.go
index 4933c4f4..e8ac1ae1 100644
--- a/internal/app/credentials_file_darwin.go
+++ b/internal/app/credentials_file_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
// macOS 的凭据后端:应用数据目录里的一个普通文件。
//
diff --git a/internal/app/credentials_file_darwin_test.go b/internal/app/credentials_file_darwin_test.go
index db84eadc..9f14fa0f 100644
--- a/internal/app/credentials_file_darwin_test.go
+++ b/internal/app/credentials_file_darwin_test.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package app
diff --git a/internal/app/credentials_mobile.go b/internal/app/credentials_mobile.go
new file mode 100644
index 00000000..7af7b6e8
--- /dev/null
+++ b/internal/app/credentials_mobile.go
@@ -0,0 +1,21 @@
+//go:build ios || android
+
+package app
+
+import (
+ "path/filepath"
+ "runtime"
+
+ "github.com/egoist/mygo"
+)
+
+func NewSystemStore(dir string) (Store, error) {
+ if !filepath.IsAbs(dir) {
+ return nil, ErrUnavailable
+ }
+ name := "android-keystore"
+ if runtime.GOOS == "ios" {
+ name = "ios-keychain"
+ }
+ return sealedSessionStore{secrets: mygo.Secrets, path: filepath.Join(dir, "bilibili-session.enc"), name: name}, nil
+}
diff --git a/internal/app/credentials_other.go b/internal/app/credentials_other.go
index 248d2727..524acec7 100644
--- a/internal/app/credentials_other.go
+++ b/internal/app/credentials_other.go
@@ -1,4 +1,4 @@
-//go:build !darwin && !windows
+//go:build !darwin && !windows && !android
// 没有系统保护存储的平台(Linux、FreeBSD…)。
//
diff --git a/internal/app/credentials_sealed.go b/internal/app/credentials_sealed.go
new file mode 100644
index 00000000..6199cda7
--- /dev/null
+++ b/internal/app/credentials_sealed.go
@@ -0,0 +1,185 @@
+package app
+
+import (
+ "bytes"
+ "context"
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/rand"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/egoist/mygo"
+)
+
+const (
+ mobileSessionKey = "bilibili-session"
+ mobileCipherKey = mobileSessionKey + "-key-v1"
+ mobileAlternateKey = mobileCipherKey + "-alternate"
+ mobileAlternateHeader = "PUDMUSIC-SESSION-ALT\x00"
+)
+
+type sessionSecrets interface {
+ Get(string) ([]byte, error)
+ Set(string, []byte) error
+ Delete(string) error
+}
+
+type sealedSessionStore struct {
+ secrets sessionSecrets
+ path string
+ name string
+}
+
+func (s sealedSessionStore) Name() string { return s.name }
+
+func (s sealedSessionStore) Load(ctx context.Context) (Session, error) {
+ if err := ctx.Err(); err != nil {
+ return Session{}, err
+ }
+ data, err := os.ReadFile(s.path)
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ data, err = s.secrets.Get(mobileSessionKey)
+ if errors.Is(err, mygo.ErrSecretNotFound) {
+ return Session{}, ErrNotLoggedIn
+ }
+ if err != nil {
+ return Session{}, mobileCredentialError("读取登录态", err)
+ }
+ case err != nil:
+ return Session{}, mobileCredentialError("读取登录态", err)
+ default:
+ keyName, ciphertext := sealedSessionRecord(data)
+ key, err := s.secrets.Get(keyName)
+ box, err := sealedSessionCipher(key, err)
+ if err != nil {
+ return Session{}, err
+ }
+ data, err = box.Open(nil, nil, ciphertext, []byte(keyName))
+ if err != nil {
+ return Session{}, fmt.Errorf("%w: 登录态解不开", ErrCorrupt)
+ }
+ }
+ var session Session
+ if err := json.Unmarshal(data, &session); err != nil {
+ return Session{}, fmt.Errorf("%w: 登录态解不开: %v", ErrCorrupt, err)
+ }
+ if !session.LoggedIn() {
+ return Session{}, ErrNotLoggedIn
+ }
+ return session, nil
+}
+
+func (s sealedSessionStore) Save(ctx context.Context, session Session) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ session.Normalize(time.Now())
+ data, err := json.Marshal(session)
+ if err != nil {
+ return fmt.Errorf("app: 序列化登录态: %w", err)
+ }
+ previous, err := os.ReadFile(s.path)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return mobileCredentialError("读取登录态", err)
+ }
+ keyName, _ := sealedSessionRecord(previous)
+ key, keyErr := s.secrets.Get(keyName)
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if keyErr != nil || len(key) != 32 {
+ if len(previous) != 0 {
+ if keyName == mobileCipherKey {
+ keyName = mobileAlternateKey
+ } else {
+ keyName = mobileCipherKey
+ }
+ }
+ key = make([]byte, 32)
+ if _, err := rand.Read(key); err != nil {
+ return mobileCredentialError("生成登录态密钥", err)
+ }
+ keyErr = s.secrets.Set(keyName, key)
+ }
+ box, err := sealedSessionCipher(key, keyErr)
+ if err != nil {
+ return err
+ }
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
+ return mobileCredentialError("创建登录态目录", err)
+ }
+ var header []byte
+ if keyName == mobileAlternateKey {
+ header = []byte(mobileAlternateHeader)
+ }
+ if err := writeFileAtomicMode(s.path, box.Seal(header, nil, data, []byte(keyName)), 0o600); err != nil {
+ return mobileCredentialError("保存登录态", err)
+ }
+ return nil
+}
+
+func (s sealedSessionStore) Clear(ctx context.Context) error {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ legacyErr := s.secrets.Delete(mobileSessionKey)
+ if errors.Is(legacyErr, mygo.ErrSecretNotFound) {
+ legacyErr = nil
+ }
+ fileErr := os.Remove(s.path)
+ if errors.Is(fileErr, os.ErrNotExist) {
+ fileErr = nil
+ }
+ keyErr := s.secrets.Delete(mobileCipherKey)
+ if errors.Is(keyErr, mygo.ErrSecretNotFound) {
+ keyErr = nil
+ }
+ alternateErr := s.secrets.Delete(mobileAlternateKey)
+ if errors.Is(alternateErr, mygo.ErrSecretNotFound) {
+ alternateErr = nil
+ }
+ if err := errors.Join(legacyErr, fileErr, keyErr, alternateErr); err != nil {
+ return mobileCredentialError("清除登录态", err)
+ }
+ return nil
+}
+
+func sealedSessionRecord(data []byte) (string, []byte) {
+ if ciphertext, ok := bytes.CutPrefix(data, []byte(mobileAlternateHeader)); ok {
+ return mobileAlternateKey, ciphertext
+ }
+ return mobileCipherKey, data
+}
+
+func sealedSessionCipher(key []byte, err error) (cipher.AEAD, error) {
+ if errors.Is(err, mygo.ErrSecretNotFound) {
+ return nil, fmt.Errorf("%w: 登录态密钥已丢失", ErrCorrupt)
+ }
+ if err != nil {
+ return nil, mobileCredentialError("读取登录态密钥", err)
+ }
+ if len(key) != 32 {
+ return nil, fmt.Errorf("%w: 登录态密钥无效", ErrCorrupt)
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, mobileCredentialError("打开登录态密钥", err)
+ }
+ return cipher.NewGCMWithRandomNonce(block)
+}
+
+func mobileCredentialError(operation string, err error) error {
+ if errors.Is(err, errors.ErrUnsupported) {
+ return fmt.Errorf("%w: %s: %v", ErrUnavailable, operation, err)
+ }
+ return fmt.Errorf("%w: %s: %v", ErrBackend, operation, err)
+}
diff --git a/internal/app/credentials_sealed_test.go b/internal/app/credentials_sealed_test.go
new file mode 100644
index 00000000..527aa031
--- /dev/null
+++ b/internal/app/credentials_sealed_test.go
@@ -0,0 +1,127 @@
+package app
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/egoist/mygo"
+)
+
+type fixtureSecrets map[string][]byte
+
+func (f fixtureSecrets) Get(key string) ([]byte, error) {
+ value, ok := f[key]
+ if !ok {
+ return nil, mygo.ErrSecretNotFound
+ }
+ return bytes.Clone(value), nil
+}
+
+func (f fixtureSecrets) Set(key string, value []byte) error {
+ if len(value) > mygo.MaxSecretSize {
+ return errors.New("fixture secret is too large")
+ }
+ f[key] = bytes.Clone(value)
+ return nil
+}
+
+func (f fixtureSecrets) Delete(key string) error { delete(f, key); return nil }
+
+type blockedSessionSave struct {
+ Store
+ started, release chan struct{}
+}
+
+func (store blockedSessionSave) Save(ctx context.Context, session Session) error {
+ close(store.started)
+ <-store.release
+ return store.Store.Save(context.WithoutCancel(ctx), session)
+}
+
+// TestCancelLoginWhileSavingLeavesNoSession verifies that a late credential write is rolled back after cancellation.
+func TestCancelLoginWhileSavingLeavesNoSession(t *testing.T) {
+ store := blockedSessionSave{Store: NewMemoryStore("fixture"), started: make(chan struct{}), release: make(chan struct{})}
+ manager := NewManager(store)
+ ctx, cancel := context.WithCancel(t.Context())
+ defer cancel()
+ lease := manager.BeginRenew()
+ account := &Account{mgr: manager, stop: cancel, loginLease: lease}
+ result := make(chan error, 1)
+ go func() {
+ result <- lease.Commit(ctx, func(session *Session) error {
+ session.SESSDATA = "synthetic-review"
+ return nil
+ })
+ }()
+ <-store.started
+ account.cancel()
+ close(store.release)
+ if err := <-result; !errors.Is(err, ErrStaleGeneration) {
+ t.Fatalf("canceled login result = %v", err)
+ }
+ if _, err := store.Load(t.Context()); !errors.Is(err, ErrNotLoggedIn) || manager.Current().LoggedIn() {
+ t.Fatalf("canceled login remains signed in, load error = %v", err)
+ }
+}
+
+type restoredSecrets struct{ fixtureSecrets }
+
+func (store restoredSecrets) Get(key string) ([]byte, error) {
+ value, err := store.fixtureSecrets.Get(key)
+ if key == mobileCipherKey && bytes.Equal(value, []byte("unreadable-backup")) {
+ return nil, errors.New("keystore authentication failed")
+ }
+ return value, err
+}
+
+// TestNewLoginReplacesAnUnreadableRestoredKey checks that a fresh login can persist after an Android backup restore.
+func TestNewLoginReplacesAnUnreadableRestoredKey(t *testing.T) {
+ secrets := restoredSecrets{fixtureSecrets{mobileCipherKey: []byte("unreadable-backup")}}
+ store := sealedSessionStore{secrets: secrets, path: filepath.Join(t.TempDir(), "session.enc")}
+ session := Session{SESSDATA: "synthetic-review"}
+ if err := store.Save(t.Context(), session); err != nil {
+ t.Fatal(err)
+ }
+ if got, err := store.Load(t.Context()); err != nil || got.SESSDATA != session.SESSDATA {
+ t.Fatalf("new login did not restore: %v", err)
+ }
+}
+
+// TestSealedSessionSurvivesTheSecretSizeLimit verifies that a large session can be restored and cleared without storing it as a plain file.
+func TestSealedSessionSurvivesTheSecretSizeLimit(t *testing.T) {
+ store := sealedSessionStore{secrets: fixtureSecrets{}, path: filepath.Join(t.TempDir(), "session.enc")}
+ ctx := t.Context()
+ const marker = "pudmusic-qa-value"
+ session := Session{SESSDATA: strings.Repeat(marker, 500)}
+ if err := store.Save(ctx, session); err != nil {
+ t.Fatal(err)
+ }
+ blob, err := os.ReadFile(store.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.Contains(blob, []byte(marker)) {
+ t.Fatal("found plaintext in the session file")
+ }
+ if got, err := store.Load(ctx); err != nil || got.SESSDATA != session.SESSDATA {
+ t.Fatalf("session did not restore: %v", err)
+ }
+ blob[len(blob)-1] ^= 1
+ if err := os.WriteFile(store.path, blob, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.Load(ctx); !errors.Is(err, ErrCorrupt) {
+ t.Fatalf("modified ciphertext loaded: %v", err)
+ }
+ if err := store.Clear(ctx); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.Load(ctx); !errors.Is(err, ErrNotLoggedIn) {
+ t.Fatalf("session still present after clearing: %v", err)
+ }
+}
diff --git a/internal/app/foldermanage.go b/internal/app/foldermanage.go
index ddc602ec..4281b303 100644
--- a/internal/app/foldermanage.go
+++ b/internal/app/foldermanage.go
@@ -186,15 +186,17 @@ func (a *App) LoadCreatedFolders(rid int64) {
// 而那一页是空的——表现是界面在收藏夹后面多出一行「空白的收藏夹」,
// 勾它等于往一个不存在的收藏夹里放东西。
func (a *App) fetchCreatedFolders(c *collections, rid int64) ([]bili.CreatedFolder, error) {
- cli := c.refs.Client
- mid := cli.SelfMid()
+ return fetchCreatedFolders(context.Background(), c.refs.Client, c.refs.Client.SelfMid(), rid)
+}
+
+func fetchCreatedFolders(ctx context.Context, cli *bili.Client, mid, rid int64) ([]bili.CreatedFolder, error) {
if mid <= 0 {
return nil, errNotLoggedInForFolders
}
var all []bili.CreatedFolder
for page := 1; ; page++ {
- batch, hasMore, err := cli.CreatedFolders(context.Background(), mid, rid, page)
+ batch, hasMore, err := cli.CreatedFolders(ctx, mid, rid, page)
if err != nil {
return nil, err
}
diff --git a/internal/app/fullplayer.go b/internal/app/fullplayer.go
index 316ed028..b599b8ab 100644
--- a/internal/app/fullplayer.go
+++ b/internal/app/fullplayer.go
@@ -317,6 +317,7 @@ func pageSetFor(current Item, parts []bili.VideoPart) PageSet {
// 未展开兼容路径的 `replaceAt` 会让身份随 cid 变化;页面组路径则直接选择已存在的
// 分集项,身份和队列位置都保持稳定。
func (a *App) PlayPart(cid string) error {
+ a.playbackIntent.Add(1)
cid = strings.TrimSpace(cid)
if cid == "" {
return errors.New("没认出来要放哪一集")
diff --git a/internal/app/listening_stats.go b/internal/app/listening_stats.go
index 467f2c66..e4ffddb7 100644
--- a/internal/app/listening_stats.go
+++ b/internal/app/listening_stats.go
@@ -108,7 +108,8 @@ type StatsDayStat struct {
// Plays 是这一天起播的次数。
Plays int64 `json:"plays"`
// Completed 是这一天「听完」的次数。
- Completed int64 `json:"completed"`
+ Completed int64 `json:"completed"`
+ HourlyMs [24]int64 `json:"hourlyMs,omitzero"`
// Tracks 是这一天每一首的明细。
//
// ⚠️ **它是必要的**:Top 歌要按「这一段时间内」排,而全局那份是「所有
@@ -751,6 +752,7 @@ func (tr *listeningTracker) Tick(in statsTickIn) {
if ms := delta.Milliseconds(); ms > 0 {
d := tr.dayStatLocked(day)
d.Ms += ms
+ d.HourlyMs[in.At.Hour()] += ms
dt := tr.dayTrackLocked(d, tr.st.key)
dt.Ms += ms
diff --git a/internal/app/listening_stats_test.go b/internal/app/listening_stats_test.go
index cc6d1f30..8aef8dad 100644
--- a/internal/app/listening_stats_test.go
+++ b/internal/app/listening_stats_test.go
@@ -104,6 +104,9 @@ func TestListeningTimeCountsThePositionDelta(t *testing.T) {
if got.DayMs("2026-11-01") != 30_000 {
t.Errorf("当天时长 = %d 毫秒,want 30000", got.DayMs("2026-11-01"))
}
+ if elapsed := got.Days["2026-11-01"].HourlyMs[10]; elapsed != 30_000 {
+ t.Errorf("10 点时段时长 = %d 毫秒,want 30000", elapsed)
+ }
}
// TestListeningTimeDoesNotCountWhilePaused 钉住「暂停不算时间」。
diff --git a/internal/app/media.go b/internal/app/media.go
index cb1e22a9..958374ee 100644
--- a/internal/app/media.go
+++ b/internal/app/media.go
@@ -21,6 +21,7 @@ import (
"time"
"github.com/ShellMonster/PudMusic/internal/media"
+ "github.com/ShellMonster/PudMusic/internal/service/audio"
)
// mediaPublishEvery 是「在放的时候多久校正一次锁屏上的进度」。
@@ -77,6 +78,7 @@ func (a *App) mediaSnapshotLocked() media.NowPlaying {
ArtworkURL: a.cover,
Duration: a.duration,
Position: a.position,
+ Rate: a.rate,
}
}
@@ -157,13 +159,16 @@ func (a *App) SeekTo(t time.Duration) {
// ⚠️ 它**不是** Toggle。用户在控制中心点了「播放」而歌本来就在放的时候,
// 按切换会把它按停——那是「按了播放反而停了」,比按了没反应更糟。
func (a *App) Play() {
+ a.playbackIntent.Add(1)
a.mu.Lock()
p := a.player
a.mu.Unlock()
if p == nil || p.Playing() {
return
}
- p.Play()
+ if !a.startPlayer(p) {
+ return
+ }
a.mu.Lock()
a.playing, a.wantPlay, a.stopped = true, true, false
@@ -175,8 +180,42 @@ func (a *App) Play() {
}
}
+func (a *App) PlaybackIntent() uint64 { return a.playbackIntent.Load() }
+
+func (a *App) SetPlaybackGate(gate func() bool) {
+ a.mu.Lock()
+ a.beforePlayback = gate
+ a.mu.Unlock()
+}
+
+func (a *App) startPlayer(p *audio.Player) bool {
+ a.mu.Lock()
+ gate, intent := a.beforePlayback, a.PlaybackIntent()
+ a.mu.Unlock()
+ allowed := gate == nil || p.Playing() || gate()
+ a.mu.Lock()
+ if a.player != p || a.PlaybackIntent() != intent {
+ a.mu.Unlock()
+ return false
+ }
+ if allowed {
+ p.Play()
+ a.mu.Unlock()
+ return true
+ }
+ a.playing, a.wantPlay = false, false
+ wake := a.wake
+ a.mu.Unlock()
+ a.publishMedia()
+ if wake != nil {
+ wake()
+ }
+ return false
+}
+
// Pause 确保停着。本来就停着就什么都不做。
func (a *App) Pause() {
+ a.playbackIntent.Add(1)
a.mu.Lock()
p := a.player
a.mu.Unlock()
@@ -203,6 +242,7 @@ func (a *App) Pause() {
// 原地、按钮回到「播放」;停止之后进度条回到开头——用户按停止的意思是
// 「这首到此为止」,不是「就停在这儿」。
func (a *App) Stop() {
+ a.playbackIntent.Add(1)
a.mu.Lock()
p := a.player
if p == nil {
diff --git a/internal/app/media_test.go b/internal/app/media_test.go
index 32f4ddff..04d5f640 100644
--- a/internal/app/media_test.go
+++ b/internal/app/media_test.go
@@ -84,6 +84,43 @@ func mountedApp(t *testing.T) (*app.App, *spy) {
// 说了什么
// ─────────────────────────────────────────────────────────────────────────────
+// TestPlaybackSpeedReachesTheSystem checks that changing playback speed updates the now-playing snapshot immediately.
+func TestPlaybackSpeedReachesTheSystem(t *testing.T) {
+ application, observer := mountedApp(t)
+ if err := application.Open(filepath.Join("..", "service", "audio", "testdata", "gapless.mp3")); err != nil {
+ t.Fatal(err)
+ }
+ application.SetRate(1.75)
+ if rate := observer.last().Rate; rate != 1.75 {
+ t.Fatalf("system playback rate = %g, want 1.75", rate)
+ }
+}
+
+// TestPlaybackWaitsForAudioFocus covers the Android focus gate before opening starts playback.
+func TestPlaybackWaitsForAudioFocus(t *testing.T) {
+ application, observer := mountedApp(t)
+ var allowed bool
+ var attempts int
+ application.SetPlaybackGate(func() bool {
+ attempts++
+ if observer.last().State == media.StatePlaying {
+ t.Error("reported playback before requesting audio focus")
+ }
+ return allowed
+ })
+ if err := application.Open(filepath.Join("..", "service", "audio", "testdata", "gapless.mp3")); err != nil {
+ t.Fatal(err)
+ }
+ if attempts != 1 || application.Snapshot().Playing || observer.last().State == media.StatePlaying {
+ t.Fatal("opening a track started playback without audio focus")
+ }
+ allowed = true
+ application.Play()
+ if attempts != 2 || !application.Snapshot().Playing {
+ t.Fatal("playback did not start after audio focus was granted")
+ }
+}
+
// TestOpeningATrackReachesTheSystem 盯「打开一首歌要说一声」。
//
// 不说的话,锁屏上永远没有歌名——而这一票要的就是那个。
diff --git a/internal/app/online.go b/internal/app/online.go
index bc6d7eca..8c9358c2 100644
--- a/internal/app/online.go
+++ b/internal/app/online.go
@@ -555,7 +555,7 @@ func (a *App) restreamOnline(tr *onlineTrack, q bili.AudioQuality, pos time.Dura
p.Seek(pos)
}
if want {
- p.Play()
+ a.startPlayer(p)
}
if wake != nil {
wake()
@@ -650,7 +650,7 @@ func (a *App) restreamFromByteCache(tr *onlineTrack, rec streamaudio.Bytes,
p.Seek(pos)
}
if want {
- p.Play()
+ a.startPlayer(p)
}
if wake != nil {
wake()
@@ -1653,7 +1653,7 @@ func (a *App) installOnlinePlayer(it Item, gen int, ref *bili.StreamRef,
if pos > 0 {
p.Seek(pos)
}
- p.Play()
+ a.startPlayer(p)
}
a.publishMedia()
// 歌词跟着换歌一起换:先重置成默认值,再从缓存恢复(见 lyrics.go)。
@@ -2900,7 +2900,7 @@ func (a *App) refreshOnlineNowFor(cause error, p *audio.Player, tr *onlineTrack,
nextPlayer.Seek(pos)
}
if want {
- nextPlayer.Play()
+ a.startPlayer(nextPlayer)
}
a.publishMedia()
if wake != nil {
diff --git a/internal/app/queue.go b/internal/app/queue.go
index eeaafb63..3685c082 100644
--- a/internal/app/queue.go
+++ b/internal/app/queue.go
@@ -960,6 +960,10 @@ func (q *Queue) setCurLocked(i int, pushHist bool) bool {
// Reset 把队列换成给定的几项并从第一首开始,返回第一项。给空就是清空。
func (q *Queue) Reset(items ...Item) (Item, bool) {
+ return q.resetAt(items, 0)
+}
+
+func (q *Queue) resetAt(items []Item, index int) (Item, bool) {
q.mu.Lock()
q.items = items
q.cur = -1
@@ -979,8 +983,8 @@ func (q *Queue) Reset(items ...Item) (Item, bool) {
q.invalidate()
return Item{}, false
}
- q.cur = 0
- it := items[0]
+ q.cur = index
+ it := items[index]
q.mu.Unlock()
q.changed()
q.invalidate()
@@ -1912,6 +1916,7 @@ func filterQueueable(items []Item) (out []Item, skipped int) {
// 抽屉里点正在放的那一行,用户想的是「把指针挪回来」;列表里点一首歌,用户想的是
// 「放它」——重播一遍是对的。
func (a *App) EnqueueAndPlayNow(item Item) error {
+ a.playbackIntent.Add(1)
// 🔴 **失效的条目进不来**(票 #624):这一条是行级入口(双击 / 回车 / 封面
// 播放钮)走的路,而它要是放进去了,应用会为一条已经不存在的稿件白跑一趟
// 带签名的取流往返(实测 200~400ms),而那一趟注定失败。
@@ -2002,6 +2007,7 @@ func (a *App) EnqueueNext(item Item) error {
// 打头一项打不开就把队列原样换回去,错误返回:播不了的歌不该把用户原来的
// 队列弄丢,也不该让播放条停在一首放不了的歌上(和 step 里同一个道理)。
func (a *App) PlayFrom(items ...Item) error {
+ a.playbackIntent.Add(1)
if len(items) == 0 {
return nil
}
@@ -2018,10 +2024,27 @@ func (a *App) PlayFrom(items ...Item) error {
}
return nil
}
+ return a.replaceQueueAndPlay(items, 0)
+}
+
+// PlayFromIndex starts a list at the selected row while retaining the preceding tracks.
+func (a *App) PlayFromIndex(items []Item, index int) error {
+ a.playbackIntent.Add(1)
+ if index < 0 || index >= len(items) {
+ return fmt.Errorf("queue: index %d out of range", index)
+ }
+ if !CanQueue(items[index]) {
+ return unplayableOf(UnplayableInvalid)
+ }
+ _, skipped := filterQueueable(items[:index])
+ playable, _ := filterQueueable(items)
+ return a.replaceQueueAndPlay(playable, index-skipped)
+}
+
+func (a *App) replaceQueueAndPlay(items []Item, index int) error {
old := a.queue.Items()
cur, hadCur := a.queue.Current()
- // 给空已经在上面挡掉了,Reset 这里一定放得下(它返回的第一项就是 items[0])。
- item, _ := a.queue.Reset(items...)
+ item, _ := a.queue.resetAt(items, index)
if err := a.play(item); err != nil {
// 换回去:Reset 把 cur 落在 0,Move 把当前项挪回它原来在的位置。
//
@@ -2055,6 +2078,7 @@ func (a *App) PlayFrom(items ...Item) error {
// (第一份),而正在放的可能正是**第二份**;按下标认,这一行会被当成「另一首」
// 而从头重播——用户点的就是他正在听的那一行。
func (a *App) PlayAt(i int) error {
+ a.playbackIntent.Add(1)
if i < 0 || i >= a.queue.Len() {
return fmt.Errorf("队列里没有第 %d 首", i+1)
}
@@ -2209,7 +2233,7 @@ func (a *App) play(item Item) error {
if item.isOnline() {
err = a.playOnline(item)
} else {
- err = a.Open(item.Path)
+ err = a.openLocal(item.Path, 0, openPlay)
}
if err != nil {
return err
@@ -2228,7 +2252,7 @@ func (a *App) play(item Item) error {
// - **随机那一档**:从**洗牌袋**里抽(不重复、不遗漏,见 queue_shuffle.go)。
//
// 队列空的时候什么都不做。
-func (a *App) Next() { a.step(1) }
+func (a *App) Next() { a.playbackIntent.Add(1); a.step(1) }
// Prev 放上一首。**上一首是谁也看播放模式**(见 Queue.MovePrev):
//
@@ -2237,7 +2261,7 @@ func (a *App) Next() { a.step(1) }
// 退回按索引退一格——见 Queue.MovePrev 的注释)。
//
// 队列空的时候什么都不做。
-func (a *App) Prev() { a.step(-1) }
+func (a *App) Prev() { a.playbackIntent.Add(1); a.step(-1) }
// step 在队列里挪 delta 格并放那一首。
//
@@ -2432,7 +2456,9 @@ func (a *App) onTrackFinished() {
// 这里再显式 seek 一次:界面上的进度条读的是 `a.position`,不等解码
// goroutine 回过劲来的那一帧。
p.Seek(0)
- p.Play()
+ if !a.startPlayer(p) {
+ return
+ }
a.mu.Lock()
a.setPositionLocked(0)
a.playing, a.wantPlay = true, true
@@ -2575,6 +2601,7 @@ func (a *App) playNextAfterCurrent() error {
// 停了还得把当前曲目清干净(见 ClearTrack):只停声的话,播放条上还是那首歌的名字,
// 队列里已经空了。
func (a *App) ClearQueue() {
+ a.playbackIntent.Add(1)
a.queue.Reset()
a.ClearTrack()
}
diff --git a/internal/app/settings.go b/internal/app/settings.go
index 661ce6d2..714431c0 100644
--- a/internal/app/settings.go
+++ b/internal/app/settings.go
@@ -1160,6 +1160,10 @@ func (s *SettingsStore) LastError() error {
// 不是只服务设置——名字带 settings 是历史,改叫通用名是为了让 `upgrade.go` 那边的
// 调用读起来诚实(它写的是标记和备份,不是设置)。
func writeFileAtomic(path string, b []byte) (err error) {
+ return writeFileAtomicMode(path, b, 0o644)
+}
+
+func writeFileAtomicMode(path string, b []byte, mode os.FileMode) (err error) {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".settings-*.tmp")
if err != nil {
@@ -1185,7 +1189,7 @@ func writeFileAtomic(path string, b []byte) (err error) {
}
// CreateTemp 建出来的是 0600。设置文件本身不是秘密,但里面有下载目录、
// 代理地址这些隐私,给成普通用户配置同样的权限。
- if err = os.Chmod(name, 0o644); err != nil {
+ if err = os.Chmod(name, mode); err != nil {
return err
}
if err = os.Rename(name, path); err != nil {
diff --git a/internal/app/track_folders.go b/internal/app/track_folders.go
new file mode 100644
index 00000000..d51b74a2
--- /dev/null
+++ b/internal/app/track_folders.go
@@ -0,0 +1,70 @@
+package app
+
+import (
+ "context"
+ "errors"
+ "strconv"
+
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+)
+
+type TrackFolders struct {
+ RID int64
+ ContentType int
+ Choices []bili.CreatedFolder
+}
+
+func (a *App) LoadTrackFolders(ctx context.Context, account AccountSnapshot, item Item) (TrackFolders, error) {
+ c := a.collectionsSnapshot()
+ if c == nil || account.SelfMid <= 0 || !a.LoggedIn() {
+ return TrackFolders{}, errNotLoggedInForFolders
+ }
+ if !item.isOnline() {
+ return TrackFolders{}, errors.New("这首歌没有可收藏的来源")
+ }
+ client := c.refs.Client
+ contentType := bili.MediaVideo
+ rid, _ := strconv.ParseInt(item.Sid, 10, 64)
+ if item.Type == "audio" {
+ contentType = bili.MediaAudio
+ } else if rid <= 0 && item.Bvid != "" {
+ var err error
+ rid, err = client.ArchiveID(ctx, item.Bvid)
+ if err != nil {
+ return TrackFolders{}, err
+ }
+ }
+ if rid <= 0 {
+ return TrackFolders{}, errors.New("这首歌没有可收藏的来源")
+ }
+ if !a.accountSnapshotCurrent(account) {
+ return TrackFolders{}, ErrStaleGeneration
+ }
+ choices, err := fetchCreatedFolders(ctx, client, account.SelfMid, rid)
+ if !a.accountSnapshotCurrent(account) {
+ return TrackFolders{}, ErrStaleGeneration
+ }
+ return TrackFolders{RID: rid, ContentType: contentType, Choices: choices}, err
+}
+
+func (a *App) SaveTrackFolders(ctx context.Context, account AccountSnapshot, target TrackFolders, add, remove []int64) error {
+ c := a.collectionsSnapshot()
+ if c == nil || account.SelfMid <= 0 || !a.LoggedIn() {
+ return errNotLoggedInForFolders
+ }
+ if !a.accountSnapshotCurrent(account) {
+ return ErrStaleGeneration
+ }
+ if len(add) == 0 && len(remove) == 0 {
+ return nil
+ }
+ if err := c.refs.Client.DealFolderMedias(ctx, target.RID, target.ContentType, add, remove); err != nil {
+ return err
+ }
+ if !a.accountSnapshotCurrent(account) {
+ return ErrStaleGeneration
+ }
+ a.forgetFavoritesIfBound(add, remove)
+ a.AutoRefreshFavorites()
+ return nil
+}
diff --git a/internal/bootstrap/mobile.go b/internal/bootstrap/mobile.go
new file mode 100644
index 00000000..1017774a
--- /dev/null
+++ b/internal/bootstrap/mobile.go
@@ -0,0 +1,34 @@
+//go:build ios || android
+
+package bootstrap
+
+import (
+ "log"
+ "runtime"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/media"
+ "github.com/egoist/mygo"
+)
+
+func MobileDependencies(run func(*app.App, *media.Session) error) Dependencies {
+ d := DefaultDependencies()
+ d.MountUpdates = nil
+ d.MountNotifications = nil
+ noteMounted := d.NoteMounted
+ d.NoteMounted = func(a *app.App) {
+ if runtime.GOOS == "android" {
+ a.SetPlaybackGate(media.RequestAudioFocus)
+ }
+ mygo.App.OnSaveState(func() []byte {
+ a.SavePlayback()
+ if err := a.FlushSettings(); err != nil {
+ log.Printf("pudmusic: 进入后台时保存设置失败:%v", err)
+ }
+ return nil
+ })
+ noteMounted(a)
+ }
+ d.Run = run
+ return d
+}
diff --git a/internal/e2e/mobile_device_test.go b/internal/e2e/mobile_device_test.go
new file mode 100644
index 00000000..4cb6b5c6
--- /dev/null
+++ b/internal/e2e/mobile_device_test.go
@@ -0,0 +1,63 @@
+package e2e
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestMobileDeviceNavigation drives the installed app and keeps a screenshot of each checked page when requested.
+func TestMobileDeviceNavigation(t *testing.T) {
+ device := os.Getenv("PUDMUSIC_DEVICE_CLI")
+ if device == "" {
+ t.Skip("set PUDMUSIC_DEVICE_CLI to the agent-device command returned by device_open")
+ }
+ if !filepath.IsAbs(device) {
+ t.Fatal("PUDMUSIC_DEVICE_CLI must be an absolute path")
+ }
+ shots := os.Getenv("PUDMUSIC_DEVICE_SHOTS")
+ if shots != "" {
+ if !filepath.IsAbs(shots) {
+ t.Fatal("PUDMUSIC_DEVICE_SHOTS must be an absolute path")
+ }
+ if err := os.MkdirAll(shots, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ run := func(args ...string) {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
+ defer cancel()
+ output, err := exec.CommandContext(ctx, device, args...).CombinedOutput()
+ if err != nil {
+ t.Fatalf("agent-device %s: %v\n%s", strings.Join(args, " "), err, output)
+ }
+ }
+ press := func(label string) { run("press", "label=\""+label+"\"", "--settle") }
+ check := func(page, label string) {
+ run("wait", "label=\""+label+"\"")
+ if shots != "" {
+ run("screenshot", filepath.Join(shots, page+".png"))
+ }
+ }
+
+ run("open", "io.github.shellmonster.biu", "--relaunch")
+ check("discover", "每日推荐")
+ press("搜索")
+ check("search", "搜索歌曲、歌手、歌单或 UP 主")
+ press("我的")
+ check("my", "本地音乐")
+ press("设置")
+ check("settings", "播放与下载")
+ press("外观")
+ check("appearance", "深浅模式")
+ press("返回")
+ check("settings-back", "播放与下载")
+ press("返回")
+ press("本地音乐")
+ check("library", "添加文件")
+}
diff --git a/internal/media/android/NowPlaying.kt b/internal/media/android/NowPlaying.kt
new file mode 100644
index 00000000..7b498637
--- /dev/null
+++ b/internal/media/android/NowPlaying.kt
@@ -0,0 +1,233 @@
+package dev.mygo
+
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.app.Service
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.media.AudioAttributes
+import android.media.AudioFocusRequest
+import android.media.AudioManager
+import android.media.MediaMetadata
+import android.media.session.MediaSession
+import android.media.session.PlaybackState
+import android.os.IBinder
+import android.util.Base64
+import org.json.JSONObject
+
+private const val PLUGIN = "pudmusic_media"
+private const val CHANNEL = "pudmusic_playback"
+private const val NOTIFICATION = 4101
+
+class PudMusicMediaPlugin : MyGoPlugin {
+ override fun call(method: String, args: JSONObject, reply: PluginReply) {
+ try {
+ when (method) {
+ "publish" -> {
+ PudMusicPlayback.publish(PluginHost.context, args)
+ reply.success(null)
+ }
+ "requestFocus" -> reply.success(JSONObject().put("Granted", PudMusicPlayback.requestFocus(PluginHost.context)))
+ else -> reply.failure(PluginFailure("NoMethod", method))
+ }
+ } catch (e: RuntimeException) {
+ reply.failure(PluginFailure("MediaSession", e.message ?: e.javaClass.simpleName))
+ }
+ }
+}
+
+class PudMusicPlaybackService : Service() {
+ override fun onBind(intent: Intent?): IBinder? = null
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ PudMusicPlayback.serviceStarting = false
+ val notification = PudMusicPlayback.notification(this)
+ if (notification == null) {
+ startForeground(NOTIFICATION, PudMusicPlayback.notificationBuilder(this).build())
+ stopSelfResult(startId)
+ return START_NOT_STICKY
+ }
+ startForeground(NOTIFICATION, notification)
+ PudMusicPlayback.foreground = this
+ intent?.action?.let { PudMusicPlayback.command(it) }
+ return START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ if (PudMusicPlayback.foreground === this) PudMusicPlayback.foreground = null
+ stopForeground(STOP_FOREGROUND_REMOVE)
+ super.onDestroy()
+ }
+}
+
+private object PudMusicPlayback {
+ var foreground: PudMusicPlaybackService? = null
+ var serviceStarting = false
+ private var session: MediaSession? = null
+ private var state = "none"
+ private var title = ""
+ private var artist = ""
+ private var duration = 0L
+ private var artworkURL = ""
+ private var artwork: Bitmap? = null
+ private var focus: AudioFocusRequest? = null
+
+ fun publish(context: Context, args: JSONObject) {
+ val previousState = state
+ state = args.optString("state", "none")
+ if (state == "none" || state == "stopped" || (state == "paused" && previousState == "playing")) abandonFocus(context)
+ if (state == "none") {
+ session?.release()
+ session = null
+ artworkURL = ""
+ artwork = null
+ stopService(context)
+ return
+ }
+
+ val newTitle = args.optString("title")
+ val newArtist = args.optString("artist")
+ val newDuration = (args.optDouble("duration", 0.0) * 1000).toLong()
+ val newURL = args.optString("artworkURL")
+ val newArtwork = args.optString("artwork")
+ val metadataChanged = session == null || newTitle != title || newArtist != artist ||
+ newDuration != duration || newURL != artworkURL || newArtwork.isNotEmpty()
+ title = newTitle
+ artist = newArtist
+ duration = newDuration
+ if (newURL != artworkURL) artwork = null
+ artworkURL = newURL
+ if (newArtwork.isNotEmpty()) artwork = decodeArtwork(newArtwork)
+
+ val media = session ?: createSession(context).also { session = it }
+ if (metadataChanged) {
+ val metadata = MediaMetadata.Builder()
+ .putString(MediaMetadata.METADATA_KEY_TITLE, title)
+ .putString(MediaMetadata.METADATA_KEY_ARTIST, artist)
+ .putLong(MediaMetadata.METADATA_KEY_DURATION, duration)
+ .putBitmap(MediaMetadata.METADATA_KEY_ART, artwork)
+ media.setMetadata(metadata.build())
+ }
+ val playbackState = when (state) {
+ "playing" -> PlaybackState.STATE_PLAYING
+ "stopped" -> PlaybackState.STATE_STOPPED
+ else -> PlaybackState.STATE_PAUSED
+ }
+ var actions = PlaybackState.ACTION_PLAY or PlaybackState.ACTION_PAUSE or
+ PlaybackState.ACTION_PLAY_PAUSE or PlaybackState.ACTION_SKIP_TO_NEXT or
+ PlaybackState.ACTION_SKIP_TO_PREVIOUS or PlaybackState.ACTION_STOP
+ if (duration > 0) actions = actions or PlaybackState.ACTION_SEEK_TO
+ media.setPlaybackState(PlaybackState.Builder().setActions(actions).setState(
+ playbackState, (args.optDouble("position", 0.0) * 1000).toLong(),
+ if (state == "playing") args.optDouble("rate", 1.0).toFloat() else 0f).build())
+ media.isActive = state != "stopped"
+
+ if (state == "stopped") {
+ stopService(context)
+ } else if (state == "playing" && foreground == null && !serviceStarting) {
+ context.startForegroundService(Intent(context, PudMusicPlaybackService::class.java))
+ serviceStarting = true
+ } else if (foreground != null && (metadataChanged || previousState != state)) {
+ notification(context)?.let { manager(context).notify(NOTIFICATION, it) }
+ }
+ }
+
+ fun requestFocus(context: Context): Boolean {
+ if (focus != null) return true
+ val manager = context.getSystemService(AudioManager::class.java)
+ val attributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
+ .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()
+ val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
+ .setAudioAttributes(attributes)
+ .setWillPauseWhenDucked(true)
+ .setOnAudioFocusChangeListener { change ->
+ if (change < 0 && state == "playing") command("pause")
+ }.build()
+ if (manager.requestAudioFocus(request) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) return false
+ focus = request
+ return true
+ }
+
+ private fun abandonFocus(context: Context) {
+ val request = focus ?: return
+ focus = null
+ context.getSystemService(AudioManager::class.java).abandonAudioFocusRequest(request)
+ }
+
+ private fun stopService(context: Context) {
+ foreground?.let { service ->
+ foreground = null
+ service.stopForeground(Service.STOP_FOREGROUND_REMOVE)
+ context.stopService(Intent(context, PudMusicPlaybackService::class.java))
+ }
+ }
+
+ private fun createSession(context: Context): MediaSession = MediaSession(context, "PudMusic").apply {
+ setSessionActivity(openApp(context))
+ setCallback(object : MediaSession.Callback() {
+ override fun onPlay() = command("play")
+ override fun onPause() = command("pause")
+ override fun onSkipToNext() = command("next")
+ override fun onSkipToPrevious() = command("prev")
+ override fun onStop() = command("stop")
+ override fun onSeekTo(pos: Long) = command("seek", pos)
+ })
+ }
+
+ fun command(name: String, pos: Long = 0) {
+ if (state == "none") return
+ PluginHost.emit(PLUGIN, "command", JSONObject().put("command", name).put("position", pos / 1000.0))
+ }
+
+ fun notification(context: Context): Notification? {
+ val media = session ?: return null
+ if (state == "stopped") return null
+ val playing = state == "playing"
+ return notificationBuilder(context)
+ .setContentTitle(title)
+ .setContentText(artist)
+ .setContentIntent(openApp(context))
+ .setLargeIcon(artwork)
+ .setOnlyAlertOnce(true)
+ .setVisibility(Notification.VISIBILITY_PUBLIC)
+ .addAction(action(context, android.R.drawable.ic_media_previous, "上一首", "prev"))
+ .addAction(if (playing) action(context, android.R.drawable.ic_media_pause, "暂停", "pause")
+ else action(context, android.R.drawable.ic_media_play, "播放", "play"))
+ .addAction(action(context, android.R.drawable.ic_media_next, "下一首", "next"))
+ .setDeleteIntent(control(context, "stop"))
+ .setStyle(Notification.MediaStyle().setMediaSession(media.sessionToken).setShowActionsInCompactView(0, 1, 2))
+ .build()
+ }
+
+ fun notificationBuilder(context: Context): Notification.Builder {
+ manager(context).createNotificationChannel(NotificationChannel(CHANNEL, "音乐播放", NotificationManager.IMPORTANCE_LOW))
+ return Notification.Builder(context, CHANNEL).setSmallIcon(android.R.drawable.ic_media_play)
+ }
+
+ private fun manager(context: Context) = context.getSystemService(NotificationManager::class.java)
+
+ private fun openApp(context: Context): PendingIntent? = context.packageManager.getLaunchIntentForPackage(context.packageName)?.let {
+ PendingIntent.getActivity(context, 0, it, PendingIntent.FLAG_IMMUTABLE)
+ }
+
+ private fun control(context: Context, command: String): PendingIntent = PendingIntent.getService(context, 0,
+ Intent(context, PudMusicPlaybackService::class.java).setAction(command), PendingIntent.FLAG_IMMUTABLE)
+
+ private fun action(context: Context, icon: Int, label: String, command: String): Notification.Action =
+ Notification.Action.Builder(android.graphics.drawable.Icon.createWithResource(context, icon), label, control(context, command)).build()
+
+ private fun decodeArtwork(encoded: String): Bitmap? {
+ val data = Base64.decode(encoded, Base64.DEFAULT)
+ val options = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeByteArray(data, 0, data.size, options)
+ var sample = 1
+ while (maxOf(options.outWidth, options.outHeight) / sample > 1024) sample *= 2
+ options.inJustDecodeBounds = false
+ options.inSampleSize = sample
+ return BitmapFactory.decodeByteArray(data, 0, data.size, options)
+ }
+}
diff --git a/internal/media/artwork_darwin.go b/internal/media/artwork_darwin.go
index 1c549a3d..e0dd6f60 100644
--- a/internal/media/artwork_darwin.go
+++ b/internal/media/artwork_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/command_darwin.go b/internal/media/command_darwin.go
index 476091c2..514c6cc4 100644
--- a/internal/media/command_darwin.go
+++ b/internal/media/command_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/command_darwin_test.go b/internal/media/command_darwin_test.go
index c1bf55b8..418fe040 100644
--- a/internal/media/command_darwin_test.go
+++ b/internal/media/command_darwin_test.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/ios/NowPlaying.swift b/internal/media/ios/NowPlaying.swift
new file mode 100644
index 00000000..08404eed
--- /dev/null
+++ b/internal/media/ios/NowPlaying.swift
@@ -0,0 +1,98 @@
+import AVFoundation
+import ImageIO
+import MediaPlayer
+import UIKit
+
+final class PudMusicMediaPlugin: MyGoPlugin {
+ private var artworkURL = ""
+ private var artwork: MPMediaItemArtwork?
+ private var targets: [(MPRemoteCommand, Any)] = []
+ private var categoryError: Error?
+
+ init() {
+ do {
+ try AVAudioSession.sharedInstance().setCategory(.playback)
+ } catch {
+ categoryError = error
+ }
+ }
+
+ func call(_ method: String, _ args: [String: Any], _ reply: @escaping PluginReply) {
+ guard method == "publish" else {
+ reply(.failure(PluginFailure("NoMethod", method)))
+ return
+ }
+ if let categoryError {
+ reply(.failure(PluginFailure("AudioSession", categoryError.localizedDescription)))
+ return
+ }
+ let center = MPNowPlayingInfoCenter.default()
+ let state = args["state"] as? String ?? "none"
+ if state == "none" {
+ center.nowPlayingInfo = nil
+ for (command, target) in targets {
+ command.removeTarget(target)
+ command.isEnabled = false
+ }
+ targets.removeAll()
+ artwork = nil
+ artworkURL = ""
+ reply(.success(nil))
+ return
+ }
+
+ if targets.isEmpty {
+ let commands = MPRemoteCommandCenter.shared()
+ register(commands.playCommand, "play")
+ register(commands.pauseCommand, "pause")
+ register(commands.togglePlayPauseCommand, "toggle")
+ register(commands.nextTrackCommand, "next")
+ register(commands.previousTrackCommand, "prev")
+ register(commands.stopCommand, "stop")
+ register(commands.changePlaybackPositionCommand, "seek")
+ }
+
+ let url = args["artworkURL"] as? String ?? ""
+ if url != artworkURL {
+ artwork = nil
+ artworkURL = url
+ }
+ if let encoded = args["artwork"] as? String,
+ let data = Data(base64Encoded: encoded),
+ let source = CGImageSourceCreateWithData(data as CFData, nil),
+ let thumbnail = CGImageSourceCreateThumbnailAtIndex(source, 0, [
+ kCGImageSourceCreateThumbnailFromImageAlways: true,
+ kCGImageSourceCreateThumbnailWithTransform: true,
+ kCGImageSourceThumbnailMaxPixelSize: 1024,
+ ] as CFDictionary) {
+ let image = UIImage(cgImage: thumbnail)
+ artwork = MPMediaItemArtwork(boundsSize: image.size) { _ in image }
+ }
+
+ let duration = args["duration"] as? Double ?? 0
+ let position = args["position"] as? Double ?? 0
+ MPRemoteCommandCenter.shared().changePlaybackPositionCommand.isEnabled = duration > 0
+ var info: [String: Any] = [
+ MPMediaItemPropertyTitle: args["title"] as? String ?? "",
+ MPNowPlayingInfoPropertyElapsedPlaybackTime: position,
+ MPNowPlayingInfoPropertyPlaybackRate: state == "playing" ? (args["rate"] as? Double ?? 1.0) : 0.0,
+ ]
+ if let artist = args["artist"] as? String, !artist.isEmpty {
+ info[MPMediaItemPropertyArtist] = artist
+ }
+ if duration > 0 { info[MPMediaItemPropertyPlaybackDuration] = duration }
+ if let artwork { info[MPMediaItemPropertyArtwork] = artwork }
+ center.nowPlayingInfo = info
+ reply(.success(nil))
+ }
+
+ private func register(_ command: MPRemoteCommand, _ name: String) {
+ command.isEnabled = true
+ let target = command.addTarget { event in
+ let position = (event as? MPChangePlaybackPositionCommandEvent)?.positionTime ?? 0
+ PluginHost.emit("pudmusic_media", "command", ["command": name, "position": position])
+ return .success
+ }
+ targets.append((command, target))
+ }
+}
diff --git a/internal/media/media.go b/internal/media/media.go
index 902e16f3..97d2cddb 100644
--- a/internal/media/media.go
+++ b/internal/media/media.go
@@ -140,6 +140,7 @@ type NowPlaying struct {
// Position 是已经播到哪儿了。
Position time.Duration
+ Rate float64
}
// position 是这个快照里**不算**语义变化的那一项:它每 50ms 都变一次。
diff --git a/internal/media/mp_darwin.go b/internal/media/mp_darwin.go
index b6d01f8a..6b911619 100644
--- a/internal/media/mp_darwin.go
+++ b/internal/media/mp_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/mygo-plugin.json b/internal/media/mygo-plugin.json
new file mode 100644
index 00000000..3798175f
--- /dev/null
+++ b/internal/media/mygo-plugin.json
@@ -0,0 +1,20 @@
+{
+ "mobile": {
+ "id": "pudmusic_media",
+ "ios": {
+ "sources": ["ios/NowPlaying.swift"],
+ "class": "PudMusicMediaPlugin",
+ "frameworks": ["AVFoundation", "MediaPlayer"],
+ "infoPlist": {"UIBackgroundModes": ["audio"]},
+ "entitlements": {"application-identifier": "PUDMUSIC00.io.github.shellmonster.biu"}
+ },
+ "android": {
+ "sources": ["android/NowPlaying.kt"],
+ "class": "PudMusicMediaPlugin",
+ "permissions": ["FOREGROUND_SERVICE", "FOREGROUND_SERVICE_MEDIA_PLAYBACK"],
+ "application": [
+ ""
+ ]
+ }
+ }
+}
diff --git a/internal/media/objc_darwin.go b/internal/media/objc_darwin.go
index 59735ea0..0dd07b37 100644
--- a/internal/media/objc_darwin.go
+++ b/internal/media/objc_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/objc_darwin_test.go b/internal/media/objc_darwin_test.go
index 2456b2d3..a88b08a6 100644
--- a/internal/media/objc_darwin_test.go
+++ b/internal/media/objc_darwin_test.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/objcthread_darwin.go b/internal/media/objcthread_darwin.go
index 60137af7..4ee2b798 100644
--- a/internal/media/objcthread_darwin.go
+++ b/internal/media/objcthread_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package media
diff --git a/internal/media/platform_mobile.go b/internal/media/platform_mobile.go
new file mode 100644
index 00000000..2496097e
--- /dev/null
+++ b/internal/media/platform_mobile.go
@@ -0,0 +1,159 @@
+//go:build ios || android
+
+package media
+
+import (
+ "context"
+ "encoding/json"
+ "log"
+ "sync"
+ "time"
+
+ "github.com/egoist/mygo"
+)
+
+const mobileMediaPlugin = "pudmusic_media"
+
+func RequestAudioFocus() bool {
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ var response struct{ Granted bool }
+ return mygo.Native(mobileMediaPlugin).Call(ctx, "requestFocus", nil, &response) == nil && response.Granted
+}
+
+type mobilePlatform struct {
+ native *mygo.NativePlugin
+ fetch func(string) ([]byte, error)
+
+ mu sync.Mutex
+ ready bool
+ dirty bool
+ working bool
+ latest NowPlaying
+ artwork []byte
+ off func()
+}
+
+type mobileNowPlaying struct {
+ State string `json:"state"`
+ Title string `json:"title"`
+ Artist string `json:"artist"`
+ Duration float64 `json:"duration"`
+ Position float64 `json:"position"`
+ Rate float64 `json:"rate"`
+ ArtworkURL string `json:"artworkURL"`
+ Artwork []byte `json:"artwork,omitempty"`
+}
+
+func newPlatform(opts Options) (platform, error) {
+ fetch := opts.Fetch
+ if fetch == nil {
+ fetch = defaultFetch
+ }
+ p := &mobilePlatform{native: mygo.Native(mobileMediaPlugin), fetch: fetch}
+ mygo.App.WhenReady(func() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.ready = true
+ p.drainLocked()
+ })
+ return p, nil
+}
+
+func (p *mobilePlatform) apply(n NowPlaying) {
+ if n.State == StateNone {
+ n = NowPlaying{}
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if n.ArtworkURL != p.latest.ArtworkURL {
+ p.artwork = nil
+ if n.ArtworkURL != "" {
+ go p.fetchArtwork(n.ArtworkURL)
+ }
+ }
+ p.latest = n
+ p.dirty = true
+ p.drainLocked()
+}
+
+func (p *mobilePlatform) fetchArtwork(url string) {
+ artwork, err := p.fetch(url)
+ if err != nil || len(artwork) == 0 {
+ return
+ }
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if url != p.latest.ArtworkURL {
+ return
+ }
+ p.artwork = artwork
+ p.dirty = true
+ p.drainLocked()
+}
+
+func (p *mobilePlatform) drainLocked() {
+ if p.ready && p.dirty && !p.working {
+ p.working = true
+ go p.publish()
+ }
+}
+
+func (p *mobilePlatform) publish() {
+ for {
+ p.mu.Lock()
+ if !p.dirty {
+ p.working = false
+ p.mu.Unlock()
+ return
+ }
+ n := p.latest
+ info := mobileNowPlaying{
+ State: n.State.String(), Title: n.Title, Artist: n.Artist,
+ Duration: n.Duration.Seconds(), Position: n.Position.Seconds(), Rate: n.Rate,
+ ArtworkURL: n.ArtworkURL, Artwork: p.artwork,
+ }
+ p.dirty = false
+ p.artwork = nil
+ p.mu.Unlock()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ err := p.native.Call(ctx, "publish", info, nil)
+ cancel()
+ if err != nil {
+ log.Printf("pudmusic: 更新移动端系统媒体会话失败:%v", err)
+ }
+ }
+}
+
+func (p *mobilePlatform) attach(fn func(Command, time.Duration)) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.off != nil {
+ p.off()
+ }
+ p.off = p.native.On("command", func(data []byte) {
+ var event struct {
+ Command string
+ Position float64
+ }
+ if json.Unmarshal(data, &event) != nil {
+ return
+ }
+ for _, cmd := range [...]Command{CommandPlay, CommandPause, CommandToggle, CommandNext, CommandPrev, CommandStop, CommandSeek} {
+ if cmd.String() == event.Command {
+ fn(cmd, time.Duration(event.Position*float64(time.Second)))
+ return
+ }
+ }
+ })
+}
+
+func (p *mobilePlatform) detach() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if p.off != nil {
+ p.off()
+ p.off = nil
+ }
+}
diff --git a/internal/media/platform_other.go b/internal/media/platform_other.go
index b08b7b12..efcdc38f 100644
--- a/internal/media/platform_other.go
+++ b/internal/media/platform_other.go
@@ -1,4 +1,4 @@
-//go:build (!darwin && !windows) || (windows && !amd64 && !arm64)
+//go:build (!darwin && !windows && !android) || (windows && !amd64 && !arm64)
package media
diff --git a/internal/mobileui/android/Documents.kt b/internal/mobileui/android/Documents.kt
new file mode 100644
index 00000000..68b6556a
--- /dev/null
+++ b/internal/mobileui/android/Documents.kt
@@ -0,0 +1,177 @@
+package dev.mygo
+
+import android.app.Activity
+import android.content.ContentResolver
+import android.content.Intent
+import android.net.Uri
+import android.os.Bundle
+import android.provider.DocumentsContract
+import android.provider.OpenableColumns
+import java.io.File
+import java.io.IOException
+import java.nio.file.Files
+import java.util.Locale
+import org.json.JSONArray
+import org.json.JSONObject
+
+class PudMusicDocumentsPlugin : MyGoPlugin {
+ override fun call(method: String, args: JSONObject, reply: PluginReply) {
+ if (method == "takeShares") {
+ reply.success(PudMusicShareActivity.takeShares())
+ return
+ }
+ if (method != "pickDirectory" && method != "pickFiles") {
+ reply.failure(PluginFailure("NoMethod", method))
+ return
+ }
+ val extensions = args.optJSONArray("Extensions") ?: JSONArray()
+ val supported = (0 until extensions.length()).map { extensions.getString(it) }.toSet()
+ val directory = method == "pickDirectory"
+ val intent = if (directory) Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) else Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
+ addCategory(Intent.CATEGORY_OPENABLE)
+ type = "audio/*"
+ putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
+ }
+ intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ PluginHost.startForResult(intent) { result, data ->
+ if (result != Activity.RESULT_OK || data == null) {
+ reply.success(JSONObject())
+ } else if (directory) {
+ val tree = data.data
+ if (tree == null) reply.success(JSONObject()) else Thread { importTree(tree, supported, reply) }.start()
+ } else {
+ val documents = data.clipData?.let { clip -> (0 until clip.itemCount).mapNotNull { clip.getItemAt(it).uri } }
+ ?: listOfNotNull(data.data)
+ val context = PluginHost.context
+ Thread { reply.success(stageSelection(context, documents, "pudmusic-pick-")) }.start()
+ }
+ }
+ }
+
+ private fun importTree(tree: Uri, supported: Set, reply: PluginReply) {
+ val context = PluginHost.context
+ var staging: File? = null
+ try {
+ val directory = Files.createTempDirectory(context.cacheDir.toPath(), "pudmusic-saf-").toFile()
+ staging = directory
+ val files = JSONArray()
+ val pending = ArrayDeque()
+ val visited = HashSet()
+ pending.add(DocumentsContract.getTreeDocumentId(tree))
+ val resolver = context.contentResolver
+ var failed = 0
+ while (pending.isNotEmpty()) {
+ val id = pending.removeFirst()
+ if (!visited.add(id)) continue
+ val children = try {
+ directoryEntries(resolver, tree, id)
+ } catch (error: Exception) {
+ failed++
+ continue
+ }
+ for (child in children) {
+ if (child.directory) {
+ pending.add(child.id)
+ } else if (".${child.name.substringAfterLast('.', "").lowercase(Locale.ROOT)}" in supported) {
+ try {
+ val document = DocumentsContract.buildDocumentUriUsingTree(tree, child.id)
+ files.put(stageDocument(resolver, document, child.name, directory))
+ } catch (error: Exception) {
+ failed++
+ }
+ }
+ }
+ }
+ reply.success(JSONObject().put("Directory", directory.absolutePath).put("Files", files).put("Failed", failed))
+ } catch (error: Exception) {
+ staging?.deleteRecursively()
+ reply.failure(PluginFailure("ReadDirectory", error.javaClass.simpleName))
+ }
+ }
+
+ private data class Entry(val id: String, val name: String, val directory: Boolean)
+
+ private fun directoryEntries(resolver: ContentResolver, tree: Uri, id: String): List {
+ val children = DocumentsContract.buildChildDocumentsUriUsingTree(tree, id)
+ val columns = arrayOf(
+ DocumentsContract.Document.COLUMN_DOCUMENT_ID,
+ DocumentsContract.Document.COLUMN_DISPLAY_NAME,
+ DocumentsContract.Document.COLUMN_MIME_TYPE,
+ )
+ val cursor = resolver.query(children, columns, null, null, null) ?: throw IOException("Directory unavailable")
+ return cursor.use {
+ buildList {
+ while (it.moveToNext()) {
+ add(Entry(it.getString(0), it.getString(1) ?: "", it.getString(2) == DocumentsContract.Document.MIME_TYPE_DIR))
+ }
+ }
+ }
+ }
+}
+
+private fun stageDocument(resolver: ContentResolver, uri: Uri, name: String, directory: File): String {
+ require(uri.scheme == ContentResolver.SCHEME_CONTENT && name.isNotBlank() && File(name).name == name && name != "." && name != "..")
+ val destination = Files.createTempDirectory(directory.toPath(), "document-").toFile()
+ val output = File(destination, name)
+ try {
+ (resolver.openInputStream(uri) ?: throw IOException("Document unavailable")).use { input ->
+ output.outputStream().use { input.copyTo(it) }
+ }
+ return output.absolutePath
+ } catch (error: Exception) {
+ destination.deleteRecursively()
+ throw error
+ }
+}
+
+private fun stageSelection(context: android.content.Context, documents: List, prefix: String): JSONObject {
+ val staging = runCatching { Files.createTempDirectory(context.cacheDir.toPath(), prefix).toFile() }.getOrNull()
+ val files = JSONArray()
+ var failed = 0
+ for (uri in documents) {
+ try {
+ if (staging == null || uri.scheme != ContentResolver.SCHEME_CONTENT) throw IOException("Document unavailable")
+ val resolver = context.contentResolver
+ val name = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)?.use {
+ if (it.moveToFirst()) it.getString(0) else null
+ } ?: throw IOException("Document has no name")
+ files.put(stageDocument(resolver, uri, name, staging))
+ } catch (error: Exception) {
+ failed++
+ }
+ }
+ return JSONObject().put("Directory", staging?.absolutePath ?: "").put("Files", files).put("Failed", failed)
+}
+
+class PudMusicShareActivity : Activity() {
+ companion object {
+ private val pending = ArrayDeque()
+
+ fun takeShares(): JSONArray = synchronized(pending) {
+ val result = JSONArray()
+ while (pending.isNotEmpty()) result.put(pending.removeFirst())
+ result
+ }
+ }
+
+ @Suppress("DEPRECATION")
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (savedInstanceState != null) { finish(); return }
+ val uris = when (intent.action) {
+ Intent.ACTION_SEND -> listOfNotNull(intent.getParcelableExtra(Intent.EXTRA_STREAM))
+ Intent.ACTION_SEND_MULTIPLE -> intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM).orEmpty()
+ else -> emptyList()
+ }
+ if (uris.isEmpty()) { finish(); return }
+ Thread {
+ val result = stageSelection(this, uris, "pudmusic-share-")
+ synchronized(pending) { pending.add(result) }
+ runOnUiThread {
+ packageManager.getLaunchIntentForPackage(packageName)?.let { startActivity(it.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)) }
+ runCatching { PluginHost.emit("pudmusic_documents", "shared") }
+ finish()
+ }
+ }.start()
+ }
+}
diff --git a/internal/mobileui/collection.go b/internal/mobileui/collection.go
new file mode 100644
index 00000000..4383e797
--- /dev/null
+++ b/internal/mobileui/collection.go
@@ -0,0 +1,514 @@
+package mobileui
+
+import (
+ "cmp"
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/notice"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+)
+
+type collectionState struct {
+ pages libraryPages[bili.Media]
+ sort bili.CollectionSort
+ keyword, query, status, infoError string
+ fallbackCover string
+ filter, menu, sorting, batch, confirm bool
+ deleteFolder bool
+ working, following bool
+ selected map[collectionMediaKey]bool
+ editor folderEditor
+}
+
+type collectionMediaKey struct {
+ id int64
+ kind int
+ bvid string
+}
+
+func mediaKey(item bili.Media) collectionMediaKey {
+ return collectionMediaKey{item.ID, item.Type, item.Bvid}
+}
+
+func (s *shell) collection(c *ui.Context, page *route) {
+ ref := page.ref
+ if ref.ID <= 0 {
+ libraryMessage(c, "这一页走丢了", "找不到这张歌单。")
+ return
+ }
+ if ref.Type == 0 {
+ ref.Type = bili.CollectionFavorite
+ }
+ state, _ := page.data.(*collectionState)
+ if state == nil || state.pages.account != s.app.AccountSnapshot() {
+ state = &collectionState{}
+ page.data = state
+ s.app.LoadCollection(ref)
+ s.collectionPage(state, ref, true)
+ }
+ for {
+ result, ok := s.app.TakeCollectionNotice(ref)
+ if !ok {
+ break
+ }
+ state.following = false
+ if result.Kind == app.NoticeCollectionChanged {
+ s.collectionPage(state, ref, true)
+ } else if result.Tone == notice.Danger && !s.app.Collection(ref).Loaded {
+ state.infoError = result.Text
+ } else {
+ state.status = result.Text
+ }
+ }
+ info := s.app.Collection(ref)
+ if info.Private && (!s.app.LoggedIn() || info.OwnerMid != s.app.SelfMid()) {
+ if s.app.LoggedIn() {
+ libraryMessage(c, "这张歌单仅自己可见", "")
+ } else {
+ s.libraryLogin(c, "私人收藏夹")
+ }
+ return
+ }
+ title := info.Title
+ if title == "" {
+ title = page.title
+ }
+ if title == "" {
+ title = "歌单"
+ }
+ if state.fallbackCover == "" && state.query == "" {
+ for _, item := range state.pages.items {
+ if item.Playable() && !item.Invalid() && item.Cover != "" {
+ state.fallbackCover = item.Cover
+ break
+ }
+ }
+ }
+ imageURL := info.Cover
+ if imageURL == "" {
+ imageURL = state.fallbackCover
+ }
+ ui.Row(c).AlignItems(ui.Center).Gap(14).Margin(10, 0, 0).Children(func() {
+ cover(c, imageURL, 122, 16)
+ ui.Column(c).Grow(1).Gap(6).Children(func() {
+ ui.Text(c, title).Bold().FontSize(21).MaxLines(2)
+ if info.OwnerName != "" {
+ ui.Row(c).Gap(5).AlignItems(ui.Center).MinHeight(30).Label(info.OwnerName).OnClick(func() { s.openCreator(info.OwnerMid, info.OwnerName) }).Children(func() {
+ cover(c, info.OwnerFace, 22, 11)
+ ui.Text(c, info.OwnerName).FontSize(13).MaxLines(1)
+ })
+ }
+ kind := ref.Type.Label()
+ if ref.Type == bili.CollectionFavorite {
+ kind = "歌单"
+ }
+ if info.Private {
+ kind += " · 私密"
+ }
+ if info.Loaded {
+ kind += fmt.Sprintf(" · %d 首", info.MediaCount)
+ }
+ ui.Text(c, kind).FontSize(12).TextColor(c.Theme().TextMuted)
+ if info.PlayCount > 0 || info.FavCount > 0 {
+ ui.Text(c, fmt.Sprintf("%d 播放 · %d 收藏", info.PlayCount, info.FavCount)).FontSize(12).TextColor(c.Theme().TextMuted)
+ }
+ })
+ })
+ if info.Intro != "" {
+ ui.Text(c, info.Intro).FontSize(14).TextColor(c.Theme().TextMuted).Margin(4, 0, 8)
+ }
+ medias := collectionMatches(ref, state.pages.items, state.query)
+ playable := app.QueueItemsOfMedias(medias)
+ owned := info.OwnerMid > 0 && info.OwnerMid == s.app.SelfMid()
+ canEdit := info.Loaded && owned && ref.Type == bili.CollectionFavorite
+ ui.Row(c).AlignItems(ui.Center).Gap(5).Margin(3, 0, 0).Children(func() {
+ if state.selected == nil {
+ label := "播放全部"
+ if state.query == "" && info.Loaded {
+ label += fmt.Sprintf(" · %d 首", info.MediaCount)
+ } else if !state.pages.more {
+ label += fmt.Sprintf(" · %d 首", len(playable))
+ }
+ libraryButton(c, "play", label, true, state.working || state.pages.loading && len(medias) == 0 || state.pages.err != nil || len(playable) == 0 && !state.pages.more, func() { s.playCollection(state, ref, false) })
+ ui.Spacer(c).Grow(1)
+ if info.Loaded && !owned && s.app.LoggedIn() {
+ icon, label := "star", "收藏歌单"
+ if info.Faved {
+ icon, label = "star-on", "取消收藏"
+ }
+ iconButton(c, icon, label).Disabled(state.following).OnClick(func() {
+ state.following = true
+ s.app.SetFavorite(ref, !info.Faved)
+ })
+ }
+ iconButton(c, "more", "歌单更多").OnClick(func() { state.menu = true })
+ } else {
+ libraryButton(c, "", "全选本页", false, len(medias) == 0, func() {
+ for _, item := range medias {
+ state.selected[mediaKey(item)] = true
+ }
+ })
+ libraryButton(c, "", fmt.Sprintf("已选 %d 首", len(state.selected)), true, len(state.selected) == 0 || state.working, func() { state.batch = true })
+ ui.Spacer(c).Grow(1)
+ libraryButton(c, "", "完成", false, false, func() { state.selected = nil })
+ }
+ })
+ if state.filter {
+ ui.Row(c).AlignItems(ui.Center).Gap(5).Children(func() {
+ libraryInput(c, &state.keyword, "在这张歌单里找歌", func() {
+ state.query = strings.TrimSpace(state.keyword)
+ s.collectionPage(state, ref, true)
+ })
+ iconButton(c, "x", "关闭筛选").OnClick(func() {
+ state.filter = false
+ state.keyword, state.query = "", ""
+ state.selected = nil
+ s.collectionPage(state, ref, true)
+ })
+ })
+ }
+ if state.status != "" {
+ ui.Text(c, state.status).FontSize(13).TextColor(c.Theme().TextMuted)
+ }
+ if state.pages.err != nil || (state.infoError != "" && len(medias) == 0) {
+ libraryMessage(c, "加载歌单失败", state.infoError)
+ libraryButton(c, "refresh", "重试", false, false, func() {
+ state.infoError = ""
+ s.app.LoadCollection(ref)
+ s.collectionPage(state, ref, len(state.pages.items) == 0)
+ })
+ }
+ if !state.pages.loading && state.pages.err == nil && state.infoError == "" && len(medias) == 0 {
+ switch {
+ case state.query != "" && !state.pages.more:
+ libraryMessage(c, "列表里没有匹配的歌曲", "试试其他歌名或 UP 主昵称。")
+ libraryButton(c, "x", "清空筛选", false, false, func() {
+ state.keyword, state.query = "", ""
+ s.collectionPage(state, ref, true)
+ })
+ case state.query == "":
+ libraryMessage(c, "这张歌单还没有歌曲", "在歌曲的更多操作里选择「添加到收藏夹」。")
+ libraryButton(c, "disc", "去发现音乐", false, false, func() { s.push(route{kind: pageMixes, title: "推荐歌单"}) })
+ }
+ }
+ if state.selected == nil {
+ if len(playable) == len(medias) {
+ ui.Column(c).Gap(2).Children(func() { s.trackList(c, playable) })
+ } else {
+ playIndex := 0
+ textSize := interfaceTextSize(s.app.SettingsSnapshot().FontScale)
+ active, activeOK := s.app.Queue().Current()
+ for _, item := range medias {
+ if item.Playable() && !item.Invalid() {
+ s.trackRow(c.Key(mediaKey(item)), playable, playIndex, 38, 54, textSize, activeOK && active.Identity() == playable[playIndex].Identity())
+ playIndex++
+ } else {
+ itemRef := app.ItemOfMedia(item)
+ if itemRef.CollectionID > 0 && !item.Invalid() {
+ libraryRow(c.Key(mediaKey(item)), item.Cover, "folder", item.Title, "合集", func() {
+ s.push(route{kind: pageCollection, title: item.Title, ref: app.CollectionRef{ID: itemRef.CollectionID, Type: bili.CollectionAlbum, OwnerMid: item.OwnerMid}})
+ })
+ } else {
+ libraryRow(c.Key(mediaKey(item)), item.Cover, "disc", item.Title, "此内容无法播放", nil)
+ }
+ }
+ }
+ }
+ } else {
+ for _, item := range medias {
+ key := mediaKey(item)
+ label := "选择 " + item.Title
+ icon := "plus"
+ if state.selected[key] {
+ label, icon = "取消选择 "+item.Title, "check"
+ }
+ libraryRow(c.Key(key), "", icon, label, item.Owner, func() {
+ if state.selected[key] {
+ delete(state.selected, key)
+ } else {
+ state.selected[key] = true
+ }
+ })
+ }
+ }
+ if state.pages.loading || state.pages.more && state.pages.err == nil {
+ libraryMore(c, state.pages.loading, func() { s.collectionPage(state, ref, false) })
+ }
+ options := []mobile.Action{
+ {Label: "随机播放", Disabled: len(playable) == 0 && (!state.pages.more || state.pages.loading) || state.working, OnTap: func() { s.playCollection(state, ref, true) }},
+ {Label: "搜索歌单", OnTap: func() { state.filter = true }},
+ {Label: "排序", OnTap: func() { state.sorting = true }},
+ {Label: "多选", Disabled: len(medias) == 0, OnTap: func() { state.selected = make(map[collectionMediaKey]bool) }},
+ }
+ if canEdit {
+ options = append(options, mobile.Action{Label: "修改收藏夹", OnTap: func() {
+ state.editor = folderEditor{open: true, id: ref.ID, title: info.Title, intro: info.Intro, private: info.Private, cover: info.Cover}
+ }})
+ }
+ if canEdit && s.app.CanDeleteCollection(ref) {
+ options = append(options, mobile.Action{Label: "删除收藏夹", Destructive: true, Disabled: state.working, OnTap: func() { state.deleteFolder = true }})
+ }
+ libraryActionSheet(c, &state.menu, mobile.ActionSheetOptions{Title: title, Cancel: "取消"}, options...)
+ sorts := make([]mobile.Action, 0, len(bili.CollectionSorts))
+ for _, order := range bili.CollectionSorts {
+ label := order.Label()
+ if ref.Type != bili.CollectionFavorite && order == bili.SortByFavTime {
+ label = "默认顺序"
+ }
+ sorts = append(sorts, mobile.Action{Label: label, OnTap: func() {
+ state.sort = order
+ state.selected = nil
+ s.collectionPage(state, ref, true)
+ }})
+ }
+ libraryActionSheet(c, &state.sorting, mobile.ActionSheetOptions{Title: "排序", Cancel: "取消"}, sorts...)
+ selected := make([]bili.Media, 0, len(state.selected))
+ for _, item := range medias {
+ if state.selected[mediaKey(item)] {
+ selected = append(selected, item)
+ }
+ }
+ actions := []mobile.Action{
+ {Label: "加入队列", Disabled: len(app.QueueItemsOfMedias(selected)) == 0, OnTap: func() {
+ if err := s.app.Enqueue(app.QueueItemsOfMedias(selected)...); err != nil {
+ state.status = err.Error()
+ } else {
+ state.status = "已加入播放队列"
+ state.selected = nil
+ }
+ }},
+ {Label: "下载音频", Disabled: !s.app.DownloaderMounted(), OnTap: func() {
+ s.collectionAction(state, "已加入下载队列", func(ctx context.Context) error { return s.app.DownloadMedias(ctx, ref, selected) })
+ }},
+ }
+ if canEdit {
+ actions = append(actions, mobile.Action{Label: "从收藏夹移除", Destructive: true, OnTap: func() { state.confirm = true }})
+ }
+ libraryActionSheet(c, &state.batch, mobile.ActionSheetOptions{Title: fmt.Sprintf("已选 %d 首", len(selected)), Cancel: "取消"}, actions...)
+ libraryActionSheet(c, &state.confirm, mobile.ActionSheetOptions{Title: "从收藏夹移除?", Message: fmt.Sprintf("将移除 %d 项内容。", len(selected)), Cancel: "取消"}, mobile.Action{
+ Label: "移除", Destructive: true, OnTap: func() {
+ s.collectionAction(state, "已从收藏夹移除", func(ctx context.Context) error { return s.app.RemoveMedias(ctx, ref, selected) })
+ },
+ })
+ libraryActionSheet(c, &state.deleteFolder, mobile.ActionSheetOptions{Title: "删除收藏夹?", Message: title + "将从 B 站账号中删除。", Cancel: "取消"}, mobile.Action{
+ Label: "删除收藏夹", Destructive: true, OnTap: func() {
+ if state.working || !s.app.CanDeleteCollection(ref) {
+ return
+ }
+ state.working = true
+ s.app.DeleteCollectionFolder(ref, title, func(text string, ok bool, _ notice.Tone) {
+ s.update(func() {
+ state.working = false
+ if ok && s.current() == page {
+ s.back()
+ }
+ s.notice = text
+ })
+ })
+ },
+ })
+ s.renderFolderEditor(c, &state.editor, func() { s.app.LoadCollection(ref) })
+}
+
+func collectionMatches(ref app.CollectionRef, items []bili.Media, query string) []bili.Media {
+ query = strings.ToLower(strings.TrimSpace(query))
+ if query == "" || ref.Type == bili.CollectionFavorite {
+ return items
+ }
+ var out []bili.Media
+ for _, item := range items {
+ if strings.Contains(strings.ToLower(item.Title+" "+item.Owner), query) {
+ out = append(out, item)
+ }
+ }
+ return out
+}
+
+func (s *shell) collectionPage(state *collectionState, ref app.CollectionRef, reset bool) {
+ keyword, order := state.query, state.sort
+ if reset {
+ state.selected = nil
+ }
+ loadLibraryPage(s, &state.pages, reset, func(ctx context.Context, page int) ([]bili.Media, bool, error) {
+ if ref.Type == bili.CollectionFavorite {
+ return s.app.LoadCollectionPage(ctx, ref, order, keyword, page)
+ }
+ if keyword == "" && order == bili.SortByFavTime {
+ return s.app.LoadCollectionPage(ctx, ref, order, "", page)
+ }
+ var items []bili.Media
+ for {
+ rows, more, err := s.app.LoadCollectionPage(ctx, ref, order, "", page)
+ if err != nil {
+ return nil, false, err
+ }
+ items = append(items, rows...)
+ if !more || len(rows) == 0 {
+ break
+ }
+ page++
+ }
+ items = collectionMatches(ref, items, keyword)
+ switch order {
+ case bili.SortByPlay:
+ slices.SortStableFunc(items, func(left, right bili.Media) int { return cmp.Compare(right.View, left.View) })
+ case bili.SortByPubTime:
+ slices.SortStableFunc(items, func(left, right bili.Media) int { return right.PubTime.Compare(left.PubTime) })
+ }
+ return items, false, nil
+ })
+}
+
+func (s *shell) playCollection(state *collectionState, ref app.CollectionRef, shuffle bool) {
+ if state.working {
+ return
+ }
+ state.working = true
+ s.collectionPlayRequest++
+ request := s.collectionPlayRequest
+ intent := s.app.PlaybackIntent()
+ account := s.app.AccountSnapshot()
+ order, query := state.sort, state.query
+ items, more, next := slices.Clone(state.pages.items), state.pages.more, state.pages.next
+ go func() {
+ var err error
+ for more && err == nil {
+ var page []bili.Media
+ keyword := query
+ if ref.Type != bili.CollectionFavorite {
+ keyword = ""
+ }
+ page, more, err = s.app.LoadCollectionPage(s.ctx, ref, order, keyword, next)
+ items = append(items, page...)
+ next++
+ }
+ playable := app.QueueItemsOfMedias(collectionMatches(ref, items, query))
+ if shuffle {
+ rand.Shuffle(len(playable), func(left, right int) { playable[left], playable[right] = playable[right], playable[left] })
+ }
+ s.update(func() {
+ state.working = false
+ if s.app.AccountSnapshot() != account || s.collectionPlayRequest != request || s.app.PlaybackIntent() != intent {
+ return
+ }
+ if err != nil {
+ state.status = "歌单没有加载完,请重试。"
+ } else if len(playable) > 0 {
+ s.play(playable, 0)
+ } else {
+ state.status = "这张歌单没有可播放的歌曲。"
+ }
+ })
+ }()
+}
+
+func (s *shell) collectionAction(state *collectionState, success string, action func(context.Context) error) {
+ if state.working {
+ return
+ }
+ state.working = true
+ go func() {
+ err := action(s.ctx)
+ s.update(func() {
+ state.working = false
+ if err != nil {
+ state.status = err.Error()
+ return
+ }
+ state.selected, state.status = nil, success
+ })
+ }()
+}
+
+type folderEditor struct {
+ open, saving, private bool
+ id int64
+ title, intro, status string
+ cover string
+ crop folderCoverCrop
+}
+
+func (s *shell) renderFolderEditor(c *ui.Context, state *folderEditor, saved func()) {
+ if state.crop.uploading {
+ if imageURL, ok := s.app.TakeCoverURL(); ok {
+ state.cover = imageURL
+ state.crop = folderCoverCrop{}
+ }
+ }
+ if state.saving || state.crop.uploading {
+ for {
+ result, ok := s.app.TakeFolderResult()
+ if !ok {
+ break
+ }
+ if state.crop.uploading && result.Op == app.FolderOpCover {
+ state.crop.uploading, state.crop.status = false, result.Text
+ break
+ }
+ if !state.saving {
+ continue
+ }
+ if state.id == 0 && result.Op != app.FolderOpCreate || state.id != 0 && result.Op != app.FolderOpEdit {
+ continue
+ }
+ state.saving, state.status = false, result.Text
+ if result.OK {
+ state.open = false
+ saved()
+ }
+ break
+ }
+ }
+ title := "新建收藏夹"
+ if state.id != 0 {
+ title = "修改收藏夹"
+ }
+ librarySheet(c, &state.open, mobile.SheetOptions{Label: title, Detents: []float32{0.67, 0.92}, NoDismiss: state.saving || state.crop.picking || state.crop.uploading}, func() {
+ ui.Scroll(c).Fill().Padding(16).Gap(10).Children(func() {
+ ui.Text(c, title).Bold().FontSize(20)
+ ui.Row(c).AlignItems(ui.Center).Gap(8).Children(func() {
+ cover(c, state.cover, 50, 8)
+ libraryButton(c, "image", "选择封面", false, state.saving || state.crop.picking || state.crop.uploading || !s.app.CollectionsMounted(), func() { s.pickFolderCover(state) })
+ })
+ ui.TextInput(c, &state.title).Placeholder("名称(必填,最多 20 字)").Label("收藏夹名称").Height(44)
+ ui.TextArea(c, &state.intro).Placeholder("简介(最多 200 字)").Label("收藏夹简介").Height(90)
+ ui.Row(c).AlignItems(ui.Center).Gap(6).Children(func() {
+ ui.Text(c, "设为私密").Grow(1)
+ ui.Switch(c, &state.private).Label("设为私密")
+ })
+ if state.status != "" {
+ ui.Text(c, state.status).FontSize(13).TextColor(c.Theme().Danger)
+ }
+ ui.Row(c).Gap(8).Children(func() {
+ libraryButton(c, "", "取消", false, state.saving || state.crop.picking || state.crop.uploading, func() { state.open = false })
+ libraryButton(c, "", "保存", true, state.saving || state.crop.picking || state.crop.uploading || strings.TrimSpace(state.title) == "", func() {
+ draft := bili.FolderDraft{Title: state.title, Intro: state.intro, Cover: state.cover}
+ if state.private {
+ draft.Privacy = 1
+ }
+ state.saving = true
+ if state.id == 0 {
+ s.app.CreateFolder(draft)
+ } else {
+ s.app.EditFolder(state.id, draft)
+ }
+ })
+ })
+ })
+ })
+ s.folderCoverSheet(c, state)
+}
+
+func (s *shell) openCreator(mid int64, title string) {
+ if mid > 0 {
+ s.push(route{kind: pageCreator, id: strconv.FormatInt(mid, 10), title: title})
+ }
+}
diff --git a/internal/mobileui/collection_cover.go b/internal/mobileui/collection_cover.go
new file mode 100644
index 00000000..29482162
--- /dev/null
+++ b/internal/mobileui/collection_cover.go
@@ -0,0 +1,138 @@
+package mobileui
+
+import (
+ "bytes"
+ "encoding/base64"
+ "errors"
+ "image"
+ "image/jpeg"
+ _ "image/png"
+ "math"
+ "os"
+
+ "github.com/egoist/mygo"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+ "golang.org/x/image/draw"
+)
+
+type folderCoverCrop struct {
+ image image.Image
+ preview *ui.Bitmap
+ zoom mobile.ZoomState
+ open, picking, uploading bool
+ status string
+}
+
+func (s *shell) pickFolderCover(state *folderEditor) {
+ if s.win == nil {
+ return
+ }
+ state.crop.picking = true
+ go func() {
+ files, err := mygo.Dialog.Open(mygo.OpenDialogOptions{Parent: s.win, Title: "选择收藏夹封面", Filters: []mygo.FileFilter{{
+ Name: "图片", Extensions: []string{"png", "jpg", "jpeg"}, MIMETypes: []string{"image/png", "image/jpeg"},
+ }}})
+ var src image.Image
+ if err == nil && len(files) > 0 {
+ src, err = readFolderCover(files[0])
+ }
+ var preview *ui.Bitmap
+ if src != nil {
+ preview = ui.NewBitmap(src)
+ }
+ s.update(func() {
+ state.crop.picking = false
+ if err != nil {
+ state.status = "无法打开这张图片。请选择有效的 PNG 或 JPEG 图片。"
+ } else if src != nil {
+ state.status = ""
+ state.crop = folderCoverCrop{image: src, preview: preview, open: true}
+ }
+ })
+ }()
+}
+
+func readFolderCover(path string) (image.Image, error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer file.Close()
+ config, _, err := image.DecodeConfig(file)
+ if err != nil {
+ return nil, err
+ }
+ if config.Width <= 0 || config.Height <= 0 || int64(config.Width)*int64(config.Height) > 30_000_000 {
+ return nil, errors.New("unsupported cover dimensions")
+ }
+ if _, err := file.Seek(0, 0); err != nil {
+ return nil, err
+ }
+ src, _, err := image.Decode(file)
+ return src, err
+}
+
+func (s *shell) folderCoverSheet(c *ui.Context, state *folderEditor) {
+ crop := &state.crop
+ librarySheet(c, &crop.open, mobile.SheetOptions{Label: "裁剪封面", Detents: []float32{0.68, 0.92}, NoDismiss: crop.uploading}, func() {
+ width, _ := c.Size()
+ side := min(width-32, float32(260))
+ ui.Column(c).AlignItems(ui.Center).Padding(16).Gap(10).Children(func() {
+ ui.Text(c, "裁剪封面").FontSize(20).Bold()
+ ui.Text(c, "双指缩放,拖动调整取景。").FontSize(13).TextColor(c.Theme().TextMuted)
+ mobile.Zoomable(c, &crop.zoom, mobile.ZoomOptions{}, func() {
+ ui.Image(c, crop.preview).Size(side, side).Fit(ui.Cover)
+ }).Size(side, side).Radius(12)
+ if crop.status != "" {
+ ui.Text(c, crop.status).FontSize(13).TextColor(c.Theme().Danger)
+ }
+ ui.Row(c).Gap(8).Children(func() {
+ libraryButton(c, "", "取消", false, crop.uploading, func() { crop.open = false })
+ libraryButton(c, "", "使用此封面", true, crop.uploading || crop.image == nil, func() { s.uploadFolderCover(crop, side) })
+ })
+ })
+ })
+}
+
+func (s *shell) uploadFolderCover(crop *folderCoverCrop, side float32) {
+ if crop.uploading {
+ return
+ }
+ crop.uploading, crop.status = true, ""
+ src, zoom := crop.image, crop.zoom
+ account := s.app.AccountSnapshot()
+ go func() {
+ var jpegData bytes.Buffer
+ err := jpeg.Encode(&jpegData, cropFolderImage(src, zoom, side), &jpeg.Options{Quality: 88})
+ s.update(func() {
+ if account != s.app.AccountSnapshot() {
+ crop.uploading = false
+ return
+ }
+ if err != nil {
+ crop.uploading, crop.status = false, "无法处理这张图片,请重试。"
+ return
+ }
+ s.app.UploadCover("data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpegData.Bytes()))
+ })
+ }()
+}
+
+func cropFolderImage(src image.Image, zoom mobile.ZoomState, previewSide float32) image.Image {
+ bounds := src.Bounds()
+ side := float64(min(bounds.Dx(), bounds.Dy()))
+ scale := float64(max(zoom.Scale, 1))
+ span := max(1, int(math.Round(side/scale)))
+ pixelsPerPoint := side / float64(max(previewSide, 1)) / scale
+ left := clampCrop(bounds.Min.X+(bounds.Dx()-span)/2-int(math.Round(float64(zoom.X)*pixelsPerPoint)), bounds.Min.X, bounds.Max.X-span)
+ top := clampCrop(bounds.Min.Y+(bounds.Dy()-span)/2-int(math.Round(float64(zoom.Y)*pixelsPerPoint)), bounds.Min.Y, bounds.Max.Y-span)
+ pixels := min(512, span)
+ output := image.NewRGBA(image.Rect(0, 0, pixels, pixels))
+ draw.CatmullRom.Scale(output, output.Bounds(), src, image.Rect(left, top, left+span, top+span), draw.Src, nil)
+ return output
+}
+
+func clampCrop(value, lower, upper int) int {
+ return min(upper, max(lower, value))
+}
diff --git a/internal/mobileui/collection_pane.go b/internal/mobileui/collection_pane.go
new file mode 100644
index 00000000..af6adb24
--- /dev/null
+++ b/internal/mobileui/collection_pane.go
@@ -0,0 +1,69 @@
+package mobileui
+
+import (
+ "strconv"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+)
+
+func (s *shell) collectionSiblings() []browseCollection {
+ stack := s.stacks[s.tab]
+ if len(stack) < 2 {
+ return nil
+ }
+ parent := stack[len(stack)-2]
+ switch state := parent.data.(type) {
+ case *discoverState:
+ return state.mixes.cards
+ case *discoverDetail:
+ if state.mixes != nil {
+ return state.mixes.cards
+ }
+ case *mobileSearchState:
+ if state.query != "" {
+ return state.results[mobileSearchMixes].mixes
+ }
+ return state.mixes.cards
+ case *myLibraryState:
+ var cards []browseCollection
+ for _, group := range []app.FavoriteGroup{app.FavoritesCreated, app.FavoritesCollected} {
+ for _, folder := range s.app.SideFavorites(group) {
+ if !folder.Invalid {
+ ref := app.CollectionRef{ID: folder.ID, OwnerMid: folder.Mid, Type: bili.ParseCollectionType(strconv.Itoa(folder.Type))}
+ cards = append(cards, browseCollection{ref: ref, title: folder.Title, cover: folder.Cover, count: folder.MediaCount})
+ }
+ }
+ }
+ return cards
+ }
+ return nil
+}
+
+func (s *shell) collectionIndex(c *ui.Context, selected app.CollectionRef, cards []browseCollection) {
+ settingsPageHeading(c, "歌单")
+ seen := make(map[string]bool, len(cards))
+ for _, card := range cards {
+ key := card.ref.Key()
+ if seen[key] {
+ continue
+ }
+ seen[key] = true
+ subtitle := card.ref.Type.Label()
+ if card.owner != "" {
+ subtitle = card.owner
+ }
+ row := libraryRow(c.Key(key), card.cover, "folder", card.title, subtitle, func() {
+ if s.current().ref.Key() == key {
+ return
+ }
+ stack := s.stacks[s.tab]
+ s.stacks[s.tab] = stack[:len(stack)-1]
+ s.push(route{kind: pageCollection, title: card.title, ref: card.ref})
+ })
+ if key == selected.Key() {
+ row.AccessSelected(true).Background(phonePalette(c).soft)
+ }
+ }
+}
diff --git a/internal/mobileui/collection_playback_test.go b/internal/mobileui/collection_playback_test.go
new file mode 100644
index 00000000..4a54af1e
--- /dev/null
+++ b/internal/mobileui/collection_playback_test.go
@@ -0,0 +1,88 @@
+package mobileui
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "testing"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+)
+
+func mixedCollectionFixture(t *testing.T) (*shell, *collectionState) {
+ t.Helper()
+ server := httptest.NewServer(http.HandlerFunc(http.NotFound))
+ t.Cleanup(server.Close)
+ client := bili.NewClient(bili.Options{Transport: server.Client().Transport})
+ client.TestOnlyPointHostsAtFixture(server.URL)
+ a := app.New()
+ t.Cleanup(a.Close)
+ a.TestOnlyNoAutoLyrics()
+ a.MountStreaming(app.Streaming{Client: client, Media: server.Client(), TempDir: t.TempDir()})
+ s := newShell(t.Context(), a)
+ state := &collectionState{}
+ state.pages.account = a.AccountSnapshot()
+ state.pages.items = []bili.Media{
+ {ID: 10, Type: 2, Bvid: "BVfixture10", Title: "第一首"},
+ {ID: 20, Type: 2, Bvid: "BVfixture20", Title: "失效内容", Attr: 1},
+ {ID: 30, Type: 2, Bvid: "BVfixture30", Title: "第三首"},
+ }
+ s.push(route{kind: pageCollection, ref: app.CollectionRef{ID: 42, Type: bili.CollectionFavorite}, data: state})
+ return s, state
+}
+
+// TestMobileMixedCollectionKeepsPlayableQueue checks that an unavailable row does not split the playlist.
+func TestMobileMixedCollectionKeepsPlayableQueue(t *testing.T) {
+ s, _ := mixedCollectionFixture(t)
+ tester := ui.NewTester(s.view, 390, 844)
+ if err := tester.Click("第三首"); err != nil {
+ t.Fatal(err)
+ }
+ queue := s.app.Queue().Snapshot()
+ first, _ := queue.At(0)
+ if queue.Len() != 2 || first.Title != "第一首" {
+ t.Fatalf("queue length = %d, first = %q", queue.Len(), first.Title)
+ }
+}
+
+// TestMobileCollectionCompletionRespectsNewerPlayback verifies that a delayed Play All cannot replace a later local selection.
+func TestMobileCollectionCompletionRespectsNewerPlayback(t *testing.T) {
+ s, state := mixedCollectionFixture(t)
+ updates := make(chan func(), 1)
+ s.dispatch = func(fn func()) { updates <- fn }
+ s.playCollection(state, s.current().ref, false)
+ update := <-updates
+ local := app.LocalItem(filepath.Join("..", "service", "audio", "testdata", "tone.mp3"))
+ if err := s.app.PlayFromIndex([]app.Item{local}, 0); err != nil {
+ t.Fatal(err)
+ }
+ update()
+ if current, ok := s.app.Queue().Current(); !ok || current.Path != local.Path {
+ t.Fatalf("collection completion replaced %q with %q", local.Path, current.Path)
+ }
+}
+
+// TestTabletCollectionSwitchesDetailsFromTheIndex verifies that related playlists stay reachable beside an open playlist.
+func TestTabletCollectionSwitchesDetailsFromTheIndex(t *testing.T) {
+ s, _ := mixedCollectionFixture(t)
+ first := s.current().ref
+ second := app.CollectionRef{ID: 43, Type: bili.CollectionFavorite}
+ s.stacks[0][0].data = &discoverState{mixes: browseMixes{cards: []browseCollection{
+ {ref: first, title: "歌单甲"}, {ref: second, title: "歌单乙"},
+ }}}
+ tester := ui.NewTester(s.view, 780, 844)
+ index, indexFound := tester.Find("歌单乙")
+ track, trackFound := tester.Find("第一首")
+ if !indexFound || !trackFound || index.X+index.W > track.X {
+ t.Fatalf("playlist list and track detail did not appear side by side: %v, %v", index, track)
+ }
+ mobileLibraryShot(t, tester, "tablet-collection.png")
+ if err := tester.Click("歌单乙"); err != nil {
+ t.Fatal(err)
+ }
+ if s.current().ref != second || len(s.stacks[0]) != 2 {
+ t.Fatalf("playlist selection = %+v, stack depth = %d", s.current().ref, len(s.stacks[0]))
+ }
+}
diff --git a/internal/mobileui/components.go b/internal/mobileui/components.go
new file mode 100644
index 00000000..e157cbb2
--- /dev/null
+++ b/internal/mobileui/components.go
@@ -0,0 +1,160 @@
+package mobileui
+
+import (
+ "runtime"
+ "strconv"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/ui/iconset"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/imgcache"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/tok"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/netimage"
+)
+
+type palette struct {
+ surface, fill, field, text, muted, accent, soft, line ui.Color
+}
+
+func phonePalette(c *ui.Context) palette {
+ tokens := tok.Of(c.Theme())
+ return palette{tokens.Surface, tokens.Bg, tokens.Surface2, tokens.Text, tokens.Text2, tokens.AccentText, tokens.AccentSoft, tokens.Line}
+}
+
+func touchSize() float32 {
+ if runtime.GOOS == "android" {
+ return 48
+ }
+ return 44
+}
+
+func glyph(c *ui.Context, name string, size float32, color ui.Color) ui.Element {
+ return ui.Icon(c, iconset.Must("Pud/"+name+".svg")).Size(size, size).TextColor(color).Shrink(0)
+}
+
+func iconButton(c *ui.Context, name, label string) ui.Element {
+ return ui.Box(c).Role(ui.RoleButton).Label(label).Size(touchSize(), touchSize()).Shrink(0).Radius(touchSize() / 2).Center().Children(func() {
+ glyph(c, name, 18, c.Theme().Text)
+ })
+}
+
+func brand(c *ui.Context) {
+ ui.Box(c).Size(24, 24).Radius(12).Background(ui.Hex("#17181b")).Center().Children(func() {
+ glyph(c, "disc", 19, ui.Hex("#f26449"))
+ })
+}
+
+func cover(c *ui.Context, url string, size, radius float32) ui.Element {
+ if url == "" {
+ palette := phonePalette(c)
+ return ui.Box(c).Size(size, size).Shrink(0).Radius(radius).Background(palette.field).Center().Children(func() {
+ glyph(c, "disc", min(size*.46, 44), palette.muted)
+ })
+ }
+ return netimage.Image(c, imgcache.FormatURLProtocol(url), netimage.Options{MaxSide: int(size * 3)}).Size(size, size).Radius(radius).Shrink(0)
+}
+
+func sectionHeading(c *ui.Context, title, action string) bool {
+ clicked := false
+ ui.Row(c).AlignItems(ui.Center).MinHeight(32).FillWidth().Children(func() {
+ ui.Text(c, title).FontSize(16).FontWeight(600).Grow(1).Basis(0)
+ if action != "" {
+ clicked = ui.Row(c).Role(ui.RoleButton).Label(action).MinHeight(touchSize()).Gap(4).AlignItems(ui.Center).Children(func() {
+ color := phonePalette(c).muted
+ ui.Text(c, action).FontSize(13).TextColor(color)
+ glyph(c, "right", 12, color)
+ }).Clicked()
+ }
+ })
+ return clicked
+}
+
+func (s *shell) trackList(c *ui.Context, items []app.Item) {
+ coverSize, height := float32(48), float32(58)
+ if s.current().kind == pageCollection {
+ coverSize, height = 38, 54
+ }
+ textSize := interfaceTextSize(s.app.SettingsSnapshot().FontScale)
+ occurrences := make(map[string]int, len(items))
+ active, activeOK := s.app.Queue().Current()
+ for index, item := range items {
+ id := item.Identity()
+ occurrences[id]++
+ key := c.Key(id + ":" + strconv.Itoa(occurrences[id]))
+ s.trackRow(key, items, index, coverSize, height, textSize, activeOK && active.Identity() == id)
+ }
+}
+
+func (s *shell) trackRow(c *ui.Context, items []app.Item, index int, coverSize, height, textSize float32, active bool) {
+ item := items[index]
+ ui.Row(c).FillWidth().MinHeight(height).Gap(4).AlignItems(ui.Center).Children(func() {
+ first := ui.Row(c).Grow(1).Basis(0).MinHeight(touchSize()).Gap(12).AlignItems(ui.Center).Role(ui.RoleButton).Label(item.Title).Disabled(!app.CanQueue(item)).Children(func() {
+ cover(c, item.Cover, coverSize, 7)
+ trackLabel(c, item.Title, item.Artist, textSize, active)
+ })
+ first.OnClick(func() { s.play(items, index) })
+ more := iconButton(c, "more", "更多操作:"+item.Title)
+ if first.LongPressed() || more.Clicked() {
+ s.player.target = item
+ s.player.show(sheetTrack)
+ }
+ })
+}
+
+func interfaceTextSize(scale app.FontScale) float32 {
+ switch scale {
+ case app.FontScaleSmall:
+ return 12
+ case app.FontScaleLarge:
+ return 17
+ default:
+ return 13
+ }
+}
+
+func trackLabel(c *ui.Context, title, subtitle string, size float32, current bool) {
+ palette := phonePalette(c)
+ ink := palette.text
+ if current {
+ ink = palette.accent
+ }
+ ui.Column(c).Grow(1).Basis(0).Gap(2).Children(func() {
+ ui.Text(c, title).FontSize(size).FontWeight(500).MaxLines(1).Ellipsis("…").TextColor(ink)
+ if subtitle != "" {
+ ui.Text(c, subtitle).FontSize(max(size-1, 12)).MaxLines(1).Ellipsis("…").TextColor(palette.muted)
+ }
+ })
+}
+
+func (s *shell) play(items []app.Item, index int) {
+ if len(items) == 0 {
+ return
+ }
+ s.report(s.app.PlayFromIndex(items, index))
+}
+
+func (s *shell) report(err error) {
+ if err != nil {
+ s.notice = err.Error()
+ }
+}
+
+func timeLabel(value time.Duration) string {
+ seconds := int(max(value, 0) / time.Second)
+ minutes := strconv.Itoa(seconds / 60)
+ rest := strconv.Itoa(seconds % 60)
+ if len(rest) == 1 {
+ rest = "0" + rest
+ }
+ return minutes + ":" + rest
+}
+
+func completedSwipe(element ui.Element) (float32, float32, bool) {
+ touches := element.Touches()
+ if len(touches) != 1 || touches[0].Phase != ui.TouchEnded {
+ return 0, 0, false
+ }
+ touch := touches[0]
+ return touch.X - touch.StartX, touch.Y - touch.StartY, true
+}
diff --git a/internal/mobileui/discover.go b/internal/mobileui/discover.go
new file mode 100644
index 00000000..4b9aeed0
--- /dev/null
+++ b/internal/mobileui/discover.go
@@ -0,0 +1,636 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/ShellMonster/PudMusic/internal/ui/iconset"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/tok"
+ "github.com/egoist/mygo/ui"
+)
+
+type browseOwner struct {
+ mid int64
+ name string
+}
+
+type browseCollection struct {
+ ref app.CollectionRef
+ title string
+ cover string
+ owner string
+ count int
+}
+
+type browseMusic struct {
+ rows []app.RecommendItem
+ started bool
+ loading bool
+ err error
+}
+
+type browseMixes struct {
+ cards []browseCollection
+ started bool
+ loading bool
+ err error
+}
+
+type discoverState struct {
+ daily browseMusic
+ mixes browseMixes
+ refresh ui.RefreshState
+ albumBusy bool
+}
+
+type discoverDetail struct {
+ music browseMusic
+ mixes *browseMixes
+ feature browseCollection
+ tracks []app.Item
+ page int
+ more bool
+ busy bool
+}
+
+func (s *shell) discoverHomeState(page *route) *discoverState {
+ if state, ok := page.data.(*discoverState); ok {
+ return state
+ }
+ state := &discoverState{}
+ page.data = state
+ return state
+}
+
+func (s *shell) discoverRefresh(page *route, scroll ui.Element) {
+ if page.kind != pageDiscover {
+ return
+ }
+ state := s.discoverHomeState(page)
+ if scroll.PullToRefresh(&state.refresh) {
+ s.loadDiscoverHome(state)
+ }
+}
+
+func (s *shell) loadDiscoverHome(state *discoverState) {
+ if state.daily.loading || state.mixes.loading {
+ return
+ }
+ state.daily.started, state.daily.loading = true, true
+ state.mixes.started, state.mixes.loading = true, true
+ refreshing := state.refresh.Refreshing
+ go func() {
+ ctx, cancel := context.WithTimeout(s.ctx, 20*time.Second)
+ defer cancel()
+ rows, _, dailyErr := s.app.RecommendOf().Feed(ctx, app.HomeTabMusic, 1)
+ s.update(func() {
+ state.daily.loading, state.daily.err = false, dailyErr
+ if dailyErr == nil {
+ state.daily.rows = rows
+ }
+ })
+ var cards []browseCollection
+ err := dailyErr
+ if err == nil {
+ cards, err = s.publicMusicCollections(ctx, recommendOwners(rows), "")
+ }
+ s.update(func() {
+ state.mixes.loading, state.mixes.err = false, err
+ if err == nil {
+ state.mixes.cards = cards
+ } else if refreshing {
+ s.notice = "暂时无法刷新推荐"
+ }
+ state.refresh.Refreshing = false
+ })
+ }()
+}
+
+func recommendOwners(rows []app.RecommendItem) []browseOwner {
+ owners := make([]browseOwner, 0, len(rows))
+ for _, row := range rows {
+ owners = append(owners, browseOwner{mid: row.OwnerMid, name: row.Owner})
+ }
+ return owners
+}
+
+func (s *shell) publicMusicCollections(ctx context.Context, owners []browseOwner, keyword string) ([]browseCollection, error) {
+ const ownerLimit = 4
+ seenOwners := make(map[int64]bool, ownerLimit)
+ seenCards := make(map[string]bool)
+ var cards []browseCollection
+ var lastErr error
+ succeeded := false
+ keyword = strings.ToLower(strings.TrimSpace(keyword))
+ for _, owner := range owners {
+ if owner.mid <= 0 || seenOwners[owner.mid] {
+ continue
+ }
+ if len(seenOwners) == ownerLimit || ctx.Err() != nil {
+ break
+ }
+ seenOwners[owner.mid] = true
+ page, err := s.app.UpSeries(ctx, owner.mid, 1, 12)
+ if err != nil {
+ lastErr = err
+ continue
+ }
+ succeeded = true
+ for _, item := range page.Items {
+ if item.ID <= 0 || item.Title == "" || !strings.Contains(strings.ToLower(item.Title), keyword) {
+ continue
+ }
+ ref := app.CollectionRef{ID: item.ID, OwnerMid: owner.mid}
+ switch item.Type {
+ case 2:
+ ref.Type = bili.CollectionAlbum
+ case 3:
+ ref.Type = bili.CollectionSeries
+ default:
+ continue
+ }
+ if seenCards[ref.Key()] {
+ continue
+ }
+ seenCards[ref.Key()] = true
+ cards = append(cards, browseCollection{ref: ref, title: item.Title, cover: item.Cover, owner: owner.name, count: item.Count})
+ }
+ }
+ if !succeeded {
+ if ctx.Err() != nil {
+ return nil, ctx.Err()
+ }
+ return nil, lastErr
+ }
+ return cards, nil
+}
+
+func (s *shell) discover(c *ui.Context, page *route) {
+ if page.kind != pageDiscover {
+ s.discoverSubpage(c, page)
+ return
+ }
+ state := s.discoverHomeState(page)
+ if !state.daily.started {
+ s.loadDiscoverHome(state)
+ }
+ palette := tok.Of(c.Theme())
+ ui.Column(c).FillWidth().Gap(18).Children(func() {
+ if ui.ButtonBase(c).Label("搜索歌曲、歌手、歌单").FillWidth().MinHeight(max(46, touchSize())).Radius(28).
+ Background(palette.Surface2).Padding(0, 15).Children(func() {
+ ui.Row(c).FillWidth().Gap(10).AlignItems(ui.Center).Children(func() {
+ glyph(c, "search", 18, palette.Text2)
+ ui.Text(c, "搜索歌曲、歌手、歌单").FontSize(13).TextColor(palette.Text2)
+ })
+ }).Clicked() {
+ s.openSearch()
+ }
+ ui.Row(c).FillWidth().Gap(4).Children(func() {
+ for _, item := range []struct {
+ kind pageKind
+ title string
+ icon string
+ }{{pageDaily, "每日推荐", "calendar"}, {pageChart, "排行榜", "stats"}, {pageNews, "新歌速递", "music"}, {pageMixes, "歌单", "queue"}} {
+ if ui.ButtonBase(c).Label(item.title).Grow(1).Width(0).Radius(12).Padding(0, 0, 4, 0).
+ Children(func() {
+ ui.Column(c).FillWidth().AlignItems(ui.Center).Gap(4).Children(func() {
+ ui.Box(c).Size(39, 39).Background(palette.AccentSoft).Radius(20).Center().Children(func() {
+ if item.icon == "music" {
+ ui.Icon(c, iconset.Must("Media/music-2-line.svg")).Size(22, 22).TextColor(palette.AccentText)
+ } else {
+ glyph(c, item.icon, 22, palette.AccentText)
+ }
+ })
+ ui.Text(c, item.title).FontSize(12).Bold().SingleLine().Ellipsis("…")
+ })
+ }).Clicked() {
+ s.push(route{kind: item.kind, title: item.title, data: &discoverDetail{mixes: &state.mixes}})
+ }
+ }
+ })
+ ui.Column(c).FillWidth().Gap(10).Children(func() {
+ if sectionHeading(c, "推荐歌单", "更多") {
+ s.push(route{kind: pageMixes, title: "推荐歌单", data: &discoverDetail{mixes: &state.mixes}})
+ }
+ s.renderMixes(c, &state.mixes, 3, func() { s.loadDiscoverHome(state) })
+ })
+ tracks := recommendTracks(state.daily.rows)
+ feature, single := discoverFeatured(state.mixes.cards, tracks)
+ if feature.title != "" || state.mixes.loading {
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ sectionHeading(c, "今日一张", "")
+ if feature.title == "" {
+ ui.Box(c).FillWidth().Height(80).Radius(16).Background(palette.Bg)
+ return
+ }
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(6).Padding(9).Radius(16).Background(palette.Bg).Children(func() {
+ open := ui.ButtonBase(c).Label("打开今日一张 " + feature.title).Grow(1).Width(0).Children(func() {
+ ui.Row(c).FillWidth().Gap(12).AlignItems(ui.Center).Children(func() {
+ cover(c, feature.cover, 62, 10)
+ ui.Column(c).Grow(1).MinWidth(0).Gap(3).Children(func() {
+ ui.Text(c, feature.title).FontSize(16).Bold().SingleLine().Ellipsis("…")
+ ui.Text(c, collectionSubtitle(feature)).FontSize(12).TextColor(palette.Text2).SingleLine().Ellipsis("…")
+ })
+ })
+ })
+ if open.Clicked() {
+ detail := &discoverDetail{feature: feature}
+ if single.Bvid != "" {
+ detail.music.started, detail.tracks = true, []app.Item{single}
+ }
+ s.push(route{kind: pageAlbum, title: "今日一张", ref: feature.ref, data: detail})
+ }
+ hit := touchSize()
+ if ui.ButtonBase(c).Size(hit, hit).Center().Radius(hit / 2).Background(palette.Surface).
+ Label("播放今日一张").Disabled(state.albumBusy).Children(func() {
+ glyph(c, "play", 18, palette.AccentText)
+ }).Clicked() {
+ if single.Bvid != "" {
+ s.play([]app.Item{single}, 0)
+ } else {
+ s.playFeatured(feature, &state.albumBusy, false)
+ }
+ }
+ })
+ })
+ }
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ if sectionHeading(c, "挑一首听", "查看全部") {
+ s.push(route{kind: pageDaily, title: "每日推荐"})
+ }
+ if len(tracks) > 0 {
+ s.trackList(c, tracks[:min(3, len(tracks))])
+ } else if state.daily.loading {
+ browseTrackPlaceholders(c, 3)
+ } else {
+ browseStatus(c, state.daily.loading, state.daily.err, "暂无推荐歌曲", func() { s.loadDiscoverHome(state) })
+ }
+ })
+ })
+}
+
+func discoverFeatured(cards []browseCollection, tracks []app.Item) (browseCollection, app.Item) {
+ if len(cards) > 0 {
+ return cards[0], app.Item{}
+ }
+ for _, track := range tracks {
+ if track.Cover != "" {
+ return browseCollection{title: track.Title, cover: track.Cover, owner: track.Artist, count: 1}, track
+ }
+ }
+ return browseCollection{}, app.Item{}
+}
+
+func (s *shell) renderMixes(c *ui.Context, mixes *browseMixes, maximum int, retry func()) {
+ if len(mixes.cards) != 0 {
+ s.collectionGrid(c, mixes.cards[:min(maximum, len(mixes.cards))])
+ return
+ }
+ if mixes.loading {
+ width, _ := c.Size()
+ size := collectionGridSize(width)
+ palette := tok.Of(c.Theme())
+ ui.Row(c).FillWidth().Gap(10).Children(func() {
+ for range 3 {
+ ui.Column(c).Width(size).Gap(6).Children(func() {
+ ui.Box(c).Size(size, size).Radius(12).Background(palette.Surface2)
+ ui.Box(c).Size(size*0.7, 13).Radius(4).Background(palette.Surface2)
+ ui.Box(c).Size(size*0.5, 12).Radius(4).Background(palette.Surface2)
+ })
+ }
+ })
+ return
+ }
+ browseStatus(c, false, mixes.err, "暂无公开歌单", retry)
+}
+
+func collectionGridSize(width float32) float32 {
+ return (max(0, width-52)) / 3
+}
+
+func (s *shell) collectionGrid(c *ui.Context, cards []browseCollection) {
+ palette := tok.Of(c.Theme())
+ width, _ := c.Size()
+ size := collectionGridSize(width)
+ ui.Column(c).FillWidth().Gap(12).Children(func() {
+ for start := 0; start < len(cards); start += 3 {
+ ui.Row(c).FillWidth().Gap(10).Children(func() {
+ for _, card := range cards[start:min(start+3, len(cards))] {
+ if ui.ButtonBase(c).Key("mix:" + card.ref.Key()).Label(card.title).Width(size).Radius(12).Children(func() {
+ ui.Column(c).FillWidth().Gap(5).Children(func() {
+ cover(c, card.cover, size, 12)
+ ui.Text(c, card.title).FontSize(13).FontWeight(550).SingleLine().Ellipsis("…")
+ ui.Text(c, fmt.Sprintf("%s · %d 首", mixKindLabel(card), card.count)).FontSize(12).TextColor(palette.Text2).SingleLine().Ellipsis("…")
+ })
+ }).Clicked() {
+ s.push(route{kind: pageCollection, title: card.title, ref: card.ref})
+ }
+ }
+ })
+ }
+ })
+}
+
+func mixKindLabel(card browseCollection) string {
+ if card.ref.Type == bili.CollectionSeries {
+ return "系列"
+ }
+ if card.ref.Type == bili.CollectionAlbum {
+ return "合集"
+ }
+ return "单曲"
+}
+
+func collectionSubtitle(card browseCollection) string {
+ if card.owner == "" {
+ return fmt.Sprintf("%s · %d 首", mixKindLabel(card), card.count)
+ }
+ return fmt.Sprintf("%s · %d 首", card.owner, card.count)
+}
+
+func (s *shell) playFeatured(feature browseCollection, busy *bool, enqueue bool) {
+ if *busy {
+ return
+ }
+ *busy = true
+ if !enqueue {
+ s.collectionPlayRequest++
+ }
+ request, intent := s.collectionPlayRequest, s.app.PlaybackIntent()
+ go func() {
+ ctx, cancel := context.WithTimeout(s.ctx, 15*time.Second)
+ defer cancel()
+ var tracks []app.Item
+ var err error
+ var more bool
+ for page := 1; page <= 10 && len(tracks) < 200; page++ {
+ medias, hasMore, loadErr := s.app.LoadCollectionPage(ctx, feature.ref, bili.SortByFavTime, "", page)
+ tracks = appendBrowseTracks(tracks, app.QueueItemsOfMedias(medias))
+ more, err = hasMore, loadErr
+ if !more || err != nil || len(medias) == 0 {
+ break
+ }
+ }
+ s.update(func() {
+ *busy = false
+ switch {
+ case !enqueue && (s.collectionPlayRequest != request || s.app.PlaybackIntent() != intent):
+ return
+ case err != nil:
+ s.notice = "暂时无法加载这张歌单"
+ case len(tracks) == 0:
+ s.notice = "这张歌单暂无可播放歌曲"
+ case enqueue:
+ s.report(s.app.Enqueue(tracks...))
+ default:
+ s.play(tracks, 0)
+ }
+ if err == nil && more && s.notice == "" {
+ s.notice = fmt.Sprintf("已加入 %d 首歌曲,歌单中还有更多", len(tracks))
+ }
+ })
+ }()
+}
+
+func (s *shell) discoverSubpage(c *ui.Context, page *route) {
+ state, ok := page.data.(*discoverDetail)
+ if !ok {
+ state = &discoverDetail{}
+ page.data = state
+ }
+ kind := page.kind
+ if kind == pageMixes {
+ if state.mixes == nil {
+ state.mixes = &browseMixes{}
+ }
+ if !state.mixes.started {
+ s.loadDiscoverMixes(state.mixes)
+ }
+ s.renderMixes(c, state.mixes, len(state.mixes.cards), func() { s.loadDiscoverMixes(state.mixes) })
+ return
+ }
+ load := func() { s.loadDiscoverDetail(state, kind) }
+ if !state.music.started {
+ load()
+ }
+ tracks := state.tracks
+ if len(tracks) == 0 {
+ browseStatus(c, state.music.loading, state.music.err, "暂无可播放歌曲", load)
+ return
+ }
+ palette := tok.Of(c.Theme())
+ coverURL, title, subtitle := tracks[0].Cover, page.title, fmt.Sprintf("%d 首", len(tracks))
+ if kind == pageAlbum {
+ coverURL, title, subtitle = state.feature.cover, state.feature.title, collectionSubtitle(state.feature)
+ }
+ ui.Column(c).FillWidth().Gap(12).Children(func() {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(12).Children(func() {
+ cover(c, coverURL, 62, 12)
+ ui.Column(c).Grow(1).MinWidth(0).Gap(4).Children(func() {
+ ui.Text(c, title).FontSize(20).Bold().SingleLine().Ellipsis("…")
+ ui.Text(c, subtitle).FontSize(12).TextColor(palette.Text2)
+ })
+ })
+ ui.Row(c).FillWidth().Gap(8).Children(func() {
+ if browseAction(c, "play", "播放全部", true) {
+ if kind == pageAlbum && state.more {
+ s.playFeatured(state.feature, &state.busy, false)
+ } else {
+ s.play(tracks, 0)
+ }
+ }
+ if kind == pageAlbum && browseAction(c, "plus", "加入队列", false) {
+ if state.more {
+ s.playFeatured(state.feature, &state.busy, true)
+ } else {
+ s.report(s.app.Enqueue(tracks...))
+ }
+ }
+ })
+ if kind == pageChart {
+ s.discoverRankedTracks(c, tracks)
+ } else {
+ s.trackList(c, tracks)
+ }
+ if state.more {
+ browseMore(c, state.music.loading, state.music.err, load)
+ }
+ })
+}
+
+func (s *shell) discoverRankedTracks(c *ui.Context, tracks []app.Item) {
+ palette := tok.Of(c.Theme())
+ active, hasActive := s.app.Queue().Current()
+ for index, track := range tracks {
+ ui.Row(c.Key(track.Identity())).FillWidth().MinHeight(58).Gap(4).AlignItems(ui.Center).Children(func() {
+ color := palette.Text2
+ if index < 3 {
+ color = palette.AccentText
+ }
+ ui.Text(c, fmt.Sprint(index+1)).Width(26).TextColor(color).FontSize(13).Bold()
+ item := ui.Row(c).Grow(1).Basis(0).MinHeight(touchSize()).Gap(10).AlignItems(ui.Center).
+ Role(ui.RoleButton).Label(track.Title).Children(func() {
+ cover(c, track.Cover, 48, 8)
+ trackLabel(c, track.Title, track.Artist, 13, hasActive && active.Identity() == track.Identity())
+ })
+ if item.Clicked() {
+ s.play(tracks, index)
+ }
+ more := iconButton(c, "more", "更多操作:"+track.Title)
+ if item.LongPressed() || more.Clicked() {
+ s.player.target = track
+ s.player.show(sheetTrack)
+ }
+ })
+ }
+}
+
+func (s *shell) loadDiscoverMixes(mixes *browseMixes) {
+ if mixes.loading {
+ return
+ }
+ mixes.started, mixes.loading = true, true
+ go func() {
+ ctx, cancel := context.WithTimeout(s.ctx, 20*time.Second)
+ defer cancel()
+ rows, _, err := s.app.RecommendOf().Feed(ctx, app.HomeTabMusic, 1)
+ var cards []browseCollection
+ if err == nil {
+ cards, err = s.publicMusicCollections(ctx, recommendOwners(rows), "")
+ }
+ s.update(func() {
+ mixes.loading, mixes.err = false, err
+ if err == nil {
+ mixes.cards = cards
+ }
+ })
+ }()
+}
+
+func (s *shell) loadDiscoverDetail(state *discoverDetail, kind pageKind) {
+ if state.music.loading {
+ return
+ }
+ state.music.started, state.music.loading, state.music.err = true, true, nil
+ page, ref := state.page+1, state.feature.ref
+ go func() {
+ ctx, cancel := context.WithTimeout(s.ctx, 15*time.Second)
+ defer cancel()
+ var tracks []app.Item
+ var more bool
+ var err error
+ if kind == pageAlbum {
+ medias, hasMore, fetchErr := s.app.LoadCollectionPage(ctx, ref, bili.SortByFavTime, "", page)
+ tracks, more, err = app.QueueItemsOfMedias(medias), hasMore, fetchErr
+ } else {
+ var rows []app.RecommendItem
+ switch kind {
+ case pageChart:
+ rows, _, err = s.app.RecommendOf().Feed(ctx, app.HomeTabHot, page)
+ case pageNews:
+ rows, _, err = s.app.RecommendOf().NewMusic(ctx)
+ default:
+ rows, _, err = s.app.RecommendOf().Feed(ctx, app.HomeTabMusic, page)
+ more = len(rows) > 0
+ }
+ tracks = recommendTracks(rows)
+ }
+ s.update(func() {
+ state.music.loading, state.music.err = false, err
+ if err == nil {
+ state.page, state.more = page, more
+ state.tracks = appendBrowseTracks(state.tracks, tracks)
+ }
+ })
+ }()
+}
+
+func recommendTracks(rows []app.RecommendItem) []app.Item {
+ tracks := make([]app.Item, 0, len(rows))
+ for _, row := range rows {
+ if row.Item.Bvid != "" {
+ tracks = append(tracks, row.Item)
+ }
+ }
+ return tracks
+}
+
+func appendBrowseTracks(existing, incoming []app.Item) []app.Item {
+ seen := make(map[string]bool, len(existing)+len(incoming))
+ for _, track := range existing {
+ seen[track.Identity()] = true
+ }
+ for _, track := range incoming {
+ identity := track.Identity()
+ if identity == "" || seen[identity] {
+ continue
+ }
+ seen[identity] = true
+ existing = append(existing, track)
+ }
+ return existing
+}
+
+func browseStatus(c *ui.Context, loading bool, err error, empty string, retry func()) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).FillWidth().AlignItems(ui.Center).Gap(8).Padding(18, 8).Children(func() {
+ switch {
+ case loading:
+ ui.Text(c, "正在加载…").FontSize(13).TextColor(palette.Text2)
+ case err != nil:
+ ui.Text(c, "加载失败,请重试").FontSize(13).TextColor(palette.Text2)
+ if retry != nil && browseAction(c, "refresh", "重试", false) {
+ retry()
+ }
+ default:
+ ui.Text(c, empty).FontSize(13).TextColor(palette.Text2)
+ }
+ })
+}
+
+func browseMore(c *ui.Context, loading bool, err error, load func()) {
+ if loading {
+ browseStatus(c, true, nil, "", nil)
+ return
+ }
+ if err != nil {
+ browseStatus(c, false, err, "", load)
+ return
+ }
+ if browseAction(c, "down", "加载更多", false) {
+ load()
+ }
+}
+
+func browseTrackPlaceholders(c *ui.Context, count int) {
+ palette := tok.Of(c.Theme())
+ for range count {
+ ui.Row(c).FillWidth().MinHeight(58).Gap(12).AlignItems(ui.Center).Children(func() {
+ ui.Box(c).Size(48, 48).Radius(8).Background(palette.Surface2)
+ ui.Column(c).Gap(4).Children(func() {
+ ui.Box(c).Size(100, 13).Radius(4).Background(palette.Surface2)
+ ui.Box(c).Size(72, 12).Radius(4).Background(palette.Surface2)
+ })
+ })
+ }
+}
+
+func browseAction(c *ui.Context, icon, label string, primary bool) bool {
+ palette := tok.Of(c.Theme())
+ background, foreground := palette.Surface2, palette.Text
+ if primary {
+ background, foreground = palette.Accent, palette.AccentInk
+ }
+ return ui.ButtonBase(c).Label(label).MinHeight(touchSize()).Padding(0, 12).Radius(22).Background(background).Children(func() {
+ ui.Row(c).Gap(6).AlignItems(ui.Center).Children(func() {
+ if icon != "" {
+ glyph(c, icon, 15, foreground)
+ }
+ ui.Text(c, label).FontSize(13).Bold().TextColor(foreground)
+ })
+ }).Clicked()
+}
diff --git a/internal/mobileui/discover_test.go b/internal/mobileui/discover_test.go
new file mode 100644
index 00000000..bb128523
--- /dev/null
+++ b/internal/mobileui/discover_test.go
@@ -0,0 +1,147 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+)
+
+// TestMobileDiscoverOpensLiveCollectionAndDailyRoutes checks that the on-screen cards and shortcuts navigate with the returned collection identity.
+func TestMobileDiscoverOpensLiveCollectionAndDailyRoutes(t *testing.T) {
+ s, wait := mobileBrowseFixture(t)
+ tester := ui.NewTester(func(c *ui.Context) {
+ ui.Scroll(c).Fill().Children(func() {
+ ui.Column(c).FillWidth().Padding(8, 16).Children(func() {
+ page := s.current()
+ if page.kind == pageCollection {
+ ui.Text(c, page.title)
+ return
+ }
+ s.discover(c, page)
+ })
+ })
+ }, 390, 740)
+ wait(tester, "公开音乐合集")
+ mobileLibraryShot(t, tester, "discover-fixture.png")
+ for _, label := range []string{"每日推荐", "排行榜", "新歌速递", "歌单", "播放今日一张"} {
+ if _, ok := tester.Find(label); !ok {
+ t.Fatalf("missing Discover action %q", label)
+ }
+ }
+ if err := tester.Click("公开音乐合集"); err != nil {
+ t.Fatal(err)
+ }
+ ref := s.current().ref
+ if s.current().kind != pageCollection || ref.ID != 101 || ref.OwnerMid != 42 || ref.Type != bili.CollectionAlbum {
+ t.Fatalf("collection route=%+v", s.current())
+ }
+ s.back()
+ tester.Frame()
+ if err := tester.Click("打开今日一张 公开音乐合集"); err != nil {
+ t.Fatal(err)
+ }
+ wait(tester, "合集曲目")
+ s.back()
+ tester.Frame()
+ if err := tester.Click("每日推荐"); err != nil {
+ t.Fatal(err)
+ }
+ wait(tester, "推荐曲目")
+ if s.current().kind != pageDaily {
+ t.Fatalf("daily shortcut opened %v", s.current().kind)
+ }
+}
+
+func mobileBrowseFixture(t *testing.T) (*shell, func(*ui.Tester, string)) {
+ t.Helper()
+ fixture := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ q := r.URL.Query()
+ var data string
+ switch r.URL.Path {
+ case "/x/web-interface/nav":
+ data = `{"wbi_img":{"img_url":"https://test.invalid/0123456789abcdef0123456789abcdef.png","sub_url":"https://test.invalid/abcdef0123456789abcdef0123456789.png"}}`
+ case "/x/web-interface/region/feed/rcmd":
+ data = `{"archives":[{"bvid":"BVtestDaily","cid":9,"title":"推荐曲目","author":{"mid":42,"name":"音乐 UP 主"}}]}`
+ case "/x/polymer/web-space/seasons_series_list":
+ data = `{"items_lists":{"page":{"total":0}}}`
+ if q.Get("mid") == "42" {
+ data = `{"items_lists":{"seasons_list":[{"meta":{"season_id":101,"name":"公开音乐合集","total":1}}],"page":{"total":1}}}`
+ }
+ case "/x/polymer/web-space/seasons_archives_list":
+ if q.Get("mid") != "42" || q.Get("season_id") != "101" {
+ t.Errorf("collection archive request: %s", q.Encode())
+ }
+ data = `{"archives":[{"aid":2,"bvid":"BVtestAlbum","title":"合集曲目","duration":60}],"page":{"page_num":1,"page_size":20,"total":1}}`
+ case "/x/copyright-music-publicity/toplist/all_period":
+ data = `{"list":{"2026":[{"ID":9,"priod":1,"publish_time":1760000000}]}}`
+ case "/x/copyright-music-publicity/toplist/music_list":
+ data = `{"list":[{"music_id":"100","music_title":"音乐","singer":"测试歌手","mv_bvid":"BVtestHot","creation_first_cid":8}]}`
+ case "/main/suggest":
+ data = `{"tag":[{"term":"音乐联想"}]}`
+ case "/x/web-interface/wbi/search/type":
+ switch {
+ case q.Get("search_type") == "bili_user":
+ data = `{"numResults":1,"result":[{"mid":42,"uname":"搜索到的 UP 主","fans":50}]}`
+ case q.Get("tids") == "":
+ data = `{"numResults":1,"result":[{"bvid":"BVtestVideo","title":"视频结果","author":"音乐 UP 主","mid":42}]}`
+ case q.Get("order") == "pubdate":
+ data = `{"numResults":1,"result":[{"bvid":"BVtestLatest","title":"最新歌曲结果","author":"音乐 UP 主","mid":42}]}`
+ default:
+ data = `{"numResults":1,"result":[{"bvid":"BVtestSong","title":"歌曲结果","author":"音乐 UP 主","mid":42}]}`
+ }
+ default:
+ t.Errorf("unexpected fixture path: %s", r.URL.Path)
+ http.NotFound(w, r)
+ return
+ }
+ fmt.Fprintf(w, `{"code":0,"data":%s}`, data)
+ }))
+ t.Cleanup(fixture.Close)
+ a := app.New()
+ t.Cleanup(a.Close)
+ client := bili.NewClient(bili.Options{Transport: fixture.Client().Transport})
+ client.TestOnlyPointHostsAtFixture(fixture.URL)
+ a.MountLogin(app.NewMemoryStore("mobile fixture"), client)
+ a.MountSearch(client)
+ a.MountRecommend(client)
+ a.MountExplore(client)
+ a.MountCollections(app.CollectionRefs{Client: client})
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ s := newShell(ctx, a)
+ updates := make(chan func(), 32)
+ s.dispatch = func(update func()) {
+ select {
+ case updates <- update:
+ case <-ctx.Done():
+ }
+ }
+ t.Cleanup(a.AddWake(func() { s.dispatch(func() {}) }))
+ wait := func(tester *ui.Tester, text string) {
+ t.Helper()
+ deadline := time.NewTimer(3 * time.Second)
+ defer deadline.Stop()
+ for {
+ tester.Frame()
+ if slices.Contains(tester.Texts(), text) {
+ return
+ }
+ select {
+ case update := <-updates:
+ update()
+ case <-deadline.C:
+ t.Fatalf("missing %q in %q", text, tester.Texts())
+ }
+ }
+ }
+ return s, wait
+}
diff --git a/internal/mobileui/document_open.go b/internal/mobileui/document_open.go
new file mode 100644
index 00000000..e952aa8f
--- /dev/null
+++ b/internal/mobileui/document_open.go
@@ -0,0 +1,49 @@
+package mobileui
+
+import (
+ "context"
+ "net/url"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/egoist/mygo"
+)
+
+type mobileDocumentSelection struct {
+ Directory string
+ Files []string
+ Failed int
+}
+
+func (s *shell) watchDocumentShares() func() {
+ if runtime.GOOS == "ios" {
+ return mygo.App.OnOpenURL(func(value string) {
+ location, err := url.Parse(value)
+ if err != nil || location.Scheme != "file" || location.Host != "" || !filepath.IsAbs(location.Path) {
+ return
+ }
+ go s.finishLocalImport(&localLibraryState{base: mobileImportBase()}, []string{location.Path}, 0, nil)
+ })
+ }
+ if runtime.GOOS != "android" {
+ return func() {}
+ }
+ plugin := mygo.Native("pudmusic_documents")
+ take := func() {
+ var shares []mobileDocumentSelection
+ if err := plugin.Call(context.WithoutCancel(s.ctx), "takeShares", nil, &shares); err != nil {
+ return
+ }
+ for _, share := range shares {
+ s.finishLocalImport(&localLibraryState{base: mobileImportBase()}, share.Files, share.Failed, nil)
+ if share.Directory != "" && strings.HasPrefix(filepath.Base(share.Directory), "pudmusic-share-") {
+ _ = os.RemoveAll(share.Directory)
+ }
+ }
+ }
+ off := plugin.On("shared", func([]byte) { go take() })
+ mygo.App.WhenReady(func() { go take() })
+ return off
+}
diff --git a/internal/mobileui/document_paths.go b/internal/mobileui/document_paths.go
new file mode 100644
index 00000000..9b4df1ec
--- /dev/null
+++ b/internal/mobileui/document_paths.go
@@ -0,0 +1,73 @@
+package mobileui
+
+import (
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+)
+
+func restoreMobileImportPaths(application *app.App, base string) error {
+ if base == "" {
+ return nil
+ }
+ settings := application.SettingsSnapshot()
+ settings.LocalMusicDirs = slices.Clone(settings.LocalMusicDirs)
+ settings.Playback.Items = slices.Clone(settings.Playback.Items)
+ changed := false
+ rebase := func(path string) string {
+ resolved := currentMobileImportPath(base, path)
+ changed = changed || resolved != path
+ return resolved
+ }
+ for index, root := range settings.LocalMusicDirs {
+ settings.LocalMusicDirs[index] = rebase(root)
+ }
+ updateIdentity := func(identity string) string {
+ if path, ok := strings.CutPrefix(identity, "local:"); ok {
+ return "local:" + rebase(path)
+ }
+ return identity
+ }
+ for index := range settings.Playback.Items {
+ settings.Playback.Items[index].ID = updateIdentity(settings.Playback.Items[index].ID)
+ }
+ settings.Playback.Current = updateIdentity(settings.Playback.Current)
+ settings.PlaybackResume.TrackKey = updateIdentity(settings.PlaybackResume.TrackKey)
+ if !changed {
+ return nil
+ }
+ updated, err := application.UpdateSettings(func(next *app.Settings) {
+ next.LocalMusicDirs = settings.LocalMusicDirs
+ next.Playback = settings.Playback
+ next.PlaybackResume = settings.PlaybackResume
+ })
+ if err == nil {
+ application.SetLocalRoots(updated.LocalMusicDirs)
+ }
+ return err
+}
+
+func currentMobileImportPath(base, path string) string {
+ if !filepath.IsAbs(path) {
+ return path
+ }
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ return path
+ }
+ _, relative, ok := strings.Cut(filepath.Clean(path), "/Library/Application Support/"+filepath.Base(filepath.Dir(base))+"/"+localImportDirectory+"/")
+ if !ok {
+ return path
+ }
+ parts := strings.Split(relative, string(filepath.Separator))
+ if len(parts) > 2 || !strings.HasPrefix(parts[0], "audio-") {
+ return path
+ }
+ candidate := filepath.Join(base, relative)
+ if info, err := os.Stat(candidate); err == nil && (len(parts) == 1 && info.IsDir() || len(parts) == 2 && info.Mode().IsRegular()) {
+ return candidate
+ }
+ return path
+}
diff --git a/internal/mobileui/document_paths_test.go b/internal/mobileui/document_paths_test.go
new file mode 100644
index 00000000..c621de9d
--- /dev/null
+++ b/internal/mobileui/document_paths_test.go
@@ -0,0 +1,52 @@
+package mobileui
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+)
+
+// TestMobileImportsSurviveASandboxMove checks that the restored queue opens the copied music at its new location.
+func TestMobileImportsSurviveASandboxMove(t *testing.T) {
+ application := app.New()
+ t.Cleanup(application.Close)
+ if err := application.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ application.TestOnlyNoAutoLyrics()
+ relative := filepath.Join("Library", "Application Support", "PudMusic", localImportDirectory)
+ sandbox := t.TempDir()
+ base := filepath.Join(sandbox, "new", relative)
+ root, err := copyMobileImport(base, filepath.Join("..", "service", "audio", "testdata", "tone.mp3"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ oldRoot := filepath.Join(sandbox, "old", relative, filepath.Base(root))
+ oldID := "local:" + filepath.Join(oldRoot, "tone.mp3")
+ unrelated := filepath.Join(sandbox, "other", "tone.mp3")
+ if _, err := application.UpdateSettings(func(settings *app.Settings) {
+ settings.LocalMusicDirs = []string{oldRoot, unrelated}
+ settings.Playback = app.PlaybackSnapshot{Current: oldID, Items: []app.PlaybackEntry{{ID: oldID, Title: "Imported audio"}}}
+ settings.PlaybackResume.TrackKey = oldID
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := restoreMobileImportPaths(application, base); err != nil {
+ t.Fatal(err)
+ }
+ if err := application.RestorePlayback(); err != nil {
+ t.Fatal(err)
+ }
+ if state := application.Snapshot(); !state.HasTrack || state.Playing || state.Path != filepath.Join(root, "tone.mp3") {
+ t.Fatalf("restored playback = %q, loaded = %t, playing = %t", state.Path, state.HasTrack, state.Playing)
+ }
+ settings := application.SettingsSnapshot()
+ if settings.LocalMusicDirs[0] != root || settings.LocalMusicDirs[1] != unrelated || settings.PlaybackResume.TrackKey != "local:"+filepath.Join(root, "tone.mp3") {
+ t.Fatalf("restored library = %v, resume = %q", settings.LocalMusicDirs, settings.PlaybackResume.TrackKey)
+ }
+ if _, err := os.Stat(oldRoot); !os.IsNotExist(err) {
+ t.Fatalf("old sandbox unexpectedly recreated: %v", err)
+ }
+}
diff --git a/internal/mobileui/library.go b/internal/mobileui/library.go
new file mode 100644
index 00000000..9cdfc31d
--- /dev/null
+++ b/internal/mobileui/library.go
@@ -0,0 +1,771 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/notice"
+ "github.com/ShellMonster/PudMusic/internal/ui/iconset"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+)
+
+type libraryPages[Item any] struct {
+ account app.AccountSnapshot
+ items []Item
+ next int
+ more bool
+ loading bool
+ err error
+ cancel context.CancelFunc
+ version uint64
+}
+
+func loadLibraryPage[Item any](s *shell, state *libraryPages[Item], reset bool, load func(context.Context, int) ([]Item, bool, error)) {
+ if reset {
+ if state.cancel != nil {
+ state.cancel()
+ }
+ state.items, state.next, state.more = nil, 1, true
+ } else if state.loading || !state.more {
+ return
+ }
+ state.version++
+ state.loading, state.err = true, nil
+ state.account = s.app.AccountSnapshot()
+ account, version, page := state.account, state.version, state.next
+ ctx, cancel := context.WithCancel(s.ctx)
+ state.cancel = cancel
+ go func() {
+ defer cancel()
+ items, more, err := load(ctx, page)
+ s.update(func() {
+ if state.version != version || s.app.AccountSnapshot() != account {
+ return
+ }
+ state.loading, state.err, state.cancel = false, err, nil
+ if err == nil {
+ state.items = append(state.items, items...)
+ state.next, state.more = page+1, more
+ }
+ })
+ }()
+}
+
+func (s *shell) library(c *ui.Context, page *route) {
+ switch page.kind {
+ case pageMy:
+ s.myLibrary(c, page)
+ case pageHistory, pageLater:
+ s.libraryHistory(c, page)
+ case pageLocal:
+ s.localMusic(c, page)
+ case pageDownloads:
+ s.downloadLibrary(c, page)
+ case pageFollowing:
+ s.followingLibrary(c, page)
+ case pageFeed:
+ s.feedLibrary(c, page)
+ case pageCreator:
+ s.libraryCreator(c, page)
+ case pageStats:
+ s.libraryStats(c, page)
+ default:
+ libraryMessage(c, "这一页走丢了", "返回上一页继续浏览。")
+ }
+}
+
+type myLibraryState struct {
+ account app.AccountSnapshot
+ nav app.AccountNav
+ group app.FavoriteGroup
+ menu bool
+ logout bool
+ bind bool
+ recent libraryPages[app.LibraryItem]
+ local []app.LibraryItem
+ editor folderEditor
+}
+
+type libraryDestination struct {
+ kind pageKind
+ label, icon, path string
+ requiresLogin bool
+}
+
+var libraryDestinations = []libraryDestination{
+ {pageHistory, "最近播放", "history", "/history", false},
+ {pageLocal, "本地音乐", "disc", "/local-music", false},
+ {pageDownloads, "下载", "download", "/download-list", false},
+ {pageLater, "稍后再看", "later", "/later", true},
+ {pageFollowing, "我的关注", "users", "/follow", true},
+ {pageFeed, "关注动态", "bell", "/dynamic-feed", true},
+ {pageStats, "听歌统计", "stats", "/stats", false},
+}
+
+func (s *shell) myLibrary(c *ui.Context, page *route) {
+ account := s.app.AccountSnapshot()
+ loggedIn := s.app.LoggedIn()
+ hidden := s.app.HiddenMenuKeySet()
+ state, _ := page.data.(*myLibraryState)
+ if state == nil || state.account != account {
+ state = &myLibraryState{account: account}
+ page.data = state
+ weekly, _ := s.app.ListeningStats()
+ state.local = libraryLocalHistory(weekly, app.LibraryQuery{})
+ if loggedIn {
+ go func(target *myLibraryState) {
+ nav, err := s.app.AccountNav(s.ctx)
+ if err == nil {
+ s.update(func() { target.nav = nav })
+ }
+ }(state)
+ if s.app.LibraryOf().Mounted() && !slices.Contains(hidden, "/history") {
+ loadLibraryPage(s, &state.recent, true, func(ctx context.Context, page int) ([]app.LibraryItem, bool, error) {
+ return s.app.LibraryOf().History(ctx, page, app.LibraryQuery{})
+ })
+ }
+ if s.app.CollectionsMounted() && !s.app.FavoriteState(app.FavoritesCreated).Loaded && !s.app.FavoritesRefreshing() {
+ s.app.AutoRefreshFavorites()
+ }
+ }
+ }
+ ui.Row(c).FillWidth().Height(52).AlignItems(ui.Center).Gap(8).Children(func() {
+ ui.Text(c, "我的").Grow(1).FontSize(21).Bold()
+ label := "登录"
+ if loggedIn {
+ label = state.nav.Name
+ if label == "" {
+ label = "我的账号"
+ }
+ }
+ ui.Row(c).Gap(6).AlignItems(ui.Center).MinHeight(44).Role(ui.RoleButton).Label(label).OnClick(func() {
+ if loggedIn {
+ state.menu = true
+ } else {
+ s.push(route{kind: pageLogin, title: "登录"})
+ }
+ }).Children(func() {
+ if loggedIn {
+ cover(c, state.nav.Face, 32, 16)
+ } else {
+ glyph(c, "user", 20, c.Theme().Text)
+ }
+ ui.Text(c, label).MaxLines(1).MaxWidth(118).FontSize(13)
+ glyph(c, "right", 13, c.Theme().TextMuted)
+ })
+ iconButton(c, "settings", "设置").OnClick(func() { s.push(route{kind: pageSettings, title: "设置"}) })
+ })
+ ui.Row(c).FillWidth().Gap(8).Children(func() {
+ for _, item := range libraryDestinations[:4] {
+ if slices.Contains(hidden, item.path) || item.requiresLogin && !loggedIn {
+ continue
+ }
+ ui.Column(c).Key(item.path).Grow(1).Basis(0).Height(62).Gap(7).Justify(ui.Center).AlignItems(ui.Center).
+ Role(ui.RoleButton).Label(item.label).OnClick(func() { s.openLibraryPage(item) }).Children(func() {
+ if item.kind == pageLocal {
+ ui.Icon(c, iconset.Must("Media/music-2-line.svg")).Size(20, 20).TextColor(c.Theme().Text)
+ } else {
+ glyph(c, item.icon, 20, c.Theme().Text)
+ }
+ ui.Text(c, item.label).Bold().FontSize(12).MaxLines(1)
+ })
+ }
+ })
+ if !loggedIn {
+ var artwork string
+ if discover, ok := s.stacks[0][0].data.(*discoverState); ok && len(discover.mixes.cards) > 0 {
+ artwork = discover.mixes.cards[0].cover
+ }
+ s.libraryFeature(c, "folder", "逛逛公开歌单", "登录后可同步喜欢与收藏", artwork, func() { s.push(route{kind: pageMixes, title: "推荐歌单"}) }, nil)
+ } else {
+ s.likedFeature(c, state)
+ s.myFolders(c, state, hidden)
+ }
+ if !slices.Contains(hidden, "/history") {
+ items := state.local
+ if len(state.recent.items) != 0 {
+ items = state.recent.items
+ }
+ if len(items) > 0 {
+ ui.Column(c).Margin(14, 0, 0).Gap(4).Children(func() {
+ if sectionHeading(c, "最近播放", "全部") {
+ s.openLibraryPage(libraryDestinations[0])
+ }
+ var playable []app.Item
+ for _, item := range items[:min(3, len(items))] {
+ if item.CanPlay {
+ playable = append(playable, item.Item)
+ }
+ }
+ ui.Column(c).Gap(2).Children(func() { s.trackList(c, playable) })
+ })
+ }
+ }
+ for _, item := range libraryDestinations[4:] {
+ if !slices.Contains(hidden, item.path) && (item.kind != pageFeed || !slices.Contains(hidden, "/follow")) && (!item.requiresLogin || loggedIn) {
+ libraryRow(c.Key(item.path), "", item.icon, item.label, "", func() { s.openLibraryPage(item) })
+ }
+ }
+ libraryActionSheet(c, &state.menu, mobile.ActionSheetOptions{Title: state.nav.Name, Cancel: "取消"},
+ mobile.Action{Label: "刷新收藏夹", OnTap: s.app.RefreshFavorites},
+ mobile.Action{Label: "绑定喜欢的歌单", OnTap: func() { state.bind = true }},
+ mobile.Action{Label: "退出登录", Destructive: true, Disabled: state.logout, OnTap: func() {
+ state.logout = true
+ go func() {
+ err := s.app.Logout()
+ s.update(func() {
+ state.logout = false
+ if err != nil {
+ s.notice = err.Error()
+ } else {
+ s.notice = "已退出登录"
+ }
+ })
+ }()
+ }},
+ )
+ s.bindLikedFolderSheet(c, state)
+ s.renderFolderEditor(c, &state.editor, func() { s.notice = "已新建收藏夹" })
+}
+
+func (s *shell) openLibraryPage(item libraryDestination) {
+ title := item.label
+ if item.kind == pageDownloads {
+ title = "下载记录"
+ }
+ s.push(route{kind: item.kind, title: title})
+}
+
+func (s *shell) likedFeature(c *ui.Context, state *myLibraryState) {
+ liked, ok := s.app.LikedFolder()
+ if !ok {
+ s.libraryFeature(c, "heart", "我喜欢的音乐", "选择收藏夹,保存红心歌曲", "", func() { state.bind = true }, nil)
+ return
+ }
+ favorite := app.Favorite{ID: liked.ID, Title: liked.Title}
+ for _, folder := range s.app.SideFavorites(app.FavoritesCreated) {
+ if folder.ID == liked.ID {
+ favorite = folder
+ break
+ }
+ }
+ ref := app.CollectionRefOf(favorite)
+ s.libraryFeature(c, "heart", "我喜欢的音乐", fmt.Sprintf("%d 首", favorite.MediaCount), favorite.Cover, func() {
+ s.push(route{kind: pageCollection, title: "我喜欢的音乐", ref: ref})
+ }, func() {
+ s.app.PlayFolder(favorite, func(text string, _ notice.Tone) { s.update(func() { s.notice = text }) })
+ })
+}
+
+func (s *shell) bindLikedFolderSheet(c *ui.Context, state *myLibraryState) {
+ liked, bound := s.app.LikedFolder()
+ librarySheet(c, &state.bind, mobile.SheetOptions{Label: "绑定喜欢的歌单", Detents: []float32{0.52, 0.84}}, func() {
+ ui.Scroll(c).Fill().Padding(16).Gap(8).Children(func() {
+ ui.Text(c, "绑定喜欢的歌单").FontSize(20).Bold()
+ ui.Text(c, "点红心的歌曲会保存到这个收藏夹。已有歌曲会保留。").FontSize(13).TextColor(c.Theme().TextMuted)
+ for _, folder := range s.app.SideFavorites(app.FavoritesCreated) {
+ if !folder.Invalid {
+ meta := fmt.Sprintf("%d 首", folder.MediaCount)
+ if folder.ID == liked.ID {
+ meta += " · 当前绑定"
+ }
+ libraryRow(c.Key(folder.ID), folder.Cover, "folder", folder.Title, meta, func() {
+ info := s.app.Collection(app.CollectionRefOf(folder))
+ s.app.BindLikedFolder(app.LikedFolder{ID: folder.ID, Title: folder.Title, Private: info.Private})
+ s.notice, state.bind = "已绑定喜欢的歌单", false
+ })
+ }
+ }
+ libraryButton(c, "plus", "新建收藏夹", false, !s.app.CollectionsMounted(), func() {
+ state.bind = false
+ state.editor = folderEditor{open: true}
+ })
+ if bound {
+ libraryButton(c, "x", "取消绑定", false, false, func() {
+ s.app.UnbindLikedFolder()
+ state.bind = false
+ })
+ }
+ })
+ })
+}
+
+func (s *shell) libraryFeature(c *ui.Context, icon, title, subtitle, imageURL string, open, play func()) {
+ theme := c.Theme()
+ ui.Row(c).Margin(4, 0, 8).Padding(9).Radius(16).Gap(12).Height(80).AlignItems(ui.Center).
+ Background(theme.Background.Mix(theme.Accent, 0.10)).Children(func() {
+ ui.Row(c).Grow(1).AlignItems(ui.Center).Gap(12).Role(ui.RoleButton).Label(title).OnClick(open).Children(func() {
+ if imageURL != "" {
+ cover(c, imageURL, 62, 12)
+ } else {
+ ui.Box(c).Size(62, 62).Radius(12).Background(theme.Background.Mix(theme.Accent, 0.18)).AlignItems(ui.Center).Justify(ui.Center).Children(func() {
+ glyph(c, icon, 20, theme.Accent)
+ })
+ }
+ ui.Column(c).Grow(1).Gap(4).Children(func() {
+ ui.Text(c, title).Bold().FontSize(14)
+ ui.Text(c, subtitle).FontSize(12).TextColor(theme.TextMuted).MaxLines(2)
+ })
+ })
+ if play != nil {
+ iconButton(c, "play", "播放我喜欢的音乐").Radius(22).Background(theme.Background).OnClick(play)
+ } else {
+ glyph(c, "right", 18, theme.TextMuted).Margin(0, 5, 0, 0)
+ }
+ })
+}
+
+func (s *shell) myFolders(c *ui.Context, state *myLibraryState, hidden []string) {
+ ui.Row(c).AlignItems(ui.Center).Height(44).Children(func() {
+ ui.Text(c, "我的歌单").Grow(1).FontSize(16).Bold()
+ iconButton(c, "plus", "新建收藏夹").OnClick(func() { state.editor = folderEditor{open: true} })
+ })
+ ui.Row(c).Gap(10).Children(func() {
+ for index, title := range []string{"创建", "收藏"} {
+ group := app.FavoriteGroup(index)
+ librarySegment(c, title, state.group == group, func() { state.group = group })
+ }
+ })
+ folders := s.app.SideFavorites(state.group)
+ status := s.app.FavoriteState(state.group)
+ shown := 0
+ for _, folder := range folders {
+ if slices.Contains(hidden, strconv.FormatInt(folder.ID, 10)) {
+ continue
+ }
+ shown++
+ meta := fmt.Sprintf("%d 首", folder.MediaCount)
+ ref := app.CollectionRefOf(folder)
+ var open func()
+ if folder.Invalid {
+ meta = "收藏夹已失效"
+ } else {
+ open = func() { s.push(route{kind: pageCollection, title: folder.Title, ref: ref}) }
+ }
+ libraryRow(c.Key(ref.Key()), folder.Cover, "folder", folder.Title, meta, open)
+ }
+ if shown == 0 {
+ switch {
+ case status.Err != "":
+ libraryMessage(c, "加载歌单失败", "")
+ libraryButton(c, "refresh", "重试", false, false, s.app.RefreshFavorites)
+ case !status.Loaded && s.app.FavoritesRefreshing():
+ libraryMore(c, true, nil)
+ default:
+ ui.Text(c, "这里还没有歌单").FontSize(14).TextColor(c.Theme().TextMuted).PaddingY(10)
+ }
+ }
+}
+
+type libraryHistoryState struct {
+ pages libraryPages[app.LibraryItem]
+ query app.LibraryQuery
+ keyword, status string
+ dateMenu, dates, confirm bool
+ from, to time.Time
+ target app.LibraryItem
+ working, clearingViewed bool
+ local app.ListeningStats
+}
+
+func (s *shell) libraryHistory(c *ui.Context, page *route) {
+ later, loggedIn := page.kind == pageLater, s.app.LoggedIn()
+ if later && !loggedIn {
+ s.libraryLogin(c, "稍后再看")
+ return
+ }
+ state, _ := page.data.(*libraryHistoryState)
+ account := s.app.AccountSnapshot()
+ if state == nil || state.pages.account != account {
+ state = &libraryHistoryState{}
+ state.pages.account = account
+ page.data = state
+ if loggedIn {
+ s.loadLibraryHistory(state, later, true)
+ } else {
+ state.local, _ = s.app.ListeningStats()
+ }
+ }
+ items := state.pages.items
+ if !loggedIn {
+ items = libraryLocalHistory(state.local, state.query)
+ }
+ var playable []app.Item
+ for _, item := range items {
+ if item.CanPlay {
+ playable = append(playable, item.Item)
+ }
+ }
+ if later {
+ ui.Text(c, "先存下来,等有空的时候再听。").FontSize(14).TextColor(c.Theme().TextMuted)
+ ui.Row(c).Gap(5).AlignItems(ui.Center).Children(func() {
+ libraryButton(c, "play", "播放全部", true, (len(playable) == 0 && (!state.pages.more || state.pages.loading)) || state.working, func() { s.playLater(state) })
+ libraryButton(c, "trash", "删除已看完的", false, len(items) == 0 || state.working, func() {
+ state.confirm, state.clearingViewed, state.target = true, true, app.LibraryItem{}
+ })
+ })
+ } else {
+ ui.Row(c).AlignItems(ui.Center).Gap(4).Children(func() {
+ libraryInput(c, &state.keyword, "搜索标题 / UP 主名称", func() {
+ state.query.Keyword = strings.TrimSpace(state.keyword)
+ if loggedIn {
+ s.loadLibraryHistory(state, false, true)
+ }
+ })
+ iconButton(c, "calendar", "按日期筛选").OnClick(func() { state.dateMenu = true })
+ })
+ if !state.query.From.IsZero() || !state.query.To.IsZero() {
+ ui.Text(c, state.query.From.Format("01-02")+" 至 "+state.query.To.Format("01-02")).FontSize(12).TextColor(c.Theme().TextMuted)
+ }
+ }
+ if state.status != "" {
+ ui.Text(c, state.status).FontSize(13).TextColor(c.Theme().TextMuted)
+ }
+ if state.pages.err != nil {
+ libraryMessage(c, "加载失败", "检查网络后重试。")
+ libraryButton(c, "refresh", "重试", false, false, func() { s.loadLibraryHistory(state, later, false) })
+ } else if len(items) == 0 && !state.pages.loading && !state.pages.more {
+ switch {
+ case later:
+ libraryMessage(c, "暂无稍后再看内容", "在歌曲的更多操作里选择「稍后再看」。")
+ libraryButton(c, "disc", "去推荐页看看", false, false, func() { s.switchTab(0) })
+ case state.query.Keyword != "":
+ libraryMessage(c, "没有匹配的记录", "换一个关键词试试。")
+ case !state.query.From.IsZero():
+ libraryMessage(c, "这段时间没有收听记录", "换一个时间范围看看。")
+ default:
+ libraryMessage(c, "暂无历史记录", "播放过的歌曲会按日期记录在这里。")
+ if !loggedIn {
+ libraryButton(c, "user", "登录查看 B 站历史", false, false, func() { s.push(route{kind: pageLogin, title: "登录"}) })
+ }
+ }
+ }
+ var lastDate string
+ for _, item := range items {
+ if !later {
+ day := item.ViewedAt.Local().Format("2006-01-02")
+ if day != lastDate {
+ lastDate = day
+ ui.Text(c, libraryDayName(item.ViewedAt)).Margin(8, 0, 0).FontSize(14).Bold()
+ }
+ }
+ ui.Row(c).Key(item.ID).AlignItems(ui.Center).Children(func() {
+ meta := libraryHistorySubtitle(item, later)
+ var play func()
+ if item.CanPlay {
+ play = func() { s.play([]app.Item{item.Item}, 0) }
+ }
+ libraryRow(c, item.Cover, "disc", item.Title, meta, play).Grow(1).Basis(0)
+ if loggedIn {
+ iconButton(c, "more", "移除 "+item.Title).Disabled(state.working).OnClick(func() {
+ state.confirm, state.clearingViewed, state.target = true, false, item
+ })
+ }
+ })
+ }
+ if state.pages.loading || state.pages.more && state.pages.err == nil {
+ libraryMore(c, state.pages.loading, func() { s.loadLibraryHistory(state, later, false) })
+ }
+ s.historyDateSheet(c, state, loggedIn)
+ confirmation := "移除这条记录?"
+ if state.clearingViewed {
+ confirmation = "删除已看完的内容?"
+ }
+ libraryActionSheet(c, &state.confirm, mobile.ActionSheetOptions{Title: confirmation, Message: state.target.Title, Cancel: "取消"},
+ mobile.Action{Label: "移除", Destructive: true, OnTap: func() { s.removeLibraryHistory(state, later) }},
+ )
+}
+
+func (s *shell) loadLibraryHistory(state *libraryHistoryState, later, reset bool) {
+ query := state.query
+ offset := len(state.pages.items)
+ if reset {
+ offset = 0
+ }
+ loadLibraryPage(s, &state.pages, reset, func(ctx context.Context, page int) ([]app.LibraryItem, bool, error) {
+ if later {
+ items, count, err := s.app.LibraryOf().ToView(ctx, page, query)
+ return items, len(items) != 0 && offset+len(items) < count, err
+ }
+ return s.app.LibraryOf().History(ctx, page, query)
+ })
+}
+
+func (s *shell) playLater(state *libraryHistoryState) {
+ if state.working {
+ return
+ }
+ state.working = true
+ items, next, more, account := slices.Clone(state.pages.items), state.pages.next, state.pages.more, state.pages.account
+ go func() {
+ var err error
+ for more && err == nil {
+ var rows []app.LibraryItem
+ var total int
+ rows, total, err = s.app.LibraryOf().ToView(s.ctx, next, app.LibraryQuery{})
+ items = append(items, rows...)
+ more = len(rows) != 0 && len(items) < total
+ next++
+ }
+ s.update(func() {
+ state.working = false
+ if s.app.AccountSnapshot() != account {
+ return
+ }
+ if err != nil {
+ state.status = "稍后再看没有加载完,请重试。"
+ return
+ }
+ var playable []app.Item
+ for _, item := range items {
+ if item.CanPlay {
+ playable = append(playable, item.Item)
+ }
+ }
+ if len(playable) > 0 {
+ s.play(playable, 0)
+ } else {
+ state.status = "没有可播放的歌曲。"
+ }
+ })
+ }()
+}
+
+func (s *shell) removeLibraryHistory(state *libraryHistoryState, later bool) {
+ state.working = true
+ target, clear, account := state.target, state.clearingViewed, state.pages.account
+ go func() {
+ var err error
+ switch {
+ case clear:
+ err = s.app.LibraryOf().ClearViewedLater(s.ctx)
+ case later:
+ err = s.app.LibraryOf().RemoveLater(s.ctx, target.ID)
+ default:
+ err = s.app.LibraryOf().RemoveHistory(s.ctx, target.ID)
+ }
+ s.update(func() {
+ state.working = false
+ if s.app.AccountSnapshot() != account {
+ return
+ }
+ if err != nil {
+ state.status = "移除失败,请重试。"
+ return
+ }
+ state.status, state.target = "已移除", app.LibraryItem{}
+ s.loadLibraryHistory(state, later, true)
+ })
+ }()
+}
+
+func (s *shell) historyDateSheet(c *ui.Context, state *libraryHistoryState, loggedIn bool) {
+ now := time.Now().Local()
+ today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
+ apply := func(from, to time.Time) {
+ state.query.From, state.query.To = from, to
+ if loggedIn {
+ s.loadLibraryHistory(state, false, true)
+ }
+ }
+ libraryActionSheet(c, &state.dateMenu, mobile.ActionSheetOptions{Title: "选择时间范围", Cancel: "取消"},
+ mobile.Action{Label: "全部时间", OnTap: func() { apply(time.Time{}, time.Time{}) }},
+ mobile.Action{Label: "今天", OnTap: func() { apply(today, now) }},
+ mobile.Action{Label: "最近 7 天", OnTap: func() { apply(today.AddDate(0, 0, -6), now) }},
+ mobile.Action{Label: "最近 30 天", OnTap: func() { apply(today.AddDate(0, 0, -29), now) }},
+ mobile.Action{Label: "自定义日期", OnTap: func() {
+ state.from, state.to = today.AddDate(0, 0, -6), today
+ state.dates = true
+ }},
+ )
+ librarySheet(c, &state.dates, mobile.SheetOptions{Label: "自定义日期", Detents: []float32{0.82, 0.95}}, func() {
+ ui.Scroll(c).Fill().Padding(16).Gap(6).Children(func() {
+ ui.Text(c, "开始日期").Bold()
+ mobile.DatePicker(c.Key("from"), &state.from)
+ ui.Text(c, "结束日期").Bold()
+ mobile.DatePicker(c.Key("to"), &state.to)
+ libraryButton(c, "", "应用日期", true, state.to.Before(state.from), func() {
+ state.dates = false
+ apply(state.from, state.to.AddDate(0, 0, 1).Add(-time.Second))
+ })
+ })
+ })
+}
+
+func libraryLocalHistory(stats app.ListeningStats, query app.LibraryQuery) []app.LibraryItem {
+ var items []app.LibraryItem
+ keyword := strings.ToLower(strings.TrimSpace(query.Keyword))
+ for day, report := range stats.Days {
+ date, err := time.ParseInLocation("2006-01-02", day, time.Local)
+ if err != nil || report == nil || !query.From.IsZero() && date.Before(query.From) || !query.To.IsZero() && date.After(query.To) {
+ continue
+ }
+ for key, track := range report.Tracks {
+ if track == nil || !strings.Contains(strings.ToLower(track.Title+" "+track.Artist), keyword) {
+ continue
+ }
+ item, err := app.ItemOfStatsKey(key, track)
+ items = append(items, app.LibraryItem{ID: day + ":" + key, Title: track.Title, Cover: item.Cover, Owner: track.Artist, ViewedAt: date, CanPlay: err == nil, Item: item})
+ }
+ }
+ slices.SortFunc(items, func(left, right app.LibraryItem) int {
+ if order := right.ViewedAt.Compare(left.ViewedAt); order != 0 {
+ return order
+ }
+ return strings.Compare(left.ID, right.ID)
+ })
+ return items
+}
+
+func libraryDayName(date time.Time) string {
+ date = date.Local()
+ now := time.Now().Local()
+ switch date.Format("2006-01-02") {
+ case now.Format("2006-01-02"):
+ return "今天"
+ case now.AddDate(0, 0, -1).Format("2006-01-02"):
+ return "昨天"
+ default:
+ return fmt.Sprintf("%d 月 %d 日", date.Month(), date.Day())
+ }
+}
+
+func libraryHistorySubtitle(item app.LibraryItem, later bool) string {
+ if !item.CanPlay {
+ return item.CannotPlay
+ }
+ if strings.HasPrefix(item.ID, "history:") {
+ return strings.TrimPrefix(item.Owner+" · "+item.ViewedAt.Local().Format("15:04")+" 播放", " · ")
+ }
+ if !later {
+ return item.Owner
+ }
+ progress := "还没看"
+ if item.Progress < 0 || item.Duration > 0 && item.Progress >= item.Duration {
+ progress = "已看完"
+ } else if item.Progress > 0 {
+ progress = fmt.Sprintf("看到 %d:%02d", item.Progress/time.Minute, item.Progress/time.Second%60)
+ }
+ return strings.TrimPrefix(item.Owner+" · "+progress, " · ")
+}
+
+func (s *shell) libraryLogin(c *ui.Context, name string) {
+ libraryMessage(c, "登录后查看"+name, "登录 B 站账号即可同步内容。")
+ libraryButton(c, "user", "去登录", true, false, func() { s.push(route{kind: pageLogin, title: "登录"}) })
+}
+
+func libraryMessage(c *ui.Context, title, subtitle string) {
+ ui.Column(c).Padding(10, 0, 12).Gap(5).Children(func() {
+ ui.Text(c, title).FontSize(16).Bold()
+ if subtitle != "" {
+ ui.Text(c, subtitle).FontSize(13).TextColor(c.Theme().TextMuted)
+ }
+ })
+}
+
+type sheetFrameKey struct{ open *bool }
+
+type sheetFrameState struct{ open, settle bool }
+
+func requestSheetFrame(c *ui.Context, open *bool) {
+ state := ui.Local(c.Root(), sheetFrameKey{open}, func() sheetFrameState { return sheetFrameState{} })
+ edge := state.open != *open
+ if edge || state.settle {
+ c.AnimationFrame()
+ }
+ state.open, state.settle = *open, edge
+}
+
+func libraryActionSheet(c *ui.Context, open *bool, options mobile.ActionSheetOptions, actions ...mobile.Action) {
+ requestSheetFrame(c, open)
+ mobile.ActionSheet(c, open, options, actions...)
+}
+
+func librarySheet(c *ui.Context, open *bool, options mobile.SheetOptions, body func()) {
+ requestSheetFrame(c, open)
+ mobile.Sheet(c, open, options, body)
+}
+
+func libraryMore(c *ui.Context, loading bool, more func()) {
+ if loading {
+ ui.Text(c, "正在加载…").FontSize(13).TextColor(c.Theme().TextMuted).PaddingY(14)
+ } else {
+ libraryButton(c, "down", "加载更多", false, false, more)
+ }
+}
+
+func libraryInput(c *ui.Context, value *string, placeholder string, submit func()) {
+ theme := c.Theme()
+ ui.Row(c).Basis(0).Grow(1).Gap(8).AlignItems(ui.Center).Height(44).PaddingX(12).Radius(13).Background(theme.Surface).Children(func() {
+ glyph(c, "search", 17, theme.TextMuted)
+ input := ui.TextInputBase(c, value).Grow(1).Basis(0).FontSize(14).Height(44).Placeholder(placeholder).Label(placeholder).
+ Search().Keyboard(ui.KeyboardSearch).ReturnKey(ui.ReturnSearch)
+ if input.Submitted() {
+ submit()
+ }
+ })
+}
+
+func libraryButton(c *ui.Context, icon, label string, primary, disabled bool, tap func()) ui.Element {
+ theme := c.Theme()
+ bg, fg := theme.Surface, theme.Text
+ if primary {
+ bg, fg = theme.Accent, theme.AccentText
+ }
+ return ui.Row(c).AlignSelf(ui.Start).AlignItems(ui.Center).Justify(ui.Center).Gap(6).MinHeight(44).PaddingX(14).
+ Radius(22).Background(bg).Role(ui.RoleButton).Label(label).Disabled(disabled).OnClick(tap).Children(func() {
+ if icon != "" {
+ glyph(c, icon, 14, fg)
+ }
+ ui.Text(c, label).FontSize(13).TextColor(fg).Bold().MaxLines(1)
+ })
+}
+
+func librarySegment(c *ui.Context, label string, selected bool, tap func()) {
+ theme := c.Theme()
+ fg, line := theme.TextMuted, theme.Background
+ if selected {
+ fg, line = theme.Accent, theme.Accent
+ }
+ ui.Column(c).MinHeight(44).Padding(10, 10, 0).Gap(6).Role(ui.RoleButton).Label(label).OnClick(tap).Children(func() {
+ ui.Text(c, label).FontSize(13).TextColor(fg).MaxLines(1)
+ ui.Spacer(c).Grow(1)
+ ui.Box(c).FillWidth().Height(2).Background(line)
+ })
+}
+
+func libraryRow(c *ui.Context, imageURL, icon, title, subtitle string, tap func()) ui.Element {
+ theme := c.Theme()
+ row := ui.Row(c).FillWidth().MinHeight(48).Gap(12).AlignItems(ui.Center)
+ if tap != nil {
+ row.Role(ui.RoleButton).Label(title).OnClick(tap)
+ }
+ return row.Children(func() {
+ if imageURL != "" || subtitle != "" {
+ if imageURL != "" {
+ cover(c, imageURL, 48, 10)
+ } else {
+ ui.Box(c).AlignItems(ui.Center).Justify(ui.Center).Size(48, 48).Radius(10).Background(theme.Surface).Children(func() {
+ glyph(c, icon, 20, theme.TextMuted)
+ })
+ }
+ } else {
+ glyph(c, icon, 20, theme.TextMuted)
+ }
+ ui.Column(c).Grow(1).Basis(0).Gap(3).Children(func() {
+ ui.Text(c, title).FontSize(14).Bold().MaxLines(1)
+ if subtitle != "" {
+ ui.Text(c, subtitle).FontSize(12).TextColor(theme.TextMuted).MaxLines(2)
+ }
+ })
+ if tap != nil {
+ glyph(c, "right", 14, theme.TextMuted)
+ }
+ })
+}
diff --git a/internal/mobileui/library_local.go b/internal/mobileui/library_local.go
new file mode 100644
index 00000000..b967c2e7
--- /dev/null
+++ b/internal/mobileui/library_local.go
@@ -0,0 +1,694 @@
+package mobileui
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/download"
+ "github.com/ShellMonster/PudMusic/internal/service/localmusic"
+ "github.com/egoist/mygo"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+)
+
+const localImportDirectory = "mobile-imports"
+
+type localLibraryState struct {
+ working, menu, confirm bool
+ base, status, undoRoot string
+ target localmusic.Track
+}
+
+func (s *shell) localMusic(c *ui.Context, page *route) {
+ state, _ := page.data.(*localLibraryState)
+ if state == nil {
+ state = &localLibraryState{base: mobileImportBase()}
+ page.data = state
+ s.app.SetLocalRoots(s.app.SettingsSnapshot().LocalMusicDirs)
+ s.app.RescanLocalMusic()
+ }
+ snapshot := s.app.LocalMusicState()
+ var items []app.Item
+ for _, track := range snapshot.Tracks {
+ if track.Playable() {
+ items = append(items, localTrackItem(track))
+ }
+ }
+ ui.Text(c, fmt.Sprintf("%d 个文件 · FLAC、MP3、M4A、WAV 等", len(snapshot.Tracks))).TextColor(c.Theme().TextMuted).FontSize(13)
+ ui.Row(c).Gap(6).AlignItems(ui.Center).Children(func() {
+ libraryButton(c, "plus", "添加文件", true, state.working || state.base == "" || !s.app.LocalMusicMounted(), func() { s.importLocalMusic(state, false) })
+ if runtime.GOOS == "android" {
+ iconButton(c, "folder", "添加文件夹").Disabled(state.working || state.base == "" || !s.app.LocalMusicMounted()).OnClick(func() { s.importLocalMusic(state, true) })
+ }
+ libraryButton(c, "play", "播放全部", false, len(items) == 0, func() { s.play(items, 0) })
+ iconButton(c, "refresh", "重新扫描").Disabled(snapshot.Scanning).OnClick(s.app.RescanLocalMusic)
+ })
+ if state.status != "" {
+ ui.Text(c, state.status).TextColor(c.Theme().TextMuted).FontSize(13)
+ }
+ if state.undoRoot != "" {
+ libraryButton(c, "", "撤销移除", false, state.working, func() {
+ root := state.undoRoot
+ if s.updateLocalRoots(state, func(roots []string) []string { return append(roots, root) }) {
+ state.undoRoot, state.status = "", "已恢复到本地音乐"
+ }
+ })
+ }
+ if !s.app.LocalMusicMounted() {
+ libraryMessage(c, "本地音乐暂时不可用", "重新打开应用后再试。")
+ } else if state.working || snapshot.Scanning {
+ ui.Text(c, "正在扫描…").FontSize(13).TextColor(c.Theme().TextMuted)
+ } else if snapshot.Err != "" {
+ libraryMessage(c, "部分文件无法读取", "确认文件仍可访问后重新扫描。")
+ } else if len(snapshot.Tracks) == 0 {
+ libraryMessage(c, "还没有打开文件", "从系统文件选择器导入音频后,即可离线播放。")
+ }
+ for _, track := range snapshot.Tracks {
+ meta := strings.ToUpper(strings.TrimPrefix(track.Format, ".")) + " · " + libraryByteSize(track.Size)
+ var play func()
+ if track.Playable() {
+ play = func() { s.play([]app.Item{localTrackItem(track)}, 0) }
+ } else {
+ meta += " · 暂不支持此格式"
+ }
+ row := func() {
+ ui.Row(c).AlignItems(ui.Center).Children(func() {
+ libraryRow(c, "", "disc", filepath.Base(track.Path), meta, play).Grow(1).Basis(0)
+ if mobileImportTrack(state.base, track) {
+ iconButton(c, "more", "更多操作:"+track.Title).OnClick(func() { state.target, state.menu = track, true })
+ }
+ })
+ }
+ if mobileImportTrack(state.base, track) {
+ mobile.SwipeRow(c.Key(track.ID), nil, mobile.SwipeOptions{Trailing: []mobile.SwipeAction{{Label: "移除", OnTap: func() { s.removeImportedTrack(state, track) }}}}, row)
+ } else {
+ ui.Box(c.Key(track.ID)).FillWidth().Children(row)
+ }
+ }
+ libraryActionSheet(c, &state.menu, mobile.ActionSheetOptions{Title: state.target.Title, Cancel: "取消"},
+ mobile.Action{Label: "从列表移除", Disabled: state.working, OnTap: func() { s.removeImportedTrack(state, state.target) }},
+ mobile.Action{Label: "删除应用内副本", Disabled: state.working, Destructive: true, OnTap: func() { state.confirm = true }},
+ )
+ libraryActionSheet(c, &state.confirm, mobile.ActionSheetOptions{Title: "删除应用内副本?", Message: "来源文件会保留。", Cancel: "取消"},
+ mobile.Action{Label: "删除", Destructive: true, OnTap: func() { s.deleteImportedTrack(state, state.target) }},
+ )
+}
+
+func mobileImportBase() string {
+ if dir, err := mygo.App.Path(mygo.PathUserData); err == nil && filepath.IsAbs(dir) {
+ return filepath.Join(dir, localImportDirectory)
+ }
+ return ""
+}
+
+func localTrackItem(track localmusic.Track) app.Item {
+ item := app.LocalItem(track.Path)
+ item.Title = track.Title
+ return item
+}
+
+func (s *shell) importLocalMusic(state *localLibraryState, directory bool) {
+ if state.working || s.win == nil {
+ return
+ }
+ state.working, state.status = true, ""
+ go func() {
+ var files []string
+ var err error
+ if runtime.GOOS == "android" {
+ var selection mobileDocumentSelection
+ method := "pickFiles"
+ if directory {
+ method = "pickDirectory"
+ }
+ err = mygo.Native("pudmusic_documents").Call(context.WithoutCancel(s.ctx), method, struct{ Extensions []string }{localmusic.Extensions}, &selection)
+ if selection.Directory != "" {
+ defer os.RemoveAll(selection.Directory)
+ }
+ files = selection.Files
+ s.finishLocalImport(state, files, selection.Failed, err)
+ return
+ }
+ files, err = mygo.Dialog.Open(mygo.OpenDialogOptions{
+ Parent: s.win, Title: "导入音频", Multiple: true,
+ Filters: []mygo.FileFilter{{Name: "音频文件", Extensions: localmusic.Extensions, MIMETypes: []string{"audio/*"}}},
+ })
+ if len(files) == 0 {
+ files = nil
+ }
+ s.finishLocalImport(state, files, 0, err)
+ }()
+}
+
+func (s *shell) finishLocalImport(state *localLibraryState, files []string, failed int, err error) {
+ var imported []string
+ if err == nil {
+ for _, file := range files {
+ root, copyErr := copyMobileImport(state.base, file)
+ if copyErr != nil {
+ failed++
+ } else {
+ imported = append(imported, root)
+ }
+ }
+ }
+ s.update(func() {
+ state.working = false
+ switch {
+ case err != nil:
+ state.status = "无法打开文件选择器,请重试。"
+ case len(imported) != 0:
+ if s.updateLocalRoots(state, func(roots []string) []string { return append(roots, imported...) }) {
+ state.status = fmt.Sprintf("已导入 %d 个文件", len(imported))
+ if failed > 0 {
+ state.status += fmt.Sprintf(",%d 个文件未能导入", failed)
+ }
+ } else {
+ for _, root := range imported {
+ _ = os.RemoveAll(root)
+ }
+ }
+ case failed > 0:
+ state.status = "无法读取选中的音频文件。"
+ case files != nil:
+ state.status = "没有可导入的音频文件。"
+ }
+ if page := s.current(); page.data != state && state.status != "" {
+ s.notice = state.status
+ }
+ })
+}
+
+func copyMobileImport(base, source string) (string, error) {
+ if base == "" || !slices.Contains(localmusic.Extensions, strings.ToLower(filepath.Ext(source))) {
+ return "", errors.New("unsupported audio file")
+ }
+ input, err := os.Open(source)
+ if err != nil {
+ return "", err
+ }
+ defer input.Close()
+ metadata, err := input.Stat()
+ if err != nil || !metadata.Mode().IsRegular() {
+ return "", errors.New("selected item is not a regular file")
+ }
+ if err := os.MkdirAll(base, 0700); err != nil {
+ return "", err
+ }
+ root, err := os.MkdirTemp(base, "audio-")
+ if err != nil {
+ return "", err
+ }
+ output, err := os.OpenFile(filepath.Join(root, filepath.Base(source)), os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
+ if err == nil {
+ _, copyErr := io.Copy(output, input)
+ err = errors.Join(copyErr, output.Close())
+ }
+ if err != nil {
+ _ = os.RemoveAll(root)
+ return "", err
+ }
+ return root, nil
+}
+
+func (s *shell) updateLocalRoots(state *localLibraryState, change func([]string) []string) bool {
+ updated, err := s.app.UpdateSettings(func(settings *app.Settings) {
+ settings.LocalMusicDirs = change(slices.Clone(settings.LocalMusicDirs))
+ })
+ if err != nil {
+ state.status = "无法保存本地音乐列表,请重试。"
+ return false
+ }
+ s.app.SetLocalRoots(updated.LocalMusicDirs)
+ return true
+}
+
+func mobileImportTrack(base string, track localmusic.Track) bool {
+ return base != "" && filepath.Dir(track.Root) == base && strings.HasPrefix(filepath.Base(track.Root), "audio-") &&
+ filepath.Dir(track.Path) == track.Root
+}
+
+func (s *shell) removeImportedTrack(state *localLibraryState, track localmusic.Track) {
+ if !mobileImportTrack(state.base, track) || state.working {
+ return
+ }
+ if s.updateLocalRoots(state, func(roots []string) []string { return withoutLocalRoot(roots, track.Root) }) {
+ state.undoRoot, state.status = track.Root, "已从列表移除"
+ }
+}
+
+func (s *shell) deleteImportedTrack(state *localLibraryState, track localmusic.Track) {
+ if !mobileImportTrack(state.base, track) || state.working {
+ return
+ }
+ if item, ok := s.app.PlayingItem(); ok && item.Path == track.Path {
+ state.status = "请先切换到其他歌曲。"
+ return
+ }
+ state.working = true
+ go func() {
+ resolved, err := filepath.EvalSymlinks(track.Path)
+ base, baseErr := filepath.EvalSymlinks(state.base)
+ if err == nil && (baseErr != nil || resolved != track.Canonical || filepath.Dir(filepath.Dir(resolved)) != base) {
+ err = errors.New("file moved outside the app folder")
+ }
+ if err == nil {
+ err = os.Remove(track.Path)
+ }
+ if err == nil {
+ _ = os.Remove(track.Root)
+ }
+ s.update(func() {
+ state.working = false
+ if err != nil {
+ state.status = "无法删除应用内副本,请重试。"
+ return
+ }
+ if s.updateLocalRoots(state, func(roots []string) []string { return withoutLocalRoot(roots, track.Root) }) {
+ state.status = "已删除应用内副本"
+ }
+ })
+ }()
+}
+
+func withoutLocalRoot(roots []string, remove string) []string {
+ return slices.DeleteFunc(roots, func(root string) bool { return root == remove })
+}
+
+type downloadLibraryState struct {
+ filter int
+ menu, confirm, clear, storage bool
+ items []offlineFile
+ target download.Snapshot
+ file offlineFile
+ deleteFile, working bool
+ status string
+}
+
+type offlineFile struct {
+ path string
+ size int64
+}
+
+func (s *shell) downloadLibrary(c *ui.Context, page *route) {
+ state, _ := page.data.(*downloadLibraryState)
+ if state == nil {
+ state = &downloadLibraryState{}
+ page.data = state
+ if page.id == "storage" && s.app.DownloadMounted() {
+ s.scanOfflineFiles(state)
+ }
+ }
+ snapshot := s.app.DownloadSnapshotList()
+ ui.Text(c, "保存到布丁音乐 · 下载完成后可离线播放").TextColor(c.Theme().TextMuted).FontSize(13)
+ ui.Row(c).Gap(5).Children(func() {
+ libraryButton(c, "folder", "管理存储", false, !s.app.DownloadMounted(), func() { s.scanOfflineFiles(state) })
+ libraryButton(c, "trash", "清空记录", false, len(snapshot.Rows) == 0 || state.working, func() { state.clear = true })
+ })
+ labels := []string{"全部", "下载中", "已完成", "失败"}
+ counts := make([]int, len(labels))
+ for _, task := range snapshot.Rows {
+ counts[0]++
+ counts[downloadCategory(task.Status)]++
+ }
+ ui.Row(c).Gap(5).Children(func() {
+ for index, title := range labels {
+ librarySegment(c, fmt.Sprintf("%s %d", title, counts[index]), state.filter == index, func() { state.filter = index })
+ }
+ })
+ if state.status != "" {
+ ui.Text(c, state.status).TextColor(c.Theme().TextMuted).FontSize(13)
+ }
+ if counts[state.filter] == 0 {
+ titles := []string{"还没有可以下载的内容", "没有进行中的下载", "没有已完成的下载", "没有失败的下载"}
+ text := ""
+ if state.filter == 0 {
+ text = "在歌曲或收藏夹的更多操作里选择下载。"
+ }
+ libraryMessage(c, titles[state.filter], text)
+ }
+ for _, task := range snapshot.Rows {
+ if state.filter == 0 || state.filter == downloadCategory(task.Status) {
+ s.downloadRow(c.Key(task.ID), state, task)
+ }
+ }
+ var more []mobile.Action
+ if state.target.Status == download.StatusDone {
+ more = append(more, mobile.Action{Label: "分享导出", OnTap: func() { s.exportOffline(s.app.DownloadDir(), state.target.Dest) }})
+ }
+ more = append(more, mobile.Action{Label: "移除记录", Destructive: true, OnTap: func() { state.confirm = true }})
+ libraryActionSheet(c, &state.menu, mobile.ActionSheetOptions{Title: state.target.Title, Cancel: "取消"}, more...)
+ libraryActionSheet(c, &state.confirm, mobile.ActionSheetOptions{Title: "移除下载记录?", Message: "已下载的文件可以在管理存储查看。", Cancel: "取消"},
+ mobile.Action{Label: "移除", Destructive: true, OnTap: func() { s.report(s.app.RemoveDownload(state.target.ID)) }},
+ )
+ libraryActionSheet(c, &state.clear, mobile.ActionSheetOptions{Title: "清空下载记录?", Message: "未完成的任务将停止。已下载的文件可以在管理存储查看。", Cancel: "取消"},
+ mobile.Action{Label: "清空", Destructive: true, OnTap: s.app.ClearDownloads},
+ )
+ s.downloadStorage(c, state)
+}
+
+func downloadCategory(status download.Status) int {
+ switch status {
+ case download.StatusDone:
+ return 2
+ case download.StatusError:
+ return 3
+ default:
+ return 1
+ }
+}
+
+func (s *shell) downloadRow(c *ui.Context, state *downloadLibraryState, task download.Snapshot) {
+ ui.Row(c).Gap(5).AlignItems(ui.Center).Children(func() {
+ cover(c, task.Cover, 48, 10)
+ ui.Column(c).Grow(1).Basis(0).Gap(3).Children(func() {
+ ui.Text(c, task.Title).FontSize(14).Bold().MaxLines(1)
+ kind := "音频"
+ if task.Video {
+ kind = "视频"
+ }
+ status := map[download.Status]string{download.StatusQueued: "排队中", download.StatusRunning: "下载中", download.StatusPaused: "下载暂停", download.StatusMuxing: "正在合成", download.StatusDone: "已完成", download.StatusError: "失败"}[task.Status]
+ if task.Status == download.StatusError && task.Err != "" {
+ status += " · " + task.Err
+ }
+ ui.Text(c, kind+" · "+status).FontSize(12).TextColor(c.Theme().TextMuted).MaxLines(2)
+ if task.Status != download.StatusDone && task.Percent >= 0 {
+ ui.Progress(c, float64(task.Percent)/100).Height(3).Label(task.Title + " 下载进度")
+ }
+ })
+ switch {
+ case task.Status == download.StatusDone:
+ iconButton(c, "play", "离线播放 "+task.Title).OnClick(func() { s.playOffline(task.Dest, task.Title) })
+ case task.Status.CanPause():
+ iconButton(c, "pause", "暂停 "+task.Title).OnClick(func() { s.report(s.app.PauseDownload(task.ID)) })
+ case task.Status == download.StatusPaused:
+ iconButton(c, "play", "继续 "+task.Title).OnClick(func() { s.report(s.app.ResumeDownload(task.ID)) })
+ case task.Status == download.StatusError && task.CanRetry:
+ iconButton(c, "refresh", "重试 "+task.Title).OnClick(func() { s.report(s.app.ResumeDownload(task.ID)) })
+ }
+ iconButton(c, "more", "下载操作:"+task.Title).OnClick(func() { state.target, state.menu = task, true })
+ })
+}
+
+func (s *shell) playOffline(path, title string) {
+ if !downloadFileInside(s.app.DownloadDir(), path) {
+ s.notice = "无法找到离线文件。"
+ return
+ }
+ item := app.LocalItem(path)
+ item.Title = title
+ s.play([]app.Item{item}, 0)
+}
+
+func (s *shell) exportOffline(dir, path string) {
+ if !downloadFileInside(dir, path) || s.win == nil {
+ return
+ }
+ go func() {
+ _, err := mygo.Dialog.SaveCopy(path, filepath.Base(path))
+ if err != nil {
+ s.update(func() { s.notice = "导出失败,请重试。" })
+ }
+ }()
+}
+
+func (s *shell) scanOfflineFiles(state *downloadLibraryState) {
+ if state.working {
+ return
+ }
+ state.storage, state.working = true, true
+ dir := s.app.DownloadDir()
+ active := make(map[string]bool)
+ for _, task := range s.app.DownloadSnapshotList().Rows {
+ if task.Status != download.StatusDone {
+ active[task.Dest] = true
+ }
+ }
+ go func() {
+ entries, err := os.ReadDir(dir)
+ files := make([]offlineFile, 0, len(entries))
+ for _, entry := range entries {
+ path := filepath.Join(dir, entry.Name())
+ if active[path] || !downloadFileInside(dir, path) {
+ continue
+ }
+ info, err := entry.Info()
+ if err == nil {
+ files = append(files, offlineFile{path, info.Size()})
+ }
+ }
+ s.update(func() {
+ state.working, state.items = false, files
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ state.status = "无法读取离线文件。"
+ }
+ })
+ }()
+}
+
+func downloadFileInside(root, path string) bool {
+ if root == "" || path == "" || filepath.Dir(filepath.Clean(path)) != filepath.Clean(root) {
+ return false
+ }
+ extension := strings.ToLower(filepath.Ext(path))
+ if !slices.Contains(localmusic.Extensions, extension) && extension != ".mp4" {
+ return false
+ }
+ stat, err := os.Lstat(path)
+ return err == nil && stat.Mode().IsRegular()
+}
+
+func (s *shell) downloadStorage(c *ui.Context, state *downloadLibraryState) {
+ librarySheet(c, &state.storage, mobile.SheetOptions{Label: "管理存储", Detents: []float32{0.65, 0.9}}, func() {
+ ui.Scroll(c).Fill().Padding(16).Gap(7).Children(func() {
+ var total int64
+ for _, file := range state.items {
+ total += file.size
+ }
+ ui.Text(c, "管理存储").FontSize(20).Bold()
+ ui.Text(c, fmt.Sprintf("%d 个文件 · %s", len(state.items), libraryByteSize(total))).FontSize(13).TextColor(c.Theme().TextMuted)
+ if state.working {
+ libraryMore(c, true, nil)
+ }
+ for _, file := range state.items {
+ name := filepath.Base(file.path)
+ ui.Row(c.Key(file.path)).AlignItems(ui.Center).Children(func() {
+ libraryRow(c, "", "download", name, libraryByteSize(file.size), func() { s.playOffline(file.path, name) }).Grow(1).Basis(0)
+ iconButton(c, "open", "导出 "+name).OnClick(func() { s.exportOffline(s.app.DownloadDir(), file.path) })
+ iconButton(c, "trash", "删除 "+name).OnClick(func() { state.file, state.deleteFile = file, true })
+ })
+ }
+ })
+ })
+ libraryActionSheet(c, &state.deleteFile, mobile.ActionSheetOptions{Title: "删除离线文件?", Message: filepath.Base(state.file.path), Cancel: "取消"},
+ mobile.Action{Label: "删除文件", Destructive: true, OnTap: func() { s.deleteOfflineFile(state, state.file.path) }},
+ )
+}
+
+func (s *shell) deleteOfflineFile(state *downloadLibraryState, path string) {
+ if item, ok := s.app.PlayingItem(); ok && item.Path == path {
+ s.notice = "请先切换到其他歌曲。"
+ return
+ }
+ for _, task := range s.app.DownloadSnapshotList().Rows {
+ if task.Dest == path && task.Status != download.StatusDone {
+ s.notice = "请先结束这项下载。"
+ return
+ }
+ }
+ if !downloadFileInside(s.app.DownloadDir(), path) || os.Remove(path) != nil {
+ s.notice = "无法删除离线文件,请重试。"
+ return
+ }
+ s.scanOfflineFiles(state)
+}
+
+func libraryByteSize(size int64) string {
+ const kib = 1024
+ const mib = 1024 * kib
+ const gib = 1024 * mib
+ if size >= gib {
+ return fmt.Sprintf("%.1f GB", float64(size)/gib)
+ }
+ if size >= mib {
+ return fmt.Sprintf("%.1f MB", float64(size)/mib)
+ }
+ if size >= kib {
+ return fmt.Sprintf("%.1f KB", float64(size)/kib)
+ }
+ return fmt.Sprintf("%d B", size)
+}
+
+type libraryStatsState struct {
+ days [7]libraryStatsDay
+ hours [24]int64
+ tracks map[string]*app.StatsTrackStat
+ artists map[int64]*app.StatsArtistStat
+ total int64
+ plays int64
+ newUsers int
+ previous int64
+}
+
+type libraryStatsDay struct {
+ name string
+ minutes int64
+}
+
+func (s *shell) libraryStats(c *ui.Context, page *route) {
+ state, _ := page.data.(*libraryStatsState)
+ if state == nil {
+ stats, _ := s.app.ListeningStats()
+ state = summarizeLibraryStats(stats, time.Now().Local())
+ page.data = state
+ }
+ ui.Text(c, "最近 7 天 · 只统计在本机的收听").FontSize(13).TextColor(c.Theme().TextMuted)
+ if state.total == 0 && state.plays == 0 {
+ libraryMessage(c, "暂无历史记录", "播放过的歌曲会按日期记录在这里。")
+ return
+ }
+ minutes := state.total / 60000
+ peak := 0
+ for hour := range state.hours {
+ if state.hours[hour] > state.hours[peak] {
+ peak = hour
+ }
+ }
+ peakTime := "—"
+ if state.hours[peak] > 0 {
+ peakTime = fmt.Sprintf("%02d:00", peak)
+ }
+ durationLabel := "收听总时长"
+ if state.previous > 0 {
+ difference := minutes - state.previous/60000
+ durationLabel = fmt.Sprintf("比上周 %+d 分钟", difference)
+ }
+ metrics := [][2]string{{fmt.Sprintf("%d 小时 %d 分", minutes/60, minutes%60), durationLabel}, {fmt.Sprintf("%d 首", len(state.tracks)), "播放过的歌曲"}, {fmt.Sprintf("%d 位", state.newUsers), "新认识的歌手"}, {peakTime, "最常收听的时段"}}
+ for index := 0; index < len(metrics); index += 2 {
+ ui.Row(c).Gap(8).Children(func() {
+ for _, metric := range metrics[index : index+2] {
+ ui.Column(c).Grow(1).Basis(0).Padding(12).Radius(12).Background(c.Theme().Surface).Gap(4).Children(func() {
+ ui.Text(c, metric[0]).FontSize(19).Bold()
+ ui.Text(c, metric[1]).FontSize(12).TextColor(c.Theme().TextMuted)
+ })
+ }
+ })
+ }
+ sectionHeading(c, "每天收听", "")
+ var maxMinutes int64
+ for _, day := range state.days {
+ maxMinutes = max(maxMinutes, day.minutes)
+ }
+ ui.Row(c).Gap(4).Padding(8).Background(c.Theme().Surface).Radius(12).Children(func() {
+ for index, day := range state.days {
+ ink := c.Theme().Border
+ if index == len(state.days)-1 {
+ ink = c.Theme().Accent
+ }
+ ui.Column(c).Grow(1).Basis(0).Height(138).Gap(4).Justify(ui.End).AlignItems(ui.Center).
+ Label(fmt.Sprintf("%s %d 分钟", day.name, day.minutes)).Children(func() {
+ ui.Text(c, fmt.Sprint(day.minutes)).FontSize(11).TextColor(c.Theme().TextMuted)
+ ui.Box(c).Width(21).Height(max(2, 91*float32(day.minutes)/float32(max(maxMinutes, 1)))).Radius(4).Background(ink)
+ ui.Text(c, day.name).FontSize(11).TextColor(c.Theme().TextMuted)
+ })
+ }
+ })
+ stats := app.ListeningStats{Tracks: state.tracks, Artists: state.artists}
+ if artists := stats.TopArtists(5); len(artists) > 0 {
+ sectionHeading(c, "最常听的歌手", "")
+ for _, artist := range artists {
+ ui.Row(c.Key(artist.Mid)).AlignItems(ui.Center).Gap(12).Children(func() {
+ ui.Text(c, artist.Name).Grow(1).FontSize(13).MaxLines(1)
+ ui.Text(c, fmt.Sprintf("%d 分钟", artist.Ms/60000)).FontSize(12).TextColor(c.Theme().TextMuted)
+ })
+ }
+ }
+ if maxHour := state.hours[peak]; maxHour > 0 {
+ sectionHeading(c, "一天里的收听时段", "")
+ palette := phonePalette(c)
+ for offset := 0; offset < len(state.hours); offset += 12 {
+ ui.Row(c).FillWidth().Gap(3).Children(func() {
+ for index, duration := range state.hours[offset : offset+12] {
+ hour := index + offset
+ color := palette.field.Mix(palette.accent, float32(duration)/float32(maxHour)*.66)
+ ui.Box(c.Key(hour)).Grow(1).Basis(0).Height(28).Radius(5).Center().Background(color).
+ Role(ui.RoleImage).Label(fmt.Sprintf("%02d 时,收听 %d 分钟", hour, duration/60000)).Children(func() {
+ ui.Text(c, fmt.Sprintf("%02d", hour)).FontSize(11)
+ })
+ }
+ })
+ }
+ }
+ sectionHeading(c, "本周单曲循环", "")
+ for _, row := range stats.TopTracks(5) {
+ item, err := app.ItemOfStatsKey(row.Key, state.tracks[row.Key])
+ var play func()
+ if err == nil {
+ play = func() { s.play([]app.Item{item}, 0) }
+ }
+ libraryRow(c.Key(row.Key), item.Cover, "disc", row.Title, fmt.Sprintf("本机播放 %d 次", row.Plays), play)
+ }
+}
+
+func summarizeLibraryStats(stats app.ListeningStats, now time.Time) *libraryStatsState {
+ state := &libraryStatsState{tracks: make(map[string]*app.StatsTrackStat), artists: make(map[int64]*app.StatsArtistStat)}
+ first := now.AddDate(0, 0, -6).Format("2006-01-02")
+ state.previous = stats.DayRangeMs(now.AddDate(0, 0, -13).Format("2006-01-02"), now.AddDate(0, 0, -7).Format("2006-01-02"))
+ days := [...]string{"周日", "周一", "周二", "周三", "周四", "周五", "周六"}
+ newUsers := make(map[int64]bool)
+ knownUsers := make(map[int64]bool)
+ for _, track := range stats.Tracks {
+ if track != nil && track.ArtistMid != 0 && track.FirstHeard != "" && track.FirstHeard < first {
+ knownUsers[track.ArtistMid] = true
+ }
+ }
+ for index := range state.days {
+ date := now.AddDate(0, 0, index-6)
+ key, name := date.Format("2006-01-02"), days[date.Weekday()]
+ if index == 6 {
+ name = "今天"
+ }
+ report := stats.Days[key]
+ state.days[index].name = name
+ if report == nil {
+ continue
+ }
+ state.days[index].minutes = report.Ms / 60000
+ state.total += report.Ms
+ state.plays += report.Plays
+ for hour, duration := range report.HourlyMs {
+ state.hours[hour] += duration
+ }
+ for id, track := range report.Tracks {
+ if track == nil {
+ continue
+ }
+ if state.tracks[id] == nil {
+ state.tracks[id] = &app.StatsTrackStat{Title: track.Title, Artist: track.Artist, ArtistMid: track.ArtistMid, Local: track.Local, FirstHeard: track.FirstHeard}
+ }
+ state.tracks[id].Ms += track.Ms
+ state.tracks[id].Plays += track.Plays
+ if track.ArtistMid != 0 {
+ if state.artists[track.ArtistMid] == nil {
+ state.artists[track.ArtistMid] = &app.StatsArtistStat{Name: track.Artist}
+ }
+ state.artists[track.ArtistMid].Ms += track.Ms
+ state.artists[track.ArtistMid].Plays += track.Plays
+ if !knownUsers[track.ArtistMid] {
+ newUsers[track.ArtistMid] = true
+ }
+ }
+ }
+ }
+ state.newUsers = len(newUsers)
+ return state
+}
diff --git a/internal/mobileui/library_social.go b/internal/mobileui/library_social.go
new file mode 100644
index 00000000..9989343f
--- /dev/null
+++ b/internal/mobileui/library_social.go
@@ -0,0 +1,568 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+)
+
+type followingLibraryState struct {
+ pages libraryPages[app.FollowUser]
+ tags []app.FollowTag
+ group *app.FollowTag
+ keyword, query string
+ sortOpen, sortByName bool
+}
+
+func (s *shell) followingLibrary(c *ui.Context, page *route) {
+ if !s.app.LoggedIn() {
+ s.libraryLogin(c, "关注")
+ return
+ }
+ account := s.app.AccountSnapshot()
+ state, _ := page.data.(*followingLibraryState)
+ if state == nil || state.pages.account != account {
+ state = &followingLibraryState{}
+ page.data = state
+ s.loadFollowing(state, true)
+ s.loadFollowTags(state)
+ }
+ ui.ScrollHorizontal(c).FillWidth().Height(44).Gap(6).Children(func() {
+ librarySegment(c, "全部关注", state.group == nil, func() {
+ state.group = nil
+ s.loadFollowing(state, true)
+ })
+ for _, tag := range state.tags {
+ librarySegment(c.Key(tag.ID), fmt.Sprintf("%s %d", tag.Name, tag.Count), state.group != nil && state.group.ID == tag.ID, func() {
+ state.group = &tag
+ s.loadFollowing(state, true)
+ })
+ }
+ })
+ ui.Row(c).Gap(4).AlignItems(ui.Center).Children(func() {
+ libraryInput(c, &state.keyword, "搜索关注", func() {
+ state.query = strings.TrimSpace(state.keyword)
+ s.loadFollowing(state, true)
+ })
+ iconButton(c, "sort", "排序").OnClick(func() { state.sortOpen = true })
+ })
+ rows := followingRows(state.pages.items, state.query, state.sortByName)
+ if len(rows) > 0 {
+ ui.Grid(c).Columns(2).Gap(8).Children(func() {
+ for _, user := range rows {
+ s.followingCard(c.Key(user.Mid), user)
+ }
+ })
+ } else if !state.pages.loading && state.pages.err == nil && !state.pages.more {
+ if state.query != "" {
+ libraryMessage(c, "没有匹配的关注", "换一个 UP 主昵称试试。")
+ } else {
+ libraryMessage(c, "这个分组还没有人", "去 UP 主的空间点「关注」,就会出现在这里。")
+ }
+ }
+ if state.pages.err != nil {
+ libraryFailure(c, func() { s.loadFollowing(state, false) })
+ } else if state.pages.loading || state.pages.more {
+ libraryMore(c, state.pages.loading, func() { s.loadFollowing(state, false) })
+ }
+ libraryActionSheet(c, &state.sortOpen, mobile.ActionSheetOptions{Title: "排序", Cancel: "取消"},
+ mobile.Action{Label: "关注时间", OnTap: func() { state.sortByName = false }},
+ mobile.Action{Label: "昵称(已加载)", OnTap: func() { state.sortByName = true }},
+ )
+}
+
+func followingRows(input []app.FollowUser, query string, alphabetical bool) []app.FollowUser {
+ query = strings.ToLower(query)
+ seen := make(map[int64]bool)
+ var rows []app.FollowUser
+ for _, user := range input {
+ if !seen[user.Mid] && strings.Contains(strings.ToLower(user.Name), query) {
+ rows = append(rows, user)
+ seen[user.Mid] = true
+ }
+ }
+ if alphabetical {
+ slices.SortStableFunc(rows, func(left, right app.FollowUser) int {
+ return strings.Compare(strings.ToLower(left.Name), strings.ToLower(right.Name))
+ })
+ }
+ return rows
+}
+
+func (s *shell) followingCard(c *ui.Context, user app.FollowUser) {
+ ui.Column(c).MinHeight(116).Padding(10).Gap(6).Radius(12).Background(c.Theme().Surface).Role(ui.RoleButton).Label(user.Name).
+ OnClick(func() { s.openCreator(user.Mid, user.Name) }).Children(func() {
+ cover(c, user.Face, 42, 21)
+ ui.Text(c, user.Name).MaxLines(1).Bold().FontSize(14)
+ if user.Sign != "" {
+ ui.Text(c, user.Sign).MaxLines(2).FontSize(12).TextColor(c.Theme().TextMuted)
+ }
+ if user.Official != "" {
+ ui.Text(c, user.Official).MaxLines(1).FontSize(11).TextColor(c.Theme().TextMuted)
+ }
+ })
+}
+
+func (s *shell) loadFollowTags(state *followingLibraryState) {
+ account := s.app.AccountSnapshot()
+ go func() {
+ tags, err := s.app.FollowTagsForAccount(s.ctx, account)
+ if err == nil {
+ s.update(func() {
+ if account == s.app.AccountSnapshot() {
+ state.tags = tags
+ }
+ })
+ }
+ }()
+}
+
+func (s *shell) loadFollowing(state *followingLibraryState, reset bool) {
+ account := s.app.AccountSnapshot()
+ query, group := state.query, state.group
+ loaded := len(state.pages.items)
+ if reset {
+ loaded = 0
+ }
+ loadLibraryPage(s, &state.pages, reset, func(ctx context.Context, page int) ([]app.FollowUser, bool, error) {
+ if group != nil {
+ users, err := s.app.FollowTagUsersForAccount(ctx, account, group.ID, page)
+ return users, len(users) != 0 && loaded+len(users) < group.Count, err
+ }
+ var response app.FollowUsersPage
+ var err error
+ if query == "" {
+ response, err = s.app.FollowListForAccount(ctx, account, page)
+ } else {
+ response, err = s.app.SearchFollowingsForAccount(ctx, account, query, page)
+ }
+ return response.Users, len(response.Users) != 0 && loaded+len(response.Users) < response.Total, err
+ })
+}
+
+type dynamicLibraryState struct {
+ pages libraryPages[app.DynamicPage]
+ pending map[string]bool
+ liked map[string]bool
+}
+
+type feedLibraryState struct {
+ feed dynamicLibraryState
+ authors libraryPages[app.FollowAuthor]
+ author int64
+}
+
+func (s *shell) feedLibrary(c *ui.Context, page *route) {
+ if !s.app.LoggedIn() {
+ s.libraryLogin(c, "动态")
+ return
+ }
+ account := s.app.AccountSnapshot()
+ state, _ := page.data.(*feedLibraryState)
+ if state == nil || state.feed.pages.account != account {
+ state = &feedLibraryState{}
+ page.data = state
+ s.loadDynamicFeed(&state.feed, 0, true)
+ s.loadFeedAuthors(state, true)
+ }
+ ui.Text(c, "关注的 UP 主最近分享了什么。").FontSize(13).TextColor(c.Theme().TextMuted)
+ ui.ScrollHorizontal(c).FillWidth().Height(44).Gap(6).Children(func() {
+ librarySegment(c, "全部", state.author == 0, func() {
+ state.author = 0
+ s.loadDynamicFeed(&state.feed, 0, true)
+ })
+ seen := make(map[int64]bool)
+ for _, author := range state.authors.items {
+ if seen[author.Mid] {
+ continue
+ }
+ seen[author.Mid] = true
+ librarySegment(c.Key(author.Mid), author.Name, state.author == author.Mid, func() {
+ state.author = author.Mid
+ s.loadDynamicFeed(&state.feed, author.Mid, true)
+ })
+ }
+ if state.authors.more && !state.authors.loading {
+ label := "更多 UP 主"
+ if state.authors.err != nil {
+ label = "重试加载 UP 主"
+ }
+ librarySegment(c, label, false, func() { s.loadFeedAuthors(state, false) })
+ }
+ })
+ s.dynamicRows(c, &state.feed, state.author)
+}
+
+func (s *shell) loadFeedAuthors(state *feedLibraryState, reset bool) {
+ account := s.app.AccountSnapshot()
+ loadLibraryPage(s, &state.authors, reset, func(ctx context.Context, page int) ([]app.FollowAuthor, bool, error) {
+ result, err := s.app.FollowedAuthorsForAccount(ctx, account, page)
+ return result.Authors, result.HasMore, err
+ })
+}
+
+func (s *shell) loadDynamicFeed(state *dynamicLibraryState, mid int64, reset bool) {
+ var offset string
+ if !reset && len(state.pages.items) != 0 {
+ offset = state.pages.items[len(state.pages.items)-1].Offset
+ }
+ if state.pending == nil {
+ state.pending, state.liked = make(map[string]bool), make(map[string]bool)
+ }
+ account := s.app.AccountSnapshot()
+ loadLibraryPage(s, &state.pages, reset, func(ctx context.Context, _ int) ([]app.DynamicPage, bool, error) {
+ var result app.DynamicPage
+ var err error
+ if mid == 0 {
+ result, err = s.app.DynamicFeedForAccount(ctx, account, offset)
+ } else {
+ result, err = s.app.UpDynamics(ctx, mid, offset)
+ }
+ return []app.DynamicPage{result}, result.HasMore && result.Offset != "" && result.Offset != offset, err
+ })
+}
+
+func (s *shell) dynamicRows(c *ui.Context, state *dynamicLibraryState, mid int64) {
+ seen := make(map[string]bool)
+ for _, data := range state.pages.items {
+ for _, dynamic := range data.Items {
+ if !seen[dynamic.ID] {
+ seen[dynamic.ID] = true
+ s.dynamicCard(c.Key(dynamic.ID), state, dynamic)
+ }
+ }
+ }
+ if state.pages.err != nil {
+ libraryFailure(c, func() { s.loadDynamicFeed(state, mid, false) })
+ } else if state.pages.more || state.pages.loading {
+ libraryMore(c, state.pages.loading, func() { s.loadDynamicFeed(state, mid, false) })
+ } else if len(seen) == 0 {
+ libraryMessage(c, "这里没有能显示的动态", "关注的 UP 主发布的新动态会显示在这里。")
+ }
+}
+
+func (s *shell) dynamicCard(c *ui.Context, state *dynamicLibraryState, dynamic app.Dynamic) {
+ liked, changed := state.liked[dynamic.ID]
+ if !changed {
+ liked = dynamic.Liked
+ }
+ ui.Column(c).Radius(12).Background(c.Theme().Surface).Padding(12).Gap(8).Children(func() {
+ ui.Row(c).Gap(8).AlignItems(ui.Center).MinHeight(44).Role(ui.RoleButton).Label(dynamic.Author.Name).
+ OnClick(func() { s.openCreator(dynamic.Author.Mid, dynamic.Author.Name) }).Children(func() {
+ cover(c, dynamic.Author.Face, 34, 17)
+ ui.Column(c).Grow(1).Gap(2).Children(func() {
+ ui.Text(c, dynamic.Author.Name).FontSize(14).Bold().MaxLines(1)
+ ui.Text(c, dynamic.Time).FontSize(12).TextColor(c.Theme().TextMuted)
+ })
+ })
+ if dynamic.Text != "" {
+ ui.Text(c, dynamic.Text).FontSize(14)
+ }
+ if len(dynamic.Pics) > 0 {
+ ui.ScrollHorizontal(c).Height(92).FillWidth().Gap(6).Children(func() {
+ for _, imageURL := range dynamic.Pics {
+ cover(c, imageURL, 92, 10)
+ }
+ })
+ }
+ if video := dynamic.Video; video != nil {
+ item := app.Item{Source: app.SourceOnline, Type: "mv", Bvid: video.Bvid, Title: video.Title, Cover: video.Cover, Artist: dynamic.Author.Name, ArtistMid: dynamic.Author.Mid}
+ s.trackList(c, []app.Item{item})
+ }
+ ui.Row(c).Gap(8).AlignItems(ui.Center).Children(func() {
+ icon, label := "thumb", "点赞"
+ if liked {
+ icon, label = "thumb-on", "取消点赞"
+ }
+ count := dynamic.LikeCount
+ if changed && liked != dynamic.Liked {
+ if liked {
+ count++
+ } else {
+ count = max(0, count-1)
+ }
+ }
+ libraryButton(c, icon, fmt.Sprintf("%s %d", label, count), false, state.pending[dynamic.ID], func() {
+ if !s.app.LoggedIn() {
+ s.push(route{kind: pageLogin, title: "登录"})
+ return
+ }
+ state.pending[dynamic.ID], state.liked[dynamic.ID] = true, !liked
+ s.app.LikeDynamicForAccount(s.app.AccountSnapshot(), dynamic.ID, !liked, func(err error) {
+ s.update(func() {
+ delete(state.pending, dynamic.ID)
+ if err != nil {
+ state.liked[dynamic.ID] = liked
+ s.notice = "点赞操作失败,请重试。"
+ }
+ })
+ })
+ })
+ if _, err := strconv.ParseUint(dynamic.ID, 10, 64); err == nil {
+ libraryButton(c, "comment", "查看评论", false, false, func() { c.OpenURL("https://t.bilibili.com/" + dynamic.ID) })
+ }
+ })
+ })
+}
+
+type libraryCreatorState struct {
+ account app.AccountSnapshot
+ space *app.UpSpace
+ tab int
+ order string
+ sort, working bool
+ videos libraryPages[app.SpaceVideo]
+ posts dynamicLibraryState
+ folders libraryPages[app.SpaceCollection]
+ series libraryPages[app.SpaceCollection]
+}
+
+func (s *shell) libraryCreator(c *ui.Context, page *route) {
+ mid, err := strconv.ParseInt(page.id, 10, 64)
+ if err != nil || mid <= 0 {
+ libraryMessage(c, "这一页走丢了", "无法找到这位 UP 主。")
+ return
+ }
+ account := s.app.AccountSnapshot()
+ state, _ := page.data.(*libraryCreatorState)
+ if state == nil || state.account != account {
+ state = &libraryCreatorState{account: account, space: s.app.UpSpaceOf(mid), order: "pubdate"}
+ page.data = state
+ state.space.Load()
+ s.loadCreatorTab(state, true)
+ }
+ header := state.space.Snapshot()
+ if header.Err != "" && !header.Loaded {
+ libraryMessage(c, "加载 UP 主失败", header.Err)
+ libraryButton(c, "refresh", "重试", false, false, state.space.Load)
+ } else {
+ s.creatorHeader(c, state, header, page.title)
+ }
+ ui.ScrollHorizontal(c).FillWidth().Height(44).Gap(6).Children(func() {
+ for index, label := range []string{"投稿", "动态", "收藏夹", "合集"} {
+ librarySegment(c, label, state.tab == index, func() {
+ state.tab = index
+ s.loadCreatorTab(state, true)
+ })
+ }
+ })
+ switch state.tab {
+ case 0:
+ s.creatorVideos(c, state, header.User.Name)
+ case 1:
+ s.dynamicRows(c, &state.posts, mid)
+ case 2:
+ s.creatorFolders(c, state, &state.folders, "他还没有公开收藏夹", bili.CollectionFavorite)
+ case 3:
+ s.creatorFolders(c, state, &state.series, "还没有合集", bili.CollectionAlbum)
+ }
+}
+
+func (s *shell) creatorHeader(c *ui.Context, state *libraryCreatorState, header app.SpaceHeaderSnapshot, fallback string) {
+ name := header.User.Name
+ if name == "" {
+ name = fallback
+ }
+ if name == "" {
+ name = "UP 主空间"
+ }
+ ui.Column(c).Padding(12).Gap(8).Radius(16).Background(c.Theme().Surface).Children(func() {
+ cover(c, header.User.Face, 64, 32)
+ ui.Row(c).Gap(6).AlignItems(ui.Center).Children(func() {
+ ui.Text(c, name).FontSize(21).Bold().MaxLines(1)
+ if header.User.Level > 0 {
+ ui.Text(c, fmt.Sprintf("LV%d", header.User.Level)).FontSize(12).Bold().TextColor(c.Theme().Accent)
+ }
+ })
+ if header.User.Sign != "" {
+ ui.Text(c, header.User.Sign).FontSize(13).TextColor(c.Theme().TextMuted)
+ }
+ if header.StatOK() {
+ ui.Row(c).Gap(14).Children(func() {
+ for _, metric := range []struct {
+ name string
+ value int64
+ }{{"粉丝", header.Stat.Follower}, {"关注", header.Stat.Following}, {"获赞", header.Stat.Likes}} {
+ ui.Column(c).Gap(2).Children(func() {
+ ui.Text(c, fmt.Sprint(metric.value)).FontSize(15).Bold()
+ ui.Text(c, metric.name).FontSize(12).TextColor(c.Theme().TextMuted)
+ })
+ }
+ })
+ }
+ ui.Row(c).Gap(5).AlignItems(ui.Center).Children(func() {
+ if state.space.Mid() != s.app.SelfMid() {
+ follow := header.Follow(s.app.SelfMid(), s.app.LoggedIn())
+ switch follow {
+ case app.FollowAskable, app.FollowDone:
+ label, icon := "关注", "plus"
+ if follow == app.FollowDone {
+ label, icon = "已关注", "check"
+ }
+ libraryButton(c, icon, label, follow == app.FollowAskable, state.working, func() { s.creatorFollow(state, follow != app.FollowDone) })
+ case app.FollowFailed:
+ libraryButton(c, "refresh", "重试关注状态", false, false, state.space.RetryRelation)
+ }
+ }
+ libraryButton(c, "play", "播放投稿", false, len(state.videos.items) == 0, func() { s.play(creatorVideoItems(state.videos.items, state.space.Mid(), name), 0) })
+ iconButton(c, "open", "在 B 站打开").OnClick(func() { c.OpenURL("https://space.bilibili.com/" + strconv.FormatInt(state.space.Mid(), 10)) })
+ })
+ })
+}
+
+func (s *shell) creatorFollow(state *libraryCreatorState, follow bool) {
+ state.working = true
+ go func() {
+ err := state.space.FollowForAccount(s.ctx, state.account, follow)
+ s.update(func() {
+ state.working = false
+ if err != nil && state.account == s.app.AccountSnapshot() {
+ s.notice = "关注操作失败,请重试。"
+ }
+ })
+ }()
+}
+
+func (s *shell) loadCreatorTab(state *libraryCreatorState, reset bool) {
+ mid := state.space.Mid()
+ switch state.tab {
+ case 0:
+ order := state.order
+ loadLibraryPage(s, &state.videos, reset, func(ctx context.Context, page int) ([]app.SpaceVideo, bool, error) {
+ result, err := s.app.UpVideos(ctx, app.SpaceVideoQuery{Mid: mid, Page: page, Order: order})
+ return result.Videos, result.HasMore, err
+ })
+ case 1:
+ s.loadDynamicFeed(&state.posts, mid, reset)
+ case 2:
+ loadLibraryPage(s, &state.folders, reset, func(ctx context.Context, page int) ([]app.SpaceCollection, bool, error) {
+ result, err := s.app.UpCollections(ctx, mid, page)
+ return result.Items, result.HasMore, err
+ })
+ case 3:
+ loadLibraryPage(s, &state.series, reset, func(ctx context.Context, page int) ([]app.SpaceCollection, bool, error) {
+ result, err := s.app.UpSeries(ctx, mid, page, 0)
+ return result.Items, result.HasMore, err
+ })
+ }
+}
+
+func (s *shell) creatorVideos(c *ui.Context, state *libraryCreatorState, name string) {
+ ui.Row(c).Gap(6).AlignItems(ui.Center).Justify(ui.End).Children(func() {
+ iconButton(c, "sort", "投稿排序").OnClick(func() { state.sort = true })
+ })
+ items := creatorVideoItems(state.videos.items, state.space.Mid(), name)
+ if len(items) > 0 {
+ s.trackList(c, items)
+ }
+ if state.videos.err != nil {
+ libraryFailure(c, func() { s.loadCreatorTab(state, false) })
+ } else if state.videos.loading || state.videos.more {
+ libraryMore(c, state.videos.loading, func() { s.loadCreatorTab(state, false) })
+ } else if len(items) == 0 {
+ libraryMessage(c, "暂无投稿", "")
+ }
+ var actions []mobile.Action
+ for _, order := range []struct{ id, name string }{{"pubdate", "最新发布"}, {"click", "最多播放"}, {"scores", "最多评论"}} {
+ actions = append(actions, mobile.Action{Label: order.name, OnTap: func() {
+ state.order = order.id
+ s.loadCreatorTab(state, true)
+ }})
+ }
+ libraryActionSheet(c, &state.sort, mobile.ActionSheetOptions{Title: "投稿排序", Cancel: "取消"}, actions...)
+}
+
+func creatorVideoItems(videos []app.SpaceVideo, owner int64, fallback string) []app.Item {
+ var items []app.Item
+ for _, video := range videos {
+ if video.Bvid == "" {
+ continue
+ }
+ artist := video.Author
+ if artist == "" {
+ artist = fallback
+ }
+ items = append(items, app.Item{Source: app.SourceOnline, Type: "mv", Bvid: video.Bvid, Cid: video.Cid, Cover: video.Cover, Title: video.Title, Artist: artist, ArtistMid: owner})
+ }
+ return items
+}
+
+func (s *shell) creatorFolders(c *ui.Context, state *libraryCreatorState, pages *libraryPages[app.SpaceCollection], empty string, fallback bili.CollectionType) {
+ seen := make(map[string]bool)
+ for _, item := range pages.items {
+ kind := fallback
+ if item.Type != 0 {
+ kind = bili.ParseCollectionType(strconv.Itoa(item.Type))
+ }
+ ref := app.CollectionRef{ID: item.ID, Type: kind, OwnerMid: state.space.Mid()}
+ if seen[ref.Key()] {
+ continue
+ }
+ seen[ref.Key()] = true
+ libraryRow(c.Key(ref.Key()), item.Cover, "folder", item.Title, fmt.Sprintf("%d 首", item.Count), func() {
+ s.push(route{kind: pageCollection, title: item.Title, ref: ref})
+ })
+ }
+ if pages.err != nil {
+ libraryFailure(c, func() { s.loadCreatorTab(state, false) })
+ } else if pages.loading || pages.more {
+ libraryMore(c, pages.loading, func() { s.loadCreatorTab(state, false) })
+ } else if len(seen) == 0 {
+ libraryMessage(c, empty, "")
+ }
+}
+
+func libraryFailure(c *ui.Context, retry func()) {
+ libraryMessage(c, "加载失败", "检查网络后重试。")
+ libraryButton(c, "refresh", "重试", false, false, retry)
+}
+
+func (s *shell) libraryRefresh(page *route, scroll ui.Element) {
+ var loading bool
+ var refresh func()
+ switch state := page.data.(type) {
+ case *libraryHistoryState:
+ loading = state.pages.loading
+ refresh = func() {
+ if s.app.LoggedIn() {
+ s.loadLibraryHistory(state, page.kind == pageLater, true)
+ } else {
+ state.local, _ = s.app.ListeningStats()
+ }
+ }
+ case *myLibraryState:
+ loading = s.app.FavoritesRefreshing()
+ refresh = func() {
+ if s.app.LoggedIn() {
+ s.app.RefreshFavorites()
+ }
+ stats, _ := s.app.ListeningStats()
+ state.local = libraryLocalHistory(stats, app.LibraryQuery{})
+ }
+ case *followingLibraryState:
+ loading = state.pages.loading
+ refresh = func() { s.loadFollowing(state, true); s.loadFollowTags(state) }
+ case *feedLibraryState:
+ loading = state.feed.pages.loading
+ refresh = func() { s.loadDynamicFeed(&state.feed, state.author, true) }
+ case *localLibraryState:
+ loading = s.app.LocalMusicState().Scanning
+ refresh = s.app.RescanLocalMusic
+ case *downloadLibraryState:
+ refresh = func() { _ = s.app.DownloadSnapshotList() }
+ }
+ if refresh != nil {
+ state := ui.Local(scroll, "library-refresh", func() ui.RefreshState { return ui.RefreshState{} })
+ state.Refreshing = state.Refreshing && loading
+ if scroll.PullToRefresh(state) {
+ refresh()
+ }
+ }
+}
diff --git a/internal/mobileui/library_test.go b/internal/mobileui/library_test.go
new file mode 100644
index 00000000..a69e101a
--- /dev/null
+++ b/internal/mobileui/library_test.go
@@ -0,0 +1,267 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+ "image"
+ "image/color"
+ "image/png"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+)
+
+// TestMobileMyRespectsSavedEntriesAndOpensGuestLibrary exercises the My tab's guest navigation and saved menu visibility.
+func TestMobileMyRespectsSavedEntriesAndOpensGuestLibrary(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.SetThemeMode(app.ThemeModeLight); err != nil {
+ t.Fatal(err)
+ }
+ a.MountLocalMusic(app.LocalMusic{})
+ localUpdates := make(chan func(), 1)
+ t.Cleanup(a.AddLocalWake(func() {
+ select {
+ case localUpdates <- func() {}:
+ default:
+ }
+ }))
+ s := newShell(t.Context(), a)
+ s.switchTab(2)
+ tester := ui.NewTester(s.view, 390, 844)
+ mobileLibraryShot(t, tester, "mobile-light-my-guest.png")
+ if err := tester.Click("最近播放"); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(tester.Texts(), "暂无历史记录") || !slices.Contains(tester.Texts(), "登录查看 B 站历史") {
+ t.Fatalf("guest history is missing its offline state or account entry: %q", tester.Texts())
+ }
+ if err := tester.Click("返回"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.UpdateSettings(func(st *app.Settings) { st.HiddenMenuKeys = []string{"/history"} }); err != nil {
+ t.Fatal(err)
+ }
+ tester.Frame()
+ if _, visible := tester.Find("最近播放"); visible {
+ t.Fatal("My still shows the history shortcut hidden in settings")
+ }
+ if err := tester.Click("本地音乐"); err != nil {
+ t.Fatal(err)
+ }
+ waitLibrary(t, tester, localUpdates, func() bool { return slices.Contains(tester.Texts(), "还没有打开文件") })
+}
+
+// TestMobileCollectionUsesServerRowsAndSearchQuery checks that a guest can open a real collection and submit a server-backed search.
+func TestMobileCollectionUsesServerRowsAndSearchQuery(t *testing.T) {
+ queries := make(chan string, 8)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var response string
+ switch r.URL.Path {
+ case "/x/v3/fav/folder/info":
+ response = `{"id":42,"title":"深夜循环","intro":"睡前的小曲。","upper":{"mid":100,"name":"拍档"},"media_count":2}`
+ case "/x/v3/fav/resource/list":
+ keyword := r.URL.Query().Get("keyword")
+ queries <- keyword
+ switch keyword {
+ case "":
+ response = `{"medias":[{"id":6,"type":2,"title":"返航","bvid":"BVfixture6"},{"id":7,"type":2,"title":"夜曲","bvid":"BVfixture7"}],"has_more":false}`
+ case "夜曲":
+ response = `{"medias":[{"id":7,"type":2,"title":"夜曲","bvid":"BVfixture7"}],"has_more":false}`
+ default:
+ t.Errorf("unexpected query %q", keyword)
+ response = `{"medias":[],"has_more":false}`
+ }
+ default:
+ t.Errorf("unexpected request %s", r.URL.Path)
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "application/json")
+ fmt.Fprintf(w, `{"code":0,"data":%s}`, response)
+ }))
+ t.Cleanup(server.Close)
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.SetThemeMode(app.ThemeModeLight); err != nil {
+ t.Fatal(err)
+ }
+ client := bili.NewClient(bili.Options{Transport: server.Client().Transport})
+ client.TestOnlyPointHostsAtFixture(server.URL)
+ a.MountCollections(app.CollectionRefs{Client: client})
+ ctx, cancel := context.WithCancel(t.Context())
+ t.Cleanup(cancel)
+ s := newShell(ctx, a)
+ updates := make(chan func(), 12)
+ s.dispatch = func(update func()) {
+ select {
+ case updates <- update:
+ case <-ctx.Done():
+ }
+ }
+ a.SetWake(func() { s.dispatch(func() {}) })
+ s.push(route{kind: pageCollection, ref: app.CollectionRef{ID: 42, Type: bili.CollectionFavorite}})
+ tester := ui.NewTester(s.view, 390, 844)
+ waitLibrary(t, tester, updates, func() bool {
+ return slices.Contains(tester.Texts(), "返航") && slices.Contains(tester.Texts(), "深夜循环")
+ })
+ mobileLibraryShot(t, tester, "mobile-light-collection.png")
+ if err := tester.Click("歌单更多"); err != nil {
+ t.Fatal(err)
+ }
+ clickLibraryControl(t, tester, "搜索歌单")
+ clickLibraryControl(t, tester, "在这张歌单里找歌")
+ tester.Type("夜曲")
+ tester.Key(0, ui.KeyEnter)
+ waitLibrary(t, tester, updates, func() bool {
+ return slices.Contains(tester.Texts(), "夜曲") && !slices.Contains(tester.Texts(), "返航")
+ })
+ if first, second := <-queries, <-queries; first != "" || second != "夜曲" {
+ t.Fatalf("collection requested queries %q, %q", first, second)
+ }
+}
+
+func waitLibrary(t *testing.T, tester *ui.Tester, updates <-chan func(), ready func() bool) {
+ t.Helper()
+ deadline := time.NewTimer(3 * time.Second)
+ defer deadline.Stop()
+ for {
+ tester.Frame()
+ if ready() {
+ return
+ }
+ select {
+ case update := <-updates:
+ update()
+ case <-deadline.C:
+ t.Fatalf("library did not reach expected state: %q", tester.Texts())
+ }
+ }
+}
+
+func clickLibraryControl(t *testing.T, tester *ui.Tester, label string) {
+ t.Helper()
+ deadline := tester.Now().Add(2 * time.Second)
+ for {
+ err := tester.Click(label)
+ if err == nil {
+ return
+ }
+ if !tester.Now().Before(deadline) {
+ t.Fatal(err)
+ }
+ tester.Advance(time.Second / 60)
+ }
+}
+
+func mobileLibraryShot(t *testing.T, tester *ui.Tester, name string) {
+ t.Helper()
+ dir := os.Getenv("BIU_SHOT_DIR")
+ if dir == "" {
+ return
+ }
+ file, err := os.Create(filepath.Join(dir, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = png.Encode(file, tester.Image())
+ if closeErr := file.Close(); err != nil || closeErr != nil {
+ t.Fatalf("screenshot %s: encode = %v, close = %v", name, err, closeErr)
+ }
+}
+
+// TestMobileImportCopiesMatchingNamesSeparately verifies that importing two files with the same name preserves both originals and both app copies.
+func TestMobileImportCopiesMatchingNamesSeparately(t *testing.T) {
+ base := filepath.Join(t.TempDir(), "app")
+ var roots []string
+ for _, content := range []string{"first file", "second file"} {
+ source := filepath.Join(t.TempDir(), "song.flac")
+ if err := os.WriteFile(source, []byte(content), 0600); err != nil {
+ t.Fatal(err)
+ }
+ root, err := copyMobileImport(base, source)
+ if err != nil {
+ t.Fatal(err)
+ }
+ roots = append(roots, root)
+ for _, name := range []string{source, filepath.Join(root, "song.flac")} {
+ bytes, err := os.ReadFile(name)
+ if err != nil || string(bytes) != content {
+ t.Fatalf("music copy %q = %q, err = %v", name, bytes, err)
+ }
+ }
+ }
+ if roots[0] == roots[1] {
+ t.Fatal("the second import overwrote the first")
+ }
+}
+
+// TestMobileDocumentSelectionKeepsPlayableCopies verifies that a mixed import keeps the good file and reports the failed file.
+func TestMobileDocumentSelectionKeepsPlayableCopies(t *testing.T) {
+ application := app.New()
+ t.Cleanup(application.Close)
+ settings := filepath.Join(t.TempDir(), app.SettingsFileName)
+ if err := application.MountSettings(settings); err != nil {
+ t.Fatal(err)
+ }
+ application.MountLocalMusic(app.LocalMusic{})
+ s := newShell(t.Context(), application)
+ s.dispatch = func(apply func()) { apply() }
+ state := &localLibraryState{base: filepath.Join(t.TempDir(), "imports"), working: true}
+ s.finishLocalImport(state, []string{
+ filepath.Join("..", "service", "audio", "testdata", "tone.mp3"),
+ filepath.Join(t.TempDir(), "missing.mp3"),
+ }, 0, nil)
+ if state.working || state.status != "已导入 1 个文件,1 个文件未能导入" {
+ t.Fatalf("import status = %q, working = %t", state.status, state.working)
+ }
+ if err := application.FlushSettings(); err != nil {
+ t.Fatal(err)
+ }
+ saved, err := app.LoadSettings(settings)
+ if err != nil || len(saved.LocalMusicDirs) != 1 {
+ t.Fatalf("saved import roots = %v, err = %v", saved.LocalMusicDirs, err)
+ }
+ if err := application.Open(filepath.Join(saved.LocalMusicDirs[0], "tone.mp3")); err != nil {
+ t.Fatalf("open imported file: %v", err)
+ }
+}
+
+// TestMobileCoverCropUsesPanAndZoom verifies that the exported square reflects the crop preview's translation and scale.
+func TestMobileCoverCropUsesPanAndZoom(t *testing.T) {
+ source := image.NewRGBA(image.Rect(0, 0, 120, 80))
+ red := color.RGBA{R: 255, A: 255}
+ blue := color.RGBA{B: 255, A: 255}
+ for y := range 80 {
+ for x := range 120 {
+ ink := blue
+ if x < 60 {
+ ink = red
+ }
+ source.SetRGBA(x, y, ink)
+ }
+ }
+ left := cropFolderImage(source, mobile.ZoomState{Scale: 2, X: 40}, 80)
+ right := cropFolderImage(source, mobile.ZoomState{Scale: 2, X: -40}, 80)
+ if left.Bounds() != image.Rect(0, 0, 40, 40) || right.Bounds() != left.Bounds() {
+ t.Fatalf("cropped bounds: left %v, right %v", left.Bounds(), right.Bounds())
+ }
+ if left.At(20, 20) != red || right.At(20, 20) != blue {
+ t.Fatalf("crop ignored pan: left %v, right %v", left.At(20, 20), right.At(20, 20))
+ }
+}
diff --git a/internal/mobileui/login.go b/internal/mobileui/login.go
new file mode 100644
index 00000000..7f214f0d
--- /dev/null
+++ b/internal/mobileui/login.go
@@ -0,0 +1,178 @@
+package mobileui
+
+import (
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/scale"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/tok"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/typo"
+ "github.com/egoist/mygo/ui"
+)
+
+type loginPageData struct {
+ started bool
+ code *bili.Code
+ bitmap *ui.Bitmap
+ openFailed bool
+}
+
+func (s *shell) leaveLogin(page *route) {
+ if page.kind != pageLogin || page.data == nil {
+ return
+ }
+ data, _ := page.data.(*loginPageData)
+ if data != nil && data.started {
+ s.app.CancelLogin()
+ }
+ page.data = nil
+}
+
+func (s *shell) login(c *ui.Context, page *route) {
+ data, _ := page.data.(*loginPageData)
+ if data == nil {
+ data = &loginPageData{}
+ page.data = data
+ }
+ palette := tok.Of(c.Theme())
+ _, height := c.Size()
+ ui.Column(c).Key("mobile-auth").FillWidth().MinHeight(min(585, max(0, height-145))).PaddingY(24).
+ Gap(12).AlignItems(ui.Start).Justify(ui.Center).Children(func() {
+ if !data.started {
+ mobileRecordMark(c, 60)
+ loginHeading(c, "登录", "继续你的音乐旅程:登录后同步收藏夹、关注和历史记录,并解锁 Hi-Res 无损音质。")
+ if s.app.Account() == nil {
+ settingsText(c, "当前无法申请二维码,请稍后重试。", 13, palette.Err).Role(ui.RoleStatus)
+ }
+ if settingsAction(c, "继续登录", true, true).Disabled(s.app.Account() == nil).Clicked() {
+ data.started = true
+ s.app.BeginLogin()
+ }
+ if loginQuietAction(c, "暂不登录").Clicked() {
+ s.back()
+ }
+ return
+ }
+ snapshot := s.app.LoginState()
+ if snapshot.Phase == app.LoginDone {
+ mobileRecordMark(c, 60)
+ created := s.app.FavoriteState(app.FavoritesCreated)
+ collected := s.app.FavoriteState(app.FavoritesCollected)
+ switch {
+ case s.app.FavoritesRefreshing():
+ loginHeading(c, "登录成功,正在同步…", "")
+ case created.Err != "" || collected.Err != "":
+ loginHeading(c, "同步失败", "登录已完成。请检查网络后重试。")
+ if settingsAction(c, "重试", true, true).Clicked() {
+ s.app.RefreshFavorites()
+ }
+ default:
+ loginHeading(c, "登录成功", "")
+ }
+ if snapshot.Err != "" {
+ settingsText(c, "登录状态未能保存。关闭应用后需要重新登录。", 13, palette.Warn).Role(ui.RoleStatus)
+ }
+ if settingsAction(c, "返回", true, true).Clicked() {
+ s.back()
+ }
+ return
+ }
+ link := snapshot.ConfirmationURL()
+ description := "请用另一台已登录 B 站的手机扫码。"
+ if link != "" {
+ description = "在本机打开 B 站确认,或用另一台设备扫码。"
+ }
+ loginHeading(c, "扫码登录", description)
+ data.drawCode(c, snapshot.QR, snapshot.Phase == app.LoginExpired)
+ message, color := snapshot.Hint, palette.Text2
+ switch snapshot.Phase {
+ case app.LoginWaiting:
+ if snapshot.Hint == bili.ScanWaiting.String() {
+ message = "正在等待扫码…"
+ }
+ case app.LoginScanned:
+ if snapshot.Hint == bili.ScanScanned.String() {
+ message = "已扫码,等待确认…"
+ }
+ case app.LoginExpired:
+ message, color = "二维码已过期,请刷新二维码", palette.Warn
+ case app.LoginFailed:
+ message, color = "未能完成登录,请检查网络后刷新二维码。", palette.Err
+ }
+ settingsText(c, message, 14, color).Role(ui.RoleStatus)
+ if link != "" {
+ if data.openFailed {
+ settingsText(c, "未能打开链接,请重试或使用另一台设备扫码。", 13, palette.Warn).Role(ui.RoleStatus)
+ }
+ if settingsAction(c, "在 B 站 App 中确认", true, true).Clicked() {
+ data.openFailed = false
+ c.OpenURLThen(link, func(err error) {
+ if page.data == data && s.app.LoginState().ConfirmationURL() == link {
+ data.openFailed = err != nil
+ }
+ })
+ }
+ }
+ if settingsAction(c, "刷新二维码", false, true).
+ Disabled(snapshot.Phase == app.LoginWaiting && snapshot.QR == nil).Clicked() {
+ data.openFailed = false
+ s.app.RefreshLoginCode()
+ }
+ if loginQuietAction(c, "暂不登录").Clicked() {
+ s.back()
+ }
+ })
+}
+
+func (data *loginPageData) drawCode(c *ui.Context, code *bili.Code, expired bool) {
+ if code != data.code {
+ data.code, data.bitmap = code, nil
+ if code != nil && !expired {
+ const quietModules = 8
+ moduleSize := max(1, 136/(code.Size()+quietModules))
+ data.bitmap = ui.NewBitmap(code.Image(moduleSize)).Pixelated()
+ }
+ }
+ ui.Box(c).Key("login-qr-card").Size(160, 160).Radius(8).
+ Background(ui.RGB(255, 255, 255)).AlignItems(ui.Center).Justify(ui.Center).Children(func() {
+ if data.bitmap != nil && !expired {
+ width, height := data.bitmap.Size()
+ ui.Image(c, data.bitmap).Size(float32(width), float32(height)).Label("B 站登录二维码")
+ } else if expired {
+ glyph(c, "refresh", 34, ui.RGB(111, 114, 121))
+ }
+ })
+}
+
+func loginHeading(c *ui.Context, title, description string) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).Key(title).FillWidth().Gap(6).Children(func() {
+ typo.Display(settingsText(c, title, 26, palette.Text), scale.Font(c, 26)).Role(ui.RoleHeading)
+ if description != "" {
+ settingsText(c, description, 14, palette.Text2)
+ }
+ })
+}
+
+func loginQuietAction(c *ui.Context, label string) ui.Element {
+ return settingsAction(c, label, false, true).Background(ui.Color{})
+}
+
+func mobileRecordMark(c *ui.Context, size float32) {
+ palette := tok.Of(c.Theme())
+ ui.Box(c).Key("mobile-record-mark").Size(size, size).Shrink(0).Draw(func(painter *ui.Painter, rect ui.Rect) {
+ centerX, centerY := rect.X+rect.W/2, rect.Y+rect.H/2
+ scale := rect.W / 32
+ circle := func(radius float32, color ui.Color) {
+ radius *= scale
+ painter.Fill(ui.Rect{X: centerX - radius, Y: centerY - radius, W: radius * 2, H: radius * 2}, color, radius)
+ }
+ ring := palette.Text.Mix(palette.Bg, 0.35)
+ circle(16, palette.Text)
+ circle(12, ring)
+ circle(11.4, palette.Text)
+ circle(9.5, ring)
+ circle(8.9, palette.Text)
+ circle(6, palette.Accent)
+ circle(1.6, palette.Text)
+ })
+}
diff --git a/internal/mobileui/login_test.go b/internal/mobileui/login_test.go
new file mode 100644
index 00000000..80da747f
--- /dev/null
+++ b/internal/mobileui/login_test.go
@@ -0,0 +1,160 @@
+package mobileui
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "image/png"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "slices"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+)
+
+// TestMobileQRLoginPollsAndRefreshes covers expiry, cancellation and same-device confirmation on the current QR session.
+func TestMobileQRLoginPollsAndRefreshes(t *testing.T) {
+ var requests atomic.Int32
+ var status atomic.Int32
+ status.Store(86090)
+ fixture := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/x/passport-login/web/qrcode/generate":
+ key := requests.Add(1)
+ fmt.Fprintf(w, `{"code":0,"data":{"url":"https://passport.bilibili.com/h5-app/passport/login/scan?qrcode_key=test-%d","qrcode_key":"test-%d"}}`, key, key)
+ case "/x/passport-login/web/qrcode/poll":
+ code := status.Load()
+ if code == 0 && r.URL.Query().Get("qrcode_key") != "test-3" {
+ code = 86101
+ } else if code == 0 {
+ http.SetCookie(w, &http.Cookie{Name: "SESSDATA", Value: "synthetic-mobile-session", Path: "/"})
+ }
+ fmt.Fprintf(w, `{"code":0,"data":{"code":%d}}`, code)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(fixture.Close)
+ a := app.New()
+ t.Cleanup(a.Close)
+ client := bili.NewClient(bili.Options{Transport: fixture.Client().Transport})
+ client.TestOnlyPointHostsAtFixture(fixture.URL)
+ store := app.NewMemoryStore("fixture")
+ a.MountLogin(store, client)
+ a.SetLoginPollInterval(2 * time.Millisecond)
+ s := newShell(context.Background(), a)
+ s.push(route{kind: pageLogin, title: "登录"})
+ tester := ui.NewTester(func(c *ui.Context) {
+ if page := s.current(); page.kind == pageLogin {
+ ui.Column(c).FillWidth().PaddingX(16).Children(func() { s.login(c, page) })
+ }
+ }, 390, 700)
+ if err := tester.Click("继续登录"); err != nil {
+ t.Fatal(err)
+ }
+ waitForMobileLogin(t, a, app.LoginScanned)
+ tester.Frame()
+ if !slices.Contains(tester.Texts(), "已扫码,等待确认…") {
+ t.Fatalf("missing scan confirmation status in %q", tester.Texts())
+ }
+ status.Store(86038)
+ waitForMobileLogin(t, a, app.LoginExpired)
+ tester.Frame()
+ if !slices.Contains(tester.Texts(), "二维码已过期,请刷新二维码") {
+ t.Fatalf("missing expired status in %q", tester.Texts())
+ }
+ if slices.Contains(tester.Texts(), "在 B 站 App 中确认") {
+ t.Fatal("expired QR session still offers same-device confirmation")
+ }
+ status.Store(86101)
+ if err := tester.Click("刷新二维码"); err != nil {
+ t.Fatal(err)
+ }
+ deadline := time.Now().Add(3 * time.Second)
+ for requests.Load() != 2 || a.LoginState().QR == nil {
+ if time.Now().After(deadline) {
+ t.Fatal("refresh did not request a new QR code")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ tester.Frame()
+ if err := tester.Click("暂不登录"); err != nil {
+ t.Fatal(err)
+ }
+ if s.current().kind == pageLogin {
+ t.Fatal("cancel did not return to the source page")
+ }
+ if phase := a.LoginState().Phase; phase != app.LoginIdle {
+ t.Fatalf("login phase after leaving the route = %v, want idle", phase)
+ }
+ s.push(route{kind: pageLogin, title: "登录"})
+ tester.Frame()
+ if err := tester.Click("继续登录"); err != nil {
+ t.Fatal(err)
+ }
+ deadline = time.Now().Add(3 * time.Second)
+ for a.LoginState().QR == nil {
+ if time.Now().After(deadline) {
+ t.Fatal("same-device login did not receive a QR code")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ tester.Frame()
+ if path := os.Getenv("PUDMUSIC_MOBILE_LOGIN_SCREENSHOT"); path != "" {
+ file, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ encodeErr := png.Encode(file, tester.Image())
+ if err := errors.Join(encodeErr, file.Close()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ tester.FailOpenURL(errors.New("no handler"))
+ if err := tester.Click("在 B 站 App 中确认"); err != nil {
+ t.Fatal(err)
+ }
+ tester.Frame()
+ if !slices.Contains(tester.Texts(), "未能打开链接,请重试或使用另一台设备扫码。") {
+ t.Fatal("failed launch did not show the scan fallback")
+ }
+ tester.FailOpenURL(nil)
+ if err := tester.Click("在 B 站 App 中确认"); err != nil {
+ t.Fatal(err)
+ }
+ const wantLink = "https://passport.bilibili.com/h5-app/passport/login/scan?qrcode_key=test-3"
+ if links := tester.OpenedURLs(); len(links) == 0 || links[len(links)-1] != wantLink || requests.Load() != 3 {
+ t.Fatal("same-device login did not open the current QR session")
+ }
+ status.Store(0)
+ waitForMobileLogin(t, a, app.LoginDone)
+ tester.Frame()
+ if !slices.Contains(tester.Texts(), "登录成功") {
+ t.Fatalf("missing successful login status in %q", tester.Texts())
+ }
+ if err := tester.Click("返回"); err != nil {
+ t.Fatal(err)
+ }
+ stored, err := store.Load(context.Background())
+ if err != nil || !stored.LoggedIn() || !a.LoggedIn() || s.current().kind == pageLogin {
+ t.Fatalf("confirmed login did not save credentials and return to source: %v", err)
+ }
+}
+
+func waitForMobileLogin(t *testing.T, a *app.App, phase app.LoginPhase) {
+ t.Helper()
+ deadline := time.Now().Add(3 * time.Second)
+ for a.LoginState().Phase != phase {
+ if time.Now().After(deadline) {
+ t.Fatalf("login phase = %v, want %v", a.LoginState().Phase, phase)
+ }
+ time.Sleep(time.Millisecond)
+ }
+}
diff --git a/internal/mobileui/mygo-plugin.json b/internal/mobileui/mygo-plugin.json
new file mode 100644
index 00000000..7a08ed14
--- /dev/null
+++ b/internal/mobileui/mygo-plugin.json
@@ -0,0 +1,12 @@
+{
+ "mobile": {
+ "id": "pudmusic_documents",
+ "android": {
+ "class": "PudMusicDocumentsPlugin",
+ "sources": ["android/Documents.kt"],
+ "application": [
+ ""
+ ]
+ }
+ }
+}
diff --git a/internal/mobileui/player.go b/internal/mobileui/player.go
new file mode 100644
index 00000000..63164103
--- /dev/null
+++ b/internal/mobileui/player.go
@@ -0,0 +1,404 @@
+package mobileui
+
+import (
+ "image"
+ "sort"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ desktop "github.com/ShellMonster/PudMusic/internal/ui"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/imgcache"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/netimage"
+)
+
+type playerSheetKind uint8
+
+const (
+ sheetNone playerSheetKind = iota
+ sheetQueue
+ sheetTrack
+ sheetOptions
+ sheetSpeed
+ sheetQuality
+ sheetSleep
+ sheetParts
+ sheetChapters
+ sheetComments
+ sheetReplies
+ sheetClearQueue
+ sheetCover
+ sheetVideoQuality
+ sheetLyricsOptions
+ sheetPrefs
+ sheetEQ
+ sheetLyricsSearch
+ sheetTrackFolders
+ sheetDownload
+ sheetPlaybackError
+)
+
+type playerView struct {
+ visible, lyrics, cinema bool
+ sheet playerSheetKind
+ parents []playerSheetKind
+ target app.Item
+ seek float64
+ bitmap *ui.Bitmap
+ bitmapWidth, bitmapHeight int
+ danmaku desktop.VideoDanmaku
+ videoPosition time.Duration
+ videoRefreshUntil time.Time
+ comments playerCommentView
+ folders *playerFolderView
+ downloadItem app.Item
+ lyricsScroll ui.ScrollState
+ lyricsKey string
+ lyricsLine int
+ lyricsManualUntil time.Time
+ hideTranslation bool
+ lyricsQuery string
+ lyricsSource int
+ queueExpanded bool
+}
+
+func (p *playerView) show(kind playerSheetKind) {
+ if kind == sheetQueue && p.sheet != sheetQueue {
+ p.queueExpanded = false
+ }
+ if p.sheet != sheetNone && p.sheet != kind {
+ p.parents = append(p.parents, p.sheet)
+ }
+ p.sheet = kind
+}
+
+func (p *playerView) back() bool {
+ switch {
+ case p.sheet != sheetNone:
+ p.sheet = sheetNone
+ if count := len(p.parents); count != 0 {
+ p.sheet = p.parents[count-1]
+ p.parents = p.parents[:count-1]
+ }
+ case p.cinema:
+ p.cinema = false
+ case p.visible:
+ p.visible = false
+ p.bitmap = nil
+ p.danmaku.Reset()
+ default:
+ return false
+ }
+ return true
+}
+
+func (s *shell) miniPlayer(c *ui.Context, state app.State) {
+ item, _ := s.app.Queue().Current()
+ palette := phonePalette(c)
+ title := state.Title
+ if item.Title != "" && (title == "" || item.Source == app.SourceLocal) {
+ title = item.Title
+ }
+ if title == "" {
+ title = state.FailedTitle
+ if title == "" {
+ title = "正在加载"
+ }
+ }
+ ui.Column(c.Key("mini-player")).Margin(0, 12, 3, 12).Height(60).Shrink(0).Radius(16).Clip().Background(palette.fill).Children(func() {
+ ui.Box(c).FillWidth().Height(2).Draw(func(p *ui.Painter, bounds ui.Rect) {
+ if state.Duration > 0 {
+ bounds.W *= float32(float64(state.Position) / float64(state.Duration))
+ p.Fill(bounds, palette.accent, 0)
+ }
+ })
+ ui.Row(c).Grow(1).Basis(0).FillWidth().PaddingX(8).AlignItems(ui.Center).Children(func() {
+ ui.Row(c).Grow(1).Basis(0).MinHeight(touchSize()).Gap(10).AlignItems(ui.Center).Role(ui.RoleButton).
+ Label("打开满屏播放器:" + title).Children(func() {
+ cover(c, state.CoverURL, 40, 8)
+ trackLabel(c, title, item.Artist, 13, false)
+ }).OnClick(func() { s.player.visible = true })
+ icon, label := playGlyph(state)
+ if state.Err != "" && !state.HasTrack {
+ iconButton(c, "info", "查看播放失败原因").OnClick(func() { s.player.show(sheetPlaybackError) })
+ } else {
+ iconButton(c, icon, label).OnClick(s.app.Toggle)
+ }
+ iconButton(c, "queue", "播放列表").OnClick(func() { s.player.show(sheetQueue) })
+ })
+ })
+}
+
+func playGlyph(state app.State) (string, string) {
+ if state.Playing {
+ return "pause", "暂停"
+ }
+ return "play", "播放"
+}
+
+func playModeGlyph(mode app.PlayMode) string {
+ switch mode {
+ case app.PlayModeSequence:
+ return "order"
+ case app.PlayModeRandom:
+ return "shuffle"
+ case app.PlayModeSingle:
+ return "repeat1"
+ default:
+ return "repeat"
+ }
+}
+
+func (s *shell) fullPlayer(c *ui.Context, state app.State) {
+ prefs := s.app.FullPlayerPrefs()
+ background := phonePalette(c).fill
+ if !prefs.ShowBlurredBackground && prefs.BackgroundColor != "" {
+ background = ui.Hex(prefs.BackgroundColor)
+ }
+ width, height := c.Size()
+ ui.Box(c.Key("full-player")).Fill().Background(background).Clip().Children(func() {
+ if prefs.ShowBlurredBackground && state.CoverURL != "" {
+ netimage.Image(c, imgcache.FormatURLProtocol(state.CoverURL), netimage.Options{MaxSide: 120, Placeholder: background}).
+ Absolute().Top(-32).Bottom(-32).Left(-32).Right(-32).Blur(38).Opacity(.24)
+ }
+ ui.Column(c).Fill().Children(func() { s.playerLayout(c, state, prefs, width, height) })
+ })
+}
+
+func (s *shell) playerLayout(c *ui.Context, state app.State, prefs app.FullPlayerPrefs, width, height float32) {
+ ui.Row(c).FillWidth().Height(touchSize()).PaddingX(8).AlignItems(ui.Center).Children(func() {
+ iconButton(c, "down", "收起满屏播放器").OnClick(func() { s.back() })
+ ui.Box(c).Grow(1).Basis(0).Center().Children(func() { ui.Text(c, "正在播放").FontSize(13).FontWeight(600) })
+ iconButton(c, "more", "更多播放设置").OnClick(func() { s.player.show(sheetOptions) })
+ })
+ if s.player.cinema && s.app.VideoPhase() != app.VideoOff {
+ s.playerVideo(c, state, prefs, width, max(100, height-110))
+ return
+ }
+ if width > height {
+ ui.Row(c).Grow(1).Basis(0).FillWidth().AlignItems(ui.Center).Children(func() {
+ s.swipeablePlayerStage(c, state, prefs, width*.48, max(110, height-100))
+ ui.Column(c).Grow(1).Basis(0).Children(func() { s.playerControls(c, state, prefs) })
+ })
+ return
+ }
+ ui.Column(c).Grow(1).Basis(0).FillWidth().AlignItems(ui.Center).Padding(max(0, min(38, height-620)), 0, 0, 0).Children(func() {
+ s.swipeablePlayerStage(c, state, prefs, width, max(110, height-344))
+ })
+ s.playerControls(c, state, prefs)
+}
+
+func (s *shell) swipeablePlayerStage(c *ui.Context, state app.State, prefs app.FullPlayerPrefs, width, height float32) {
+ stage := ui.Box(c).Width(width).Center().Children(func() { s.playerStage(c, state, prefs, width, height) })
+ if !prefs.ShowLyrics || s.app.VideoPhase() != app.VideoOff {
+ return
+ }
+ dx, dy, completed := completedSwipe(stage)
+ if !completed || abs32(dx) < max(48, 1.5*abs32(dy)) {
+ return
+ }
+ if toLyrics := dx < 0; toLyrics != s.player.lyrics {
+ s.player.lyrics = toLyrics
+ c.AnimationFrame()
+ }
+}
+
+func abs32(number float32) float32 { return max(number, -number) }
+
+func (s *shell) playerStage(c *ui.Context, state app.State, prefs app.FullPlayerPrefs, width, height float32) {
+ if s.app.VideoPhase() != app.VideoOff {
+ videoWidth := min(width-32, height*16/9)
+ s.playerVideo(c, state, prefs, videoWidth, videoWidth*9/16)
+ return
+ }
+ lyric := s.app.Lyrics()
+ position := state.Position - time.Duration(lyric.OffsetMS)*time.Millisecond
+ index := sort.Search(len(lyric.Rows), func(index int) bool { return lyric.Rows[index].At > position }) - 1
+ if s.player.lyrics && prefs.ShowLyrics {
+ s.playerLyrics(c, lyric, index, width, height, prefs.LyricsColor)
+ return
+ }
+ ui.Column(c).Width(width).MaxHeight(height).Center().Gap(9).Children(func() {
+ if prefs.ShowCover {
+ size := max(80, min(width*.82, 329, height-65))
+ ui.Box(c).Role(ui.RoleButton).Label("当前封面的操作").Size(size, size).Children(func() {
+ cover(c, state.CoverURL, size, 16)
+ }).OnClick(func() { s.player.show(sheetCover) })
+ }
+ if prefs.ShowSpectrum {
+ color := phonePalette(c).muted
+ if prefs.SpectrumColor != "" {
+ color = ui.Hex(prefs.SpectrumColor)
+ }
+ ui.Box(c).Width(min(width*.75, 284)).Height(22).Draw(func(p *ui.Painter, bounds ui.Rect) {
+ for index, height := range s.app.SpectrumBars(48, bounds.H) {
+ step := bounds.W / 48
+ p.Fill(ui.Rect{X: bounds.X + float32(index)*step, Y: bounds.Y + (bounds.H-height)/2, W: step / 2, H: height}, color, 1)
+ }
+ if state.Playing {
+ p.AnimationFrame()
+ }
+ })
+ }
+ if prefs.ShowLyrics {
+ line := "暂无歌词"
+ if lyric.Loading && !lyric.HasLyrics {
+ line = "歌词加载中…"
+ } else if index >= 0 {
+ line = lyric.Rows[index].Text
+ }
+ ui.Box(c).Width(width - 32).MinHeight(32).Center().Role(ui.RoleButton).Label("展开歌词").Children(func() {
+ ui.Text(c, line).FontSize(13).MaxLines(1).Ellipsis("…").TextColor(phonePalette(c).muted)
+ }).OnClick(func() { s.player.lyrics = true })
+ }
+ })
+}
+
+func (s *shell) playerControls(c *ui.Context, state app.State, prefs app.FullPlayerPrefs) {
+ palette := phonePalette(c)
+ item, _ := s.app.Queue().Current()
+ width, height := c.Size()
+ side := float32(16)
+ if width <= height {
+ side = max(side, (width-330)/2)
+ }
+ ui.Column(c).FillWidth().Padding(8, side, 12, side).Gap(8).Children(func() {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ ui.Column(c).Grow(1).Basis(0).Gap(3).Children(func() {
+ title := state.Title
+ if item.Title != "" && (title == "" || item.Source == app.SourceLocal) {
+ title = item.Title
+ }
+ ui.Text(c, title).FontSize(21).FontWeight(650).MaxLines(2).Ellipsis("…")
+ if item.Artist != "" {
+ ui.Text(c, item.Artist).FontSize(13).TextColor(palette.muted).MaxLines(1).Ellipsis("…")
+ }
+ })
+ if s.app.Likeable() {
+ liked := s.app.LikeState().Liked
+ icon := "heart"
+ if liked {
+ icon = "heart-on"
+ }
+ iconButton(c, icon, "喜欢").AccessSelected(liked).OnClick(func() { s.app.SetLike(!liked, s.playerResult("")) })
+ }
+ })
+ if state.Err != "" {
+ playerTool(c, "info", "打不开这一首").OnClick(func() { s.player.show(sheetPlaybackError) })
+ }
+ s.playerProgress(c, state)
+ ui.Row(c).FillWidth().Height(66).Justify(ui.SpaceBetween).AlignItems(ui.Center).Children(func() {
+ mode := s.app.PlayMode()
+ iconButton(c, playModeGlyph(mode), mode.Desc()).OnClick(s.app.CyclePlayMode)
+ iconButton(c, "prev", "上一首").OnClick(s.app.Prev)
+ icon, label := playGlyph(state)
+ ui.Box(c).Size(62, 62).Radius(31).Center().Background(palette.text).Role(ui.RoleButton).Label(label).Children(func() {
+ glyph(c, icon, 26, palette.surface)
+ }).OnClick(s.app.Toggle)
+ iconButton(c, "next", "下一首").OnClick(s.app.Next)
+ iconButton(c, "queue", "播放列表").OnClick(func() { s.player.show(sheetQueue) })
+ })
+ ui.Row(c).FillWidth().Center().Gap(8).Children(func() {
+ if s.app.CommentsWorthAsking() {
+ playerTool(c, "comment", "评论").OnClick(func() {
+ if s.app.LoggedIn() {
+ s.app.RefreshComments()
+ } else {
+ s.app.EnsureComments()
+ }
+ s.player.show(sheetComments)
+ })
+ }
+ if prefs.ShowLyrics {
+ label := "歌词"
+ if s.player.lyrics {
+ label = "封面"
+ }
+ playerTool(c, "lyrics", label).OnClick(func() { s.app.StopVideo(); s.player.lyrics = !s.player.lyrics })
+ }
+ if item.Source == app.SourceOnline {
+ playerTool(c, "eq", s.app.AudioQuality().Label()).OnClick(func() { s.player.show(sheetQuality) })
+ }
+ })
+ })
+}
+
+func (s *shell) playerProgress(c *ui.Context, state app.State) {
+ if state.Duration > 0 {
+ s.player.seek = float64(state.Position) / float64(state.Duration)
+ }
+ ui.Slider(c, &s.player.seek, 0, 1).FillWidth().Height(26).Label("播放进度").Disabled(state.Duration <= 0).OnChange(func() {
+ s.app.SeekTo(time.Duration(s.player.seek * float64(state.Duration)))
+ })
+ ui.Row(c).FillWidth().Justify(ui.SpaceBetween).AlignItems(ui.Center).Children(func() {
+ muted := phonePalette(c).muted
+ ui.Text(c, timeLabel(state.Position)).FontSize(12).TextColor(muted)
+ if len(state.Chapters) > 0 {
+ playerTool(c, "parts", "章节").OnClick(func() { s.player.show(sheetChapters) })
+ }
+ ui.Text(c, timeLabel(state.Duration)).FontSize(12).TextColor(muted)
+ })
+}
+
+func playerTool(c *ui.Context, icon, label string) ui.Element {
+ return ui.Row(c).MinHeight(touchSize()).PaddingX(6).AlignItems(ui.Center).Gap(5).Role(ui.RoleButton).Label(label).Children(func() {
+ color := phonePalette(c).muted
+ glyph(c, icon, 15, color)
+ ui.Text(c, label).FontSize(12).TextColor(color)
+ })
+}
+
+func (s *shell) playerResult(message string) func(error) {
+ return func(err error) {
+ s.update(func() {
+ if err != nil {
+ s.report(err)
+ } else if message != "" {
+ s.notice = message
+ }
+ })
+ }
+}
+
+func (s *shell) playerVideo(c *ui.Context, state app.State, prefs app.FullPlayerPrefs, width, height float32) {
+ p := &s.player
+ if p.videoPosition != state.Position {
+ p.videoPosition, p.videoRefreshUntil = state.Position, c.Now().Add(time.Second)
+ }
+ ui.Column(c).Width(width).Center().Children(func() {
+ if err := s.app.VideoError(); err != nil {
+ ui.Text(c, err.Error()).FontSize(13).MaxLines(2)
+ } else {
+ video := ui.Box(c).Size(width, height).Radius(12).Role(ui.RoleButton).Label("切换视频全屏").Draw(func(painter *ui.Painter, bounds ui.Rect) {
+ if frame, ok := s.app.VideoFrame(s.app.PlayPosition()); ok {
+ pixels := &image.RGBA{Pix: frame.Pix, Stride: frame.W * 4, Rect: image.Rect(0, 0, frame.W, frame.H)}
+ if p.bitmap == nil || p.bitmapWidth != frame.W || p.bitmapHeight != frame.H {
+ p.bitmap, p.bitmapWidth, p.bitmapHeight = ui.NewBitmap(pixels), frame.W, frame.H
+ } else {
+ p.bitmap.Update(pixels)
+ }
+ }
+ painter.Fill(bounds, ui.RGB(0, 0, 0), 12)
+ if p.bitmap != nil {
+ painter.Clip(bounds, 12, func() { painter.Image(p.bitmap, bounds, ui.Contain) })
+ }
+ if state.Playing || p.bitmap == nil || painter.Now().Before(p.videoRefreshUntil) {
+ painter.AnimationFrame()
+ }
+ }).OnClick(func() { p.cinema = !p.cinema })
+ if prefs.ShowDanmaku {
+ p.danmaku.Draw(c, video, state, s.app.Danmaku().Items, width, height)
+ } else {
+ p.danmaku.Reset()
+ }
+ }
+ ui.Row(c).Center().Children(func() {
+ playerTool(c, "video", "视频画质").OnClick(func() { p.show(sheetVideoQuality) })
+ playerTool(c, "x", "关闭视频").OnClick(func() {
+ p.bitmap, p.cinema = nil, false
+ p.danmaku.Reset()
+ s.app.StopVideo()
+ })
+ })
+ })
+}
diff --git a/internal/mobileui/player_comments.go b/internal/mobileui/player_comments.go
new file mode 100644
index 00000000..23b14e07
--- /dev/null
+++ b/internal/mobileui/player_comments.go
@@ -0,0 +1,229 @@
+package mobileui
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+)
+
+type playerCommentView struct {
+ track, draft, replyName string
+ account app.AccountSnapshot
+ root, parent int64
+ thread bili.Comment
+ focused, sending, filter bool
+ likes map[int64]bool
+ pending map[int64]bool
+ expanded map[int64]bool
+}
+
+func (s *shell) playerComments(c *ui.Context, replies bool) {
+ item, _ := s.app.CurrentItem()
+ account := s.app.AccountSnapshot()
+ view := &s.player.comments
+ if view.track != item.Identity() || view.account != account {
+ wasOpen := view.track != ""
+ *view = playerCommentView{track: item.Identity(), account: account, likes: map[int64]bool{}, pending: map[int64]bool{}, expanded: map[int64]bool{}}
+ if wasOpen && replies {
+ s.player.back()
+ return
+ }
+ }
+ if replies {
+ s.commentRow(c, item, view.thread, true)
+ replies := s.app.CommentReplies(view.thread.Rpid)
+ if replies == nil {
+ ui.Spinner(c).Label("加载评论回复")
+ }
+ for _, comment := range replies {
+ s.commentRow(c, item, comment, true)
+ }
+ return
+ }
+ s.app.EnsureComments()
+ ui.Text(c, "这首歌的评论 · "+item.Title).FontSize(12).TextColor(phonePalette(c).muted).MaxLines(1).Ellipsis("…")
+ ui.Row(c).FillWidth().Justify(ui.SpaceBetween).AlignItems(ui.Center).Children(func() {
+ for _, choice := range []struct {
+ value bili.CommentSort
+ label string
+ }{{bili.CommentSortHot, "最热"}, {bili.CommentSortLatest, "最新"}} {
+ label := choice.label
+ selected := choice.value == s.app.CommentsSort()
+ if selected {
+ label = "✓ " + label
+ }
+ playerTool(c, "sort", label).AccessSelected(selected).OnClick(func() { s.app.SetCommentsSort(choice.value) })
+ }
+ playerTool(c, "search", "仅看提及歌名").AccessSelected(view.filter).OnClick(func() { view.filter = !view.filter })
+ iconButton(c, "refresh", "刷新评论").OnClick(s.app.RefreshComments)
+ })
+ comments := s.app.Comments()
+ switch {
+ case len(comments) > 0:
+ visible := 0
+ for _, comment := range comments {
+ if !view.filter || strings.Contains(comment.Message, item.Title) {
+ s.commentRow(c, item, comment, false)
+ visible++
+ }
+ }
+ if visible == 0 {
+ ui.Text(c, "当前没有提及歌名的评论").FontSize(13)
+ }
+ case s.app.CommentsLoading():
+ ui.Spinner(c).Label("加载评论")
+ case s.app.CommentsErr() != nil:
+ ui.Text(c, s.app.CommentsErr().Error()).FontSize(13).MaxLines(3)
+ default:
+ ui.Text(c, "暂无评论").FontSize(13)
+ }
+ if s.app.CommentsHasMore() {
+ sheetAction(c, "down", "加载更多评论", "", false, func() { s.app.LoadMoreComments() })
+ }
+}
+
+func (s *shell) commentRow(c *ui.Context, item app.Item, comment bili.Comment, inThread bool) {
+ palette := phonePalette(c)
+ view := &s.player.comments
+ ui.Row(c.Key(comment.Rpid)).FillWidth().Gap(9).PaddingY(8).Children(func() {
+ cover(c, comment.Avatar, 34, 17)
+ ui.Column(c).Grow(1).Basis(0).Gap(4).Children(func() {
+ ui.Text(c, comment.Uname).FontSize(13).FontWeight(600).MaxLines(1)
+ message := ui.Text(c, comment.Message).FontSize(13).Wrap()
+ if !view.expanded[comment.Rpid] && !inThread {
+ message.MaxLines(3).Ellipsis("…")
+ }
+ if len([]rune(comment.Message)) > 90 && !inThread {
+ label := "展开"
+ if view.expanded[comment.Rpid] {
+ label = "收起"
+ }
+ playerTool(c, "down", label).OnClick(func() { view.expanded[comment.Rpid] = !view.expanded[comment.Rpid] })
+ }
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(8).Children(func() {
+ ui.Text(c, time.Unix(comment.Ctime, 0).Format("01-02")).FontSize(12).TextColor(palette.muted)
+ s.commentLike(c, item, comment)
+ playerTool(c, "comment", "回复").OnClick(func() {
+ if !s.app.LoggedIn() {
+ s.openPlayerLogin()
+ return
+ }
+ view.root = comment.Root
+ if view.root == 0 {
+ view.root = comment.Rpid
+ }
+ view.parent, view.replyName, view.focused = comment.Rpid, comment.Uname, true
+ })
+ })
+ if !inThread && comment.Count > 0 {
+ playerTool(c, "down", fmt.Sprintf("%d 条回复", comment.Count)).OnClick(func() {
+ view.thread = comment
+ s.player.show(sheetReplies)
+ })
+ }
+ })
+ })
+}
+
+func (s *shell) commentLike(c *ui.Context, item app.Item, comment bili.Comment) {
+ view := &s.player.comments
+ liked, exists := view.likes[comment.Rpid]
+ if !exists {
+ liked = comment.Liked
+ }
+ icon, count := "thumb", comment.Like
+ if liked {
+ icon = "thumb-on"
+ }
+ if liked && !comment.Liked {
+ count++
+ }
+ if !liked && comment.Liked {
+ count--
+ }
+ playerTool(c, icon, fmt.Sprintf("%d 赞", max(0, count))).AccessSelected(liked).Disabled(view.pending[comment.Rpid]).OnClick(func() {
+ if !s.app.LoggedIn() {
+ s.openPlayerLogin()
+ return
+ }
+ view.pending[comment.Rpid] = true
+ account, track := view.account, view.track
+ go func() {
+ err := s.app.LikeComment(s.ctx, account, item, comment.Rpid, !liked)
+ s.update(func() {
+ if view.track != track || view.account != account {
+ return
+ }
+ delete(view.pending, comment.Rpid)
+ if err == nil {
+ view.likes[comment.Rpid] = !liked
+ } else {
+ s.notice = bili.Friendly(err)
+ }
+ })
+ }()
+ })
+}
+
+func (s *shell) commentComposer(c *ui.Context) {
+ view := &s.player.comments
+ if !s.app.LoggedIn() {
+ sheetAction(c, "user", "登录后发表评论", "", false, s.openPlayerLogin)
+ return
+ }
+ placeholder := "写评论…"
+ if view.replyName != "" {
+ placeholder = "回复 " + view.replyName
+ }
+ ui.Row(c).FillWidth().MinHeight(touchSize()).AlignItems(ui.Center).Gap(8).Children(func() {
+ ui.TextInputBase(c, &view.draft).Label("评论内容").Placeholder(placeholder).Grow(1).Basis(0).FontSize(13).
+ MinHeight(touchSize()).FocusBind(&view.focused, false).OnSubmit(s.submitMobileComment)
+ if view.replyName != "" {
+ iconButton(c, "x", "取消回复").OnClick(func() { view.root, view.parent, view.replyName = 0, 0, "" })
+ }
+ playerTool(c, "comment", "发送").Disabled(view.sending || strings.TrimSpace(view.draft) == "").OnClick(s.submitMobileComment)
+ })
+}
+
+func (s *shell) submitMobileComment() {
+ view := &s.player.comments
+ message := strings.TrimSpace(view.draft)
+ item, ok := s.app.CurrentItem()
+ if !ok || item.Identity() != view.track || view.sending || message == "" {
+ return
+ }
+ root, parent, account, track := view.root, view.parent, view.account, view.track
+ if root == 0 && s.player.sheet == sheetReplies {
+ root, parent = view.thread.Rpid, view.thread.Rpid
+ }
+ view.sending = true
+ go func() {
+ err := s.app.AddComment(s.ctx, account, item, root, parent, message)
+ s.update(func() {
+ if view.track != track || view.account != account {
+ return
+ }
+ view.sending = false
+ if err != nil {
+ s.notice = bili.Friendly(err)
+ return
+ }
+ if strings.TrimSpace(view.draft) == message {
+ view.draft = ""
+ }
+ view.root, view.parent, view.replyName, view.focused = 0, 0, "", false
+ s.notice = "已发布"
+ })
+ }()
+}
+
+func (s *shell) openPlayerLogin() {
+ s.closePlayerSheets()
+ s.player.visible = false
+ s.app.StopVideo()
+ s.push(route{kind: pageLogin, title: "登录"})
+}
diff --git a/internal/mobileui/player_folders.go b/internal/mobileui/player_folders.go
new file mode 100644
index 00000000..7e1ca5ad
--- /dev/null
+++ b/internal/mobileui/player_folders.go
@@ -0,0 +1,118 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo/ui"
+)
+
+type playerFolderView struct {
+ item app.Item
+ account app.AccountSnapshot
+ target app.TrackFolders
+ picked map[int64]bool
+ loading, saving bool
+ err string
+ editor folderEditor
+}
+
+func (s *shell) openPlayerFolders(item app.Item) {
+ if !s.app.LoggedIn() {
+ s.openPlayerLogin()
+ return
+ }
+ view := &playerFolderView{item: item, account: s.app.AccountSnapshot(), picked: map[int64]bool{}}
+ s.player.folders = view
+ s.player.show(sheetTrackFolders)
+ s.loadPlayerFolders(view)
+}
+
+func (s *shell) loadPlayerFolders(view *playerFolderView) {
+ view.loading, view.err = true, ""
+ go func() {
+ target, err := s.app.LoadTrackFolders(s.ctx, view.account, view.item)
+ s.update(func() {
+ if s.player.folders != view {
+ return
+ }
+ view.loading = false
+ if err != nil {
+ view.err = bili.Friendly(err)
+ return
+ }
+ for _, folder := range target.Choices {
+ if _, chose := view.picked[folder.ID]; !chose {
+ view.picked[folder.ID] = folder.Faved
+ }
+ }
+ view.target = target
+ })
+ }()
+}
+
+func (s *shell) playerFolderChoices(c *ui.Context) {
+ view := s.player.folders
+ if view == nil {
+ return
+ }
+ ui.Text(c, view.item.Title).FontSize(13).MaxLines(2)
+ if view.account != s.app.AccountSnapshot() {
+ ui.Text(c, "登录状态已变化,请重新打开收藏夹选择。").FontSize(13)
+ return
+ }
+ if view.loading {
+ ui.Spinner(c).Label("正在加载收藏夹")
+ return
+ }
+ if view.err != "" {
+ ui.Text(c, view.err).FontSize(13).Wrap()
+ }
+ if view.target.RID == 0 {
+ sheetAction(c, "refresh", "重试", "", false, func() { s.loadPlayerFolders(view) })
+ return
+ }
+ if !view.saving {
+ sheetAction(c, "plus", "新建收藏夹", "", false, func() { view.editor = folderEditor{open: true} })
+ }
+ var add, remove []int64
+ for _, folder := range view.target.Choices {
+ picked := view.picked[folder.ID]
+ if picked && !folder.Faved {
+ add = append(add, folder.ID)
+ }
+ if !picked && folder.Faved {
+ remove = append(remove, folder.ID)
+ }
+ ui.Box(c.Key(folder.ID)).FillWidth().Disabled(view.saving).Children(func() {
+ sheetAction(c, "folder", folder.Title, fmt.Sprintf("%d 首", folder.MediaCount), picked, func() {
+ if !view.saving {
+ view.picked[folder.ID] = !picked
+ }
+ })
+ })
+ }
+ settingsAction(c, "保存收藏夹选择", true, true).Disabled(view.saving || len(add)+len(remove) == 0).OnClick(func() {
+ view.saving, view.err = true, ""
+ target := view.target
+ go func(ctx context.Context) {
+ err := s.app.SaveTrackFolders(ctx, view.account, target, add, remove)
+ s.update(func() {
+ if s.player.folders != view {
+ return
+ }
+ view.saving = false
+ if err != nil {
+ view.err = bili.Friendly(err)
+ return
+ }
+ if s.player.sheet == sheetTrackFolders {
+ s.player.back()
+ }
+ s.notice = "收藏夹已更新"
+ })
+ }(s.ctx)
+ })
+}
diff --git a/internal/mobileui/player_preferences.go b/internal/mobileui/player_preferences.go
new file mode 100644
index 00000000..9652bf47
--- /dev/null
+++ b/internal/mobileui/player_preferences.go
@@ -0,0 +1,208 @@
+package mobileui
+
+import (
+ "fmt"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/audio"
+ "github.com/ShellMonster/PudMusic/internal/service/lyrics"
+ "github.com/egoist/mygo/ui"
+)
+
+func (s *shell) playerLyrics(c *ui.Context, lyric app.LyricsSnapshot, index int, width, height float32, color string) {
+ p := &s.player
+ if p.lyricsKey != lyric.Key {
+ p.lyricsKey, p.lyricsLine = lyric.Key, -2
+ p.lyricsScroll = ui.ScrollState{}
+ p.lyricsManualUntil = time.Time{}
+ }
+ palette := phonePalette(c)
+ ink := palette.accent
+ if color != "" {
+ ink = ui.Hex(color)
+ }
+ rowHeight := max(56, lyric.FontSize+29)
+ ui.Column(c).Width(width).Height(height).PaddingX(24).Children(func() {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ ui.Text(c, "歌词").FontSize(13).Grow(1).TextColor(palette.muted)
+ iconButton(c, "settings", "歌词设置").OnClick(func() { p.show(sheetLyricsOptions) })
+ })
+ if !lyric.HasLyrics {
+ label := "暂无歌词"
+ if lyric.Loading {
+ label = "歌词加载中…"
+ }
+ ui.Box(c).Grow(1).FillWidth().Center().Children(func() { ui.Text(c, label).FontSize(13) })
+ return
+ }
+ scroll := ui.Scroll(c).Grow(1).Basis(0).FillWidth().TrackScroll(&p.lyricsScroll)
+ if scroll.Dragging() {
+ p.lyricsManualUntil = c.Now().Add(4 * time.Second)
+ p.lyricsLine = -2
+ }
+ if index != p.lyricsLine && !c.Now().Before(p.lyricsManualUntil) {
+ p.lyricsLine = index
+ p.lyricsScroll.ScrollTo(0, max(0, float32(index)*rowHeight-height*.30), ui.Smooth)
+ }
+ scroll.Children(func() {
+ for row, line := range lyric.Rows {
+ textColor := palette.muted
+ if row == index {
+ textColor = ink
+ }
+ ui.Column(c.Key(row)).FillWidth().Height(rowHeight).Justify(ui.Center).Gap(3).Role(ui.RoleButton).Label(line.Text).AccessSelected(row == index).Children(func() {
+ ui.Text(c, line.Text).FontSize(max(14, lyric.FontSize)).FontWeight(550).TextColor(textColor).MaxLines(2)
+ if !p.hideTranslation && line.Translation != "" {
+ ui.Text(c, line.Translation).FontSize(12).TextColor(textColor).MaxLines(1).Ellipsis("…")
+ }
+ }).OnClick(func() { s.app.SeekTo(line.At + time.Duration(lyric.OffsetMS)*time.Millisecond) })
+ }
+ })
+ })
+}
+
+func (s *shell) playerLyricsOptions(c *ui.Context) {
+ lyric := s.app.Lyrics()
+ if settingSwitch(c, "歌词翻译", !s.player.hideTranslation, false) {
+ s.player.hideTranslation = !s.player.hideTranslation
+ }
+ settingRow(c, "lyric-offset", "歌词偏移", fmt.Sprintf("%+.1f 秒", float64(lyric.OffsetMS)/1000), func() {
+ iconButton(c, "minus", "歌词提前 0.5 秒").OnClick(func() { s.app.SetLyricsOffset(lyric.OffsetMS - 500) })
+ iconButton(c, "plus", "歌词延后 0.5 秒").OnClick(func() { s.app.SetLyricsOffset(lyric.OffsetMS + 500) })
+ })
+ settingRow(c, "lyric-size", "歌词字号", fmt.Sprintf("%.0f", lyric.FontSize), func() {
+ iconButton(c, "minus", "减小歌词字号").OnClick(func() { s.app.SetLyricsFontSize(lyric.FontSize - 2) })
+ iconButton(c, "plus", "增大歌词字号").OnClick(func() { s.app.SetLyricsFontSize(lyric.FontSize + 2) })
+ })
+ sheetAction(c, "search", "找歌词", "", false, func() { s.player.show(sheetLyricsSearch) })
+}
+
+func (s *shell) playerPreferences(c *ui.Context) {
+ prefs := s.app.FullPlayerPrefs()
+ for _, row := range []struct {
+ title string
+ value *bool
+ }{
+ {"显示歌词", &prefs.ShowLyrics}, {"显示频谱图", &prefs.ShowSpectrum}, {"显示封面", &prefs.ShowCover},
+ {"显示虚化背景", &prefs.ShowBlurredBackground}, {"显示弹幕", &prefs.ShowDanmaku},
+ } {
+ settingRow(c, row.title, row.title, "", func() {
+ if settingSwitch(c, row.title, *row.value, false) {
+ *row.value = !*row.value
+ s.app.SetFullPlayerPrefs(prefs)
+ }
+ })
+ }
+ for _, group := range []struct {
+ title string
+ value *string
+ color string
+ visible bool
+ }{
+ {"歌词颜色", &prefs.LyricsColor, "#b9c8ff", prefs.ShowLyrics},
+ {"频谱颜色", &prefs.SpectrumColor, "#ff5d3d", prefs.ShowSpectrum},
+ {"背景颜色", &prefs.BackgroundColor, "#101826", !prefs.ShowBlurredBackground},
+ } {
+ if group.visible {
+ settingSelect(c, group.title, *group.value, []settingChoice[string]{{value: "", label: "默认"}, {value: group.color, label: "自选色"}}, false, func(color string) {
+ *group.value = color
+ s.app.SetFullPlayerPrefs(prefs)
+ })
+ }
+ }
+}
+
+func (s *shell) playerEqualizer(c *ui.Context) {
+ settings := s.app.SettingsSnapshot()
+ save := func(change func(*app.Settings)) { _, err := s.app.UpdateSettings(change); s.report(err) }
+ for _, preset := range append(slices.Clone(audio.EQPresets), settings.EQCustomPresets...) {
+ custom := !slices.ContainsFunc(audio.EQPresets, func(item audio.EQPreset) bool { return item.ID == preset.ID })
+ selected := settings.EQCustomOn && custom && settings.EQCustomGains == preset.Gains ||
+ !settings.EQCustomOn && !custom && audio.EQPresetByID(settings.EQPreset).ID == preset.ID
+ sheetAction(c, "eq", preset.Name, "", selected, func() {
+ save(func(next *app.Settings) {
+ next.EQCustomOn = custom
+ if custom {
+ next.EQCustomGains = preset.Gains
+ } else {
+ next.EQPreset = preset.ID
+ }
+ })
+ })
+ }
+ gains := settings.EQGains()
+ for band, frequency := range audio.EQBands {
+ gain := gains[band]
+ settingRow(c, fmt.Sprintf("eq:%d", band), fmt.Sprintf("%g Hz", frequency), fmt.Sprintf("%+.0f dB", gain), func() {
+ ui.Slider(c, &gain, -12, 12).Width(140).Label(fmt.Sprintf("%g Hz 频段", frequency)).OnChange(func() {
+ gains[band] = gain
+ save(func(next *app.Settings) { next.EQCustomOn, next.EQCustomGains = true, gains })
+ })
+ })
+ }
+}
+
+func (s *shell) playerLyricsSearch(c *ui.Context) {
+ preview := s.app.LyricPreview()
+ if preview.Open {
+ ui.Text(c, preview.Title).FontSize(14).FontWeight(600)
+ sheetAction(c, "left", "返回搜索结果", "", false, s.app.CloseLyricPreview)
+ switch {
+ case preview.Loading:
+ ui.Spinner(c).Label("加载歌词预览")
+ case preview.Err != "":
+ ui.Text(c, preview.Err).FontSize(13)
+ case preview.Adoptable:
+ sheetAction(c, "check", "采用歌词", "", false, func() {
+ if message := s.app.AdoptLyricPreview(); message != "" {
+ s.notice = message
+ return
+ }
+ s.player.lyrics = true
+ s.closePlayerSheets()
+ })
+ for index, line := range lyrics.Parse(preview.LRC) {
+ ui.Text(c.Key(index), line.Text).FontSize(13).MarginY(4)
+ }
+ default:
+ ui.Text(c, "这一条没有歌词").FontSize(13)
+ }
+ return
+ }
+ sources := s.app.LyricSources()
+ if len(sources) == 0 {
+ ui.Text(c, "暂无可用歌词来源").FontSize(13)
+ return
+ }
+ search := func() { s.app.SearchLyrics(s.player.lyricsSource, strings.TrimSpace(s.player.lyricsQuery)) }
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ ui.TextInputBase(c, &s.player.lyricsQuery).Label("歌词关键词").Placeholder("输入歌名搜索").Grow(1).Height(44).FontSize(13).OnSubmit(search)
+ iconButton(c, "search", "搜索歌词").OnClick(search)
+ })
+ ui.Row(c).FillWidth().Children(func() {
+ for index, source := range sources {
+ playerTool(c, "lyrics", source.Name).Selected(index == s.player.lyricsSource).OnClick(func() {
+ s.player.lyricsSource = index
+ if strings.TrimSpace(s.player.lyricsQuery) != "" {
+ search()
+ }
+ })
+ }
+ })
+ results := s.app.LyricSearch()
+ switch {
+ case results.Loading:
+ ui.Spinner(c).Label("搜索歌词中")
+ case results.Err != "":
+ ui.Text(c, results.Err).FontSize(13)
+ case results.Searched && len(results.Candidates) == 0:
+ ui.Text(c, "没有找到歌词").FontSize(13)
+ default:
+ for _, candidate := range results.Candidates {
+ sheetAction(c, "lyrics", candidate.Title, candidate.Artist, false, func() { s.app.OpenLyricPreview(results.Tab, candidate) })
+ }
+ }
+}
diff --git a/internal/mobileui/player_sheets.go b/internal/mobileui/player_sheets.go
new file mode 100644
index 00000000..97619861
--- /dev/null
+++ b/internal/mobileui/player_sheets.go
@@ -0,0 +1,365 @@
+package mobileui
+
+import (
+ "fmt"
+ "strconv"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/service/bili"
+ "github.com/egoist/mygo"
+ "github.com/egoist/mygo/ui"
+)
+
+var playerSheetTitles = [...]string{
+ sheetQueue: "播放列表", sheetTrack: "歌曲操作", sheetOptions: "更多播放设置",
+ sheetSpeed: "播放速度", sheetQuality: "音质", sheetSleep: "睡眠定时", sheetParts: "分集",
+ sheetChapters: "章节", sheetComments: "评论", sheetReplies: "评论回复", sheetClearQueue: "清空播放列表",
+ sheetCover: "当前封面的操作", sheetVideoQuality: "视频画质", sheetLyricsOptions: "歌词设置",
+ sheetPrefs: "满屏播放器", sheetEQ: "均衡器", sheetLyricsSearch: "找歌词",
+ sheetTrackFolders: "添加到收藏夹", sheetDownload: "下载选项",
+ sheetPlaybackError: "打不开这一首",
+}
+
+func (s *shell) playerSheet(c *ui.Context, state app.State) {
+ kind := s.player.sheet
+ if kind == sheetNone {
+ return
+ }
+ title := playerSheetTitles[kind]
+ palette := phonePalette(c)
+ width, height := c.Size()
+ _, _, bottomInset, _ := c.SafeArea()
+ tall := kind == sheetComments || kind == sheetReplies || kind == sheetQueue || kind == sheetEQ || kind == sheetLyricsSearch || kind == sheetTrackFolders
+ sheetHeight := min(height*.65, 520)
+ if kind == sheetQueue {
+ sheetHeight = min(height*.78, 740)
+ if s.player.queueExpanded {
+ sheetHeight = height * .92
+ }
+ } else if tall {
+ sheetHeight = min(height*.84, 740)
+ } else if kind == sheetClearQueue {
+ sheetHeight = min(height, 180)
+ }
+ ui.Box(c.Key("player-overlay")).Absolute().Top(0).Bottom(0).Left(0).Right(0).Modal().Role(ui.RoleDialog).Label(title).Children(func() {
+ ui.Box(c).Absolute().Top(0).Bottom(0).Left(0).Right(0).Background(ui.RGBA(0, 0, 0, .38)).OnClick(func() { s.back() })
+ ui.Column(c.Key(kind)).Absolute().Bottom(0).Left(max(0, (width-560)/2)).Width(min(560, width)).MaxHeight(sheetHeight).
+ Padding(6, 16, max(12, bottomInset), 16).Radius(24, 24, 0, 0).Clip().Background(palette.surface).Children(func() {
+ header := ui.Column(c).FillWidth().Children(func() {
+ ui.Box(c).FillWidth().Height(9).Center().Children(func() { ui.Box(c).Size(34, 4).Radius(2).Background(palette.line) })
+ ui.Row(c).FillWidth().Height(touchSize()).AlignItems(ui.Center).Children(func() {
+ ui.Text(c, title).Grow(1).Basis(0).FontSize(16).FontWeight(650)
+ iconButton(c, "x", "关闭"+title).OnClick(func() { s.back() })
+ })
+ })
+ if dx, dy, completed := completedSwipe(header); completed && abs32(dy) >= max(44, 1.5*abs32(dx)) {
+ switch {
+ case kind == sheetQueue && dy < 0:
+ s.player.queueExpanded = true
+ case kind == sheetQueue && s.player.queueExpanded:
+ s.player.queueExpanded = false
+ case dy > 0:
+ s.back()
+ }
+ c.AnimationFrame()
+ }
+ bodyHeight := sheetHeight - touchSize() - max(12, bottomInset) - 17
+ queueHasItems := kind == sheetQueue && s.app.Queue().Snapshot().Len() > 0
+ if queueHasItems {
+ bodyHeight -= touchSize()
+ }
+ commentComposer := kind == sheetComments || kind == sheetReplies
+ if commentComposer {
+ bodyHeight -= touchSize() + 6
+ }
+ scroll := ui.Scroll(c).FillWidth().MaxHeight(max(50, bodyHeight))
+ if tall {
+ scroll = scroll.Height(max(50, bodyHeight))
+ }
+ scroll.Children(func() {
+ ui.Column(c).FillWidth().Gap(2).Children(func() { s.playerSheetBody(c, kind, state) })
+ })
+ if queueHasItems {
+ ui.Row(c).FillWidth().Justify(ui.End).Children(func() {
+ playerTool(c, "trash", "清空播放列表").OnClick(func() { s.player.show(sheetClearQueue) })
+ })
+ }
+ if commentComposer {
+ s.commentComposer(c)
+ }
+ })
+ })
+ if kind == sheetTrackFolders && s.player.folders != nil && s.player.folders.editor.open {
+ folders := s.player.folders
+ s.renderFolderEditor(c, &folders.editor, func() { s.loadPlayerFolders(folders) })
+ }
+}
+
+func (s *shell) playerSheetBody(c *ui.Context, kind playerSheetKind, state app.State) {
+ item, _ := s.app.Queue().Current()
+ finish := func(action func()) func() { return func() { action(); s.player.back() } }
+ switch kind {
+ case sheetQueue:
+ s.playerQueue(c)
+ case sheetTrack:
+ s.trackActions(c, s.player.target)
+ case sheetOptions:
+ if s.app.VideoAvailable() {
+ sheetAction(c, "video", "看视频", "", false, func() { s.closePlayerSheets(); s.app.StartVideo() })
+ }
+ for _, choice := range []struct {
+ kind playerSheetKind
+ icon string
+ }{
+ {sheetSleep, "moon"}, {sheetSpeed, "play"}, {sheetEQ, "eq"}, {sheetPrefs, "settings"},
+ {sheetLyricsSearch, "lyrics"}, {sheetCover, "image"},
+ } {
+ sheetAction(c, choice.icon, playerSheetTitles[choice.kind], "", false, func() { s.player.show(choice.kind) })
+ }
+ if item.Source == app.SourceOnline {
+ sheetAction(c, "download", "下载当前歌曲", "", false, func() { s.openPlayerDownload(item) })
+ sheetAction(c, "star", "添加到收藏夹…", "", false, func() { s.openPlayerFolders(item) })
+ }
+ if len(s.app.Parts()) > 1 {
+ sheetAction(c, "parts", "分集", "", false, func() { s.player.show(sheetParts) })
+ }
+ if item.ArtistMid > 0 {
+ sheetAction(c, "user", "打开 UP 主空间", "", false, func() {
+ s.closePlayerSheets()
+ s.player.visible = false
+ s.app.StopVideo()
+ s.push(route{kind: pageCreator, title: item.Artist, id: strconv.FormatInt(item.ArtistMid, 10)})
+ })
+ }
+ case sheetSpeed:
+ for _, speed := range []float64{.5, .75, 1, 1.25, 1.5, 1.75, 2} {
+ sheetAction(c, "", fmt.Sprintf("%g×", speed), "", speed == state.Rate, finish(func() { s.app.SetRate(speed) }))
+ }
+ case sheetQuality:
+ for _, quality := range []bili.AudioQuality{bili.AudioLossless, bili.AudioDolby, bili.AudioHigh, bili.AudioMedium, bili.AudioLow} {
+ sheetAction(c, "", quality.Label(), "", quality == s.app.AudioQuality(), finish(func() { s.app.SetAudioQuality(quality) }))
+ }
+ case sheetSleep:
+ for _, duration := range app.SleepTimerSteps {
+ sheetAction(c, "", fmt.Sprintf("%d 分钟", int(duration/time.Minute)), "", state.SleepFor == duration,
+ finish(func() { s.app.SetSleepTimer(duration) }))
+ }
+ sheetAction(c, "", "放完这一首就停", "", state.SleepAfterTrack, finish(s.app.SleepAfterTrack))
+ sheetAction(c, "", "关闭定时", "", state.SleepAt.IsZero() && !state.SleepAfterTrack, finish(s.app.CancelSleepTimer))
+ case sheetParts:
+ for _, part := range s.app.Parts() {
+ sheetAction(c, "", part.Part, timeLabel(part.Duration), item.Cid == part.Cid, finish(func() { s.report(s.app.PlayPart(part.Cid)) }))
+ }
+ case sheetChapters:
+ for index, chapter := range state.Chapters {
+ active := state.Position >= chapter.At && (index == len(state.Chapters)-1 || state.Position < state.Chapters[index+1].At)
+ sheetAction(c, "", chapter.Title, timeLabel(chapter.At), active, finish(func() { s.app.SeekTo(chapter.At) }))
+ }
+ case sheetComments, sheetReplies:
+ s.playerComments(c, kind == sheetReplies)
+ case sheetClearQueue:
+ ui.Text(c, "确定清空当前播放列表?").FontSize(13)
+ sheetAction(c, "trash", "确认清空", "", false, func() { s.app.ClearQueue(); s.closePlayerSheets() })
+ case sheetCover:
+ if s.app.VideoAvailable() {
+ sheetAction(c, "video", "看视频", "", false, func() { s.closePlayerSheets(); s.app.StartVideo() })
+ }
+ if item.Cover != "" {
+ sheetAction(c, "open", "查看封面原图", "", false, func() { c.OpenURL(item.Cover) })
+ sheetAction(c, "copy", "复制封面链接", "", false, finish(func() { mygo.Clipboard.WriteText(item.Cover); s.notice = "已复制封面链接" }))
+ }
+ if !s.app.VideoAvailable() && item.Cover == "" {
+ ui.Text(c, "这首歌没有可用封面").FontSize(13)
+ }
+ case sheetVideoQuality:
+ qualities, current := s.app.VideoQualities()
+ if len(qualities) == 0 {
+ ui.Text(c, "正在获取可用画质…").FontSize(13)
+ }
+ for _, quality := range qualities {
+ sheetAction(c, "", quality.Label(), "", quality == current, finish(func() { s.player.bitmap = nil; s.app.SetVideoQuality(quality) }))
+ }
+ case sheetLyricsOptions:
+ s.playerLyricsOptions(c)
+ case sheetPrefs:
+ s.playerPreferences(c)
+ case sheetEQ:
+ s.playerEqualizer(c)
+ case sheetLyricsSearch:
+ s.playerLyricsSearch(c)
+ case sheetTrackFolders:
+ s.playerFolderChoices(c)
+ case sheetDownload:
+ s.playerDownloadOptions(c)
+ case sheetPlaybackError:
+ if state.Err == "" {
+ ui.Text(c, "播放已恢复").FontSize(13)
+ return
+ }
+ reason := state.ErrDetail
+ if reason == "" {
+ reason = state.Err
+ }
+ ui.Text(c, reason).FontSize(13).Wrap()
+ if state.CanRetry {
+ sheetAction(c, "refresh", "重试播放", "", false, finish(func() { s.report(s.app.Retry()) }))
+ }
+ if state.BiliURL != "" {
+ sheetAction(c, "open", "在 B 站打开", "", false, func() { c.OpenURL(state.BiliURL) })
+ }
+ if s.app.Queue().Len() > 1 {
+ sheetAction(c, "next", "播放下一首", "", false, finish(s.app.Next))
+ }
+ }
+}
+
+func (s *shell) closePlayerSheets() {
+ s.player.sheet = sheetNone
+ s.player.parents = nil
+}
+
+func sheetAction(c *ui.Context, icon, title, subtitle string, selected bool, action func()) {
+ palette := phonePalette(c)
+ ui.Row(c).FillWidth().MinHeight(touchSize()).PaddingX(5).AlignItems(ui.Center).Gap(9).Role(ui.RoleButton).Label(title).AccessSelected(selected).Children(func() {
+ if icon != "" {
+ glyph(c, icon, 17, palette.muted)
+ }
+ ui.Text(c, title).Grow(1).Basis(0).FontSize(13).MaxLines(2).Ellipsis("…")
+ if subtitle != "" {
+ ui.Text(c, subtitle).FontSize(12).TextColor(palette.muted).MaxLines(1)
+ }
+ if selected {
+ glyph(c, "check", 16, palette.accent)
+ }
+ }).OnClick(action)
+}
+
+func (s *shell) playerQueue(c *ui.Context) {
+ queue := s.app.Queue()
+ view := queue.Snapshot()
+ mode := view.PlayMode()
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ ui.Text(c, fmt.Sprintf("%d 首", view.Len())).FontSize(12).Grow(1).TextColor(phonePalette(c).muted)
+ playerTool(c, playModeGlyph(mode), mode.Desc()).OnClick(s.app.CyclePlayMode)
+ })
+ occurrences := make(map[string]int, view.Len())
+ for index := 0; index < view.Len(); index++ {
+ item, _ := view.At(index)
+ current := view.CurrentIndex() == index
+ label := ""
+ switch {
+ case current:
+ label = "正在播放"
+ case index == view.CurrentIndex()+1:
+ label = "接下来"
+ case index == 0:
+ label = "已播放"
+ }
+ id := item.Identity()
+ occurrences[id]++
+ key := c.Key(id + ":" + strconv.Itoa(occurrences[id]))
+ if label != "" {
+ ui.Text(c.Key("group:"+strconv.Itoa(index)), label).FontSize(12).TextColor(phonePalette(c).muted).Margin(5, 0, 0, 0)
+ }
+ const rowHeight = float32(58)
+ row := ui.Row(key).Height(rowHeight).FillWidth().AlignItems(ui.Center).Gap(4).Children(func() {
+ iconButton(c, "grip", "移动 "+item.Title).Drag(playerQueueDrag{index, view.Revision()}).OnClick(func() {
+ queue.MoveAtBefore(index, index-1)
+ })
+ ui.Row(c).Grow(1).Basis(0).MinHeight(touchSize()).AlignItems(ui.Center).Gap(8).Role(ui.RoleButton).Label(item.Title).AccessSelected(current).Children(func() {
+ cover(c, item.Cover, 48, 8)
+ trackLabel(c, item.Title, item.Artist, 13, current)
+ }).OnClick(func() { s.report(s.app.PlayAt(index)) })
+ if current {
+ ui.Box(c).Size(touchSize(), touchSize()).Center().Children(func() { glyph(c, "eq", 18, phonePalette(c).accent) })
+ } else {
+ iconButton(c, "x", "移除 "+item.Title).OnClick(func() { s.report(s.app.RemoveAt(index)) })
+ }
+ })
+ if view.Len() < 2 {
+ continue
+ }
+ if drag, over := ui.DragOver[playerQueueDrag](row); over && drag.index != index {
+ _, y, _ := row.PointerPosition()
+ accent := phonePalette(c).accent
+ row.DrawOver(func(painter *ui.Painter, bounds ui.Rect) {
+ if y >= rowHeight/2 {
+ bounds.Y += bounds.H - 2
+ }
+ bounds.H = 2
+ painter.Fill(bounds, accent, 1)
+ })
+ }
+ if drag, dropped := ui.Drop[playerQueueDrag](row); dropped && drag.revision == queue.Snapshot().Revision() {
+ before := index
+ if _, y, _ := row.PointerPosition(); y >= rowHeight/2 {
+ before++
+ }
+ queue.MoveAtBefore(drag.index, before)
+ }
+ }
+ if view.Len() == 0 {
+ ui.Text(c, "暂无播放内容").FontSize(13)
+ }
+}
+
+type playerQueueDrag struct {
+ index int
+ revision uint64
+}
+
+func (s *shell) trackActions(c *ui.Context, item app.Item) {
+ ui.Row(c).MinHeight(54).FillWidth().AlignItems(ui.Center).Gap(10).Children(func() {
+ cover(c, item.Cover, 44, 8)
+ trackLabel(c, item.Title, item.Artist, 13, false)
+ })
+ for _, action := range []struct {
+ icon, title string
+ run func() error
+ }{
+ {"play", "立即播放", func() error { return s.app.EnqueueAndPlayNow(item) }},
+ {"next1", "下一首播放", func() error { return s.app.EnqueueNext(item) }},
+ {"queue", "添加到播放列表", func() error { return s.app.Enqueue(item) }},
+ } {
+ sheetAction(c, action.icon, action.title, "", false, func() {
+ if err := action.run(); err != nil {
+ s.report(err)
+ return
+ }
+ s.player.back()
+ })
+ }
+ if item.Source != app.SourceOnline {
+ return
+ }
+ sheetAction(c, "star", "添加到收藏夹…", "", false, func() { s.openPlayerFolders(item) })
+ sheetAction(c, "download", "下载", "", false, func() { s.openPlayerDownload(item) })
+ if item.Bvid != "" {
+ link := "https://www.bilibili.com/video/" + item.Bvid
+ sheetAction(c, "open", "在 B 站打开", "", false, func() { c.OpenURL(link) })
+ sheetAction(c, "link", "分享", "", false, func() {
+ go func() { s.playerResult("")(mygo.Share(mygo.ShareOptions{Text: item.Title, URL: link})) }()
+ })
+ }
+}
+
+func (s *shell) openPlayerDownload(item app.Item) {
+ s.player.downloadItem = item
+ s.player.show(sheetDownload)
+}
+
+func (s *shell) playerDownloadOptions(c *ui.Context) {
+ item := s.player.downloadItem
+ ui.Text(c, item.Title).FontSize(13).MaxLines(2)
+ sheetAction(c, "download", "下载音频", s.app.AudioQuality().Label(), false, func() {
+ s.player.back()
+ s.app.DownloadItem(item, s.playerResult("已添加下载任务"))
+ })
+ if item.Bvid != "" {
+ sheetAction(c, "video", "下载视频", "", false, func() {
+ s.player.back()
+ s.app.DownloadItemVideo(item, s.playerResult("已添加下载任务"))
+ })
+ }
+}
diff --git a/internal/mobileui/player_test.go b/internal/mobileui/player_test.go
new file mode 100644
index 00000000..080516e4
--- /dev/null
+++ b/internal/mobileui/player_test.go
@@ -0,0 +1,92 @@
+package mobileui
+
+import (
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/egoist/mygo/ui"
+)
+
+// TestMobilePlaybackErrorShowsTheFailureReason checks that a file which vanished can be diagnosed from the mini player.
+func TestMobilePlaybackErrorShowsTheFailureReason(t *testing.T) {
+ application := app.New()
+ t.Cleanup(application.Close)
+ if err := application.Open(filepath.Join(t.TempDir(), "missing.mp3")); err == nil {
+ t.Fatal("opening missing fixture succeeded")
+ }
+ state := application.Snapshot()
+ s := newShell(t.Context(), application)
+ s.switchTab(2)
+ tester := ui.NewTester(s.view, 390, 844)
+ if err := tester.Click("查看播放失败原因"); err != nil {
+ t.Fatal(err)
+ }
+ reason := state.ErrDetail
+ if reason == "" {
+ reason = state.Err
+ }
+ if reason == "" || !slices.Contains(tester.Texts(), reason) {
+ t.Fatalf("playback error sheet did not show the failure: %q", tester.Texts())
+ }
+ if _, exists := tester.Find("重试播放"); exists {
+ t.Fatal("missing local file was offered an online retry")
+ }
+}
+
+// TestMobilePlayerKeepsEarlierTracksInQueue verifies that opening a list at the second song retains the first song as a selectable entry.
+func TestMobilePlayerKeepsEarlierTracksInQueue(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.SetThemeMode(app.ThemeModeLight); err != nil {
+ t.Fatal(err)
+ }
+ a.TestOnlyNoAutoLyrics()
+ a.SetVolume(0)
+ tracks := []app.Item{
+ {Source: app.SourceLocal, Title: "第一首", Path: filepath.Join("..", "service", "audio", "testdata", "tone.mp3")},
+ {Source: app.SourceLocal, Title: "第二首", Path: filepath.Join("..", "service", "audio", "testdata", "gapless.mp3")},
+ }
+ if err := a.PlayFromIndex(tracks, 1); err != nil {
+ t.Fatal(err)
+ }
+ a.Pause()
+ s := newShell(t.Context(), a)
+ s.switchTab(2)
+ tester := ui.NewTester(s.view, 390, 844)
+ if err := tester.Click("打开满屏播放器:第二首"); err != nil {
+ t.Fatal(err)
+ }
+ mobileLibraryShot(t, tester, "mobile-light-player.png")
+ artwork, ok := tester.Find("当前封面的操作")
+ if !ok {
+ t.Fatal("the artwork cannot be reached")
+ }
+ startX, startY := artwork.X+artwork.W*.75, artwork.Y+artwork.H/2
+ tester.TouchDown(1, startX, startY)
+ tester.TouchMove(1, startX-100, startY)
+ tester.TouchUp(1, startX-100, startY)
+ tester.Frame()
+ if _, ok := tester.Find("歌词设置"); !ok {
+ t.Fatal("swiping left on the artwork did not open lyrics")
+ }
+ for _, label := range []string{"封面", "播放列表", "第一首"} {
+ if err := tester.Click(label); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if current := a.Queue().Snapshot().CurrentIndex(); current != 0 {
+ t.Fatalf("playing queue index %d after selecting the first entry", current)
+ }
+ mobileLibraryShot(t, tester, "mobile-light-queue.png")
+ if err := tester.Click("关闭播放列表"); err != nil {
+ t.Fatal(err)
+ }
+ if _, found := tester.Find("收起满屏播放器"); !found {
+ t.Fatal("closing the queue did not return to the full player")
+ }
+}
diff --git a/internal/mobileui/search.go b/internal/mobileui/search.go
new file mode 100644
index 00000000..e1a79bdb
--- /dev/null
+++ b/internal/mobileui/search.go
@@ -0,0 +1,776 @@
+package mobileui
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/tok"
+ "github.com/egoist/mygo"
+ "github.com/egoist/mygo/ui"
+ "github.com/egoist/mygo/ui/mobile"
+)
+
+type mobileSearchTab uint8
+
+const (
+ mobileSearchSongs mobileSearchTab = iota
+ mobileSearchMixes
+ mobileSearchCreators
+ mobileSearchVideos
+ mobileSearchTabCount
+)
+
+var mobileSearchNames = [mobileSearchTabCount]string{"歌曲", "歌单", "UP 主", "视频"}
+
+type mobileSearchResult struct {
+ rows []app.SearchItem
+ mixes []browseCollection
+ started bool
+ loading bool
+ err error
+ page int
+ more bool
+ cancel context.CancelFunc
+}
+
+type mobileSearchState struct {
+ draft, query string
+ inputFocus bool
+ readyAt time.Time
+ tab mobileSearchTab
+ sort [mobileSearchTabCount]app.SearchSort
+ results [mobileSearchTabCount]mobileSearchResult
+ sortOpen bool
+ history mobileSearchHistory
+ hot browseMusic
+ mixes browseMixes
+ preview mobileSearchPreview
+}
+
+type mobileSearchPreview struct {
+ keyword string
+ songs app.SearchPage
+ users app.SearchPage
+ songOK bool
+ userOK bool
+ cancel context.CancelFunc
+}
+
+type mobileSearchHistory struct {
+ words []string
+ path string
+ loaded bool
+ started bool
+ dirty bool
+ saving bool
+}
+
+func (s *shell) search(c *ui.Context, page *route) {
+ state, ok := page.data.(*mobileSearchState)
+ if !ok {
+ state = &mobileSearchState{}
+ page.data = state
+ }
+ if page.focus {
+ state.inputFocus = true
+ page.focus = false
+ }
+ if page.query != "" {
+ s.submitMobileSearch(state, page.query)
+ page.query = ""
+ }
+ if !state.history.started {
+ s.loadMobileSearchHistory(&state.history)
+ }
+ palette := tok.Of(c.Theme())
+ ui.Column(c).FillWidth().Gap(18).Children(func() {
+ ui.Row(c).FillWidth().MinHeight(50).Radius(28).AlignItems(ui.Center).Gap(10).Padding(0, 6, 0, 14).
+ Background(palette.Surface2).Children(func() {
+ glyph(c, "search", 18, palette.Text2)
+ field := ui.TextInputBase(c.Key("search:query"), &state.draft).Label("搜索歌曲、歌手、歌单或 UP 主").
+ Placeholder("搜歌、歌手、歌单或 UP 主").PlaceholderColor(palette.Text2).FontSize(13).
+ Grow(1).MinWidth(0).Height(50).Search().Keyboard(ui.KeyboardSearch).ReturnKey(ui.ReturnSearch).
+ FocusBind(&state.inputFocus, true)
+ if field.Changed() {
+ keyword := strings.TrimSpace(state.draft)
+ state.readyAt = c.Now().Add(375 * time.Millisecond)
+ if state.preview.keyword != keyword {
+ cancelSearchPreview(state)
+ }
+ if keyword == "" {
+ s.resetMobileSearchResults(state)
+ state.query = ""
+ s.app.SearchSuggest("")
+ }
+ }
+ if state.draft != "" && iconButton(c, "x", "清除搜索词").Clicked() {
+ s.clearMobileSearch(state)
+ }
+ hit := touchSize()
+ submit := ui.ButtonBase(c).Label("搜索").Size(hit, hit).Center().Children(func() {
+ glyph(c, "right", 16, palette.AccentText)
+ })
+ if field.Submitted() || submit.Clicked() {
+ s.submitMobileSearch(state, state.draft)
+ }
+ })
+ draft := strings.TrimSpace(state.draft)
+ switch {
+ case draft != "" && draft != state.query:
+ s.mobileSearchSuggestions(c, state, draft)
+ case state.query == "" || draft == "":
+ s.mobileSearchLanding(c, state)
+ default:
+ s.mobileSearchResults(c, state)
+ }
+ })
+ if state.sortOpen {
+ mobile.ActionSheet(c, &state.sortOpen, mobile.ActionSheetOptions{Title: "排序", Cancel: "取消"}, s.mobileSearchSortActions(state)...)
+ }
+}
+
+func (s *shell) dismissSearchKeyboard() bool {
+ page := s.current()
+ state, ok := page.data.(*mobileSearchState)
+ if page.kind != pageSearch || !ok {
+ return false
+ }
+ if state.sortOpen {
+ state.sortOpen = false
+ return true
+ }
+ if state.inputFocus || page.focus {
+ state.inputFocus, page.focus = false, false
+ return true
+ }
+ return false
+}
+
+func (s *shell) submitMobileSearch(state *mobileSearchState, keyword string) {
+ keyword = strings.TrimSpace(keyword)
+ if keyword == "" {
+ s.clearMobileSearch(state)
+ return
+ }
+ state.draft, state.inputFocus = keyword, false
+ if state.preview.keyword != keyword {
+ cancelSearchPreview(state)
+ } else if state.preview.cancel != nil {
+ state.preview.cancel()
+ state.preview.cancel = nil
+ }
+ if state.query == keyword {
+ return
+ }
+ s.resetMobileSearchResults(state)
+ state.query, state.tab = keyword, mobileSearchSongs
+ if s.app.SettingsSnapshot().ShowSearchHistory {
+ state.history.words = slices.DeleteFunc(state.history.words, func(word string) bool { return word == keyword })
+ state.history.words = append([]string{keyword}, state.history.words...)
+ state.history.words = state.history.words[:min(20, len(state.history.words))]
+ state.history.dirty = true
+ s.saveMobileSearchHistory(&state.history)
+ }
+}
+
+func (s *shell) clearMobileSearch(state *mobileSearchState) {
+ s.resetMobileSearchResults(state)
+ cancelSearchPreview(state)
+ state.draft, state.query, state.inputFocus = "", "", false
+ s.app.SearchSuggest("")
+}
+
+func (s *shell) resetMobileSearchResults(state *mobileSearchState) {
+ for _, result := range state.results {
+ if result.cancel != nil {
+ result.cancel()
+ }
+ }
+ state.results = [mobileSearchTabCount]mobileSearchResult{}
+ state.sort = [mobileSearchTabCount]app.SearchSort{}
+}
+
+func (s *shell) loadMobileSearchHistory(history *mobileSearchHistory) {
+ history.started = true
+ if s.win == nil {
+ history.loaded = true
+ return
+ }
+ go func() {
+ var path string
+ var words []string
+ if dir, err := mygo.App.Path(mygo.PathUserData); err == nil && dir != "" {
+ path = filepath.Join(dir, "mobile-search-history.json")
+ if data, err := os.ReadFile(path); err == nil {
+ _ = json.Unmarshal(data, &words)
+ }
+ }
+ s.update(func() {
+ history.path, history.loaded = path, true
+ for _, word := range words {
+ if len(history.words) == 20 {
+ break
+ }
+ if word != "" && !slices.Contains(history.words, word) {
+ history.words = append(history.words, word)
+ }
+ }
+ s.saveMobileSearchHistory(history)
+ })
+ }()
+}
+
+func (s *shell) saveMobileSearchHistory(history *mobileSearchHistory) {
+ if !history.loaded || history.path == "" || history.saving || !history.dirty {
+ return
+ }
+ history.saving, history.dirty = true, false
+ path, words := history.path, slices.Clone(history.words)
+ go func() {
+ writeMobileSearchHistory(path, words)
+ s.update(func() {
+ history.saving = false
+ s.saveMobileSearchHistory(history)
+ })
+ }()
+}
+
+func writeMobileSearchHistory(path string, words []string) {
+ file, err := os.CreateTemp(filepath.Dir(path), ".mobile-search-*")
+ if err != nil {
+ return
+ }
+ defer os.Remove(file.Name())
+ err = json.NewEncoder(file).Encode(words)
+ closeErr := file.Close()
+ if err == nil && closeErr == nil {
+ _ = os.Rename(file.Name(), path)
+ }
+}
+
+func (s *shell) mobileSearchLanding(c *ui.Context, state *mobileSearchState) {
+ if !state.hot.started {
+ s.loadSearchHot(&state.hot)
+ }
+ if !state.mixes.started {
+ s.loadDiscoverMixes(&state.mixes)
+ }
+ if state.history.loaded && s.app.SettingsSnapshot().ShowSearchHistory && len(state.history.words) > 0 {
+ s.mobileSearchHistoryView(c, state)
+ }
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ sectionHeading(c, "热搜", "")
+ if len(state.hot.rows) == 0 {
+ if state.hot.loading {
+ s.searchHotGrid(c, state, nil)
+ return
+ }
+ browseStatus(c, state.hot.loading, state.hot.err, "暂无热搜", func() { s.loadSearchHot(&state.hot) })
+ return
+ }
+ s.searchHotGrid(c, state, state.hot.rows)
+ })
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ sectionHeading(c, "热门歌手", "")
+ s.searchSingers(c, state, state.hot.rows)
+ })
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ sectionHeading(c, "找张歌单", "")
+ s.renderMixes(c, &state.mixes, 3, func() { s.loadDiscoverMixes(&state.mixes) })
+ })
+}
+
+func (s *shell) mobileSearchHistoryView(c *ui.Context, state *mobileSearchState) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ ui.Text(c, "搜索历史").FontSize(16).Bold().Grow(1)
+ if iconButton(c, "trash", "清空搜索历史").Clicked() {
+ state.history.words, state.history.dirty = nil, true
+ s.saveMobileSearchHistory(&state.history)
+ }
+ })
+ ui.ScrollHorizontal(c.Key("search:history")).FillWidth().Gap(8).Children(func() {
+ for _, word := range state.history.words {
+ ui.Row(c).Key("history:" + word).MinHeight(touchSize()).Shrink(0).Radius(24).Background(palette.Surface2).Children(func() {
+ if ui.ButtonBase(c).Label(word).Padding(0, 0, 0, 10).Children(func() {
+ ui.Text(c, word).FontSize(13).TextColor(palette.Text2).SingleLine().Ellipsis("…").MaxWidth(150)
+ }).Clicked() {
+ s.submitMobileSearch(state, word)
+ }
+ if iconButton(c, "x", "删除搜索记录 "+word).Clicked() {
+ state.history.words = slices.DeleteFunc(slices.Clone(state.history.words), func(item string) bool { return item == word })
+ state.history.dirty = true
+ s.saveMobileSearchHistory(&state.history)
+ }
+ })
+ }
+ })
+ })
+}
+
+func (s *shell) loadSearchHot(hot *browseMusic) {
+ if hot.loading {
+ return
+ }
+ hot.started, hot.loading = true, true
+ go func() {
+ ctx, cancel := context.WithTimeout(s.ctx, 15*time.Second)
+ defer cancel()
+ rows, _, err := s.app.RecommendOf().Feed(ctx, app.HomeTabHot, 1)
+ s.update(func() { hot.rows, hot.err, hot.loading = rows, err, false })
+ }()
+}
+
+func (s *shell) searchHotGrid(c *ui.Context, state *mobileSearchState, rows []app.RecommendItem) {
+ palette := tok.Of(c.Theme())
+ var terms []string
+ for _, row := range rows {
+ if row.Title != "" && !slices.Contains(terms, row.Title) {
+ terms = append(terms, row.Title)
+ if len(terms) == 6 {
+ break
+ }
+ }
+ }
+ if len(terms) == 0 {
+ terms = make([]string, 6)
+ }
+ ui.Row(c).FillWidth().Gap(10).Padding(8, 12).Radius(16).Background(palette.Bg).Children(func() {
+ for start := 0; start < len(terms); start += 3 {
+ ui.Column(c).Grow(1).Width(0).MinWidth(0).Children(func() {
+ for index, term := range terms[start:min(start+3, len(terms))] {
+ if term == "" {
+ ui.Row(c).FillWidth().MinHeight(touchSize()).AlignItems(ui.Center).Children(func() {
+ ui.Box(c).Size(76, 13).Radius(5).Background(palette.Surface2)
+ })
+ continue
+ }
+ rank := start + index + 1
+ foreground := palette.Text
+ if rank <= 3 {
+ foreground = palette.AccentText
+ }
+ if ui.ButtonBase(c).Key("hot:" + term).Label(term).FillWidth().MinHeight(touchSize()).Children(func() {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(8).Children(func() {
+ ui.Text(c, strconv.Itoa(rank)).FontSize(13).Bold().TextColor(foreground)
+ ui.Text(c, term).Grow(1).MinWidth(0).FontSize(13).Bold().SingleLine().Ellipsis("…")
+ })
+ }).Clicked() {
+ s.submitMobileSearch(state, term)
+ }
+ }
+ })
+ }
+ })
+}
+
+func (s *shell) searchSingers(c *ui.Context, state *mobileSearchState, rows []app.RecommendItem) {
+ palette := tok.Of(c.Theme())
+ seen := make(map[string]bool, 4)
+ ui.Row(c).FillWidth().Gap(6).Children(func() {
+ for _, row := range rows {
+ name := strings.TrimSpace(row.Owner)
+ if name == "" || seen[name] {
+ continue
+ }
+ seen[name] = true
+ if ui.ButtonBase(c).Key("singer:" + name).Label("搜索歌手 " + name).Grow(1).Width(0).MinWidth(0).Children(func() {
+ ui.Column(c).FillWidth().AlignItems(ui.Center).Gap(7).Children(func() {
+ cover(c, row.Cover, 64, 32)
+ ui.Text(c, name).FontSize(13).Bold().SingleLine().Ellipsis("…")
+ })
+ }).Clicked() {
+ s.submitMobileSearch(state, name)
+ }
+ if len(seen) == 4 {
+ break
+ }
+ }
+ if len(seen) == 0 {
+ if state.hot.loading {
+ for range 4 {
+ ui.Column(c).Grow(1).Width(0).Gap(7).AlignItems(ui.Center).Children(func() {
+ ui.Box(c).Size(64, 64).Radius(32).Background(palette.Surface2)
+ ui.Box(c).Size(38, 13).Radius(4).Background(palette.Surface2)
+ })
+ }
+ } else {
+ ui.Text(c, "暂无热门歌手").FontSize(13).TextColor(palette.Text2)
+ }
+ }
+ })
+}
+
+func (s *shell) mobileSearchSuggestions(c *ui.Context, state *mobileSearchState, keyword string) {
+ if delay := state.readyAt.Sub(c.Now()); delay > 0 {
+ c.After(delay)
+ } else {
+ s.app.SearchSuggest(keyword)
+ if state.preview.keyword != keyword {
+ s.loadSearchPreview(state, keyword)
+ }
+ }
+ if browseAction(c, "search", "搜索「"+keyword+"」", false) {
+ s.submitMobileSearch(state, keyword)
+ }
+ suggestions := s.app.SuggestState()
+ if suggestions.Query != keyword {
+ return
+ }
+ if suggestions.Failed {
+ ui.Text(c, "暂时无法获取联想词").FontSize(13).TextColor(tok.Of(c.Theme()).Text2)
+ }
+ for _, word := range suggestions.Items {
+ if word != keyword && browseAction(c, "search", word, false) {
+ s.submitMobileSearch(state, word)
+ }
+ }
+ if tracks := searchTracks(state.preview.songs.Items); len(tracks) > 0 {
+ sectionHeading(c, "歌曲", "")
+ s.trackList(c, tracks[:min(6, len(tracks))])
+ }
+ if users := state.preview.users.Items; len(users) > 0 {
+ sectionHeading(c, "UP 主", "")
+ s.searchCreatorRows(c, users[:min(2, len(users))])
+ }
+}
+
+func cancelSearchPreview(state *mobileSearchState) {
+ if state.preview.cancel != nil {
+ state.preview.cancel()
+ }
+ state.preview = mobileSearchPreview{}
+}
+
+func (s *shell) loadSearchPreview(state *mobileSearchState, keyword string) {
+ cancelSearchPreview(state)
+ ctx, cancel := context.WithTimeout(s.ctx, 12*time.Second)
+ state.preview = mobileSearchPreview{keyword: keyword, cancel: cancel}
+ go func() {
+ search := s.app.SearchOf()
+ songs, songErr := search.Page(ctx, app.SearchQuery{Tab: app.SearchTabSong, Keyword: keyword, Page: 1})
+ users, userErr := search.Page(ctx, app.SearchQuery{Tab: app.SearchTabUser, Keyword: keyword, Page: 1})
+ songs.Items = appendSearchRows(nil, songs.Items)
+ users.Items = appendSearchRows(nil, users.Items)
+ s.update(func() {
+ defer cancel()
+ if ctx.Err() != nil {
+ return
+ }
+ state.preview = mobileSearchPreview{keyword: keyword, songs: songs, users: users, songOK: songErr == nil, userOK: userErr == nil}
+ })
+ }()
+}
+
+func (s *shell) mobileSearchResults(c *ui.Context, state *mobileSearchState) {
+ palette := tok.Of(c.Theme())
+ ui.Row(c).FillWidth().Children(func() {
+ for index, name := range mobileSearchNames {
+ tab := mobileSearchTab(index)
+ color, line := palette.Text2, ui.Color{}
+ if tab == state.tab {
+ color, line = palette.AccentText, palette.Accent
+ }
+ if ui.ButtonBase(c).Key("search:result-tab:" + name).Label(name).Selected(tab == state.tab).Grow(1).Width(0).MinHeight(touchSize()).Children(func() {
+ ui.Column(c).FillWidth().Children(func() {
+ ui.Box(c).FillWidth().MinHeight(touchSize() - 2).Center().Children(func() { ui.Text(c, name).FontSize(13).Bold().TextColor(color) })
+ ui.Box(c).FillWidth().Height(2).Background(line)
+ })
+ }).Clicked() {
+ state.tab = tab
+ }
+ }
+ })
+ result := &state.results[state.tab]
+ load := func() { s.loadMobileSearchResult(state, state.tab) }
+ if !result.started {
+ load()
+ }
+ if len(result.rows) == 0 && len(result.mixes) == 0 {
+ if result.loading || result.err != nil {
+ var searchErr *app.SearchError
+ if errors.As(result.err, &searchErr) && !searchErr.Retryable {
+ ui.Text(c, searchErr.Message).FontSize(13).TextColor(palette.Text2)
+ return
+ }
+ browseStatus(c, result.loading, result.err, "", load)
+ return
+ }
+ if state.tab == mobileSearchMixes {
+ ui.Text(c, "未在相关 UP 主的公开合集中找到匹配歌单").FontSize(13).TextColor(palette.Text2)
+ } else {
+ ui.Text(c, "没有找到相关"+mobileSearchNames[state.tab]).FontSize(13).TextColor(palette.Text2)
+ }
+ if browseAction(c, "x", "清空搜索", false) {
+ s.clearMobileSearch(state)
+ }
+ return
+ }
+ tracks := searchTracks(result.rows)
+ if state.tab != mobileSearchMixes {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ if len(tracks) > 0 && browseAction(c, "play", "播放全部", true) {
+ s.play(tracks, 0)
+ }
+ ui.Spacer(c).Grow(1)
+ if iconButton(c, "sort", "排序").Clicked() {
+ state.sortOpen = true
+ }
+ })
+ }
+ switch state.tab {
+ case mobileSearchMixes:
+ s.collectionGrid(c, result.mixes)
+ case mobileSearchCreators:
+ s.searchCreatorRows(c, result.rows)
+ case mobileSearchVideos:
+ s.searchVideoRows(c, result.rows, tracks)
+ default:
+ s.trackList(c, tracks)
+ }
+ if result.more {
+ browseMore(c, result.loading, result.err, load)
+ }
+}
+
+func (s *shell) loadMobileSearchResult(state *mobileSearchState, tab mobileSearchTab) {
+ result := &state.results[tab]
+ if result.loading || state.query == "" {
+ return
+ }
+ page, keyword, sort := result.page+1, state.query, state.sort[tab]
+ if page == 1 && sort == app.SearchSortDefault && state.preview.keyword == keyword {
+ preview, available := state.preview.songs, tab == mobileSearchSongs && state.preview.songOK
+ if tab == mobileSearchCreators {
+ preview, available = state.preview.users, state.preview.userOK
+ }
+ if available {
+ result.started, result.page, result.more = true, page, preview.HasMore
+ result.rows = appendSearchRows(nil, preview.Items)
+ return
+ }
+ }
+ ctx, cancel := context.WithTimeout(s.ctx, 20*time.Second)
+ result.cancel = cancel
+ result.started, result.loading, result.err = true, true, nil
+ sources := state.preview
+ if sources.keyword != keyword {
+ sources = mobileSearchPreview{}
+ }
+ if result := state.results[mobileSearchSongs]; result.page > 0 && !sources.songOK {
+ sources.songs.Items, sources.songOK = result.rows, true
+ }
+ if result := state.results[mobileSearchCreators]; result.page > 0 && !sources.userOK {
+ sources.users.Items, sources.userOK = result.rows, true
+ }
+ go func() {
+ var found app.SearchPage
+ var mixes []browseCollection
+ var err error
+ search := s.app.SearchOf()
+ switch tab {
+ case mobileSearchMixes:
+ mixes, err = s.findSearchCollections(ctx, search, keyword, sources)
+ default:
+ serverTab := app.SearchTabSong
+ if tab == mobileSearchCreators {
+ serverTab = app.SearchTabUser
+ } else if tab == mobileSearchVideos {
+ serverTab = app.SearchTabVideo
+ }
+ found, err = search.Page(ctx, app.SearchQuery{Tab: serverTab, Keyword: keyword, Sort: sort, Page: page})
+ }
+ s.update(func() {
+ defer cancel()
+ if errors.Is(ctx.Err(), context.Canceled) {
+ return
+ }
+ result.cancel = nil
+ result.loading, result.err = false, err
+ if err == nil {
+ result.rows = appendSearchRows(result.rows, found.Items)
+ result.mixes = mixes
+ result.page, result.more = page, found.HasMore
+ }
+ })
+ }()
+}
+
+func appendSearchRows(existing, incoming []app.SearchItem) []app.SearchItem {
+ seen := make(map[string]bool, len(existing)+len(incoming))
+ for _, row := range existing {
+ seen[row.ID] = true
+ }
+ for _, row := range incoming {
+ if row.ID != "" && !seen[row.ID] {
+ seen[row.ID] = true
+ existing = append(existing, row)
+ }
+ }
+ return existing
+}
+
+func (s *shell) findSearchCollections(ctx context.Context, search *app.Search, keyword string, sources mobileSearchPreview) ([]browseCollection, error) {
+ creators, songs := sources.users, sources.songs
+ var creatorErr, songErr error
+ if !sources.userOK {
+ creators, creatorErr = search.Page(ctx, app.SearchQuery{Tab: app.SearchTabUser, Keyword: keyword, Page: 1})
+ }
+ if !sources.songOK {
+ songs, songErr = search.Page(ctx, app.SearchQuery{Tab: app.SearchTabSong, Keyword: keyword, Page: 1})
+ }
+ if creatorErr != nil && songErr != nil {
+ return nil, songErr
+ }
+ owners := make([]browseOwner, 0, len(songs.Items)+len(creators.Items))
+ for index, row := range creators.Items {
+ mid, _ := strconv.ParseInt(row.Item.Bvid, 10, 64)
+ owners = append(owners, browseOwner{mid: mid, name: row.Title})
+ if index == 1 {
+ break
+ }
+ }
+ for _, row := range songs.Items {
+ owners = append(owners, browseOwner{mid: row.OwnerMid, name: row.Owner})
+ }
+ return s.publicMusicCollections(ctx, owners, keyword)
+}
+
+func searchTracks(rows []app.SearchItem) []app.Item {
+ tracks := make([]app.Item, 0, len(rows))
+ for _, row := range rows {
+ if row.Item.Type != app.ItemTypeUser && row.Item.Bvid != "" {
+ tracks = append(tracks, row.Item)
+ }
+ }
+ return tracks
+}
+
+func (s *shell) searchCreatorRows(c *ui.Context, rows []app.SearchItem) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ for start := 0; start < len(rows); start += 2 {
+ ui.Row(c).FillWidth().Gap(8).Children(func() {
+ for _, row := range rows[start:min(start+2, len(rows))] {
+ if ui.ButtonBase(c).Key("creator:" + row.ID).Label("打开 " + row.Title + " 的空间").Grow(1).Width(0).MinWidth(0).
+ MinHeight(112).Padding(10).Radius(12).Background(palette.Bg).Children(func() {
+ ui.Column(c).FillWidth().Gap(4).Children(func() {
+ ui.Row(c).FillWidth().AlignItems(ui.Center).Children(func() {
+ cover(c, row.Cover, 42, 21)
+ ui.Spacer(c).Grow(1)
+ if row.Level > 0 {
+ ui.Text(c, fmt.Sprintf("LV%d", row.Level)).FontSize(11).TextColor(palette.Text2)
+ }
+ })
+ ui.Text(c, row.Title).FontSize(14).Bold().SingleLine().Ellipsis("…")
+ ui.Text(c, fmt.Sprintf("%d 粉丝", row.Fans)).FontSize(12).TextColor(palette.Text2)
+ if row.Owner != "" {
+ ui.Text(c, row.Owner).FontSize(12).TextColor(palette.Text2).SingleLine().Ellipsis("…")
+ }
+ })
+ }).Clicked() {
+ s.dismissSearchKeyboard()
+ s.push(route{kind: pageCreator, id: row.Item.Bvid, title: row.Title})
+ }
+ }
+ if len(rows)-start == 1 {
+ ui.Spacer(c).Grow(1).Width(0)
+ }
+ })
+ }
+ })
+}
+
+func (s *shell) searchVideoRows(c *ui.Context, rows []app.SearchItem, tracks []app.Item) {
+ palette := tok.Of(c.Theme())
+ mode := s.app.SettingsSnapshot().DisplayMode
+ width, _ := c.Size()
+ mediaWidth, mediaHeight := float32(48), float32(48)
+ if mode == app.DisplayModeCard {
+ mediaWidth = max(1, width-32-touchSize())
+ mediaHeight = mediaWidth * 9 / 16
+ } else if mode == app.DisplayModeCompact {
+ mediaWidth, mediaHeight = 32, 32
+ }
+ ui.Column(c).FillWidth().Gap(8).Children(func() {
+ for index, row := range rows {
+ ui.Row(c).Key("video:" + row.ID).FillWidth().AlignItems(ui.End).Children(func() {
+ button := ui.ButtonBase(c).Label("播放 " + row.Title).Grow(1).Width(0).MinHeight(touchSize()).Radius(8).Children(func() {
+ var layout ui.Element
+ if mode == app.DisplayModeCard {
+ layout = ui.Column(c).FillWidth().Gap(6)
+ } else {
+ layout = ui.Row(c).FillWidth().AlignItems(ui.Center).Gap(10)
+ }
+ layout.Children(func() {
+ media := ui.Box(c).Size(mediaWidth, mediaHeight).Shrink(0).Radius(8).Clip().Center()
+ if mode == app.DisplayModeCard {
+ media = media.FillWidth()
+ }
+ media.Children(func() { cover(c, row.Cover, mediaWidth, 0) })
+ ui.Column(c).Grow(1).MinWidth(0).Gap(3).Children(func() {
+ ui.Text(c, row.Title).FontSize(13).Bold().SingleLine().Ellipsis("…")
+ ui.Text(c, fmt.Sprintf("%s · %d 播放", row.Owner, row.View)).FontSize(12).TextColor(palette.Text2).SingleLine().Ellipsis("…")
+ })
+ })
+ })
+ if button.Clicked() {
+ s.playSearchVideo(tracks, index)
+ }
+ more := iconButton(c, "more", "更多操作:"+row.Title)
+ if button.LongPressed() || more.Clicked() {
+ s.player.target = row.Item
+ s.player.show(sheetTrack)
+ }
+ })
+ }
+ })
+}
+
+func (s *shell) playSearchVideo(tracks []app.Item, index int) {
+ if err := s.app.PlayFromIndex(tracks, index); err != nil {
+ s.report(err)
+ return
+ }
+ if s.app.VideoAvailable() {
+ s.player.visible = true
+ s.app.StartVideo()
+ }
+}
+
+func (s *shell) mobileSearchSortActions(state *mobileSearchState) []mobile.Action {
+ labels := []string{"综合排序", "播放最多", "最新发布", "弹幕最多", "收藏最多"}
+ if state.tab == mobileSearchCreators {
+ labels = []string{"默认排序", "粉丝最多", "粉丝最少", "等级最高", "等级最低"}
+ }
+ tab := state.tab
+ actions := make([]mobile.Action, 0, len(labels))
+ for index, label := range labels {
+ sort := app.SearchSort(index)
+ if sort == state.sort[tab] {
+ label += "(当前)"
+ }
+ actions = append(actions, mobile.Action{Label: label, OnTap: func() {
+ if sort == state.sort[tab] {
+ return
+ }
+ result := &state.results[tab]
+ if result.cancel != nil {
+ result.cancel()
+ }
+ *result = mobileSearchResult{}
+ state.sort[tab] = sort
+ }})
+ }
+ return actions
+}
diff --git a/internal/mobileui/search_test.go b/internal/mobileui/search_test.go
new file mode 100644
index 00000000..50d95394
--- /dev/null
+++ b/internal/mobileui/search_test.go
@@ -0,0 +1,65 @@
+package mobileui
+
+import (
+ "testing"
+ "time"
+
+ "github.com/egoist/mygo/ui"
+)
+
+// TestMobileSearchSubmitsAndShowsDistinctResultTypes checks native search focus, suggestions, and the four real result paths.
+func TestMobileSearchSubmitsAndShowsDistinctResultTypes(t *testing.T) {
+ s, wait := mobileBrowseFixture(t)
+ s.openSearch()
+ tester := ui.NewTester(func(c *ui.Context) {
+ ui.Scroll(c).Fill().Children(func() {
+ ui.Column(c).FillWidth().Padding(8, 16).Children(func() {
+ page := s.current()
+ if page.kind == pageSearch {
+ s.search(c, page)
+ }
+ })
+ })
+ }, 390, 740)
+ const input = "搜索歌曲、歌手、歌单或 UP 主"
+ if !tester.Focused(input) {
+ t.Fatal("opening search did not focus its input")
+ }
+ tester.Type("音乐")
+ tester.Advance(time.Second)
+ wait(tester, "音乐联想")
+ tester.Key(0, ui.KeyEnter)
+ wait(tester, "歌曲结果")
+ mobileLibraryShot(t, tester, "search-fixture.png")
+ if tester.Focused(input) {
+ t.Fatal("submission did not dismiss input focus")
+ }
+ if err := tester.Click("排序"); err != nil {
+ t.Fatal(err)
+ }
+ for until := tester.Now().Add(time.Second); tester.FramePending() && tester.Now().Before(until); {
+ tester.Advance(10 * time.Millisecond)
+ }
+ if err := tester.Click("最新发布"); err != nil {
+ t.Fatal(err)
+ }
+ wait(tester, "最新歌曲结果")
+ for _, tab := range []struct{ label, want string }{
+ {"歌单", "公开音乐合集"}, {"UP 主", "搜索到的 UP 主"}, {"视频", "视频结果"},
+ } {
+ if err := tester.Click(tab.label); err != nil {
+ t.Fatal(err)
+ }
+ wait(tester, tab.want)
+ }
+ if err := tester.Click("清除搜索词"); err != nil {
+ t.Fatal(err)
+ }
+ wait(tester, "搜索历史")
+ if err := tester.Click("删除搜索记录 音乐"); err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := tester.Find("删除搜索记录 音乐"); ok {
+ t.Fatal("removed search term still appears in history")
+ }
+}
diff --git a/internal/mobileui/settings.go b/internal/mobileui/settings.go
new file mode 100644
index 00000000..53003e86
--- /dev/null
+++ b/internal/mobileui/settings.go
@@ -0,0 +1,688 @@
+package mobileui
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/licensing"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/scale"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/tok"
+ "github.com/ShellMonster/PudMusic/internal/ui/widgets/typo"
+ "github.com/egoist/mygo"
+ "github.com/egoist/mygo/ui"
+)
+
+var settingsLinks = []struct{ id, title, icon string }{
+ {"general", "播放与下载", "settings"},
+ {"appearance", "外观", "palette"},
+ {"menu", "我的页面", "menu"},
+ {"proxy", "网络代理", "globe"},
+ {"about", "关于布丁音乐", "info"},
+}
+
+var mobileMenuEntries = []struct{ key, title string }{
+ {"/follow", "我的关注"},
+ {"/later", "稍后再看"},
+ {"/history", "历史记录"},
+ {"/local-music", "本地音乐"},
+ {"/download-list", "下载记录"},
+ {"/stats", "听歌统计"},
+}
+
+type settingsPageData struct {
+ message string
+ failed bool
+ proxy proxyDraft
+}
+
+type proxyDraft struct {
+ custom, testing bool
+ kind app.ProxyType
+ host, port, user string
+ secret string
+ hostError, portError string
+ result string
+ failed bool
+}
+
+func (s *shell) settings(c *ui.Context, page *route) {
+ if page.kind == pageSettings {
+ s.settingsIndex(c, "")
+ return
+ }
+ if page.title != "" {
+ settingsPageHeading(c, page.title)
+ }
+ if page.id == "license-text" {
+ text, _ := page.data.(string)
+ for _, line := range strings.Split(strings.TrimSpace(text), "\n\n") {
+ settingsText(c, line, 13, tok.Of(c.Theme()).Text2)
+ }
+ return
+ }
+ state, _ := page.data.(*settingsPageData)
+ if state == nil {
+ state = &settingsPageData{}
+ page.data = state
+ }
+ st := s.app.SettingsSnapshot()
+ readOnly := s.app.SettingsReadOnly()
+ if err := s.app.TakeSettingsError(); err != nil {
+ state.message, state.failed = "无法读取或保存设置,请检查应用存储。", true
+ }
+ if readOnly {
+ settingsText(c, "此设置文件由较新的版本创建,当前只能查看。", 13, tok.Of(c.Theme()).Warn)
+ }
+ if state.message != "" {
+ palette := tok.Of(c.Theme())
+ color := palette.Text2
+ if state.failed {
+ color = palette.Err
+ }
+ settingsText(c, state.message, 13, color).Role(ui.RoleStatus)
+ }
+ switch page.id {
+ case "general":
+ s.generalSettings(c, state, st, readOnly)
+ case "appearance":
+ s.appearanceSettings(c, state, st, readOnly)
+ case "menu":
+ s.menuSettings(c, state, st, readOnly)
+ case "proxy":
+ s.proxySettings(c, state, st, readOnly)
+ case "about":
+ s.aboutSettings(c, state, st)
+ case "licenses":
+ s.licenseSettings(c, state)
+ }
+}
+
+func (s *shell) settingsIndex(c *ui.Context, selected string) {
+ settingsPageHeading(c, "设置")
+ settingsPanel(c, "settings-index", func() {
+ for index, link := range settingsLinks {
+ if index > 0 {
+ settingsDivider(c)
+ }
+ if !settingsLink(c, link.id, link.title, link.icon) || link.id == selected {
+ continue
+ }
+ stack := s.stacks[s.tab]
+ for position := len(stack) - 1; position >= 0; position-- {
+ if stack[position].kind == pageSettings {
+ s.stacks[s.tab] = stack[:position+1]
+ break
+ }
+ }
+ s.push(route{kind: pageSetting, title: link.title, id: link.id})
+ }
+ })
+}
+
+func (s *shell) saveSetting(state *settingsPageData, change func(*app.Settings)) bool {
+ if _, err := s.app.UpdateSettings(change); err != nil {
+ state.message, state.failed = "设置保存失败,请重试。", true
+ return false
+ }
+ state.message, state.failed = "", false
+ return true
+}
+
+func settingsPanel(c *ui.Context, key string, content func()) {
+ ui.Column(c).Key(key).FillWidth().PaddingX(14).Radius(16).
+ Background(tok.Of(c.Theme()).Surface).Children(content)
+}
+
+func settingsDivider(c *ui.Context) {
+ ui.Box(c).FillWidth().Height(1).Shrink(0).Background(tok.Of(c.Theme()).Line)
+}
+
+func settingsLink(c *ui.Context, key, title, icon string) bool {
+ palette := tok.Of(c.Theme())
+ button := ui.ButtonBase(c).Key(key).Label(title).FillWidth().MinHeight(58).
+ Padding(6, 0).Gap(12).AlignItems(ui.Center)
+ button.Children(func() {
+ if icon != "" {
+ glyph(c, icon, 18, palette.AccentText)
+ }
+ settingsText(c, title, 14, palette.Text).Grow(1)
+ glyph(c, "right", 14, palette.Text3)
+ })
+ return button.Clicked()
+}
+
+func settingsText(c *ui.Context, text string, size float32, color ui.Color) ui.Element {
+ return ui.Text(c, text).FontSize(scale.Font(c, size)).TextColor(color).Wrap().MinWidth(0)
+}
+
+func settingsPageHeading(c *ui.Context, title string) {
+ settingsText(c, title, 20, tok.Of(c.Theme()).Text).FontWeight(700).
+ Role(ui.RoleHeading).Margin(4, 0, 10, 0)
+}
+
+func settingsGroup(c *ui.Context, title, note string, content func()) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).Key(title).FillWidth().Gap(10).Margin(12, 0, 0, 0).Children(func() {
+ settingsText(c, title, 14, palette.Text2).FontWeight(600)
+ if note != "" {
+ settingsText(c, note, 12, palette.Text2)
+ }
+ content()
+ })
+}
+
+func settingRow(c *ui.Context, key, title, note string, control func()) {
+ palette := tok.Of(c.Theme())
+ ui.Row(c).Key(key).FillWidth().MinHeight(56).PaddingY(6).Gap(12).AlignItems(ui.Center).Children(func() {
+ ui.Column(c).Grow(1).Shrink(1).MinWidth(0).Gap(3).Children(func() {
+ settingsText(c, title, 14, palette.Text)
+ if note != "" {
+ settingsText(c, note, 12, palette.Text2)
+ }
+ })
+ if control != nil {
+ control()
+ }
+ })
+}
+
+func settingSwitch(c *ui.Context, label string, on, disabled bool) bool {
+ palette := tok.Of(c.Theme())
+ button := ui.ButtonBase(c).Key(label).Label(label).Role(ui.RoleSwitch).Checked(on).
+ Size(touchSize(), touchSize()).Shrink(0).Disabled(disabled)
+ button.Draw(func(painter *ui.Painter, rect ui.Rect) {
+ left, top := rect.X+(rect.W-44)/2, rect.Y+(rect.H-24)/2
+ track, knobX := palette.LineStrong, left+3
+ if on {
+ track, knobX = palette.Accent, left+23
+ }
+ if disabled {
+ track = track.Mix(palette.Surface, 0.45)
+ }
+ painter.Fill(ui.Rect{X: left, Y: top, W: 44, H: 24}, track, 12)
+ painter.Fill(ui.Rect{X: knobX, Y: top + 3, W: 18, H: 18}, ui.RGB(255, 255, 255), 9)
+ })
+ return button.Clicked()
+}
+
+type settingChoice[T comparable] struct {
+ value T
+ label string
+}
+
+func settingSelect[T comparable](c *ui.Context, title string, value T, options []settingChoice[T], disabled bool, change func(T)) {
+ labels := make([]string, 0, len(options))
+ var selected string
+ for _, choice := range options {
+ labels = append(labels, choice.label)
+ if choice.value == value {
+ selected = choice.label
+ }
+ }
+ c.Key(title)
+ if ui.Select(c, &selected, labels).Label("选择" + title).MinHeight(touchSize()).MaxWidth(148).Shrink(0).Disabled(disabled).Changed() {
+ for _, choice := range options {
+ if choice.label == selected && choice.value != value {
+ change(choice.value)
+ return
+ }
+ }
+ }
+}
+
+func settingsAction(c *ui.Context, label string, primary, wide bool) ui.Element {
+ palette := tok.Of(c.Theme())
+ text, fill := palette.Text2, palette.Surface2
+ if primary {
+ text, fill = palette.AccentInk, palette.Accent
+ } else if !wide {
+ fill = ui.Color{}
+ }
+ button := ui.ButtonBase(c).Key(label).Label(label).MinHeight(touchSize()).PaddingX(14).Shrink(0).
+ Radius(22).Background(fill).AlignItems(ui.Center).Justify(ui.Center)
+ if wide {
+ button = button.FillWidth()
+ }
+ button.Children(func() { settingsText(c, label, 14, text).FontWeight(600) })
+ return button
+}
+
+func (s *shell) generalSettings(c *ui.Context, state *settingsPageData, st app.Settings, readOnly bool) {
+ qualities := []settingChoice[app.AudioQuality]{
+ {app.AudioQualityLossless, "Hi-Res 无损"}, {app.AudioQualityDolby, "杜比全景声"},
+ {app.AudioQualityHigh, "高品质"}, {app.AudioQualityMedium, "标准"}, {app.AudioQualityLow, "流畅"},
+ }
+ if !s.app.LoggedIn() {
+ qualities = qualities[2:]
+ if st.AudioQuality == app.AudioQualityLossless || st.AudioQuality == app.AudioQualityDolby {
+ qualities = append([]settingChoice[app.AudioQuality]{{st.AudioQuality, "登录后可用"}}, qualities...)
+ }
+ }
+ settingsGroup(c, "播放", "", func() {
+ settingsPanel(c, "playback-settings", func() {
+ settingRow(c, "audio-quality", "默认音质", "切换后会重新取流,并从当前位置继续播放", func() {
+ settingSelect(c, "默认音质", st.AudioQuality, qualities, readOnly, func(value app.AudioQuality) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.AudioQuality = value })
+ })
+ })
+ settingsDivider(c)
+ settingRow(c, "video-quality", "视频画质", "满屏播放器里看视频时用的清晰度", func() {
+ quality := st.VideoQuality
+ if quality == 0 {
+ quality = 64
+ }
+ choices := []settingChoice[int]{{120, "4K"}, {80, "1080P 高清"}, {64, "720P 准高清"}, {32, "480P 标清"}, {16, "360P 流畅"}}
+ settingSelect(c, "视频画质", quality, choices, readOnly, func(value int) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.VideoQuality = value })
+ })
+ })
+ settingsDivider(c)
+ syncNote := "把播放进度同步到 B 站账号,换设备可以接着看"
+ if !s.app.LoggedIn() {
+ syncNote = "登录后可把播放进度同步到 B 站账号"
+ }
+ settingRow(c, "report-history", "上报本机播放记录", syncNote, func() {
+ loggedIn := s.app.LoggedIn()
+ if settingSwitch(c, "上报本机播放记录", loggedIn && st.ReportPlayHistory, readOnly || !loggedIn) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.ReportPlayHistory = !settings.ReportPlayHistory })
+ }
+ })
+ })
+ })
+ settingsGroup(c, "下载", "", func() {
+ settingsPanel(c, "download-settings", func() {
+ settingRow(c, "download-location", "下载目录", "布丁音乐 · 应用存储", func() {
+ if settingsAction(c, "管理存储", false, false).Disabled(!s.app.DownloadMounted()).Clicked() {
+ s.push(route{kind: pageDownloads, title: "下载记录", id: "storage"})
+ }
+ })
+ })
+ })
+}
+
+func (s *shell) appearanceSettings(c *ui.Context, state *settingsPageData, st app.Settings, readOnly bool) {
+ palette := tok.Of(c.Theme())
+ settingsGroup(c, "深浅模式", "", func() {
+ ui.Row(c).FillWidth().Gap(8).Children(func() {
+ for _, theme := range []struct {
+ value app.ThemeMode
+ label string
+ color ui.Color
+ }{
+ {app.ThemeModeLight, "浅色", ui.RGB(233, 234, 235)},
+ {app.ThemeModeDark, "深色", ui.RGB(23, 24, 27)},
+ {app.ThemeModeSystem, "跟随系统", ui.RGB(153, 155, 160)},
+ } {
+ selected := theme.value == st.ThemeMode
+ background, border := palette.Surface, ui.Color{}
+ if selected {
+ background, border = palette.AccentSoft, palette.Accent
+ }
+ button := ui.ButtonBase(c).Key(string(theme.value)).Label(theme.label).Selected(selected).
+ Grow(1).Width(0).MinWidth(0).Column().AlignItems(ui.Center).Gap(5).Padding(8, 4).
+ Radius(12).Background(background).Border(1, border).Disabled(readOnly)
+ button.Children(func() {
+ ui.Box(c).FillWidth().Height(34).Radius(8).Background(theme.color)
+ settingsText(c, theme.label, 13, palette.Text)
+ })
+ if button.Clicked() {
+ s.saveSetting(state, func(settings *app.Settings) { settings.ThemeMode = theme.value })
+ }
+ }
+ })
+ })
+ settingsGroup(c, "颜色与字体", "", func() {
+ settingsPanel(c, "appearance-colors", func() {
+ settingRow(c, "accent", "强调色", "用在正在播放、选中和主要按钮上", func() {
+ ui.Row(c).Shrink(0).Children(func() {
+ choices := []settingChoice[app.Accent]{{app.AccentCinnabar, "朱砂"}, {app.AccentIndigo, "靛青"}, {app.AccentPine, "松绿"}, {app.AccentAmber, "琥珀"}}
+ for _, choice := range choices {
+ selected := choice.value == st.Accent
+ button := ui.ButtonBase(c).Key(string(choice.value)).Label(choice.label).Selected(selected).Column().
+ Width(38).MinHeight(46).AlignItems(ui.Center).Justify(ui.Center).Gap(3).Disabled(readOnly)
+ button.Children(func() {
+ ring := ui.Color{}
+ if selected {
+ ring = palette.Focus
+ }
+ ui.Box(c).Size(26, 26).Radius(13).Border(1, ring).AlignItems(ui.Center).Justify(ui.Center).Children(func() {
+ ui.Box(c).Size(22, 22).Radius(11).Background(tok.AccentColor(string(choice.value), c.Theme().Dark))
+ })
+ settingsText(c, choice.label, 11, palette.Text2)
+ })
+ if button.Clicked() {
+ s.saveSetting(state, func(settings *app.Settings) { settings.Accent = choice.value })
+ }
+ }
+ })
+ })
+ settingsDivider(c)
+ settingRow(c, "cover-accent", "封面取色", "强调色跟着当前歌曲的封面变", func() {
+ if settingSwitch(c, "封面取色", st.CoverAccent, readOnly) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.CoverAccent = !settings.CoverAccent })
+ }
+ })
+ settingsDivider(c)
+ settingRow(c, "font-scale", "界面字号", "", func() {
+ choices := []settingChoice[app.FontScale]{{app.FontScaleSmall, "紧凑"}, {app.FontScaleStd, "标准"}, {app.FontScaleLarge, "大"}}
+ settingSelect(c, "界面字号", st.FontScale, choices, readOnly, func(value app.FontScale) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.FontScale = value })
+ })
+ })
+ })
+ })
+ settingsGroup(c, "字体", "", func() {
+ settingsPanel(c, "mobile-font-families", func() {
+ families := []settingChoice[string]{{app.DefaultFontFamily, "系统默认"}, {"PingFang SC", "苹方"}, {"Hiragino Sans GB", "冬青黑体"}, {"Songti SC", "宋体"}, {"Kaiti SC", "楷体"}, {"Microsoft YaHei", "微软雅黑"}}
+ for index, family := range families {
+ if index > 0 {
+ settingsDivider(c)
+ }
+ if settingOption(c, family.value, family.label, "", family.value, family.value == st.FontFamily, readOnly) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.FontFamily = family.value })
+ }
+ }
+ })
+ })
+ settingsGroup(c, "数据显示样式", "", func() {
+ settingsPanel(c, "display-settings", func() {
+ settingRow(c, "video-display", "视频列表的显示方式", "搜索结果的「视频」、UP 主投稿都会跟着变", func() {
+ choices := []settingChoice[app.DisplayMode]{{app.DisplayModeCard, "卡片"}, {app.DisplayModeList, "列表"}, {app.DisplayModeCompact, "紧凑"}}
+ settingSelect(c, "视频列表的显示方式", st.DisplayMode, choices, readOnly, func(value app.DisplayMode) {
+ s.saveSetting(state, func(settings *app.Settings) { settings.DisplayMode = value })
+ })
+ })
+ })
+ })
+}
+
+func settingOption(c *ui.Context, key, title, note, font string, selected, disabled bool) bool {
+ palette := tok.Of(c.Theme())
+ button := ui.ButtonBase(c).Key(key).Label(title).Selected(selected).FillWidth().MinHeight(50).
+ Padding(6, 4).Gap(10).AlignItems(ui.Center).Disabled(disabled)
+ if selected {
+ button = button.Radius(8).Background(palette.AccentSoft)
+ }
+ button.Children(func() {
+ ui.Column(c).Grow(1).Shrink(1).Gap(3).Children(func() {
+ text := settingsText(c, title, 14, palette.Text)
+ if font != "" {
+ text.Font(font)
+ settingsText(c, "晴天 夜航电台 0123", 12, palette.Text2).Font(font)
+ }
+ if note != "" {
+ settingsText(c, note, 12, palette.Text2)
+ }
+ })
+ if selected {
+ glyph(c, "check", 16, palette.AccentText)
+ }
+ })
+ return button.Clicked()
+}
+
+func (s *shell) menuSettings(c *ui.Context, state *settingsPageData, st app.Settings, readOnly bool) {
+ settingsGroup(c, "入口显示", "关掉的入口会从「我的」隐藏,数据仍保留。", func() {
+ settingsPanel(c, "menu-entries", func() {
+ for index, entry := range mobileMenuEntries {
+ if index > 0 {
+ settingsDivider(c)
+ }
+ s.visibilitySetting(c, state, st, entry.key, entry.title, "", readOnly)
+ }
+ })
+ })
+ settingsGroup(c, "歌单显示", "", func() {
+ settingsPanel(c, "playlist-entries", func() {
+ seen := make(map[int64]bool)
+ for _, group := range []app.FavoriteGroup{app.FavoritesCreated, app.FavoritesCollected} {
+ for _, item := range s.app.SideFavorites(group) {
+ if seen[item.ID] {
+ continue
+ }
+ if len(seen) > 0 {
+ settingsDivider(c)
+ }
+ seen[item.ID] = true
+ key := strconv.FormatInt(item.ID, 10)
+ note := fmt.Sprintf("%s · %d 首", group, item.MediaCount)
+ s.visibilitySetting(c, state, st, key, item.Title, note, readOnly)
+ }
+ }
+ if len(seen) == 0 {
+ message := "暂无可显示的歌单"
+ if !s.app.LoggedIn() {
+ message = "登录后可设置收藏夹显示"
+ }
+ settingRow(c, "playlist-empty", message, "", nil)
+ }
+ })
+ })
+}
+
+func (s *shell) visibilitySetting(c *ui.Context, state *settingsPageData, st app.Settings, key, title, note string, readOnly bool) {
+ settingRow(c, key, title, note, func() {
+ shown := !slices.Contains(st.HiddenMenuKeys, key)
+ if settingSwitch(c, "显示"+title, shown, readOnly) {
+ s.saveSetting(state, func(settings *app.Settings) {
+ if shown {
+ if !slices.Contains(settings.HiddenMenuKeys, key) {
+ settings.HiddenMenuKeys = append(slices.Clone(settings.HiddenMenuKeys), key)
+ }
+ } else {
+ settings.HiddenMenuKeys = slices.DeleteFunc(slices.Clone(settings.HiddenMenuKeys), func(hidden string) bool { return hidden == key })
+ }
+ })
+ }
+ })
+}
+
+func (s *shell) proxySettings(c *ui.Context, state *settingsPageData, st app.Settings, readOnly bool) {
+ draft := &state.proxy
+ stored := st.ProxySettings
+ custom := draft.custom || stored.Type != app.ProxyNone && stored.Type != app.ProxyDirect
+ settingsGroup(c, "代理设置", "", func() {
+ settingsPanel(c, "proxy-modes", func() {
+ options := []struct {
+ mode app.ProxyType
+ label, note string
+ selected bool
+ }{
+ {app.ProxyDirect, "不使用代理", "直接连接", !custom && stored.Type == app.ProxyDirect},
+ {app.ProxyNone, "使用系统代理", "跟随系统网络设置", !custom && stored.Type == app.ProxyNone},
+ {app.ProxyHTTP, "自定义代理", "手动填写类型、地址和端口", custom},
+ }
+ for index, option := range options {
+ if index > 0 {
+ settingsDivider(c)
+ }
+ if !settingOption(c, string(option.mode), option.label, option.note, "", option.selected, readOnly || draft.testing) {
+ continue
+ }
+ if option.mode == app.ProxyHTTP {
+ draft.custom = true
+ continue
+ }
+ if s.saveSetting(state, func(settings *app.Settings) { settings.ProxySettings.Type = option.mode }) {
+ draft.custom, draft.result = false, ""
+ }
+ }
+ })
+ })
+ if !custom {
+ return
+ }
+ if draft.kind == "" {
+ draft.kind = stored.Type
+ if draft.kind == app.ProxyNone || draft.kind == app.ProxyDirect {
+ draft.kind = app.ProxyHTTP
+ }
+ draft.host, draft.user = stored.Host, stored.Username
+ if stored.Port != nil {
+ draft.port = strconv.Itoa(*stored.Port)
+ }
+ }
+ palette := tok.Of(c.Theme())
+ ui.Column(c).Key("custom-proxy-form").FillWidth().Gap(10).Margin(12, 0, 0, 0).Children(func() {
+ disabled := readOnly || draft.testing
+ settingRow(c, "proxy-protocol", "代理类型", "", func() {
+ choices := []settingChoice[app.ProxyType]{{app.ProxyHTTP, "HTTP 代理"}, {app.ProxyHTTPS, "HTTPS 代理"}, {app.ProxySOCKS4, "SOCKS4 代理"}, {app.ProxySOCKS5, "SOCKS5 代理"}}
+ settingSelect(c, "代理类型", draft.kind, choices, disabled, func(value app.ProxyType) { draft.kind = value })
+ })
+ proxyField(c, "代理主机", "127.0.0.1", draft.hostError, &draft.host, ui.KeyboardURL, false, disabled)
+ proxyField(c, "代理端口", "7890", draft.portError, &draft.port, ui.KeyboardNumber, false, disabled)
+ proxyField(c, "代理用户名", "没有就留空", "", &draft.user, ui.KeyboardDefault, false, disabled)
+ secretHint, savedSecret := "", ""
+ if stored.Password != "" && draft.user == stored.Username &&
+ strings.Trim(strings.TrimSpace(draft.host), "[]") == stored.Host && stored.Port != nil &&
+ strings.TrimSpace(draft.port) == strconv.Itoa(*stored.Port) && draft.kind == stored.Type {
+ secretHint = "留空保留已保存的密码"
+ savedSecret = stored.Password
+ }
+ proxyField(c, "代理密码", secretHint, "", &draft.secret, ui.KeyboardDefault, true, disabled)
+ if settingsAction(c, "保存并测试", true, true).Disabled(disabled).Clicked() {
+ s.saveMobileProxy(state, savedSecret)
+ }
+ if draft.testing {
+ settingsText(c, "正在测试…", 13, palette.Text2).Role(ui.RoleStatus)
+ } else if draft.result != "" {
+ color := palette.Text2
+ if draft.failed {
+ color = palette.Err
+ }
+ settingsText(c, draft.result, 13, color).Role(ui.RoleStatus)
+ }
+ })
+}
+
+func proxyField(c *ui.Context, label, placeholder, message string, value *string, keyboard ui.KeyboardType, masked, disabled bool) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).Key(label).FillWidth().Gap(5).Children(func() {
+ settingsText(c, label, 13, palette.Text)
+ input := ui.TextInputBase(c, value).Label(label).Placeholder(placeholder).FillWidth().MinHeight(touchSize()).
+ PaddingX(12).Radius(8).Background(palette.Surface2).TextColor(palette.Text).Disabled(disabled).
+ Keyboard(keyboard).Capitalize(ui.CapitalizeNone).Autocorrect(false).ReturnKey(ui.ReturnNext)
+ if masked {
+ input.Password().ReturnKey(ui.ReturnDone)
+ }
+ if message != "" {
+ settingsText(c, message, 12, palette.Err)
+ }
+ })
+}
+
+func (s *shell) saveMobileProxy(state *settingsPageData, storedSecret string) {
+ draft := &state.proxy
+ draft.hostError, draft.portError, draft.result = "", "", ""
+ host := strings.TrimSpace(draft.host)
+ if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
+ host = host[1 : len(host)-1]
+ }
+ port, err := strconv.Atoi(strings.TrimSpace(draft.port))
+ if host == "" {
+ draft.hostError = "请填写代理主机"
+ } else if strings.ContainsAny(host, "/?#@[] \t\r\n") || strings.Contains(host, ":") && net.ParseIP(host) == nil {
+ draft.hostError = "请填写主机名或 IP 地址"
+ }
+ if port < 1 || port > 65535 || err != nil {
+ draft.portError = "端口必须为 1–65535"
+ }
+ if draft.hostError != "" || draft.portError != "" {
+ return
+ }
+ secret := draft.secret
+ if secret == "" {
+ secret = storedSecret
+ }
+ if !s.saveSetting(state, func(settings *app.Settings) {
+ settings.ProxySettings = app.ProxySettings{Type: draft.kind, Host: host, Port: &port, Username: draft.user, Password: secret}
+ }) {
+ return
+ }
+ draft.testing, draft.secret = true, ""
+ go func() {
+ ctx, cancel := context.WithTimeout(s.ctx, 5*time.Second)
+ defer cancel()
+ var dialer net.Dialer
+ conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, strconv.Itoa(port)))
+ if err == nil {
+ _ = conn.Close()
+ }
+ s.update(func() {
+ draft.testing = false
+ draft.result, draft.failed = "已保存,代理端口可连接。", err != nil
+ if err != nil {
+ draft.result = "已保存,但无法连接代理端口。请检查地址及网络后重试。"
+ }
+ })
+ }()
+}
+
+func (s *shell) aboutSettings(c *ui.Context, state *settingsPageData, st app.Settings) {
+ palette := tok.Of(c.Theme())
+ ui.Column(c).Key("about-brand").FillWidth().AlignItems(ui.Center).Gap(8).PaddingY(24).Children(func() {
+ mobileRecordMark(c, 60)
+ typo.Display(settingsText(c, "布丁音乐 PudMusic", 20, palette.Text), scale.Font(c, 20))
+ settingsText(c, "原生音乐播放器 · Go + MyGo", 13, palette.Text2)
+ })
+ settingsPanel(c, "about-actions", func() {
+ updateNote := "通过安装来源的应用商店更新"
+ if runtime.GOOS == "ios" {
+ updateNote = "通过 App Store 更新"
+ }
+ settingRow(c, "app-update", "应用更新", updateNote, nil)
+ settingsDivider(c)
+ settingRow(c, "about-license", "开源许可", "基于 Biu 重新实现与扩展", func() {
+ if settingsAction(c, "查看", false, false).Clicked() {
+ s.push(route{kind: pageSetting, title: "开源许可", id: "licenses"})
+ }
+ })
+ settingsDivider(c)
+ settingRow(c, "diagnostic", "诊断信息", "遇到问题时附在反馈里", func() {
+ if settingsAction(c, "复制", false, false).Disabled(s.win == nil).Clicked() {
+ mygo.Clipboard.WriteText(fmt.Sprintf("PudMusic %s\n系统:%s/%s,Go %s\n音质偏好:%s,视频画质:%d\n主题:%s / %s,封面取色:%v,字号:%s\n代理:%s",
+ mygo.App.Version(), runtime.GOOS, runtime.GOARCH, runtime.Version(), st.AudioQuality, st.VideoQuality,
+ st.ThemeMode, st.Accent, st.CoverAccent, st.FontScale, st.ProxySettings.Type))
+ state.message, state.failed = "已复制诊断信息", false
+ }
+ })
+ })
+}
+
+func (s *shell) licenseSettings(c *ui.Context, state *settingsPageData) {
+ settingsPanel(c, "license-list", func() {
+ for index, document := range []struct{ name, path string }{
+ {"Biu", licensing.BiuLicenseRelPath},
+ {"Remix Icon", licensing.IconLicenseRelPath},
+ {"思源宋体", licensing.FontLicenseRelPath},
+ {"第三方组件许可", licensing.NoticesRelPath},
+ } {
+ if index > 0 {
+ settingsDivider(c)
+ }
+ if !settingsLink(c, document.path, document.name, "") {
+ continue
+ }
+ resources, err := mygo.App.Path(mygo.PathResources)
+ if err == nil {
+ var text []byte
+ text, err = os.ReadFile(filepath.Join(resources, licensing.NoticesDirName, filepath.Base(document.path)))
+ if err == nil {
+ s.push(route{kind: pageSetting, title: document.name, id: "license-text", data: string(text)})
+ }
+ }
+ if err != nil {
+ state.message, state.failed = "无法读取随包提供的许可文件。", true
+ }
+ }
+ })
+}
diff --git a/internal/mobileui/settings_test.go b/internal/mobileui/settings_test.go
new file mode 100644
index 00000000..5d744a09
--- /dev/null
+++ b/internal/mobileui/settings_test.go
@@ -0,0 +1,192 @@
+package mobileui
+
+import (
+ "context"
+ "image/png"
+ "os"
+ "path/filepath"
+ "slices"
+ "testing"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/egoist/mygo/ui"
+)
+
+// TestMobileSettingsOpensSubpage checks that the native settings menu opens a subpage and returns to the menu.
+func TestMobileSettingsOpensSubpage(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.SetThemeMode(app.ThemeModeLight); err != nil {
+ t.Fatal(err)
+ }
+ s := newShell(context.Background(), a)
+ s.switchTab(2)
+ s.push(route{kind: pageSettings, title: "设置"})
+ tester := ui.NewTester(s.view, 390, 844)
+ if dir := os.Getenv("BIU_SHOT_DIR"); dir != "" {
+ file, err := os.Create(filepath.Join(dir, "mobile-light-settings.png"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ err = png.Encode(file, tester.Image())
+ closeErr := file.Close()
+ if err != nil || closeErr != nil {
+ t.Fatalf("settings screenshot: encode = %v, close = %v", err, closeErr)
+ }
+ }
+ if err := tester.Click("外观"); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(tester.Texts(), "深浅模式") {
+ t.Fatalf("appearance settings did not open, got %q", tester.Texts())
+ }
+ if err := tester.Click("返回"); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Contains(tester.Texts(), "播放与下载") {
+ t.Fatalf("back did not return to settings, got %q", tester.Texts())
+ }
+}
+
+// TestTabletSettingsKeepsTheIndexBesideTheDetail verifies that switching sections uses the master list and that Back returns to Settings.
+func TestTabletSettingsKeepsTheIndexBesideTheDetail(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ s := newShell(t.Context(), a)
+ s.switchTab(2)
+ s.push(route{kind: pageSettings, title: "设置"})
+ tester := ui.NewTester(s.view, 780, 844)
+ for _, label := range []string{"外观", "网络代理"} {
+ if err := tester.Click(label); err != nil {
+ t.Fatal(err)
+ }
+ }
+ index, foundIndex := tester.Find("播放与下载")
+ detail, foundDetail := tester.Find("使用系统代理")
+ if !foundIndex || !foundDetail || index.X+index.W > detail.X || detail.Y > index.Y+160 {
+ t.Fatalf("settings list and detail did not appear side by side: %v, %v", index, detail)
+ }
+ mobileLibraryShot(t, tester, "tablet-settings.png")
+ if err := tester.Click("返回"); err != nil {
+ t.Fatal(err)
+ }
+ if _, found := tester.Find("使用系统代理"); found {
+ t.Fatal("Back left the settings detail open")
+ }
+}
+
+// TestMobileSettingsVisibilityPersists checks that hiding and restoring a My page entry changes the saved preference.
+func TestMobileSettingsVisibilityPersists(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ path := filepath.Join(t.TempDir(), app.SettingsFileName)
+ if err := a.MountSettings(path); err != nil {
+ t.Fatal(err)
+ }
+ s := &shell{app: a}
+ page := &route{kind: pageSetting, id: "menu"}
+ tester := ui.NewTester(func(c *ui.Context) {
+ ui.Column(c).FillWidth().PaddingX(16).Children(func() { s.settings(c, page) })
+ }, 390, 700)
+ for _, hidden := range []bool{true, false} {
+ if err := tester.Click("显示历史记录"); err != nil {
+ t.Fatal(err)
+ }
+ if err := a.FlushSettings(); err != nil {
+ t.Fatal(err)
+ }
+ settings, err := app.LoadSettings(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := slices.Contains(settings.HiddenMenuKeys, "/history"); got != hidden {
+ t.Fatalf("saved history visibility hidden = %v, want %v", got, hidden)
+ }
+ }
+}
+
+// TestMobileSettingsThemePersists checks that choosing a theme updates both the running app and its saved settings.
+func TestMobileSettingsThemePersists(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ path := filepath.Join(t.TempDir(), app.SettingsFileName)
+ if err := a.MountSettings(path); err != nil {
+ t.Fatal(err)
+ }
+ s := &shell{app: a}
+ page := &route{kind: pageSetting, id: "appearance"}
+ tester := ui.NewTester(func(c *ui.Context) {
+ ui.Column(c).FillWidth().PaddingX(16).Children(func() { s.settings(c, page) })
+ }, 390, 700)
+ if err := tester.Click("深色"); err != nil {
+ t.Fatal(err)
+ }
+ if got := a.SettingsSnapshot().ThemeMode; got != app.ThemeModeDark {
+ t.Fatalf("running theme = %q, want dark", got)
+ }
+ if err := a.FlushSettings(); err != nil {
+ t.Fatal(err)
+ }
+ persisted, err := app.LoadSettings(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if persisted.ThemeMode != app.ThemeModeDark {
+ t.Fatalf("saved theme = %q, want dark", persisted.ThemeMode)
+ }
+}
+
+// TestMobileSettingsQualityChooser checks that the touch picker applies a playback quality preference.
+func TestMobileSettingsQualityChooser(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ s := &shell{app: a}
+ page := &route{kind: pageSetting, id: "general"}
+ tester := ui.NewTester(func(c *ui.Context) {
+ ui.Column(c).FillWidth().PaddingX(16).Children(func() { s.settings(c, page) })
+ }, 390, 800)
+ for _, label := range []string{"选择默认音质", "标准"} {
+ if err := tester.Click(label); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if got := a.SettingsSnapshot().AudioQuality; got != app.AudioQualityMedium {
+ t.Fatalf("audio quality = %q, want standard", got)
+ }
+}
+
+// TestMobileSettingsProxyRejectsIncompleteEndpoint checks that an invalid custom proxy leaves the current connection mode intact.
+func TestMobileSettingsProxyRejectsIncompleteEndpoint(t *testing.T) {
+ a := app.New()
+ t.Cleanup(a.Close)
+ if err := a.MountSettings(filepath.Join(t.TempDir(), app.SettingsFileName)); err != nil {
+ t.Fatal(err)
+ }
+ s := &shell{app: a}
+ page := &route{kind: pageSetting, id: "proxy"}
+ tester := ui.NewTester(func(c *ui.Context) {
+ ui.Column(c).FillWidth().PaddingX(16).Children(func() { s.settings(c, page) })
+ }, 390, 800)
+ for _, label := range []string{"自定义代理", "保存并测试"} {
+ if err := tester.Click(label); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, message := range []string{"请填写代理主机", "端口必须为 1–65535"} {
+ if !slices.Contains(tester.Texts(), message) {
+ t.Fatalf("missing validation message %q in %q", message, tester.Texts())
+ }
+ }
+ if got := a.SettingsSnapshot().ProxySettings.Type; got != app.ProxyNone {
+ t.Fatalf("proxy mode = %q after rejecting invalid custom proxy, want system", got)
+ }
+}
diff --git a/internal/mobileui/shell.go b/internal/mobileui/shell.go
new file mode 100644
index 00000000..e1022e2c
--- /dev/null
+++ b/internal/mobileui/shell.go
@@ -0,0 +1,326 @@
+package mobileui
+
+import (
+ "context"
+ "log"
+ "runtime"
+
+ "github.com/ShellMonster/PudMusic/internal/app"
+ "github.com/ShellMonster/PudMusic/internal/media"
+ desktop "github.com/ShellMonster/PudMusic/internal/ui"
+ "github.com/egoist/mygo"
+ "github.com/egoist/mygo/ui"
+)
+
+type pageKind uint8
+
+const (
+ pageDiscover pageKind = iota
+ pageSearch
+ pageMy
+ pageDaily
+ pageChart
+ pageNews
+ pageMixes
+ pageAlbum
+ pageCollection
+ pageHistory
+ pageLocal
+ pageDownloads
+ pageLater
+ pageFollowing
+ pageFeed
+ pageCreator
+ pageStats
+ pageSettings
+ pageSetting
+ pageLogin
+)
+
+type route struct {
+ kind pageKind
+ title string
+ id string
+ ref app.CollectionRef
+ query string
+ focus bool
+ data any
+ key uint64
+}
+
+type shell struct {
+ app *app.App
+ win *mygo.Window
+ ctx context.Context
+ tab int
+ stacks [3][]*route
+ serial uint64
+ player playerView
+ notice string
+ dispatch func(func())
+ collectionPlayRequest uint64
+}
+
+func newShell(ctx context.Context, application *app.App) *shell {
+ return &shell{
+ app: application, ctx: ctx, serial: 3,
+ stacks: [3][]*route{
+ {{kind: pageDiscover, title: "发现", key: 1}},
+ {{kind: pageSearch, title: "搜索", key: 2}},
+ {{kind: pageMy, title: "我的", key: 3}},
+ },
+ }
+}
+
+func Run(application *app.App, session *media.Session) error {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ defer application.Close()
+ if session != nil {
+ defer session.Close()
+ }
+ s := newShell(ctx, application)
+ if runtime.GOOS == "ios" {
+ if err := restoreMobileImportPaths(application, mobileImportBase()); err != nil {
+ log.Printf("pudmusic: restore mobile import paths: %v", err)
+ }
+ }
+ if err := application.RestorePlayback(); err != nil {
+ log.Printf("pudmusic: restore mobile playback: %v", err)
+ }
+ mygo.App.WhenReady(func() {
+ application.NoteReady()
+ s.win = mygo.NewWindow(mygo.WindowOptions{
+ Title: "布丁音乐", Width: 390, Height: 844, Content: ui.View(s.view),
+ })
+ remove := application.AddWake(s.win.Invalidate)
+ removeLocal := application.AddLocalWake(s.win.Invalidate)
+ s.win.OnClosed(func() { removeLocal(); remove() })
+ })
+ defer s.watchDocumentShares()()
+ return mygo.App.Run()
+}
+
+func (s *shell) current() *route {
+ stack := s.stacks[s.tab]
+ return stack[len(stack)-1]
+}
+
+func (s *shell) push(page route) {
+ if previous := s.current(); previous.kind == pageLogin {
+ s.leaveLogin(previous)
+ }
+ s.serial++
+ page.key = s.serial
+ s.stacks[s.tab] = append(s.stacks[s.tab], &page)
+}
+
+func (s *shell) switchTab(tab int) {
+ if previous := s.current(); previous.kind == pageLogin {
+ s.leaveLogin(previous)
+ s.stacks[s.tab] = s.stacks[s.tab][:len(s.stacks[s.tab])-1]
+ }
+ if s.tab == tab {
+ s.stacks[tab] = s.stacks[tab][:1]
+ }
+ s.tab = tab
+}
+
+func (s *shell) openSearch() {
+ s.switchTab(1)
+ s.stacks[1] = s.stacks[1][:1]
+ s.current().focus = true
+}
+
+func (s *shell) back() bool {
+ if s.player.sheet == sheetTrackFolders && s.player.folders != nil {
+ view := s.player.folders
+ if view.saving || view.editor.saving || view.editor.crop.uploading {
+ return true
+ }
+ if view.editor.open {
+ view.editor.open = false
+ return true
+ }
+ }
+ if (s.player.sheet == sheetComments || s.player.sheet == sheetReplies) && s.player.comments.focused {
+ s.player.comments.focused = false
+ return true
+ }
+ if s.dismissSearchKeyboard() {
+ return true
+ }
+ if s.player.back() {
+ if !s.player.visible {
+ s.app.StopVideo()
+ }
+ return true
+ }
+ stack := s.stacks[s.tab]
+ if len(stack) > 1 {
+ if page := s.current(); page.kind == pageLogin {
+ s.leaveLogin(page)
+ }
+ s.stacks[s.tab] = stack[:len(stack)-1]
+ return true
+ }
+ if s.tab != 0 {
+ s.switchTab(0)
+ return true
+ }
+ return false
+}
+
+func (s *shell) update(fn func()) {
+ if s.ctx.Err() != nil {
+ return
+ }
+ if s.dispatch != nil {
+ s.dispatch(fn)
+ } else if s.win != nil {
+ s.win.Update(fn)
+ }
+}
+
+func (s *shell) view(c *ui.Context) {
+ desktop.ApplyTheme(c, s.app.SettingsSnapshot(), c.Theme().Dark)
+ desktop.Guard(s.draw, func(value any) { log.Printf("pudmusic: mobile view: %v", value) })(c)
+}
+
+func (s *shell) draw(c *ui.Context) {
+ if (s.player.visible || s.player.sheet != sheetNone || s.tab != 0 || len(s.stacks[s.tab]) > 1) && c.Shortcut(0, ui.KeyBack) {
+ s.back()
+ }
+ if s.notice != "" {
+ c.Toast(s.notice)
+ s.notice = ""
+ }
+ state := s.app.Snapshot()
+ if s.player.visible && !state.HasTrack && !state.Loading && state.Err == "" {
+ s.player.visible = false
+ }
+ s.app.SetSpectrumWantedFor(app.SpectrumFull, s.player.visible && !s.player.lyrics && state.Playing && s.app.FullPlayerPrefs().ShowSpectrum)
+ palette := phonePalette(c)
+ background := palette.surface
+ if page := s.current(); !s.player.visible && (page.kind == pageSettings || page.kind == pageSetting || page.kind == pageLogin) {
+ background = palette.fill
+ }
+ ui.Column(c).Fill().Background(background).AccessHidden(s.player.sheet != sheetNone).Children(func() {
+ if s.player.visible {
+ s.fullPlayer(c, state)
+ return
+ }
+ page := s.current()
+ s.topBar(c, page)
+ width, _ := c.Size()
+ var siblings []browseCollection
+ if width >= 600 && page.kind == pageCollection {
+ siblings = s.collectionSiblings()
+ }
+ if width >= 600 && (page.kind == pageSetting || len(siblings) > 0) {
+ ui.Row(c).FillWidth().Grow(1).Basis(0).AlignItems(ui.Stretch).Children(func() {
+ ui.Scroll(c.Key("tablet-index")).Width(244).Shrink(0).FillHeight().Children(func() {
+ ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Children(func() {
+ if page.kind == pageSetting {
+ s.settingsIndex(c, page.id)
+ } else {
+ s.collectionIndex(c, page.ref, siblings)
+ }
+ })
+ })
+ ui.Box(c).Width(1).FillHeight().Background(palette.line)
+ s.pageBody(c, page)
+ })
+ } else {
+ s.pageBody(c, page)
+ }
+ if state.HasTrack || state.Loading || state.Err != "" {
+ s.miniPlayer(c, state)
+ }
+ s.tabs(c)
+ })
+ s.playerSheet(c, state)
+}
+
+func (s *shell) pageBody(c *ui.Context, page *route) {
+ scroll := ui.Scroll(c.Key(page.key)).Grow(1).Basis(0).FillWidth()
+ if page.kind == pageDiscover || page.kind == pageDaily || page.kind == pageChart || page.kind == pageNews || page.kind == pageMixes || page.kind == pageAlbum {
+ s.discoverRefresh(page, scroll)
+ } else {
+ s.libraryRefresh(page, scroll)
+ }
+ scroll.Children(func() {
+ ui.Column(c).FillWidth().Padding(8, 16, 24, 16).Gap(8).Children(func() {
+ s.drawPage(c, page)
+ })
+ })
+}
+
+func (s *shell) drawPage(c *ui.Context, page *route) {
+ switch page.kind {
+ case pageDiscover, pageDaily, pageChart, pageNews, pageMixes, pageAlbum:
+ s.discover(c, page)
+ case pageSearch:
+ s.search(c, page)
+ case pageCollection:
+ s.collection(c, page)
+ case pageLogin:
+ s.login(c, page)
+ case pageSettings, pageSetting:
+ s.settings(c, page)
+ default:
+ s.library(c, page)
+ }
+}
+
+func (s *shell) topBar(c *ui.Context, page *route) {
+ if page.kind == pageMy || page.kind == pageSearch {
+ return
+ }
+ if page.kind == pageDiscover {
+ ui.Row(c).Height(touchSize()).FillWidth().PaddingX(16).Gap(8).AlignItems(ui.Center).Children(func() {
+ brand(c)
+ ui.Text(c, "布丁音乐").FontSize(16).FontWeight(600)
+ })
+ return
+ }
+ ui.Row(c).Height(touchSize()).FillWidth().PaddingX(8).AlignItems(ui.Center).Children(func() {
+ iconButton(c, "left", "返回").OnClick(func() { s.back() })
+ if page.kind == pageSettings || page.kind == pageSetting || page.kind == pageLogin {
+ return
+ }
+ label := page.title
+ if page.kind == pageCollection {
+ label = "歌单"
+ }
+ ui.Box(c).Grow(1).Basis(0).Center().Children(func() {
+ ui.Text(c, label).FontSize(13).FontWeight(600).MaxLines(1)
+ })
+ ui.Box(c).Size(touchSize(), touchSize())
+ })
+}
+
+func (s *shell) tabs(c *ui.Context) {
+ palette := phonePalette(c)
+ height := float32(56)
+ if runtime.GOOS == "android" {
+ height = 60
+ }
+ ui.Row(c).FillWidth().Height(height).Children(func() {
+ for index, tab := range [...]struct{ label, icon string }{{"发现", "disc"}, {"搜索", "search"}, {"我的", "user"}} {
+ selected := s.tab == index
+ ink := palette.muted
+ if selected {
+ ink = palette.accent
+ }
+ ui.Column(c.Key(index)).Role(ui.RoleButton).Label(tab.label).AccessSelected(selected).Grow(1).Basis(0).Height(height).Center().Gap(2).Children(func() {
+ if runtime.GOOS == "android" && selected {
+ ui.Box(c).Size(52, 29).Radius(15).Center().Background(palette.soft).Children(func() { glyph(c, tab.icon, 22, ink) })
+ } else {
+ glyph(c, tab.icon, 22, ink)
+ }
+ ui.Text(c, tab.label).FontSize(12).TextColor(ink).FontWeight(500)
+ }).OnClick(func() { s.switchTab(index) })
+ }
+ })
+}
diff --git a/internal/platform/downloadsdir.go b/internal/platform/downloadsdir.go
index dcfafafb..12f296d0 100644
--- a/internal/platform/downloadsdir.go
+++ b/internal/platform/downloadsdir.go
@@ -24,6 +24,7 @@ package platform
import (
"fmt"
"path/filepath"
+ "runtime"
"github.com/egoist/mygo"
)
@@ -37,7 +38,8 @@ import (
// (AGENTS.md §5)。这一件是第四件:**新下载落哪儿**。
const DownloadsDirName = "PudMusic"
-// DefaultDownloadsDir 返回默认下载目录的路径:**音乐**目录下的应用子目录。
+// DefaultDownloadsDir 返回默认下载目录。移动端使用应用数据目录中的
+// downloads 子目录,桌面端使用**音乐**目录下的应用子目录。
//
// # 各平台上它是哪一条路径
//
@@ -64,6 +66,16 @@ const DownloadsDirName = "PudMusic"
// `ensureDir`)——不是开应用的时候。开应用就建的话,**光是打开应用就会在用户
// 的磁盘上留下一个文件夹**,测试里也一样(那不是临时的目录,是用户自己的)。
func DefaultDownloadsDir() (string, error) {
+ if runtime.GOOS == "ios" || runtime.GOOS == "android" {
+ dir, err := mygo.App.Path(mygo.PathUserData)
+ if err != nil {
+ return "", err
+ }
+ if !filepath.IsAbs(dir) {
+ return "", fmt.Errorf("应用数据目录不是绝对路径(%q),无法保存下载文件", dir)
+ }
+ return filepath.Join(dir, "downloads"), nil
+ }
music, musicErr := musicRoot()
if musicErr == nil {
return filepath.Join(music, DownloadsDirName), nil
diff --git a/internal/platform/single_instance_darwin.go b/internal/platform/single_instance_darwin.go
index 696d6ad6..dbf02e90 100644
--- a/internal/platform/single_instance_darwin.go
+++ b/internal/platform/single_instance_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
// macOS 上的「收起来 / 叫回来」。
//
diff --git a/internal/platform/single_instance_other.go b/internal/platform/single_instance_other.go
index c8d35c7e..7b908b9e 100644
--- a/internal/platform/single_instance_other.go
+++ b/internal/platform/single_instance_other.go
@@ -1,4 +1,4 @@
-//go:build !darwin && !windows
+//go:build (!darwin && !windows) || ios
// Linux(以及别的还没发的平台)上的「收起来 / 叫回来」。
//
diff --git a/internal/service/audio/containers.go b/internal/service/audio/containers.go
index 57c78223..aac95e38 100644
--- a/internal/service/audio/containers.go
+++ b/internal/service/audio/containers.go
@@ -67,24 +67,14 @@ func openExtAudioFile(r io.ReadSeeker) (mygoaudio.Decoder, error) {
return platformDecoderOpen(r)
}
-// mediaFoundationDecoderOpen 是「Windows 自带的解码器」的入口。
-//
-// 生产代码里它就是 `mfadec.Open`(Media Foundation 的 AAC MFT)。做成变量
-// 只有一个理由:**测试要模拟「这台机器没有 Media Foundation」**——真 Windows
-// 上它恒可用,macOS 上恒不可用,不注入的话这条路径在唯一能跑测试的这个平台上
-// **一条都测不到**(和 `platformDecoderOpen` 同一个道理)。
+// systemAACDecoderOpen 让测试能在任意平台模拟系统 AAC 后端成功或失败。
//
// ⚠️ 它是**包级变量**:换掉它的那条测试必须自己串行(不要 `t.Parallel`),
// 同包其它测试会看见换掉之后的值。
-var mediaFoundationDecoderOpen = openWithMediaFoundation
+var systemAACDecoderOpen = openWithSystemAAC
-// openWithMediaFoundation 用 Windows 的 Media Foundation 打开 r。
-//
-// 它解两种容器:MP4 家族(`.m4a` / `.m4s`,B 站有损流那种)和裸 ADTS
-// (`.aac`)。别的平台上没有 Media Foundation,`mfadec.Open` 会返回
-// `mfadec.ErrUnsupported`——那一层是平台无关的,所以这一行在 macOS 上也
-// 编得过、也跑得起来(只是永远走不到成功那一支)。
-func openWithMediaFoundation(r io.ReadSeeker) (mygoaudio.Decoder, error) {
+// openWithSystemAAC 用 Windows Media Foundation 或 Android MediaCodec 解 AAC。
+func openWithSystemAAC(r io.ReadSeeker) (mygoaudio.Decoder, error) {
d, err := mfadec.Open(r)
if err != nil {
return nil, err
diff --git a/internal/service/audio/fallback_test.go b/internal/service/audio/fallback_test.go
index ac9825fd..729ebae8 100644
--- a/internal/service/audio/fallback_test.go
+++ b/internal/service/audio/fallback_test.go
@@ -301,9 +301,9 @@ func stubPlatformDecoder(t *testing.T, open func(io.ReadSeeker) (mygoaudio.Decod
// ⚠️ 和 `stubPlatformDecoder` 一样:换掉的是包级变量,所以不能 `t.Parallel`。
func stubMediaFoundation(t *testing.T, open func(io.ReadSeeker) (mygoaudio.Decoder, error)) {
t.Helper()
- old := mediaFoundationDecoderOpen
- mediaFoundationDecoderOpen = open
- t.Cleanup(func() { mediaFoundationDecoderOpen = old })
+ old := systemAACDecoderOpen
+ systemAACDecoderOpen = open
+ t.Cleanup(func() { systemAACDecoderOpen = old })
}
// platformFakeDecoder 是「平台解码器成功」时的占位解码器。
diff --git a/internal/service/audio/mfadec/codec.go b/internal/service/audio/mfadec/codec.go
index 5a0f117e..234f396d 100644
--- a/internal/service/audio/mfadec/codec.go
+++ b/internal/service/audio/mfadec/codec.go
@@ -162,8 +162,7 @@ func userDataBlob(rate, chans int, v inputVariant, asc []byte) []byte {
// aacDecoder 是解码器要提供的那一点。
//
-// 这一层(容器、码流)是平台无关的,而解码器本身只在 Windows 上有——
-// 所以这里用接口而不是具体类型,`codec.go` 才能在没有 Windows 的机器上编译。
+// 容器和码流逻辑通过这个接口将帧交给系统解码器。
type aacDecoder interface {
// Feed 喂一帧 AAC,返回这一次解出来的 PCM。
Feed(frame []byte) ([]float32, error)
diff --git a/internal/service/audio/mfadec/decoder.go b/internal/service/audio/mfadec/decoder.go
index c15fd369..4a27626a 100644
--- a/internal/service/audio/mfadec/decoder.go
+++ b/internal/service/audio/mfadec/decoder.go
@@ -2,8 +2,8 @@ package mfadec
// 解码器这一层:把「一串 AAC 帧」变成「MyGo 的 audio 包能播的交织 float32」。
//
-// 这一层是**平台无关**的:拆帧在 `source.go`,解码在 Windows 上是 Media
-// Foundation(`transform_windows.go`),而这里只管把两者接起来、把采样交出去。
+// 这一层是**平台无关**的:拆帧在 `source.go`,解码由 Windows 的 Media
+// Foundation 或 Android 的 MediaCodec 完成,这里负责接合两者、把采样交出去。
// 平台无关的意思是**这一层在 macOS 上也能编译、也能测**——用一个假的解码器
// 就能验「采样怎么数、丢多少、跳到哪」这些算术,而那些算术错了症状是
// 「播出来的东西错位几百毫秒」,在真机上极难看出来。
@@ -22,12 +22,12 @@ import (
// 这一包返回的错误。
var (
- // ErrUnsupported 是「这个平台没有 Media Foundation」时 Open 返回的错误。
+ // ErrUnsupported 是「这个构建没有 AAC 后端」时 Open 返回的错误。
//
// 它和「文件解不了」是两回事:前者是平台没能力,后者是文件本身不对,
// 两者在界面上要显示不同的提示,所以分开(和 `extaf.ErrUnsupported` 同一个
// 道理)。
- ErrUnsupported = errors.New("mfadec: this platform has no Media Foundation audio decoder")
+ ErrUnsupported = errors.New("mfadec: no system AAC decoder backend in this build")
// ErrFormat 是「这串字节不是 AAC」——不是 MP4 家族里的 AAC,也不是裸 ADTS。
ErrFormat = errors.New("mfadec: not an AAC stream")
@@ -40,9 +40,7 @@ var (
// aacCodec 是「解码器」那一半,Decoder 只看得见这五个方法。
//
-// 真正的实现是 `*Codec`(Media Foundation 的 `IMFTransform`),只在 Windows
-// 上编译。这一层用接口而不是具体类型,`decoder.go` 才能在没有 Windows 的
-// 机器上编译——而这一层恰恰是最需要被测的那一层(见文件顶上那段)。
+// Windows 的 `*Codec` 和 Android 的 `*androidCodec` 都实现这一接口。
type aacCodec interface {
aacDecoder
// SampleRate 是输出采样率。
@@ -72,7 +70,8 @@ type Decoder struct {
//
// 生产代码里它就是 `openCodec`;测试换成假的——没有这一层,跳位置那条路
// 在没有 Windows 的机器上**一条都测不到**。
- newCodec func(*frameSource) (aacCodec, error)
+ newCodec func(*frameSource) (aacCodec, error)
+ keepsPriming bool
// buf 是解出来还没交出去的 PCM(交织),head 是下一个要交出去的采样。
buf []float32
@@ -86,11 +85,7 @@ type Decoder struct {
pos int64
// skip 是还要丢掉多少个采样(每声道)才轮到交出去。
//
- // ⚠️ **它只有一个来源:seek**(跳过去的那一段)。
- //
- // 它**不是**容器的 `EncoderDelay`——解码器的输出本来就从呈现音频的开头起
- //(解码器自己吞掉了它输出的第一帧,也就是编码器的预热),按 `EncoderDelay`
- // 再丢一遍就是丢了两遍。理由见 `Open` 里那段。
+ // 跳转时丢弃预滚,保留首帧的后端也用它裁掉 MP4 的编码器预热。
skip int
// drained 记着「已经 drain 过了」——流读完只 drain 一次。
drained bool
@@ -116,6 +111,10 @@ func Open(r io.ReadSeeker) (*Decoder, error) {
if err := platformAvailable(); err != nil {
return nil, err
}
+ return open(r, openCodec, codecKeepsPriming)
+}
+
+func open(r io.ReadSeeker, newCodec func(*frameSource) (aacCodec, error), keepsPriming bool) (*Decoder, error) {
start, err := r.Seek(0, io.SeekCurrent)
if err != nil {
return nil, err
@@ -130,7 +129,17 @@ func Open(r io.ReadSeeker) (*Decoder, error) {
}
return nil, err
}
- codec, err := openCodec(src)
+ var skip int
+ if keepsPriming && src.payloadType == aacPayloadRaw {
+ skip, err = src.seek(0, keepsPriming)
+ if err != nil {
+ if _, serr := r.Seek(start, io.SeekStart); serr != nil {
+ return nil, errors.Join(err, serr)
+ }
+ return nil, err
+ }
+ }
+ codec, err := newCodec(src)
if err != nil {
if _, serr := r.Seek(start, io.SeekStart); serr != nil {
return nil, errors.Join(err, serr)
@@ -138,29 +147,14 @@ func Open(r io.ReadSeeker) (*Decoder, error) {
return nil, err
}
return &Decoder{
- src: src,
- codec: codec,
- newCodec: openCodec,
- rate: codec.SampleRate(),
- chans: codec.Channels(),
- total: src.total,
- // ⚠️ **这里不丢容器的 `EncoderDelay`**——丢两遍就把音频挪早了。
- //
- // 理由(issue #128 的评审 + 本仓库量过的数):**解码器的输出本来就从
- // 呈现音频的开头起**。AAC 的 MDCT 是有重叠的,解码器**自己吞掉**第一帧
- // 那半个重叠(那一帧是「不完整的」,也就是编码器的预热),所以:
- //
- // - 原始输出 = 173 帧 = 177152 个采样,**正好等于** ffmpeg 解同一份
- // .m4a 的结果(`fixture_test.go` 的 `refFrames`);
- // - macOS 的 AudioToolbox 给 176400 帧,而它和参考 WAV 的**前 176400
- // 个采样**逐样本对齐(平均差 29/32768、最大 2313/32768)。
- //
- // 也就是说:那 1024 个预热采样**根本不在解码输出里**。再按
- // `EncoderDelay` 丢一遍,就等于**凭空砍掉 1024 个真实采样**:音频比
- // 参考晚 23 毫秒,而且比容器说的呈现长度少 272 个采样。
- //
- // 详见 `mfadec/decoder_test.go` 的 `TestTheDecoderDoesNotDropTheEncoderDelayTwice`。
- skip: 0,
+ src: src,
+ codec: codec,
+ newCodec: newCodec,
+ keepsPriming: keepsPriming,
+ rate: codec.SampleRate(),
+ chans: codec.Channels(),
+ total: src.total,
+ skip: skip,
}, nil
}
@@ -180,7 +174,7 @@ func (d *Decoder) Channels() int { return d.chans }
// 进度条),扫完把游标拨回原处,解码不受影响。
func (d *Decoder) Len() int64 {
if d.total < 0 && d.src.measure != nil {
- d.total = d.src.measure()
+ d.total = d.src.measure(d.keepsPriming)
}
return d.total
}
@@ -333,12 +327,18 @@ func (d *Decoder) SetPosition(frame int64) error {
if d.total >= 0 && frame > d.total {
return fmt.Errorf("mfadec: frame %d 超出 [0, %d]: %w", frame, d.total, ErrSeekRange)
}
- skip, err := d.src.seek(frame)
+ if d.total >= 0 && frame == d.total {
+ d.pos = frame
+ d.atEnd = true
+ return nil
+ }
+ codec, err := d.newCodec(d.src)
if err != nil {
return err
}
- codec, err := d.newCodec(d.src)
+ skip, err := d.src.seek(frame, d.keepsPriming)
if err != nil {
+ codec.Close()
return err
}
d.codec.Close()
diff --git a/internal/service/audio/mfadec/decoder_test.go b/internal/service/audio/mfadec/decoder_test.go
index 12edf4b6..32326120 100644
--- a/internal/service/audio/mfadec/decoder_test.go
+++ b/internal/service/audio/mfadec/decoder_test.go
@@ -22,6 +22,7 @@ import (
"bytes"
"errors"
"io"
+ "slices"
"testing"
)
@@ -121,6 +122,20 @@ func (c *fakeCodec) SampleRate() int { return c.rate }
func (c *fakeCodec) Channels() int { return c.chans }
func (c *fakeCodec) Close() error { c.closed++; return nil }
+type primingCodec struct {
+ fakeCodec
+ frameIndex map[string]int
+}
+
+func (c *primingCodec) Feed(frame []byte) ([]float32, error) {
+ index := c.frameIndex[string(frame)]
+ pcm := make([]float32, c.perFrame*c.chans)
+ for sample := range pcm {
+ pcm[sample] = float32(index*len(pcm) + sample)
+ }
+ return pcm, nil
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// 工具
// ─────────────────────────────────────────────────────────────────────────────
@@ -350,6 +365,65 @@ func TestTheDecoderCountsHowLongTheADTSStreamIs(t *testing.T) {
}
}
+// TestKeepingThePrimingFramePreservesPresentation verifies length and sample-accurate seeks with a codec that outputs every access unit.
+func TestKeepingThePrimingFramePreservesPresentation(t *testing.T) {
+ for _, fixture := range []struct {
+ name string
+ first int
+ length int64
+ }{
+ {name: "aaclc-stereo.m4a", first: fakeUnitLen, length: 176400},
+ {name: "aaclc-stereo.aac", length: 178176},
+ } {
+ t.Run(fixture.name, func(t *testing.T) {
+ data := readFixture(t, fixture.name)
+ src, err := openFrameSource(bytes.NewReader(data))
+ if err != nil {
+ t.Fatal(err)
+ }
+ frameIndex := make(map[string]int)
+ for index := 0; ; index++ {
+ frame, err := src.next()
+ if errors.Is(err, io.EOF) {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ frameIndex[string(frame)] = index
+ }
+ factory := func(src *frameSource) (aacCodec, error) {
+ return &primingCodec{
+ fakeCodec: fakeCodec{rate: src.rate, chans: src.chans, perFrame: fakeUnitLen},
+ frameIndex: frameIndex,
+ }, nil
+ }
+ decoder, err := open(bytes.NewReader(data), factory, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { decoder.Close() })
+ if got := decoder.Len(); got != fixture.length {
+ t.Fatalf("length = %d, want %d", got, fixture.length)
+ }
+ all := readAll(t, decoder)
+ chans := decoder.Channels()
+ if len(all) != int(fixture.length)*chans || all[0] != float32(fixture.first*chans) {
+ t.Fatalf("decoded %d samples, want %d with first sample %d", len(all), int(fixture.length)*chans, fixture.first*chans)
+ }
+ for _, frame := range []int64{fixture.length, fakeUnitLen - 1, fakeUnitLen + 9, fixture.length - 1, 0} {
+ if err := decoder.SetPosition(frame); err != nil {
+ t.Fatalf("seek to %d: %v", frame, err)
+ }
+ got := readAll(t, decoder)
+ if !slices.Equal(got, all[int(frame)*chans:]) {
+ t.Errorf("seek to %d: remaining samples differ from sequential decode", frame)
+ }
+ }
+ })
+ }
+}
+
// TestTheContainerIsRecognizedByItsHeader 断「认容器按头几个字节,而且不认错」。
//
// ⚠️ **MP3 认成 ADTS 是最危险的一种认错**:两者都以 `FF` 开头,只断前 12 个
diff --git a/internal/service/audio/mfadec/open_android.go b/internal/service/audio/mfadec/open_android.go
new file mode 100644
index 00000000..8251e623
--- /dev/null
+++ b/internal/service/audio/mfadec/open_android.go
@@ -0,0 +1,238 @@
+//go:build android && cgo
+
+package mfadec
+
+/*
+#cgo LDFLAGS: -lmediandk
+#include
+
+static const char *aac_mime = "audio/mp4a-latm";
+enum { pcm_16_bit = 2 };
+
+static AMediaCodec *create_aac_decoder(void) {
+ return AMediaCodec_createDecoderByType(aac_mime);
+}
+
+static media_status_t configure_aac_decoder(AMediaCodec *codec, int rate, int channels,
+ const void *asc, size_t asc_size, bool adts) {
+ AMediaFormat *format = AMediaFormat_new();
+ if (format == NULL) {
+ return AMEDIA_ERROR_UNKNOWN;
+ }
+ AMediaFormat_setString(format, AMEDIAFORMAT_KEY_MIME, aac_mime);
+ AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, rate);
+ AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, channels);
+ AMediaFormat_setInt32(format, "pcm-encoding", pcm_16_bit);
+ AMediaFormat_setBuffer(format, "csd-0", asc, asc_size);
+ if (adts) {
+ AMediaFormat_setInt32(format, AMEDIAFORMAT_KEY_IS_ADTS, 1);
+ }
+ media_status_t status = AMediaCodec_configure(codec, format, NULL, NULL, 0);
+ AMediaFormat_delete(format);
+ return status;
+}
+
+static bool get_pcm_format(AMediaCodec *codec, int32_t *rate, int32_t *channels, int32_t *encoding) {
+ AMediaFormat *format = AMediaCodec_getOutputFormat(codec);
+ if (format == NULL) {
+ return false;
+ }
+ bool ok = AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_SAMPLE_RATE, rate) &&
+ AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_CHANNEL_COUNT, channels);
+ if (!AMediaFormat_getInt32(format, "pcm-encoding", encoding)) {
+ *encoding = pcm_16_bit;
+ }
+ AMediaFormat_delete(format);
+ return ok;
+}
+*/
+import "C"
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "time"
+ "unsafe"
+)
+
+const (
+ codecKeepsPriming = true
+ codecWaitTimeout = 2 * time.Second
+)
+
+type androidCodec struct {
+ codec *C.AMediaCodec
+ rate, chans int
+ unitLen int
+ queuedFrames int64
+ pcm []float32
+}
+
+func platformAvailable() error { return nil }
+
+func openCodec(src *frameSource) (aacCodec, error) {
+ if src.rate <= 0 || src.chans <= 0 || len(src.asc) == 0 {
+ return nil, fmt.Errorf("mfadec: Android AAC: invalid input format: %w", ErrFormat)
+ }
+ codec := C.create_aac_decoder()
+ if codec == nil {
+ return nil, fmt.Errorf("mfadec: Android AAC: MediaCodec could not create a decoder: %w", ErrUnsupported)
+ }
+ status := C.configure_aac_decoder(codec, C.int(src.rate), C.int(src.chans),
+ unsafe.Pointer(&src.asc[0]), C.size_t(len(src.asc)), C.bool(src.payloadType == aacPayloadADTS))
+ if status != C.AMEDIA_OK {
+ C.AMediaCodec_delete(codec)
+ return nil, fmt.Errorf("mfadec: Android AAC: configure: MediaCodec status %d", status)
+ }
+ if status := C.AMediaCodec_start(codec); status != C.AMEDIA_OK {
+ C.AMediaCodec_delete(codec)
+ return nil, fmt.Errorf("mfadec: Android AAC: start: MediaCodec status %d", status)
+ }
+ return &androidCodec{codec: codec, rate: src.rate, chans: src.chans, unitLen: src.unitLen}, nil
+}
+
+func (c *androidCodec) SampleRate() int { return c.rate }
+
+func (c *androidCodec) Channels() int { return c.chans }
+
+func (c *androidCodec) Close() error {
+ if c.codec == nil {
+ return nil
+ }
+ status := C.AMediaCodec_delete(c.codec)
+ c.codec = nil
+ if status != C.AMEDIA_OK {
+ return fmt.Errorf("mfadec: Android AAC: release decoder: MediaCodec status %d", status)
+ }
+ return nil
+}
+
+func (c *androidCodec) Feed(frame []byte) ([]float32, error) {
+ return c.process(frame, false)
+}
+
+func (c *androidCodec) Drain() ([]float32, error) {
+ return c.process(nil, true)
+}
+
+func (c *androidCodec) process(frame []byte, drain bool) ([]float32, error) {
+ c.pcm = c.pcm[:0]
+ inputDeadline := time.Now().Add(codecWaitTimeout)
+ for {
+ remaining := min(time.Until(inputDeadline), 10*time.Millisecond)
+ if remaining <= 0 {
+ return nil, errors.New("mfadec: Android AAC: timed out waiting for a MediaCodec input buffer")
+ }
+ index := C.AMediaCodec_dequeueInputBuffer(c.codec, C.int64_t(remaining.Microseconds()))
+ if index >= 0 {
+ if err := c.queueInput(C.size_t(index), frame, drain); err != nil {
+ return nil, err
+ }
+ if err := c.pullOutput(drain); err != nil {
+ return nil, err
+ }
+ return c.pcm, nil
+ }
+ if index != C.AMEDIACODEC_INFO_TRY_AGAIN_LATER {
+ return nil, fmt.Errorf("mfadec: Android AAC: dequeue input: MediaCodec status %d", index)
+ }
+ if err := c.pullOutput(false); err != nil {
+ return nil, err
+ }
+ }
+}
+
+func (c *androidCodec) queueInput(index C.size_t, frame []byte, drain bool) error {
+ var flags C.uint32_t
+ if drain {
+ flags = C.AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM
+ } else {
+ var capacity C.size_t
+ input := C.AMediaCodec_getInputBuffer(c.codec, index, &capacity)
+ if input == nil || C.size_t(len(frame)) > capacity {
+ return fmt.Errorf("mfadec: Android AAC: input buffer cannot hold a %d-byte frame", len(frame))
+ }
+ copy(unsafe.Slice((*byte)(unsafe.Pointer(input)), len(frame)), frame)
+ }
+ pts := C.uint64_t(c.queuedFrames * int64(time.Second/time.Microsecond) / int64(c.rate))
+ status := C.AMediaCodec_queueInputBuffer(c.codec, index, 0, C.size_t(len(frame)), pts, flags)
+ if status != C.AMEDIA_OK {
+ return fmt.Errorf("mfadec: Android AAC: queue input: MediaCodec status %d", status)
+ }
+ c.queuedFrames += int64(c.unitLen)
+ return nil
+}
+
+func (c *androidCodec) pullOutput(drain bool) error {
+ deadline := time.Now().Add(codecWaitTimeout)
+ for {
+ var wait C.int64_t
+ if drain {
+ remaining := time.Until(deadline)
+ if remaining <= 0 {
+ return errors.New("mfadec: Android AAC: timed out waiting for MediaCodec end of stream")
+ }
+ wait = C.int64_t(remaining.Microseconds())
+ }
+ var info C.AMediaCodecBufferInfo
+ index := C.AMediaCodec_dequeueOutputBuffer(c.codec, &info, wait)
+ switch {
+ case index >= 0:
+ if err := c.readOutput(C.size_t(index), &info); err != nil {
+ return err
+ }
+ if info.flags&C.AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM != 0 {
+ if !drain {
+ return errors.New("mfadec: Android AAC: unexpected MediaCodec end of stream")
+ }
+ return nil
+ }
+ case index == C.AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED:
+ if err := c.checkOutputFormat(); err != nil {
+ return err
+ }
+ case index == C.AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED:
+ case index == C.AMEDIACODEC_INFO_TRY_AGAIN_LATER:
+ if !drain {
+ return nil
+ }
+ default:
+ return fmt.Errorf("mfadec: Android AAC: dequeue output: MediaCodec status %d", index)
+ }
+ }
+}
+
+func (c *androidCodec) checkOutputFormat() error {
+ var rate, chans, encoding C.int32_t
+ if !C.get_pcm_format(c.codec, &rate, &chans, &encoding) {
+ return errors.New("mfadec: Android AAC: MediaCodec did not report its output format")
+ }
+ if int(rate) != c.rate || int(chans) != c.chans || encoding != C.pcm_16_bit {
+ return fmt.Errorf("mfadec: Android AAC: unexpected PCM format: %d Hz, %d channels, encoding %d (want %d Hz, %d channels, 16-bit PCM)",
+ rate, chans, encoding, c.rate, c.chans)
+ }
+ return nil
+}
+
+func (c *androidCodec) readOutput(index C.size_t, info *C.AMediaCodecBufferInfo) error {
+ var readErr error
+ size := int(info.size)
+ if size != 0 && info.flags&C.AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG == 0 {
+ // API 21–35 only reports a valid byte count in AMediaCodecBufferInfo.size.
+ output := C.AMediaCodec_getOutputBuffer(c.codec, index, nil)
+ if output == nil || size < 0 || size%(2*c.chans) != 0 {
+ readErr = fmt.Errorf("mfadec: Android AAC: invalid %d-byte MediaCodec PCM buffer", size)
+ } else {
+ pcm := unsafe.Slice((*byte)(unsafe.Pointer(output)), size)
+ for sample := 0; sample < len(pcm); sample += 2 {
+ c.pcm = append(c.pcm, float32(int16(binary.LittleEndian.Uint16(pcm[sample:])))/32768)
+ }
+ }
+ }
+ status := C.AMediaCodec_releaseOutputBuffer(c.codec, index, false)
+ if status != C.AMEDIA_OK {
+ return errors.Join(readErr, fmt.Errorf("mfadec: Android AAC: release output buffer: MediaCodec status %d", status))
+ }
+ return readErr
+}
diff --git a/internal/service/audio/mfadec/open_other.go b/internal/service/audio/mfadec/open_other.go
index 10c04809..8a3adf92 100644
--- a/internal/service/audio/mfadec/open_other.go
+++ b/internal/service/audio/mfadec/open_other.go
@@ -1,20 +1,21 @@
-//go:build !windows || (!amd64 && !arm64)
+//go:build (!windows || (!amd64 && !arm64)) && (!android || !cgo)
package mfadec
// 其它平台这一半:**没有**解码器。
//
-// Media Foundation 是 Windows 自带的系统组件,别的地方没有对应的东西。所以
-// 这一层在 macOS 上只提供「认容器」的能力(`openFrameSource` 是平台无关的,
-// 在 macOS 上照样能测),解码那一步一律报「这个平台没有」。
+// Windows 和开启 cgo 的 Android 分别有自己的系统解码器。这里在其余构建中
+// 只提供平台无关的拆帧能力。
//
// ⚠️ 报的是 `ErrUnsupported` 而不是 `ErrFormat`:前者是「这台机器没这个
// 能力」,后者是「这个文件不对」。上层(`internal/service/audio` 的
// `openDecoder`)靠这个分别决定要不要落回别的解码器——把「没能力」说成
// 「文件坏了」,用户看到的就是一句假话。
-// platformAvailable 报「这个平台有没有 Media Foundation」。
+// platformAvailable 报「这个构建有没有 AAC 后端」。
func platformAvailable() error { return ErrUnsupported }
+const codecKeepsPriming = false
+
// openCodec 开解码器。其它平台上没有解码器可开。
func openCodec(src *frameSource) (aacCodec, error) { return nil, ErrUnsupported }
diff --git a/internal/service/audio/mfadec/open_windows.go b/internal/service/audio/mfadec/open_windows.go
index c27aa05f..a11e823d 100644
--- a/internal/service/audio/mfadec/open_windows.go
+++ b/internal/service/audio/mfadec/open_windows.go
@@ -2,6 +2,8 @@
package mfadec
+const codecKeepsPriming = false
+
// Windows 这一半:解码器是 Media Foundation 的 AAC MFT。
//
// 这里是**唯一**碰平台的地方。`decoder.go` 那一层只看得见 `aacCodec` 这
diff --git a/internal/service/audio/mfadec/source.go b/internal/service/audio/mfadec/source.go
index 3f877a3b..fcdc3a20 100644
--- a/internal/service/audio/mfadec/source.go
+++ b/internal/service/audio/mfadec/source.go
@@ -77,19 +77,14 @@ type frameSource struct {
//
// 只有裸 ADTS 用得上:它没有容器,没有长度可读,而「不知道有多长」在
// 界面上的表现是**进度条没有长度**(`Player.Duration()` 返回 0)。
- measure func() int64
+ measure func(keepsPriming bool) int64
// next 拿下一帧。
next func() ([]byte, error)
// seek 把源挪到含第 sample 个采样(每声道,**从呈现出来的音频算起**)的
// 那一帧,并报「从那一帧的开头起,要丢掉多少个采样(每声道)」。
//
- // ⚠️ **「sample」是解码器输出的坐标**,而解码器**吞掉了它输出的第一帧**
- //(MDCT 重叠不完整的冷启动帧 = 编码器的预热)——所以输出的第 0 个采样在
- // 码流的第 1 帧里。
- //
- // 实现会**往回退一帧**再解:解码器会吞掉**它输出的第一帧**,所以退一帧
- // 之后它交出来的第一帧正好是目标所在的那一帧(**一退一吞,抵掉**)。
- seek func(sample int64) (int, error)
+ // 实现会从目标前一帧开始解码,保留冷启动帧的后端需把这一帧计入丢弃量。
+ seek func(sample int64, keepsPriming bool) (int, error)
}
// openFrameSource 认出 r 是哪一种容器,拆成帧源。
@@ -173,7 +168,7 @@ func openM4A(r io.ReadSeeker) (*frameSource, error) {
total: presentedFrames(info.Duration, info.SampleRate),
next: rd.ReadFrame,
}
- src.seek = func(sample int64) (int, error) {
+ src.seek = func(sample int64, keepsPriming bool) (int, error) {
d := time.Duration(sample) * time.Second / time.Duration(info.SampleRate)
idx, off, err := rd.SeekTime(d)
if err != nil {
@@ -183,16 +178,12 @@ func openM4A(r io.ReadSeeker) (*frameSource, error) {
// 目标就在第一帧里:没有前一帧可以退。
return int(off), nil
}
- // 往回退一帧:解码器**自己会吞掉**它输出的第一帧(那一帧是 MDCT
- // 重叠不完整的「冷启动」帧,也就是编码器的预热),所以退一帧之后,
- // 解码器交出来的第一帧正好是目标所在的那一帧。
- //
- // ⚠️ **退一帧 + 解码器吞一帧 = 一帧不多一帧不少**。多退一帧的话,
- // 跳过去的位置会**早 1024 个采样**(23 毫秒)——肉耳听不出来,
- // 但拖进度条之后听到的位置和界面上写的差了一拍。
if err := rd.SeekSample(idx - 1); err != nil {
return 0, fmt.Errorf("mfadec: 跳到第 %d 帧:%w", sample, err)
}
+ if keepsPriming {
+ off += int64(unitLen)
+ }
return int(off), nil
}
return src, nil
@@ -245,7 +236,7 @@ func openADTS(r io.ReadSeeker) (*frameSource, error) {
//
// 它要**从头扫一遍**(ADTS 没有索引表),扫完把游标拨回原处——所以扫完
// 之后解码还能接着往下走。
-func (s *adtsSource) measure() int64 {
+func (s *adtsSource) measure(keepsPriming bool) int64 {
pos, err := s.r.Seek(0, io.SeekCurrent)
if err != nil {
return -1
@@ -266,10 +257,10 @@ func (s *adtsSource) measure() int64 {
if frames == 0 {
return -1
}
- // ⚠️ **减一帧**:解码器**吞掉了它输出的第一帧**(MDCT 重叠不完整的冷启动
- // 帧 = 编码器的预热),那一帧不属于呈现出来的音频。数帧数的是码流里的帧,
- // 呈现出来的比它少一帧。
- return (frames - 1) * int64(aacUnitLen)
+ if !keepsPriming {
+ frames--
+ }
+ return frames * int64(aacUnitLen)
}
// next 拿下一帧。
@@ -290,23 +281,22 @@ func (s *adtsSource) next() ([]byte, error) {
//
// ADTS 里**没有**采样索引:每一帧都是 1024 个采样(按 AAC-LC 算),所以
// 第几帧是算得出来的。代价是要**从头再扫一遍**——ADTS 没有索引表可查。
-func (s *adtsSource) seek(sample int64) (int, error) {
+func (s *adtsSource) seek(sample int64, keepsPriming bool) (int, error) {
if sample < 0 {
return 0, fmt.Errorf("mfadec: 跳到第 %d 帧:%w", sample, ErrSeekRange)
}
- // ⚠️ **「第 sample 个采样」是解码器输出的坐标**,而解码器**吞掉了它输出的
- // 第一帧**(MDCT 重叠不完整的冷启动帧 = 编码器的预热)。所以输出的第 0 个
- // 采样在**码流的第 1 帧**里——坐标差一帧。
skip := int(sample % int64(aacUnitLen))
- unit := int(sample/int64(aacUnitLen)) + 1
+ unit := sample / int64(aacUnitLen)
+ if keepsPriming && unit > 0 {
+ unit--
+ skip += aacUnitLen
+ }
// 拨回开头。
if _, err := s.r.Seek(s.start, io.SeekStart); err != nil {
return 0, fmt.Errorf("mfadec: 跳到第 %d 帧:%w", sample, err)
}
s.pend = nil
- // 停在目标帧的**前一帧**:解码器会吞掉它输出的第一帧(冷启动帧),
- // 所以退一帧之后,解码器交出来的第一帧正好是目标所在的那一帧。
- for i := 0; i < unit-1; i++ {
+ for i := int64(0); i < unit; i++ {
if _, _, err := readADTSFrame(s.r); err != nil {
return 0, fmt.Errorf("mfadec: 跳到第 %d 帧:%w", sample, err)
}
diff --git a/internal/service/audio/player.go b/internal/service/audio/player.go
index 9a49b580..d19c5670 100644
--- a/internal/service/audio/player.go
+++ b/internal/service/audio/player.go
@@ -178,15 +178,14 @@ func OpenStream(r CloserReadSeeker) (*Player, error) {
// 2. 认不出来(`ErrFormat`)就试 `flacdec`——那是**本地裸 `.flac` 文件**的
// 路子,而 MyGo 的表是对字面量做匹配的,没法给变长的 magic(`fLaC` +
// STREAMINFO)注册一条。
-// 3. **平台解码器不可用**(`extaf.ErrUnsupported`)就试 **Media
-// Foundation**(`mfadec`)——那是 Windows 自带的 AAC 解码器,B 站有损流
-// (`.m4a` / `.m4s`)和本地 `.aac` 都是它解的。
+// 3. **AudioToolbox 不可用**(`extaf.ErrUnsupported`)就试 `mfadec`:Windows
+// 用 Media Foundation、Android 用 MediaCodec 解 MP4 中的 AAC 和裸 ADTS。
// 4. 还是不行就试 `flacdec`——它解 MP4 里的 FLAC(`flacdec/mp4.go`:B 站
// 无损流的那种形状)。不落回的话,Windows 上 B 站在线音频**一档都放不出
// 来**:MP4 家族先被格式表认成 mp4,交给 `extaf` 拿到 `ErrUnsupported`,
// 而 `ErrUnsupported` 不是 `ErrFormat`,于是这里就直接返回错误了。
//
-// ⚠️ **第 3 步和第 4 步的顺序是有讲究的**:Media Foundation 只解 AAC,
+// ⚠️ **第 3 步和第 4 步的顺序是有讲究的**:`mfadec` 只解 AAC,
// `flacdec` 只解 FLAC,两边认的是**不同的容器内容**,所以谁先谁后都行。
// 但**落回的前提是「这个平台没有解码器」**:`extaf` 报别的错(文件坏了、
// AudioToolbox 打不开)时**不落回**——那是「这个文件解不了」,落回只会把它
@@ -198,7 +197,7 @@ func OpenStream(r CloserReadSeeker) (*Player, error) {
// `internal/service/bili/testdata/lossless/`。
//
// ⚠️ **第 3 步会读整个 MP4**:`mfadec` 用 `go-m4a` 拆帧,而 `go-m4a` 要先知道
-// 这个流有多长、还要把每一个顶层盒子走一遍——所以在 Windows 上打开一条
+// 这个流有多长、还要把每一个顶层盒子走一遍——所以在 Windows 和 Android 上打开一条
// **在线**流会等它**整个下完**才开口(`flacdec` 的 MP4 那条路也一样)。
// macOS 上没有这个问题:那条路走 AudioToolbox,它是按需读的。
//
@@ -225,25 +224,13 @@ func openDecoder(r io.ReadSeeker) (mygoaudio.Decoder, string, error) {
// audio format」就是靠 `errors.Is` 判的。
return nil, "", fmt.Errorf("%w: %w", ErrUnsupportedFormat, err)
}
- // mfErr 是 Media Foundation 那边的真实原因。
- //
- // ⚠️ **它必须进最终那句错**:Windows 上**有**系统解码器(Media
- // Foundation),只是它解不了这一个文件(比如 E-AC-3、比如 ALAC)。只报
- // 「这台机器没有系统解码器」的话,用户看到的是一句**假话**——而真实
- // 原因(「这个 MP4 里不是 AAC」)才是他能拿去做决定的。
- var mfErr error
+ var aacErr error
if errors.Is(err, extaf.ErrUnsupported) {
- // 这台机器没有 AudioToolbox。Windows 上它有 Media Foundation,
- // 它解 AAC(B 站有损流、本地 `.m4a`、裸 `.aac`)。
- //
- // ⚠️ 认不出来的时候**不要往下走**:Media Foundation 认不出的 MP4
- // (比如里面装的是 FLAC)应该交给 `flacdec`,而它和「这不是 AAC」
- // 是两回事——所以这里只把「成了」当成功。
- md, merr := mediaFoundationDecoderOpen(r)
+ md, merr := systemAACDecoderOpen(r)
if merr == nil {
return md, "aac", nil
}
- mfErr = merr
+ aacErr = merr
}
fd, ferr := flacdec.Open(r)
if ferr != nil {
@@ -256,18 +243,11 @@ func openDecoder(r io.ReadSeeker) (mygoaudio.Decoder, string, error) {
// 比 flacdec 的那句「不像 FLAC」有用得多——后者会让人以为
// 文件损坏,而它可能只是一段还没下到的字节。
if errors.Is(err, extaf.ErrUnsupported) {
- // ⚠️ 这一条要**三句**一起报:没有 AudioToolbox、Media Foundation
- // 的真实原因、这也不像 FLAC。
- //
- // 只报一句的话,界面上会出现「文件坏了」这种**其实不是**的提示——
- // 而把 Media Foundation 的原因漏掉更糟:Windows 上明明有系统
- // 解码器,界面上却说「没有」。
- //
// 🔴 **外面还包一层 `ErrUnsupportedFormat`**(票 #282):界面上那句
// 要说的是「这个格式解不了」,而这一长串是给日志和诊断看的。
- if mfErr != nil {
+ if aacErr != nil {
return nil, "", fmt.Errorf("%w: %w: %w: %w", ErrUnsupportedFormat,
- extaf.ErrUnsupported, mfErr, ferr)
+ extaf.ErrUnsupported, aacErr, ferr)
}
return nil, "", fmt.Errorf("%w: %w: %w", ErrUnsupportedFormat,
extaf.ErrUnsupported, ferr)
diff --git a/internal/service/bili/comment.go b/internal/service/bili/comment.go
index aa2d4e8b..c518dd5e 100644
--- a/internal/service/bili/comment.go
+++ b/internal/service/bili/comment.go
@@ -341,7 +341,8 @@ type Comment struct {
// RCount 是这条评论下的**楼中楼条数**(不含「查看更多回复」那几层)。
RCount int64
// Like 是点赞数。
- Like int64
+ Like int64
+ Liked bool `json:"-"`
// Ctime 是发表时间(Unix 秒)。
Ctime int64
@@ -495,6 +496,7 @@ type commentReply struct {
Count int64 `json:"count"`
RCount int64 `json:"rcount"`
Like int64 `json:"like"`
+ Action int `json:"action"`
Ctime int64 `json:"ctime"`
Member struct {
@@ -548,6 +550,7 @@ type commentSubReplyData struct {
// 主发的」就靠它**(理由见 `Comment.IsUpper`)。
func (r commentReply) toComment(upperMid int64) Comment {
c := Comment{
+ Liked: r.Action == 1,
Rpid: r.Rpid,
Mid: r.Mid,
Root: r.Root,
diff --git a/internal/service/bili/comment_write.go b/internal/service/bili/comment_write.go
new file mode 100644
index 00000000..88c90bc4
--- /dev/null
+++ b/internal/service/bili/comment_write.go
@@ -0,0 +1,44 @@
+package bili
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+)
+
+func (c *Client) AddComment(ctx context.Context, kind, object, root, parent int64, message string) error {
+ message = strings.TrimSpace(message)
+ if message == "" || root < 0 || parent < 0 || (root == 0) != (parent == 0) {
+ return errors.New("请输入有效的评论内容")
+ }
+ return c.writeComment(ctx, "/x/v2/reply/add", kind, object, url.Values{
+ "message": {message}, "plat": {"1"},
+ "root": {strconv.FormatInt(root, 10)}, "parent": {strconv.FormatInt(parent, 10)},
+ })
+}
+
+func (c *Client) LikeComment(ctx context.Context, kind, object, reply int64, liked bool) error {
+ if reply <= 0 {
+ return errors.New("评论不存在")
+ }
+ action := "0"
+ if liked {
+ action = "1"
+ }
+ return c.writeComment(ctx, "/x/v2/reply/action", kind, object, url.Values{
+ "rpid": {strconv.FormatInt(reply, 10)}, "action": {action},
+ })
+}
+
+func (c *Client) writeComment(ctx context.Context, path string, kind, object int64, form url.Values) error {
+ if object <= 0 || kind != CommentTypeVideo && kind != CommentTypeAudio {
+ return errors.New("这首歌没有评论区")
+ }
+ form.Set("type", strconv.FormatInt(kind, 10))
+ form.Set("oid", strconv.FormatInt(object, 10))
+ _, err := c.Do(ctx, Call{Method: http.MethodPost, URL: c.hostAPI + path, Form: form, CSRF: true})
+ return err
+}
diff --git a/internal/service/bili/comment_write_test.go b/internal/service/bili/comment_write_test.go
new file mode 100644
index 00000000..7182a28e
--- /dev/null
+++ b/internal/service/bili/comment_write_test.go
@@ -0,0 +1,37 @@
+package bili
+
+import (
+ "net/http"
+ "testing"
+)
+
+// TestCommentWritesKeepTheReplyTarget verifies that replies and likes use the selected comment and video.
+func TestCommentWritesKeepTheReplyTarget(t *testing.T) {
+ fixture := newFakeBili(t)
+ for _, test := range []struct {
+ path string
+ form map[string]string
+ }{
+ {"/x/v2/reply/add", map[string]string{"root": "20", "parent": "21", "message": "测试回复"}},
+ {"/x/v2/reply/action", map[string]string{"rpid": "21", "action": "0"}},
+ } {
+ fixture.on(test.path, func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.PostForm.Get("type") != "1" || r.PostForm.Get("oid") != "77" {
+ t.Errorf("unexpected comment target: %s %v", r.Method, r.PostForm)
+ }
+ for key, value := range test.form {
+ if got := r.PostForm.Get(key); got != value {
+ t.Errorf("%s = %q, want %q", key, got, value)
+ }
+ }
+ writeJSON(w, jsonData(t, 0, "0", nil))
+ })
+ }
+ client := fixture.client(t, Options{})
+ if err := client.AddComment(t.Context(), CommentTypeVideo, 77, 20, 21, " 测试回复 "); err != nil {
+ t.Fatal(err)
+ }
+ if err := client.LikeComment(t.Context(), CommentTypeVideo, 77, 21, false); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/service/bili/login.go b/internal/service/bili/login.go
index 9afa155b..e07ebaeb 100644
--- a/internal/service/bili/login.go
+++ b/internal/service/bili/login.go
@@ -177,6 +177,13 @@ type ScanResult struct {
LoggedInAt time.Time
}
+func (c *Client) NewLoginClient() *Client {
+ login := NewClient(Options{Transport: c.http.Transport, UserAgent: c.ua, Referer: c.referer, Now: c.now, OnRequest: c.onReq})
+ login.hostAPI, login.hostPassport, login.hostMember = c.hostAPI, c.hostPassport, c.hostMember
+ login.hostWWW, login.hostSearch, login.sessionBase = c.hostWWW, c.hostSearch, c.sessionBase
+ return login
+}
+
// PollScan 问一次「这张二维码扫得怎么样了」。
//
// **这是协议层**:它只发一次请求就返回,不循环、不等。
diff --git a/internal/service/video/open_android.go b/internal/service/video/open_android.go
new file mode 100644
index 00000000..93616c13
--- /dev/null
+++ b/internal/service/video/open_android.go
@@ -0,0 +1,236 @@
+//go:build android && cgo
+
+package video
+
+/*
+#cgo LDFLAGS: -lmediandk
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+typedef struct {
+ AMediaExtractor *extractor;
+ AMediaCodec *codec;
+ AImageReader *reader;
+} Decoder;
+
+static void close_decoder(Decoder *decoder) {
+ if (decoder->codec) AMediaCodec_delete(decoder->codec);
+ if (decoder->reader) AImageReader_delete(decoder->reader);
+ if (decoder->extractor) AMediaExtractor_delete(decoder->extractor);
+ free(decoder);
+}
+
+static Decoder *open_decoder(const char *path) {
+ Decoder *decoder = calloc(1, sizeof(Decoder));
+ if (!decoder) return NULL;
+ decoder->extractor = AMediaExtractor_new();
+ int file = open(path, O_RDONLY | O_CLOEXEC);
+ struct stat metadata;
+ bool source_ready = decoder->extractor && file >= 0 && fstat(file, &metadata) == 0 &&
+ AMediaExtractor_setDataSourceFd(decoder->extractor, file, 0, metadata.st_size) == AMEDIA_OK;
+ if (file >= 0) close(file);
+ if (!source_ready) {
+ close_decoder(decoder);
+ return NULL;
+ }
+ for (size_t index = 0; index < AMediaExtractor_getTrackCount(decoder->extractor); ++index) {
+ AMediaFormat *format = AMediaExtractor_getTrackFormat(decoder->extractor, index);
+ if (!format) continue;
+ const char *mime;
+ int32_t width, height;
+ bool usable = AMediaFormat_getString(format, AMEDIAFORMAT_KEY_MIME, &mime) &&
+ strncmp(mime, "video/", 6) == 0 &&
+ AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_WIDTH, &width) &&
+ AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_HEIGHT, &height) &&
+ width > 0 && height > 0;
+ if (!usable) {
+ AMediaFormat_delete(format);
+ continue;
+ }
+ ANativeWindow *surface = NULL;
+ bool ready = AMediaExtractor_selectTrack(decoder->extractor, index) == AMEDIA_OK &&
+ AImageReader_new(width, height, AIMAGE_FORMAT_YUV_420_888, 2, &decoder->reader) == AMEDIA_OK &&
+ AImageReader_getWindow(decoder->reader, &surface) == AMEDIA_OK;
+ if (ready) decoder->codec = AMediaCodec_createDecoderByType(mime);
+ ready = decoder->codec && AMediaCodec_configure(decoder->codec, format, surface, NULL, 0) == AMEDIA_OK &&
+ AMediaCodec_start(decoder->codec) == AMEDIA_OK;
+ AMediaFormat_delete(format);
+ if (ready) return decoder;
+ break;
+ }
+ close_decoder(decoder);
+ return NULL;
+}
+
+static int push_sample(Decoder *decoder) {
+ ssize_t slot = AMediaCodec_dequeueInputBuffer(decoder->codec, 0);
+ if (slot < 0) return slot == AMEDIACODEC_INFO_TRY_AGAIN_LATER ? 0 : -1;
+ size_t capacity;
+ uint8_t *buffer = AMediaCodec_getInputBuffer(decoder->codec, slot, &capacity);
+ if (!buffer) return -1;
+ ssize_t count = AMediaExtractor_readSampleData(decoder->extractor, buffer, capacity);
+ if (count < 0) {
+ return AMediaCodec_queueInputBuffer(decoder->codec, slot, 0, 0, 0, AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM) == AMEDIA_OK ? 2 : -1;
+ }
+ if ((size_t)count > capacity || AMediaCodec_queueInputBuffer(decoder->codec, slot, 0, count,
+ AMediaExtractor_getSampleTime(decoder->extractor), 0) != AMEDIA_OK) return -1;
+ AMediaExtractor_advance(decoder->extractor);
+ return 1;
+}
+
+typedef struct {
+ uint8_t *data;
+ int length, row, pixel;
+} Plane;
+
+static bool plane_data(AImage *image, int index, Plane *plane) {
+ return AImage_getPlaneData(image, index, &plane->data, &plane->length) == AMEDIA_OK &&
+ AImage_getPlaneRowStride(image, index, &plane->row) == AMEDIA_OK &&
+ AImage_getPlanePixelStride(image, index, &plane->pixel) == AMEDIA_OK &&
+ plane->length > 0 && plane->row > 0 && plane->pixel > 0;
+}
+
+static uint8_t color_byte(int value) {
+ return value < 0 ? 0 : value > 255 ? 255 : (uint8_t)value;
+}
+
+static bool copy_image(AImage *image, AImageCropRect crop, uint8_t *rgba) {
+ Plane y, u, v;
+ if (!plane_data(image, 0, &y) || !plane_data(image, 1, &u) || !plane_data(image, 2, &v)) return false;
+ int right = crop.right - 1, bottom = crop.bottom - 1;
+ if ((int64_t)bottom*y.row + (int64_t)right*y.pixel >= y.length ||
+ (int64_t)(bottom/2)*u.row + (int64_t)(right/2)*u.pixel >= u.length ||
+ (int64_t)(bottom/2)*v.row + (int64_t)(right/2)*v.pixel >= v.length) return false;
+ for (int row = crop.top; row < crop.bottom; ++row) {
+ for (int col = crop.left; col < crop.right; ++col) {
+ int light = 298 * (y.data[row*y.row + col*y.pixel] - 16);
+ int cb = u.data[(row/2)*u.row + (col/2)*u.pixel] - 128;
+ int cr = v.data[(row/2)*v.row + (col/2)*v.pixel] - 128;
+ rgba[0] = color_byte((light + 459*cr + 128) >> 8);
+ rgba[1] = color_byte((light - 55*cb - 136*cr + 128) >> 8);
+ rgba[2] = color_byte((light + 541*cb + 128) >> 8);
+ rgba[3] = 255;
+ rgba += 4;
+ }
+ }
+ return true;
+}
+*/
+import "C"
+
+import (
+ "errors"
+ "time"
+ "unsafe"
+)
+
+const supported = true
+
+func Open(path string, pool BufferPool) (*Source, error) {
+ name := C.CString(path)
+ decoder := C.open_decoder(name)
+ C.free(unsafe.Pointer(name))
+ if decoder == nil {
+ return nil, errors.New("video: Android 无法打开视频轨")
+ }
+ source := newSource(pool)
+ go source.decodeAndroid(decoder)
+ return source, nil
+}
+
+func (s *Source) decodeAndroid(decoder *C.Decoder) {
+ defer close(s.done)
+ defer close(s.frames)
+ defer C.close_decoder(decoder)
+ inputEnded := false
+ deadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(deadline) {
+ select {
+ case <-s.quit:
+ return
+ default:
+ }
+ if !inputEnded {
+ pushed := C.push_sample(decoder)
+ if pushed < 0 {
+ s.fail(errors.New("video: Android 无法读取视频样本"))
+ return
+ }
+ inputEnded = pushed == 2
+ }
+ var info C.AMediaCodecBufferInfo
+ slot := C.AMediaCodec_dequeueOutputBuffer(decoder.codec, &info, 10000)
+ if slot < 0 {
+ switch slot {
+ case C.AMEDIACODEC_INFO_TRY_AGAIN_LATER, C.AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED, C.AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED:
+ continue
+ default:
+ s.fail(errors.New("video: Android 视频解码失败"))
+ return
+ }
+ }
+ end := info.flags&C.AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM != 0
+ render := info.size > 0 && info.flags&C.AMEDIACODEC_BUFFER_FLAG_CODEC_CONFIG == 0
+ if C.AMediaCodec_releaseOutputBuffer(decoder.codec, C.size_t(slot), C.bool(render)) != C.AMEDIA_OK {
+ s.fail(errors.New("video: Android 无法输出视频画面"))
+ return
+ }
+ if render && !s.readAndroidFrame(decoder.reader, time.Duration(info.presentationTimeUs)*time.Microsecond) {
+ return
+ }
+ if end {
+ return
+ }
+ deadline = time.Now().Add(3 * time.Second)
+ }
+ s.fail(errors.New("video: Android 视频解码超时"))
+}
+
+func (s *Source) readAndroidFrame(reader *C.AImageReader, pts time.Duration) bool {
+ var frame *C.AImage
+ deadline := time.NewTimer(500 * time.Millisecond)
+ defer deadline.Stop()
+ retry := time.NewTicker(2 * time.Millisecond)
+ defer retry.Stop()
+ for C.AImageReader_acquireNextImage(reader, &frame) != C.AMEDIA_OK {
+ select {
+ case <-s.quit:
+ return false
+ case <-deadline.C:
+ s.fail(errors.New("video: Android 视频画面读取超时"))
+ return false
+ case <-retry.C:
+ }
+ }
+ defer C.AImage_delete(frame)
+ var crop C.AImageCropRect
+ if C.AImage_getCropRect(frame, &crop) != C.AMEDIA_OK || crop.left < 0 || crop.top < 0 || crop.right <= crop.left || crop.bottom <= crop.top {
+ s.fail(errors.New("video: Android 视频画面尺寸无效"))
+ return false
+ }
+ width, height := int(crop.right-crop.left), int(crop.bottom-crop.top)
+ pixels, err := s.acquire(int64(width) * int64(height) * 4)
+ if err != nil {
+ s.fail(err)
+ return false
+ }
+ if !C.copy_image(frame, crop, (*C.uint8_t)(unsafe.Pointer(&pixels[0]))) {
+ s.Recycle(pixels)
+ s.fail(errors.New("video: Android 视频画面格式无效"))
+ return false
+ }
+ select {
+ case s.frames <- Frame{PTS: pts, W: width, H: height, Pix: pixels}:
+ return true
+ case <-s.quit:
+ s.Recycle(pixels)
+ return false
+ }
+}
diff --git a/internal/service/video/open_other.go b/internal/service/video/open_other.go
index 1d64a6c1..df3d99ed 100644
--- a/internal/service/video/open_other.go
+++ b/internal/service/video/open_other.go
@@ -1,4 +1,4 @@
-//go:build !darwin
+//go:build !darwin && (!android || !cgo)
package video
diff --git a/internal/service/video/supported_other.go b/internal/service/video/supported_other.go
index 0fa2283a..c6456f1c 100644
--- a/internal/service/video/supported_other.go
+++ b/internal/service/video/supported_other.go
@@ -1,4 +1,4 @@
-//go:build !darwin
+//go:build !darwin && (!android || !cgo)
package video
diff --git a/internal/ui/danmaku_mount_test.go b/internal/ui/danmaku_mount_test.go
index cf14e5af..2cc331a8 100644
--- a/internal/ui/danmaku_mount_test.go
+++ b/internal/ui/danmaku_mount_test.go
@@ -78,7 +78,7 @@ func TestMountDanmakuIsWiredBeforeTheWindow(t *testing.T) {
if mount < 0 {
t.Fatalf("bootstrap.go 里没有 ui.MountDanmaku 的默认装配")
}
- assemble := strings.Index(mainText, "bootstrap.Assemble(bootstrap.DefaultDependencies())")
+ assemble := strings.Index(mainText, "bootstrap.Assemble(platformDependencies())")
if assemble < 0 {
t.Fatalf("main.go 里没有通过 bootstrap.Assemble 启动")
}
diff --git a/internal/ui/fullplayer_danmaku.go b/internal/ui/fullplayer_danmaku.go
index 85c6b06f..87c56ff0 100644
--- a/internal/ui/fullplayer_danmaku.go
+++ b/internal/ui/fullplayer_danmaku.go
@@ -123,7 +123,10 @@ func (s *Shell) drawFullDanmaku(c *ui.Context, st app.State, area ui.Rect) {
// 时间索引和窗口二分仍然是 #647 交付的那一份(`d.itemsByTime` + `sort.Search`,
// 见 `danmakuLayer.rewind`)——这一票没有重新实现它,只是不再每帧都二分。
func (s *Shell) paintDanmaku(p *ui.Painter, r ui.Rect) {
- d := &s.full.danmaku
+ s.full.danmaku.paint(p, r, s.presence.seen())
+}
+
+func (d *danmakuLayer) paint(p *ui.Painter, r ui.Rect, visible bool) {
if !d.ready || len(d.itemsByTime) == 0 {
return
}
@@ -174,8 +177,23 @@ func (s *Shell) paintDanmaku(p *ui.Painter, r ui.Rect) {
// 没开减动效 那个偏好下不逐帧重画(位置仍旧跟着整窗重建走)
// 窗口看得见 失焦/最小化时框架自己不管,链子会在绘制路径里续下去
// (票 #156,和波形、频谱、播放条那根线同一条纪律)
- if d.playing && d.animate && s.presence.seen() {
+ if d.playing && d.animate && visible {
d.requests++
p.AnimationFrame()
}
}
+
+type VideoDanmaku struct {
+ layer danmakuLayer
+}
+
+func (d *VideoDanmaku) Draw(c *ui.Context, surface ui.Element, state app.State, items []app.DanmakuItem, width, height float32) {
+ if len(items) == 0 || width <= 0 || height <= 0 {
+ d.Reset()
+ return
+ }
+ d.layer.sync(c, state, items, ui.Rect{W: width, H: height})
+ surface.DrawOver(func(painter *ui.Painter, bounds ui.Rect) { d.layer.paint(painter, bounds, true) })
+}
+
+func (d *VideoDanmaku) Reset() { d.layer.reset() }
diff --git a/internal/ui/lyrics_test.go b/internal/ui/lyrics_test.go
index 22502740..91827b00 100644
--- a/internal/ui/lyrics_test.go
+++ b/internal/ui/lyrics_test.go
@@ -1446,7 +1446,7 @@ func TestMountLyricsIsWiredBeforeTheWindow(t *testing.T) {
if strings.Index(bootstrapText, "MountLyrics: ui.MountLyrics") < 0 {
t.Fatalf("bootstrap.go 里没有 ui.MountLyrics 的默认装配")
}
- if strings.Index(mainText, "bootstrap.Assemble(bootstrap.DefaultDependencies())") < 0 {
+ if strings.Index(mainText, "bootstrap.Assemble(platformDependencies())") < 0 {
t.Fatalf("main.go 里没有通过 bootstrap.Assemble 启动")
}
if strings.Index(bootstrapText, "d.MountLyrics(a)") < 0 {
diff --git a/internal/ui/notch_darwin.go b/internal/ui/notch_darwin.go
index 1b392e96..0a01a1c1 100644
--- a/internal/ui/notch_darwin.go
+++ b/internal/ui/notch_darwin.go
@@ -1,4 +1,4 @@
-//go:build darwin
+//go:build darwin && !ios
package ui
diff --git a/internal/ui/notch_other.go b/internal/ui/notch_other.go
index d94421b0..fd3ca2a2 100644
--- a/internal/ui/notch_other.go
+++ b/internal/ui/notch_other.go
@@ -1,4 +1,4 @@
-//go:build !darwin
+//go:build !darwin || ios
package ui
diff --git a/main.go b/main.go
index 8695cf8d..bfe63fa8 100644
--- a/main.go
+++ b/main.go
@@ -48,7 +48,7 @@ func main() {
log.Printf("pudmusic: 接不上崩溃日志,崩溃堆栈只在 stderr 上:%v", err)
}
- if _, err := bootstrap.Assemble(bootstrap.DefaultDependencies()); err != nil {
+ if _, err := bootstrap.Assemble(platformDependencies()); err != nil {
log.Fatal(err)
}
}
diff --git a/main_test.go b/main_test.go
index f784ff4a..d28d8808 100644
--- a/main_test.go
+++ b/main_test.go
@@ -8,28 +8,53 @@ import (
)
func TestMainDelegatesApplicationAssemblyToBootstrap(t *testing.T) {
- f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
+ calls := functionCalls(t, "main.go", "main")
+ if !containsCall(calls, "bootstrap.Assemble") || !containsCall(calls, "platformDependencies") {
+ t.Fatalf("main does not delegate to bootstrap.Assemble with platform dependencies: %v", calls)
+ }
+ for file, want := range map[string]string{
+ "entry_desktop.go": "bootstrap.DefaultDependencies",
+ "entry_mobile.go": "bootstrap.MobileDependencies",
+ } {
+ if calls := functionCalls(t, file, "platformDependencies"); !containsCall(calls, want) {
+ t.Fatalf("%s does not use %s: %v", file, want, calls)
+ }
+ }
+ for _, name := range calls {
+ if name == "app.New" || name == "platform.PinUserDataDir" || name == "ui.MountSettings" || name == "ui.Run" {
+ t.Fatalf("main owns application assembly call %s; keep assembly in bootstrap: %v", name, calls)
+ }
+ }
+}
+
+func functionCalls(t *testing.T, path, name string) []string {
+ t.Helper()
+ f, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
if err != nil {
- t.Fatalf("parse main.go: %v", err)
+ t.Fatalf("parse %s: %v", path, err)
}
- var mainFn *ast.FuncDecl
+ var body *ast.BlockStmt
for _, decl := range f.Decls {
fn, ok := decl.(*ast.FuncDecl)
- if ok && fn.Name.Name == "main" {
- mainFn = fn
+ if ok && fn.Name.Name == name {
+ body = fn.Body
break
}
}
- if mainFn == nil {
- t.Fatal("main.go has no func main")
+ if body == nil {
+ t.Fatalf("%s has no func %s", path, name)
}
var calls []string
- ast.Inspect(mainFn.Body, func(node ast.Node) bool {
+ ast.Inspect(body, func(node ast.Node) bool {
call, ok := node.(*ast.CallExpr)
if !ok {
return true
}
+ if id, ok := call.Fun.(*ast.Ident); ok {
+ calls = append(calls, id.Name)
+ return true
+ }
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
@@ -41,17 +66,7 @@ func TestMainDelegatesApplicationAssemblyToBootstrap(t *testing.T) {
return true
})
- if !containsCall(calls, "bootstrap.Assemble") {
- t.Fatalf("main does not delegate to bootstrap.Assemble: %v", calls)
- }
- if !containsCall(calls, "bootstrap.DefaultDependencies") {
- t.Fatalf("main does not use production bootstrap dependencies: %v", calls)
- }
- for _, name := range calls {
- if name == "app.New" || name == "platform.PinUserDataDir" || name == "ui.MountSettings" || name == "ui.Run" {
- t.Fatalf("main owns application assembly call %s; keep assembly in bootstrap: %v", name, calls)
- }
- }
+ return calls
}
func containsCall(calls []string, want string) bool {
diff --git a/mygo.json b/mygo.json
index 9d68ad26..d21cb5ee 100644
--- a/mygo.json
+++ b/mygo.json
@@ -29,6 +29,18 @@
]
}
},
+ "ios": {
+ "infoPlist": {
+ "LSSupportsOpeningDocumentsInPlace": false,
+ "CFBundleDocumentTypes": [
+ {
+ "CFBundleTypeName": "音频文件",
+ "CFBundleTypeRole": "Viewer",
+ "LSItemContentTypes": ["public.audio"]
+ }
+ ]
+ }
+ },
"windows": {
"installerInclude": "resources/windows/fileassoc.nsh"
},
diff --git a/resources/licenses/THIRD-PARTY-NOTICES.txt b/resources/licenses/THIRD-PARTY-NOTICES.txt
index 519348e7..3666225a 100644
--- a/resources/licenses/THIRD-PARTY-NOTICES.txt
+++ b/resources/licenses/THIRD-PARTY-NOTICES.txt
@@ -58,7 +58,7 @@
github.com/Eyevinn/mp4ff v0.62.0 MIT github.com-Eyevinn-mp4ff-LICENSE.txt
github.com/ebitengine/purego v0.11.3 Apache-2.0 github.com-ebitengine-purego-LICENSE.txt
-github.com/egoist/mygo v0.9.1 MIT github.com-egoist-mygo-LICENSE.txt
+github.com/egoist/mygo v0.10.0 MIT github.com-egoist-mygo-LICENSE.txt
github.com/go-text/typesetting v0.3.5 Unlicense OR BSD-3-Clause github.com-go-text-typesetting-LICENSE.txt
github.com/icza/bitio v1.1.0 Apache-2.0 github.com-icza-bitio-LICENSE.txt
github.com/jfreymuth/oggvorbis v1.0.5 MIT github.com-jfreymuth-oggvorbis-LICENSE.txt