Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions entry_desktop.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
//go:build !ios && !android

package main

import "github.com/ShellMonster/PudMusic/internal/bootstrap"

func platformDependencies() bootstrap.Dependencies {
return bootstrap.DefaultDependencies()
}
12 changes: 12 additions & 0 deletions entry_mobile.go
Original file line number Diff line number Diff line change
@@ -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)
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
73 changes: 42 additions & 31 deletions internal/app/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -86,13 +87,25 @@ type LoginState struct {
Err string
// LoggedIn 是此刻有没有登录态。登录成功后为 true。
LoggedIn bool
qrURL string
}

// Busy 报登录流程是不是还在跑。
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 风控),太慢用户会干等。
Expand All @@ -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 掐掉,
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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 认的形式。
Expand Down Expand Up @@ -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++
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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 // 用户取消了,这不是错误
Expand All @@ -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()
Expand All @@ -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
Expand All @@ -467,15 +484,15 @@ 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
}
}
}
}

// 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
Expand All @@ -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)
Expand All @@ -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):
// 用户在这中间退了登。**什么都不写**,安静收工——
Expand All @@ -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,
Expand Down Expand Up @@ -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 站那边把这个会话也作废,**然后**再清本地的。
//
Expand All @@ -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
}
Expand Down
15 changes: 11 additions & 4 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -986,6 +986,8 @@ type App struct {
// ⚠️ **它让进度条不必靠整树重建来走**:没有这一栏时,界面只能从 `State`
// 里拿到建树那一刻的位置,于是「让那根线往前走」只能靠每 50ms 重建整棵树。
playPositionNS atomic.Int64
playbackIntent atomic.Uint64
beforePlayback func() bool
// danmakuSeq 是**在途序号**。每发起一趟取弹幕就加一(**不管是哪一集**)。
//
// 🔴 **它挡的是「同一个 key 上慢的那一趟把新的盖掉」**:代次
Expand Down Expand Up @@ -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 是「打开一个本地文件」时的那一档。
//
Expand Down Expand Up @@ -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)。
Expand All @@ -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()
Expand All @@ -1756,7 +1762,7 @@ func (a *App) Toggle() {
if p.Playing() {
p.Pause()
} else {
p.Play()
a.startPlayer(p)
}

a.mu.Lock()
Expand Down Expand Up @@ -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()
}
Expand All @@ -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 不跑,界面下一帧读的就是这里写的值。
Expand Down
13 changes: 8 additions & 5 deletions internal/app/collection.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,8 @@ type CollectionRef struct {
ID int64
// Type 是哪一类容器。
Type bili.CollectionType
// OwnerMid 是来源已知的合集或系列创建者。
OwnerMid int64
}

// Key 是这一份状态属于哪个容器。界面拿它认出「换容器了,该重建了」。
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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` 参数。合集 / 系列
// 里按歌名找是把这一页筛掉吗?不——**本地筛不能筛没拉下来的页**(理由见
Expand Down Expand Up @@ -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)
Expand Down
Loading