diff --git a/.github/scripts/select-simulator.py b/.github/scripts/select-simulator.py
new file mode 100644
index 0000000..df7cc49
--- /dev/null
+++ b/.github/scripts/select-simulator.py
@@ -0,0 +1,19 @@
+import json
+import os
+import subprocess
+
+def simctl(*args):
+ return json.loads(subprocess.check_output(["xcrun", "simctl", "list", *args, "--json"]))
+
+runtimes = simctl("runtimes")["runtimes"]
+eligible = {r["identifier"] for r in runtimes if r.get("isAvailable") and r["name"].startswith("iOS") and tuple(map(int, r["version"].split("."))) >= (26, 5)}
+devices = simctl("devices", "available")["devices"]
+for runtime in sorted(eligible, reverse=True):
+ phones = [d for d in devices.get(runtime, []) if d["name"].startswith("iPhone")]
+ if phones:
+ with open(os.environ["GITHUB_ENV"], "a") as f:
+ f.write("SIMULATOR_ID=" + phones[0]["udid"] + "\n")
+ print("Using", runtime, phones[0]["name"])
+ break
+else:
+ raise SystemExit("No available iOS >=26.5 iPhone simulator")
diff --git a/.github/workflows/ios-validation.yml b/.github/workflows/ios-validation.yml
new file mode 100644
index 0000000..b15415b
--- /dev/null
+++ b/.github/workflows/ios-validation.yml
@@ -0,0 +1,57 @@
+name: iOS Build and Tests
+on:
+ push:
+ branches: ['codex/**']
+ pull_request:
+ workflow_dispatch:
+permissions:
+ contents: read
+concurrency:
+ group: ios-${{ github.ref }}
+ cancel-in-progress: true
+jobs:
+ verify:
+ runs-on: macos-26
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v4
+ - name: Select Xcode
+ run: sudo xcode-select -s /Applications/Xcode_26.6.app/Contents/Developer
+ - name: Resolve dependencies
+ run: xcodebuild -resolvePackageDependencies -project PiliPod.xcodeproj -scheme PiliPod -clonedSourcePackagesDirPath build/Packages
+ - name: Build unsigned device app
+ run: |
+ set -o pipefail
+ xcodebuild build -project PiliPod.xcodeproj -scheme PiliPod -configuration Debug \
+ -destination 'generic/platform=iOS' -derivedDataPath build/Device \
+ -clonedSourcePackagesDirPath build/Packages CODE_SIGNING_ALLOWED=NO \
+ 2>&1 | tee build/device-build.log | xcbeautify
+ - name: Select simulator
+ run: python3 .github/scripts/select-simulator.py
+ - name: Run unit tests
+ run: |
+ set -o pipefail
+ xcodebuild test -project PiliPod.xcodeproj -scheme PiliPod -configuration Debug \
+ -destination "platform=iOS Simulator,id=$SIMULATOR_ID" \
+ -derivedDataPath build/Simulator -clonedSourcePackagesDirPath build/Packages \
+ -resultBundlePath build/Tests.xcresult CODE_SIGNING_ALLOWED=NO \
+ 2>&1 | tee build/tests.log | xcbeautify
+ - name: Upload diagnostics
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: ios-validation
+ path: |
+ build/*.log
+ build/Tests.xcresult
+ if-no-files-found: ignore
+ - name: Package unsigned IPA
+ run: |
+ mkdir -p build/Payload
+ cp -R build/Device/Build/Products/Debug-iphoneos/PiliPod.app build/Payload/
+ cd build
+ zip -qr PiliPod-unsigned.ipa Payload
+ - uses: actions/upload-artifact@v4
+ with:
+ name: PiliPod-unsigned
+ path: build/PiliPod-unsigned.ipa
diff --git a/PiliPod.xcodeproj/xcshareddata/xcschemes/PiliPod.xcscheme b/PiliPod.xcodeproj/xcshareddata/xcschemes/PiliPod.xcscheme
new file mode 100644
index 0000000..f1404ee
--- /dev/null
+++ b/PiliPod.xcodeproj/xcshareddata/xcschemes/PiliPod.xcscheme
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/PiliPod/Auth/BiliAuthService.swift b/PiliPod/Auth/BiliAuthService.swift
index 81bd6aa..8bf47b1 100644
--- a/PiliPod/Auth/BiliAuthService.swift
+++ b/PiliPod/Auth/BiliAuthService.swift
@@ -2,6 +2,28 @@ import CryptoKit
import Foundation
import Security
+struct BiliQRCode {
+ let url: String
+ let authCode: String
+ let expiresIn: Int
+}
+
+enum BiliQRPollStatus {
+ case waiting(String), expired, login(BiliLoginStatus)
+}
+
+enum BiliSMSSendStatus {
+ case sent(String), captcha(BiliPreCaptchaData), failed(String)
+}
+
+struct BiliLoginCountry: Identifiable, Hashable {
+ let id: Int
+ let name: String
+ let dialCode: String
+ var callingCode: Int { Int(dialCode) ?? 0 }
+ static let china = BiliLoginCountry(id: 1, name: "中国大陆", dialCode: "86")
+}
+
// MARK: - 1. 严格的 RFC3986 编码器
extension String {
@@ -76,9 +98,180 @@ public class BiliAuthService {
private let appSecret = "b5475a8825547a4fc26c7d518eaaa02e"
private let config = BiliDeviceConfig.shared
- public init() {}
+ private let session: URLSession
+ public init(session: URLSession? = nil) {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.httpShouldSetCookies = false
+ configuration.httpCookieStorage = nil
+ configuration.urlCache = nil
+ self.session = session ?? URLSession(configuration: configuration)
+ }
+
+ func countries() async throws -> [BiliLoginCountry] {
+ let request = URLRequest(url: URL(string: "https://passport.bilibili.com/web/generic/country/list")!)
+ let json = try await authJSON(request)
+ guard json["code"] as? Int == 0, let payload = json["data"] as? [String: Any] else {
+ throw authError("获取地区列表失败")
+ }
+ let rows = (payload["common"] as? [[String: Any]] ?? []) + (payload["others"] as? [[String: Any]] ?? [])
+ var seen = Set()
+ return rows.compactMap { row in
+ guard let id = row["id"] as? Int, let name = row["cname"] as? String,
+ let code = row["country_id"], seen.insert(id).inserted else { return nil }
+ return BiliLoginCountry(id: id, name: name, dialCode: String(describing: code))
+ }
+ }
+
+ func generateQRCode() async throws -> BiliQRCode {
+ let json = try await postAuth("/x/passport-tv-login/qrcode/auth_code", parameters:
+ ["local_id": "0", "platform": config.platform, "mobi_app": config.mobiApp], inQuery: true)
+ guard json["code"] as? Int == 0, let payload = json["data"] as? [String: Any],
+ let url = payload["url"] as? String, let code = payload["auth_code"] as? String,
+ URL(string: url)?.scheme == "https", !code.isEmpty else { throw authError("获取二维码失败") }
+ return BiliQRCode(url: url, authCode: code, expiresIn: min(max(payload["expires_in"] as? Int ?? 180, 1), 600))
+ }
+
+ func pollQRCode(_ authCode: String) async throws -> BiliQRPollStatus {
+ let json = try await postAuth("/x/passport-tv-login/qrcode/poll", parameters: ["auth_code": authCode, "local_id": "0"], inQuery: true)
+ switch json["code"] as? Int {
+ case 0: return .login(await loginStatus(json))
+ case 86038: return .expired
+ case 86039, 86090: return .waiting(json["message"] as? String ?? "等待扫码确认")
+ default: throw authError(json["message"] as? String ?? "扫码登录失败")
+ }
+ }
+
+ func sendLoginSMS(phone: String, countryID: Int,
+ captcha: (result: GeetestValidateResult, token: String)? = nil) async throws -> BiliSMSSendStatus {
+ var params = deviceParameters()
+ params["tel"] = phone
+ params["cid"] = String(countryID)
+ let seed = config.buvid + String(Int(Date().timeIntervalSince1970 * 1000))
+ params["login_session_id"] = Insecure.MD5.hash(data: Data(seed.utf8)).map { String(format: "%02x", $0) }.joined()
+ if let captcha {
+ params["gee_challenge"] = captcha.result.challenge
+ params["gee_validate"] = captcha.result.validate
+ params["gee_seccode"] = captcha.result.seccode
+ params["recaptcha_token"] = captcha.token
+ }
+ let json = try await postAuth("/x/passport-login/sms/send", parameters: params)
+ let payload = json["data"] as? [String: Any] ?? [:]
+ let rawURL = payload["recaptcha_url"] as? String ?? ""
+ if json["code"] as? Int == 0, rawURL.isEmpty,
+ let key = payload["captcha_key"] as? String, !key.isEmpty { return .sent(key) }
+ if !rawURL.isEmpty || json["code"] as? Int == -105 {
+ let items = URLComponents(string: rawURL)?.queryItems ?? []
+ let token = items.first { $0.name == "recaptcha_token" }?.value ?? ""
+ let gt = items.first { $0.name == "gee_gt" }?.value ?? ""
+ let challenge = items.first { $0.name == "gee_challenge" }?.value ?? ""
+ if !token.isEmpty, !gt.isEmpty, !challenge.isEmpty {
+ return .captcha(BiliPreCaptchaData(recaptchaToken: token, gt: gt, challenge: challenge))
+ }
+ return .captcha(try await preCapture().get())
+ }
+ return .failed(json["message"] as? String ?? "短信发送失败")
+ }
+
+ func loginBySMS(phone: String, countryID: Int, code: String, captchaKey: String) async -> BiliLoginStatus {
+ do {
+ let key = try await fetchOAuth2Key()
+ var params = deviceParameters()
+ params.merge(["tel": phone, "cid": String(countryID), "code": code, "captcha_key": captchaKey,
+ "bili_local_id": config.deviceId, "device_id": config.deviceId, "device": config.device,
+ "device_name": config.deviceName, "device_platform": config.devicePlatform,
+ "dt": try rsaEncrypt(payload: generateRandomString(length: 16), publicKeyPEM: key.key).biliUrlEncoded(),
+ "from_pv": "main.my-information.my-login.0.click",
+ "from_url": "bilibili://user_center/mine".biliUrlEncoded()], uniquingKeysWith: { _, new in new })
+ let json = try await postAuth("/x/passport-login/login/sms", parameters: params)
+ return await loginStatus(json)
+ } catch { return .failed(code: -1, message: "短信登录请求失败,请重试") }
+ }
+
+ static func parseCookie(_ text: String) throws -> BiliAccount {
+ guard !text.contains("\r"), !text.contains("\n") else { throw AccountStorageError.invalidAccount }
+ var cookies: [String: String] = [:]
+ for part in text.split(separator: ";", omittingEmptySubsequences: true) {
+ let pair = part.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
+ guard pair.count == 2 else { throw AccountStorageError.invalidAccount }
+ let name = pair[0].trimmingCharacters(in: .whitespaces)
+ let value = pair[1].trimmingCharacters(in: .whitespaces)
+ guard !name.isEmpty, cookies[name] == nil else { throw AccountStorageError.invalidAccount }
+ cookies[name] = value
+ }
+ guard let uid = cookies["DedeUserID"] else { throw AccountStorageError.invalidAccount }
+ let payload: [String: Any] = [uid: ["cookies": cookies]]
+ return try LoginImportService.decode(JSONSerialization.data(withJSONObject: payload))[0]
+ }
+
+ func validateCookie(_ text: String) async throws -> BiliAccount {
+ var account = try Self.parseCookie(text)
+ account.username = try await fetchAccountName(account)
+ return account
+ }
+
+ func fetchAccountName(_ account: BiliAccount) async throws -> String {
+ var request = URLRequest(url: URL(string: "https://api.bilibili.com/x/web-interface/nav")!)
+ AccountRequest.apply(account, to: &request)
+ let json = try await authJSON(request)
+ guard json["code"] as? Int == 0, let payload = json["data"] as? [String: Any],
+ payload["isLogin"] as? Bool == true,
+ let mid = payload["mid"] as? NSNumber, mid.stringValue == account.id else {
+ throw authError("Cookie 已失效或 UID 不匹配")
+ }
+ guard let name = payload["uname"] as? String, !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ throw authError("无法获取账号用户名")
+ }
+ return name
+ }
+
+ private func deviceParameters() -> [String: String] {
+ ["build": config.build, "buvid": config.buvid, "local_id": config.buvid,
+ "c_locale": "zh_CN", "s_locale": "zh_CN", "channel": "master", "disable_rcmd": "0",
+ "mobi_app": config.mobiApp, "platform": config.platform, "statistics": config.statistics]
+ }
+ private func postAuth(_ path: String, parameters: [String: String], inQuery: Bool = false) async throws -> [String: Any] {
+ var params = parameters
+ params["appkey"] = appKey
+ params["ts"] = String(Int(Date().timeIntervalSince1970))
+ params["sign"] = generateSign(for: params)
+ let body = makeOrderedBodyString(from: params)
+ var request = URLRequest(url: URL(string: "https://passport.bilibili.com" + path + (inQuery ? "?" + body : ""))!)
+ request.httpMethod = "POST"
+ request.httpShouldHandleCookies = false
+ request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
+ request.setValue(config.userAgent, forHTTPHeaderField: "User-Agent")
+ request.setValue(config.buvid, forHTTPHeaderField: "buvid")
+ request.setValue("android_hd", forHTTPHeaderField: "app-key")
+ request.setValue("prod", forHTTPHeaderField: "env")
+ request.setValue(makeTraceId(), forHTTPHeaderField: "x-bili-trace-id")
+ request.setValue("cronet", forHTTPHeaderField: "bili-http-engine")
+ if !inQuery { request.httpBody = Data(body.utf8) }
+ return try await authJSON(request)
+ }
+ private func authJSON(_ request: URLRequest) async throws -> [String: Any] {
+ var request = request
+ request.httpShouldHandleCookies = false
+ let (data, response) = try await session.data(for: request)
+ guard let response = response as? HTTPURLResponse, (200...299).contains(response.statusCode),
+ let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ throw authError("登录服务器响应无效")
+ }
+ return json
+ }
+ private func loginStatus(_ json: [String: Any]) async -> BiliLoginStatus {
+ let payload = json["data"] as? [String: Any] ?? [:]
+ guard json["code"] as? Int == 0 else {
+ return .failed(code: json["code"] as? Int ?? -1, message: json["message"] as? String ?? "登录失败")
+ }
+ if payload["status"] as? Int == 2 { return await makeNeedPhoneVerifyStatus(payload: payload, fallbackMessage: "需要安全验证") }
+ return .success(data: payload)
+ }
+ private func authError(_ message: String) -> NSError {
+ NSError(domain: "BiliAuth", code: -1, userInfo: [NSLocalizedDescriptionKey: message])
+ }
@discardableResult
+ @MainActor
public func persistLogin(data: [String: Any]) -> Bool {
let accessToken = (data["access_token"] as? String)
?? ((data["token_info"] as? [String: Any])?["access_token"] as? String)
@@ -109,15 +302,17 @@ public class BiliAuthService {
bili_jct: biliJct,
DedeUserID: dedeUserID,
sid: cookieDict["sid"],
- buvid3: cookieDict["buvid3"] ?? BiliDeviceConfig.shared.buvid
+ buvid3: cookieDict["buvid3"] ?? BiliDeviceConfig.shared.buvid,
+ extraCookies: cookieDict
)
- LoginSession.shared.cookies = cookie
- LoginSession.shared.accessKey = accessToken
- LoginSession.shared.refresh = refreshToken
- LoginSession.shared.type = nil
- LoginSession.shared.isLogin = true
- LoginImportService.saveToLocal(cookie)
+ do {
+ try LoginSession.shared.add([BiliAccount(cookies: cookie, accessKey: accessToken,
+ refresh: refreshToken, type: nil)])
+ } catch {
+ ErrorLogService.record(error, context: "保存登录信息")
+ return false
+ }
return true
}
@@ -198,7 +393,7 @@ public class BiliAuthService {
let bodyString = makeOrderedBodyString(from: params)
request.httpBody = bodyString.data(using: .utf8)
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
// 8. 处理返回结果
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
@@ -258,7 +453,7 @@ public class BiliAuthService {
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = makeOrderedBodyString(from: params).data(using: .utf8)
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let code = json["code"] as? Int, code == 0,
let resData = json["data"] as? [String: Any],
@@ -350,7 +545,7 @@ public class BiliAuthService {
request.httpBody = makeOrderedBodyString(from: params).data(using: .utf8)
do {
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return .failure(NSError(domain: "Auth", code: -2001, userInfo: [NSLocalizedDescriptionKey: "preCapture 解析失败"]))
}
@@ -399,7 +594,7 @@ public class BiliAuthService {
request.httpBody = makeOrderedBodyString(from: params).data(using: .utf8)
do {
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return .failure(NSError(domain: "Auth", code: -2002, userInfo: [NSLocalizedDescriptionKey: "发送短信解析失败"]))
}
@@ -445,7 +640,7 @@ public class BiliAuthService {
request.httpBody = makeOrderedBodyString(from: params).data(using: .utf8)
do {
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return .failure(NSError(domain: "Auth", code: -2003, userInfo: [NSLocalizedDescriptionKey: "短信验证解析失败"]))
}
@@ -488,16 +683,13 @@ public class BiliAuthService {
request.setValue("android_hd", forHTTPHeaderField: "app-key")
request.setValue(makeTraceId(), forHTTPHeaderField: "x-bili-trace-id")
request.setValue("cronet", forHTTPHeaderField: "bili-http-engine")
- print(makeOrderedBodyString(from: params))
request.httpBody = makeOrderedBodyString(from: params).data(using: .utf8)
do {
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
return .failed(code: -2004, message: "access_token 解析失败")
}
- print(String(data: data, encoding: .utf8))
- print(json)
let retCode = json["code"] as? Int ?? -2004
let msg = json["message"] as? String ?? "未知错误"
if retCode == 0 {
@@ -530,7 +722,7 @@ public class BiliAuthService {
request.setValue(config.userAgent, forHTTPHeaderField: "User-Agent")
do {
- let (data, _) = try await URLSession.shared.data(for: request)
+ let (data, _) = try await session.data(for: request)
guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let code = json["code"] as? Int, code == 0,
let info = json["data"] as? [String: Any],
diff --git a/PiliPod/Auth/BiliCookie.swift b/PiliPod/Auth/BiliCookie.swift
index 2f12f46..8941c37 100644
--- a/PiliPod/Auth/BiliCookie.swift
+++ b/PiliPod/Auth/BiliCookie.swift
@@ -13,4 +13,15 @@ struct BiliCookie: Codable {
let DedeUserID: String
let sid: String?
let buvid3: String?
+ var extraCookies: [String: String]? = nil
+
+ var dictionary: [String: String] {
+ var result = extraCookies ?? [:]
+ result["SESSDATA"] = SESSDATA
+ result["bili_jct"] = bili_jct
+ result["DedeUserID"] = DedeUserID
+ result["sid"] = sid
+ result["buvid3"] = buvid3
+ return result
+ }
}
diff --git a/PiliPod/Auth/LoginImportService.swift b/PiliPod/Auth/LoginImportService.swift
index 81886b1..7b64216 100644
--- a/PiliPod/Auth/LoginImportService.swift
+++ b/PiliPod/Auth/LoginImportService.swift
@@ -1,81 +1,52 @@
-//
-// LoginImportService.swift
-// PiliPod
-//
-// Created by co on 2026/5/21.
-//
-
import Foundation
enum LoginImportService {
- static func importFrom(url: URL) throws {
- let didAccess = url.startAccessingSecurityScopedResource()
- defer {
- if didAccess {
- url.stopAccessingSecurityScopedResource()
- }
+ static func decode(_ data: Data) throws -> [BiliAccount] {
+ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], !json.isEmpty else {
+ throw AccountStorageError.invalidAccount
}
-
- let data = try Data(contentsOf: url)
- let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
-
- guard
- let firstUser = json?.values.first as? [String: Any],
- let cookies = firstUser["cookies"] as? [String: Any]
- else {
- throw NSError(domain: "Invalid JSON", code: -1)
+ return try json.keys.sorted().map { key in
+ guard let user = json[key] as? [String: Any], let cookie = user["cookies"] as? [String: Any],
+ let sessdata = cookie["SESSDATA"] as? String, !sessdata.isEmpty,
+ let csrf = cookie["bili_jct"] as? String, !csrf.isEmpty,
+ let uid = cookie["DedeUserID"] as? String, uid == key, UInt64(uid).map({ $0 > 0 }) == true
+ else { throw AccountStorageError.invalidAccount }
+ guard let cookieStrings = cookie as? [String: String],
+ cookieStrings.allSatisfy({ !$0.key.contains(";") && !$0.value.contains(";") && !$0.value.contains("\r") && !$0.value.contains("\n") })
+ else { throw AccountStorageError.invalidAccount }
+ if let rawTypes = user["type"], !(rawTypes is NSNull) {
+ guard let types = rawTypes as? [Int], types.allSatisfy({ (0...3).contains($0) }) else {
+ throw AccountStorageError.invalidAccount
+ }
+ }
+ return BiliAccount(cookies: BiliCookie(SESSDATA: sessdata, bili_jct: csrf, DedeUserID: uid,
+ sid: cookie["sid"] as? String, buvid3: cookie["buvid3"] as? String, extraCookies: cookieStrings),
+ accessKey: user["accessKey"] as? String, refresh: user["refresh"] as? String, type: user["type"] as? [Int])
}
-
- let biliCookie = BiliCookie(
- SESSDATA: cookies["SESSDATA"] as? String ?? "",
- bili_jct: cookies["bili_jct"] as? String ?? "",
- DedeUserID: cookies["DedeUserID"] as? String ?? "",
- sid: cookies["sid"] as? String,
- buvid3: cookies["buvid3"] as? String
- )
-
- LoginSession.shared.cookies = biliCookie
- LoginSession.shared.accessKey = firstUser["accessKey"] as? String
- LoginSession.shared.refresh = firstUser["refresh"] as? String
- LoginSession.shared.type = firstUser["type"] as? [Int]
- LoginSession.shared.isLogin = true
-
- saveToLocal(biliCookie)
}
-
- static func saveToLocal(_ cookie: BiliCookie) {
- let data = try? JSONEncoder().encode(cookie)
- UserDefaults.standard.set(data, forKey: "bili_cookie")
- UserDefaults.standard.set(LoginSession.shared.accessKey, forKey: "bili_accessKey")
- UserDefaults.standard.set(LoginSession.shared.refresh, forKey: "bili_refresh")
- UserDefaults.standard.set(LoginSession.shared.type, forKey: "bili_type")
- }
-
- static func restore() {
- guard
- let data = UserDefaults.standard.data(forKey: "bili_cookie"),
- let cookie = try? JSONDecoder().decode(BiliCookie.self, from: data)
- else {
- return
+ static func encode(_ state: AccountState) throws -> Data {
+ var payload: [String: Any] = [:]
+ for account in state.accounts {
+ let roles = AccountRole.allCases.enumerated().compactMap { index, role in
+ state.assignments[role] == account.id ? index : nil
+ }
+ payload[account.id] = ["cookies": account.cookies.dictionary,
+ "accessKey": account.accessKey.map { $0 as Any } ?? NSNull(),
+ "refresh": account.refresh.map { $0 as Any } ?? NSNull(), "type": roles]
}
-
- LoginSession.shared.cookies = cookie
- LoginSession.shared.accessKey = UserDefaults.standard.string(forKey: "bili_accessKey")
- LoginSession.shared.refresh = UserDefaults.standard.string(forKey: "bili_refresh")
- LoginSession.shared.type = UserDefaults.standard.array(forKey: "bili_type") as? [Int]
- LoginSession.shared.isLogin = true
+ return try JSONSerialization.data(withJSONObject: payload, options: [.prettyPrinted, .sortedKeys])
}
-
- static func clearLoginState() {
- LoginSession.shared.cookies = nil
- LoginSession.shared.accessKey = nil
- LoginSession.shared.refresh = nil
- LoginSession.shared.type = nil
- LoginSession.shared.isLogin = false
-
- UserDefaults.standard.removeObject(forKey: "bili_cookie")
- UserDefaults.standard.removeObject(forKey: "bili_accessKey")
- UserDefaults.standard.removeObject(forKey: "bili_refresh")
- UserDefaults.standard.removeObject(forKey: "bili_type")
+ @MainActor
+ static func importFrom(url: URL) throws {
+ let accessed = url.startAccessingSecurityScopedResource()
+ defer { if accessed { url.stopAccessingSecurityScopedResource() } }
+ try LoginSession.shared.add(decode(Data(contentsOf: url)))
+ }
+ @MainActor
+ static func restore() { LoginSession.shared.restore() }
+ @MainActor
+ static func clearLoginState() throws {
+ let id = LoginSession.shared.selectedID(for: .main)
+ if id != "0" { try LoginSession.shared.remove(id) }
}
}
diff --git a/PiliPod/Auth/LoginSession.swift b/PiliPod/Auth/LoginSession.swift
index b6af7b9..0d022e3 100644
--- a/PiliPod/Auth/LoginSession.swift
+++ b/PiliPod/Auth/LoginSession.swift
@@ -1,41 +1,229 @@
-//
-// LoginSession.swift
-// PiliPod
-//
-// Created by co on 2026/5/21.
-//
-
import Combine
import Foundation
+import Security
-final class LoginSession: ObservableObject {
- static let shared = LoginSession()
-
- @Published var cookies: BiliCookie?
- @Published var accessKey: String?
- @Published var refresh: String?
- @Published var type: [Int]?
- @Published var isLogin = false
-
- private init() {}
+enum AccountRole: String, Codable, CaseIterable, Identifiable {
+ case main, history, recommendation, playback
+ var id: String { rawValue }
+ var title: String {
+ switch self {
+ case .main: "主账号"
+ case .history: "记录观看"
+ case .recommendation: "推荐"
+ case .playback: "视频取流"
+ }
+ }
+}
+struct BiliAccount: Codable, Identifiable {
+ let cookies: BiliCookie
+ var accessKey: String?
+ var refresh: String?
+ var type: [Int]?
+ var username: String? = nil
+ var id: String { cookies.DedeUserID }
+ var displayName: String {
+ guard let name = username?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty else { return id }
+ return "\(name)(\(id))"
+ }
var cookieString: String {
- guard let c = cookies else { return "" }
+ cookies.dictionary.keys.sorted().map { "\($0)=\(cookies.dictionary[$0] ?? "")" }.joined(separator: "; ")
+ }
+}
- var items: [String] = [
- "SESSDATA=\(c.SESSDATA)",
- "bili_jct=\(c.bili_jct)",
- "DedeUserID=\(c.DedeUserID)"
- ]
+struct AccountState: Codable {
+ var accounts: [BiliAccount] = []
+ var assignments: [AccountRole: String] = [:]
+ var incognito = false
+ func account(for role: AccountRole) -> BiliAccount? {
+ guard let id = assignments[role], id != "0" else { return nil }
+ return accounts.first { $0.id == id }
+ }
+ mutating func add(_ account: BiliAccount, activate: Bool) {
+ var account = account
+ if account.username == nil { account.username = accounts.first { $0.id == account.id }?.username }
+ let wasEmpty = accounts.isEmpty
+ accounts.removeAll { $0.id == account.id }
+ accounts.append(account)
+ if wasEmpty {
+ for role in AccountRole.allCases { assignments[role] = account.id }
+ } else if activate { assignments[.main] = account.id }
+ }
+ mutating func remove(_ id: String) {
+ accounts.removeAll { $0.id == id }
+ for role in AccountRole.allCases where assignments[role] == id { assignments[role] = "0" }
+ }
+ var shouldReportHistory: Bool { !incognito && account(for: .history) != nil }
+}
- if let sid = c.sid {
- items.append("sid=\(sid)")
+protocol AccountVault {
+ func load() throws -> Data?
+ func save(_ data: Data) throws
+}
+struct KeychainAccountVault: AccountVault {
+ private var query: [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: "PiliPod.accounts.v1", kSecAttrAccount as String: "accounts"]
+ }
+ func load() throws -> Data? {
+ var lookup = query
+ lookup[kSecReturnData as String] = true
+ lookup[kSecMatchLimit as String] = kSecMatchLimitOne
+ var result: CFTypeRef?
+ let status = SecItemCopyMatching(lookup as CFDictionary, &result)
+ if status == errSecItemNotFound { return nil }
+ guard status == errSecSuccess else { throw AccountStorageError.keychain(status) }
+ return result as? Data
+ }
+ func save(_ data: Data) throws {
+ var status = SecItemUpdate(query as CFDictionary, [kSecValueData as String: data] as CFDictionary)
+ if status == errSecItemNotFound {
+ var item = query
+ item[kSecValueData as String] = data
+ item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ status = SecItemAdd(item as CFDictionary, nil)
+ }
+ guard status == errSecSuccess else { throw AccountStorageError.keychain(status) }
+ }
+}
+enum AccountStorageError: LocalizedError {
+ case keychain(OSStatus), invalidAccount
+ var errorDescription: String? {
+ switch self {
+ case .keychain: "无法读写安全登录存储,请解锁设备后重试。"
+ case .invalidAccount: "登录数据无效或账号不存在。"
}
+ }
+}
- if let buvid3 = c.buvid3 {
- items.append("buvid3=\(buvid3)")
+final class LoginSession: ObservableObject {
+ static let shared = LoginSession()
+ @Published private(set) var revision = 0
+ @Published private(set) var isLogin = false
+ @Published private(set) var storageError: String?
+ private let lock = NSRecursiveLock()
+ private var state = AccountState()
+ private var restoreFailed = false
+ private let vault: AccountVault
+ init(vault: AccountVault = KeychainAccountVault()) { self.vault = vault }
+ var snapshot: AccountState {
+ lock.lock()
+ defer { lock.unlock() }
+ return state
+ }
+ var accounts: [BiliAccount] { snapshot.accounts }
+ var cookies: BiliCookie? { account(for: .main)?.cookies }
+ var accessKey: String? { account(for: .main)?.accessKey }
+ var refresh: String? { account(for: .main)?.refresh }
+ var type: [Int]? { account(for: .main)?.type }
+ var cookieString: String { account(for: .main)?.cookieString ?? "" }
+ var incognito: Bool { snapshot.incognito }
+ var shouldReportHistory: Bool { snapshot.shouldReportHistory }
+ func account(for role: AccountRole) -> BiliAccount? { snapshot.account(for: role) }
+ func selectedID(for role: AccountRole) -> String { snapshot.assignments[role] ?? "0" }
+ // Save before publishing; failed writes leave the working session intact.
+ @MainActor
+ private func update(_ mutation: (inout AccountState) throws -> Void) throws {
+ // Retry a failed read before writing, so an empty in-memory state cannot overwrite existing accounts.
+ if restoreFailed {
+ restore()
+ guard !restoreFailed else { throw AccountStorageError.keychain(errSecNotAvailable) }
+ }
+ lock.lock()
+ defer { lock.unlock() }
+ var next = state
+ try mutation(&next)
+ try vault.save(JSONEncoder().encode(next))
+ state = next
+ storageError = nil
+ isLogin = next.account(for: .main) != nil
+ revision += 1
+ }
+ @MainActor
+ func add(_ accounts: [BiliAccount], activate: Bool = true) throws {
+ guard !accounts.isEmpty, accounts.allSatisfy({
+ UInt64($0.id).map { $0 > 0 } == true && !$0.cookies.SESSDATA.isEmpty && !$0.cookies.bili_jct.isEmpty
+ }) else { throw AccountStorageError.invalidAccount }
+ try update { state in
+ for (index, account) in accounts.enumerated() { state.add(account, activate: activate && index == 0) }
+ if accounts.allSatisfy({ $0.type != nil }) {
+ for (index, role) in AccountRole.allCases.enumerated() {
+ state.assignments[role] = accounts.first { $0.type?.contains(index) == true }?.id ?? "0"
+ }
+ }
+ }
+ }
+ @MainActor
+ func assign(_ id: String, to role: AccountRole? = nil) throws {
+ try update { state in
+ guard id == "0" || state.accounts.contains(where: { $0.id == id }) else { throw AccountStorageError.invalidAccount }
+ for target in role.map({ [$0] }) ?? AccountRole.allCases { state.assignments[target] = id }
+ }
+ }
+ @MainActor
+ func remove(_ id: String) throws { try update { $0.remove(id) } }
+ @MainActor
+ func setIncognito(_ enabled: Bool) throws { try update { $0.incognito = enabled } }
+ @MainActor
+ func updateUsername(_ username: String, for account: BiliAccount) throws {
+ let name = username.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !name.isEmpty,
+ let current = accounts.first(where: { $0.id == account.id }),
+ current.cookies.SESSDATA == account.cookies.SESSDATA,
+ current.username != name else { return }
+ try update { state in
+ guard let index = state.accounts.firstIndex(where: { $0.id == account.id }) else { return }
+ state.accounts[index].username = name
+ }
+ }
+ @MainActor
+ func restore(defaults: UserDefaults = .standard) {
+ restoreFailed = false
+ storageError = nil
+ do {
+ if let data = try vault.load() {
+ let restored = try JSONDecoder().decode(AccountState.self, from: data)
+ lock.lock()
+ state = restored
+ lock.unlock()
+ isLogin = restored.account(for: .main) != nil
+ revision += 1
+ clearLegacy(defaults)
+ } else if let data = defaults.data(forKey: "bili_cookie") {
+ let cookie = try JSONDecoder().decode(BiliCookie.self, from: data)
+ try add([BiliAccount(cookies: cookie, accessKey: defaults.string(forKey: "bili_accessKey"),
+ refresh: defaults.string(forKey: "bili_refresh"), type: nil)])
+ clearLegacy(defaults)
+ }
+ } catch {
+ restoreFailed = true
+ storageError = error.localizedDescription
}
+ }
+ @MainActor
+ private func clearLegacy(_ defaults: UserDefaults) {
+ for key in ["bili_cookie", "bili_accessKey", "bili_refresh", "bili_type"] { defaults.removeObject(forKey: key) }
+ }
+}
+enum AccountRequest {
+ static func historyRequest(state: AccountState, aid: Int, cid: Int, progress: Int) -> URLRequest? {
+ guard state.shouldReportHistory, let account = state.account(for: .history) else { return nil }
+ var components = URLComponents(string: "https://api.bilibili.com/x/v2/history/report")
+ components?.queryItems = [
+ URLQueryItem(name: "aid", value: String(aid)), URLQueryItem(name: "cid", value: String(cid)),
+ URLQueryItem(name: "progress", value: String(progress)), URLQueryItem(name: "platform", value: "web"),
+ URLQueryItem(name: "csrf", value: account.cookies.bili_jct)
+ ]
+ guard let url = components?.url else { return nil }
+ var request = URLRequest(url: url)
+ apply(account, to: &request)
+ request.httpMethod = "POST"
+ return request
+ }
- return items.joined(separator: "; ")
+ static func apply(_ account: BiliAccount?, to request: inout URLRequest) {
+ request.httpShouldHandleCookies = false
+ request.cachePolicy = .reloadIgnoringLocalCacheData
+ request.setValue(account?.cookieString, forHTTPHeaderField: "Cookie")
}
}
diff --git a/PiliPod/Services/AVPlayerSession.swift b/PiliPod/Services/AVPlayerSession.swift
index 8e06399..0ffb233 100644
--- a/PiliPod/Services/AVPlayerSession.swift
+++ b/PiliPod/Services/AVPlayerSession.swift
@@ -217,7 +217,7 @@ final class AVPlayerSession: NSObject, AVPictureInPictureControllerDelegate {
activeStream = nil
wantsPlayback = true
errorMessage = nil
- let asset = AVURLAsset(url: liveURL, options: ["AVURLAssetHTTPHeaderFieldsKey": headers])
+ let asset = AVURLAsset(url: liveURL, options: ["AVURLAssetHTTPHeaderFieldsKey": headers, "AVURLAssetHTTPCookiesKey": [HTTPCookie]()])
let item = AVPlayerItem(asset: asset)
install(item)
player.playImmediately(atRate: Float(playbackRate))
@@ -714,7 +714,7 @@ private final class LocalDASHHLSBridge: @unchecked Sendable {
return DASHByteRange(start: start, end: end)
}
private static func fetch(url: URL, range: DASHByteRange, headers: [String: String]) async throws -> Data {
- var request = URLRequest(url: url); request.setValue(range.header, forHTTPHeaderField: "Range"); request.timeoutInterval = 15
+ var request = URLRequest(url: url); request.httpShouldHandleCookies = false; request.setValue(range.header, forHTTPHeaderField: "Range"); request.timeoutInterval = 15
headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
let (data, response) = try await URLSession.shared.data(for: request)
guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode) else { throw DASHBridgeError.unsupported }
@@ -787,7 +787,7 @@ private final class LoopbackHTTPServer: @unchecked Sendable {
func start() async throws { try await withCheckedThrowingContinuation { continuation in var resumed = false; listener.stateUpdateHandler = { state in if resumed { return }; switch state { case .ready: resumed = true; continuation.resume(); case let .failed(error): resumed = true; continuation.resume(throwing: error); default: break } }; listener.newConnectionHandler = { [weak self] in self?.accept($0) }; listener.start(queue: queue) } }
func stop() { listener.cancel(); connections.values.forEach { $0.cancel() }; connections.removeAll() }
private func accept(_ connection: NWConnection) { guard case let .hostPort(host, _) = connection.endpoint, host == .ipv4(IPv4Address("127.0.0.1")!) || host == .ipv6(IPv6Address("::1")!) else { connection.cancel(); return }; let id = ObjectIdentifier(connection); connections[id] = connection; connection.start(queue: queue); connection.receive(minimumIncompleteLength: 1, maximumLength: 16384) { [weak self] data, _, _, _ in self?.respond(connection, data ?? Data(), id: id) } }
- private func respond(_ c: NWConnection, _ data: Data, id: ObjectIdentifier) { defer { connections[id] = nil }; guard let line = String(data: data, encoding: .utf8)?.split(separator: "\n").first else { return send(c, status: "400 Bad Request", data: Data(), type: "text/plain") }; let pieces = line.split(separator: " "); guard pieces.count > 1, let route = routes[String(pieces[1])] else { return send(c, status: "404 Not Found", data: Data(), type: "text/plain") }; switch route { case let .data(payload): send(c, status: "200 OK", data: payload, type: "application/vnd.apple.mpegurl"); case let .local(payload): send(c, status: "200 OK", data: payload, type: "video/iso.segment"); case let .remote(url, range, timeOffset): Task { [headers, metrics] in do { var request = URLRequest(url: url); request.setValue(range.header, forHTTPHeaderField: "Range"); headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }; metrics.beginRequest(); let payload = try await RemoteRangeLoader { metrics.record(bytes: $0) }.load(request); metrics.finishRequest(success: true); self.queue.async { self.send(c, status: "200 OK", data: MP4Timeline.normalize(payload, subtracting: timeOffset), type: "video/iso.segment") } } catch { metrics.finishRequest(success: false); self.queue.async { self.send(c, status: "502 Bad Gateway", data: Data(), type: "text/plain") } } } } }
+ private func respond(_ c: NWConnection, _ data: Data, id: ObjectIdentifier) { defer { connections[id] = nil }; guard let line = String(data: data, encoding: .utf8)?.split(separator: "\n").first else { return send(c, status: "400 Bad Request", data: Data(), type: "text/plain") }; let pieces = line.split(separator: " "); guard pieces.count > 1, let route = routes[String(pieces[1])] else { return send(c, status: "404 Not Found", data: Data(), type: "text/plain") }; switch route { case let .data(payload): send(c, status: "200 OK", data: payload, type: "application/vnd.apple.mpegurl"); case let .local(payload): send(c, status: "200 OK", data: payload, type: "video/iso.segment"); case let .remote(url, range, timeOffset): Task { [headers, metrics] in do { var request = URLRequest(url: url); request.httpShouldHandleCookies = false; request.setValue(range.header, forHTTPHeaderField: "Range"); headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }; metrics.beginRequest(); let payload = try await RemoteRangeLoader { metrics.record(bytes: $0) }.load(request); metrics.finishRequest(success: true); self.queue.async { self.send(c, status: "200 OK", data: MP4Timeline.normalize(payload, subtracting: timeOffset), type: "video/iso.segment") } } catch { metrics.finishRequest(success: false); self.queue.async { self.send(c, status: "502 Bad Gateway", data: Data(), type: "text/plain") } } } } }
private func send(_ c: NWConnection, status: String, data: Data, type: String) { let head = "HTTP/1.1 \(status)\r\nContent-Type: \(type)\r\nContent-Length: \(data.count)\r\nConnection: close\r\n\r\n"; var response = Data(head.utf8); response.append(data); c.send(content: response, completion: .contentProcessed { _ in c.cancel() }) }
deinit { stop() }
}
diff --git a/PiliPod/Services/AudioEnvelopeAnalyzer.swift b/PiliPod/Services/AudioEnvelopeAnalyzer.swift
index eaad8f2..fc7abfb 100644
--- a/PiliPod/Services/AudioEnvelopeAnalyzer.swift
+++ b/PiliPod/Services/AudioEnvelopeAnalyzer.swift
@@ -190,6 +190,7 @@ final class AudioEnvelopeAnalyzer: @unchecked Sendable {
private static func fetch(_ url: URL, range: ByteRange, headers: [String: String]) async throws -> Data {
var request = URLRequest(url: url)
+ request.httpShouldHandleCookies = false
request.setValue("bytes=\(range.start)-\(range.end)", forHTTPHeaderField: "Range")
request.timeoutInterval = 20
headers.forEach { request.setValue($0.value, forHTTPHeaderField: $0.key) }
diff --git a/PiliPod/Services/BiliAPI.swift b/PiliPod/Services/BiliAPI.swift
index 8725541..32d87c9 100644
--- a/PiliPod/Services/BiliAPI.swift
+++ b/PiliPod/Services/BiliAPI.swift
@@ -26,10 +26,11 @@ class BiliAPI {
// MARK: - 创建带登录状态的http请求
- private func makeRequest(url: URL) -> URLRequest {
+ private func makeRequest(account: BiliAccount? = LoginSession.shared.account(for: .main), url: URL) -> URLRequest {
var request = URLRequest(url: url)
+ AccountRequest.apply(account, to: &request)
- let cookie = LoginSession.shared.cookieString
+ let cookie = account?.cookieString ?? ""
if !cookie.isEmpty {
request.setValue(cookie, forHTTPHeaderField: "Cookie")
}
@@ -40,12 +41,13 @@ class BiliAPI {
// MARK: - 轻量表单 POST(不加签)
private func makePostFormRequest(
+ account: BiliAccount? = LoginSession.shared.account(for: .main),
urlString: String,
parameters: [String: String]
) -> URLRequest? {
guard let url = URL(string: urlString) else { return nil }
- var request = makeRequest(url: url)
+ var request = makeRequest(account: account, url: url)
request.httpMethod = "POST"
request.setValue(
"application/x-www-form-urlencoded",
@@ -57,11 +59,6 @@ class BiliAPI {
)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
- // cookie登录状态
- let cookie = LoginSession.shared.cookieString
- if !cookie.isEmpty {
- request.setValue(cookie, forHTTPHeaderField: "Cookie")
- }
var components = URLComponents()
components.queryItems = parameters.map {
@@ -73,7 +70,8 @@ class BiliAPI {
// MARK: - 构建移动端 App 请求(加签 + 公共参数)
- private func makeAppRequest(
+ func makeAppRequest(
+ account: BiliAccount? = LoginSession.shared.account(for: .main),
baseURLString: String,
method: String = "GET",
parameters: [String: String] = [:]
@@ -82,13 +80,14 @@ class BiliAPI {
// 合并业务参数与系统公共移动端参数
var allParams = parameters
+ allParams.removeValue(forKey: "access_key")
allParams["appkey"] = BiliAPI.appKey
allParams["mobi_app"] = "android_hd"
allParams["platform"] = "android"
allParams["ts"] = String(Int(Date().timeIntervalSince1970))
// 写入移动端凭证 accessKey
- if let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty {
+ if let accessKey = account?.accessKey, !accessKey.isEmpty {
allParams["access_key"] = accessKey
}
@@ -98,6 +97,7 @@ class BiliAPI {
// 组装真正的 URLRequest
var request = URLRequest(url: baseURL)
+ AccountRequest.apply(account, to: &request)
request.httpMethod = method
// 伪造符合 iOS 移动端行为的公共 Header
@@ -105,7 +105,7 @@ class BiliAPI {
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
// 移动端请求作为稳妥保障,一并带上 Cookie
- let cookie = LoginSession.shared.cookieString
+ let cookie = account?.cookieString ?? ""
if !cookie.isEmpty {
request.setValue(cookie, forHTTPHeaderField: "Cookie")
}
@@ -141,6 +141,7 @@ class BiliAPI {
// MARK: - 私信
func fetchPrivateMessageSessions() async throws -> [PrivateMessageSession] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.vc.bilibili.com/session_svr/v1/session_svr/get_sessions"
)
@@ -155,7 +156,7 @@ class BiliAPI {
]
guard let url = components?.url else { throw APIError.invalidURL }
- var request = makeRequest(url: url)
+ var request = makeRequest(account: account, url: url)
request.setValue(
"bili-universal/103300 (iPhone; iOS 18.2; Scale/3.00)",
forHTTPHeaderField: "User-Agent"
@@ -197,6 +198,7 @@ class BiliAPI {
beginSeqno: UInt64 = 0,
size: Int32 = 50
) async throws -> [Bilibili_Im_Type_Msg] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.vc.bilibili.com/svr_sync/v1/svr_sync/fetch_session_msgs"
)
@@ -217,7 +219,7 @@ class BiliAPI {
components?.queryItems = queryItems
guard let url = components?.url else { throw APIError.invalidURL }
- var request = makeRequest(url: url)
+ var request = makeRequest(account: account, url: url)
request.setValue(
"bili-universal/103300 (iPhone; iOS 18.2; Scale/3.00)",
forHTTPHeaderField: "User-Agent"
@@ -238,6 +240,7 @@ class BiliAPI {
}
private func fetchPrivateMessageUserCards(mids: [UInt64]) async throws -> [PrivateMessageUserCard] {
+ let account = LoginSession.shared.account(for: .main)
guard !mids.isEmpty else { return [] }
var components = URLComponents(string: "https://api.vc.bilibili.com/account/v1/user/cards")
@@ -248,7 +251,7 @@ class BiliAPI {
]
guard let url = components?.url else { throw APIError.invalidURL }
- let (data, response) = try await URLSession.shared.data(for: makeRequest(url: url))
+ let (data, response) = try await URLSession.shared.data(for: makeRequest(account: account, url: url))
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
else { throw APIError.requestFailed }
@@ -327,6 +330,7 @@ class BiliAPI {
}
private func sendGrpcUnary(path: String, body: Data) async throws -> Data {
+ let account = LoginSession.shared.account(for: .main)
guard let url = URL(string: "https://grpc.biliapi.net\(path)") else {
throw APIError.invalidURL
}
@@ -339,6 +343,7 @@ class BiliAPI {
grpcBody.append(body)
var request = URLRequest(url: url)
+ AccountRequest.apply(account, to: &request)
request.httpMethod = "POST"
request.httpBody = grpcBody
request.setValue("application/grpc", forHTTPHeaderField: "Content-Type")
@@ -350,11 +355,11 @@ class BiliAPI {
)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
- let cookie = LoginSession.shared.cookieString
+ let cookie = account?.cookieString ?? ""
if !cookie.isEmpty {
request.setValue(cookie, forHTTPHeaderField: "Cookie")
}
- if let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty {
+ if let accessKey = account?.accessKey, !accessKey.isEmpty {
request.setValue("identify_v1 \(accessKey)", forHTTPHeaderField: "Authorization")
}
@@ -444,8 +449,9 @@ class BiliAPI {
}
private func fetchMessageFeed(urlString: String, type: T.Type) async throws -> T {
+ let account = LoginSession.shared.account(for: .main)
guard let url = URL(string: urlString) else { throw APIError.invalidURL }
- let (data, response) = try await URLSession.shared.data(for: makeRequest(url: url))
+ let (data, response) = try await URLSession.shared.data(for: makeRequest(account: account, url: url))
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
else { throw APIError.requestFailed }
@@ -491,7 +497,8 @@ class BiliAPI {
}
private func requestUnreadMessageFeed(url: URL) async throws -> MessageFeedUnreadData {
- let (data, response) = try await URLSession.shared.data(for: makeRequest(url: url))
+ let account = LoginSession.shared.account(for: .main)
+ let (data, response) = try await URLSession.shared.data(for: makeRequest(account: account, url: url))
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
else {
@@ -512,7 +519,8 @@ class BiliAPI {
}
private func requestUnreadPrivateMessages(url: URL) async throws -> PrivateMessageUnreadData {
- let (data, response) = try await URLSession.shared.data(for: makeRequest(url: url))
+ let account = LoginSession.shared.account(for: .main)
+ let (data, response) = try await URLSession.shared.data(for: makeRequest(account: account, url: url))
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
else {
@@ -545,6 +553,7 @@ class BiliAPI {
freshType: Int,
brush: Int
) async throws -> [VideoItem] {
+ let account = LoginSession.shared.account(for: .recommendation)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/index/top/feed/rcmd"
)
@@ -558,7 +567,7 @@ class BiliAPI {
return []
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -577,6 +586,7 @@ class BiliAPI {
page: Int = 1,
pageSize: Int = 20
) async throws -> (videos: [VideoItem], noMore: Bool) {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/popular"
)
@@ -589,7 +599,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -610,6 +620,7 @@ class BiliAPI {
// MARK: - 获取首页直播 Feed
func fetchLiveHomeFeed() async throws -> LiveHomeFeedPayload {
+ let account = LoginSession.shared.account(for: .recommendation)
let urlString = "https://api.live.bilibili.com/xlive/app-interface/v2/index/feed"
let params: [String: String] = [
"channel": "master",
@@ -633,7 +644,7 @@ class BiliAPI {
"statistics": #"{"appId":1,"platform":3,"version":"8.43.0","abtest":""}"#
]
- guard let request = makeAppRequest(baseURLString: urlString, method: "GET", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "GET", parameters: params) else {
throw APIError.invalidURL
}
@@ -694,10 +705,11 @@ class BiliAPI {
rooms: rooms
)
}
-
+
// MARK: - 获取直播分区
func fetchLiveAreaFeed(areaID: Int, parentAreaID: Int) async throws -> [LiveCardModel] {
+ let account = LoginSession.shared.account(for: .recommendation)
let urlString = "https://api.live.bilibili.com/xlive/app-interface/v2/second/getList"
let params: [String: String] = [
"actionKey": "appkey",
@@ -726,7 +738,7 @@ class BiliAPI {
"version": "8.43.0"
]
- guard let request = makeAppRequest(baseURLString: urlString, method: "GET", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "GET", parameters: params) else {
throw APIError.invalidURL
}
@@ -744,10 +756,11 @@ class BiliAPI {
return (decoded.data?.list ?? []).map(mapLiveAreaRoom)
}
-
+
// MARK: - 获取直播数据
func fetchLivePlaybackInfo(roomID: String, qn: Int = 10000) async throws -> LivePlaybackInfo {
+ let account = LoginSession.shared.account(for: .playback)
var components = URLComponents(
string: "https://api.live.bilibili.com/xlive/web-room/v2/index/getRoomPlayInfo"
)
@@ -768,7 +781,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- let request = makeRequest(url: signedURL)
+ let request = makeRequest(account: account, url: signedURL)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -845,6 +858,7 @@ class BiliAPI {
}
func fetchLiveDanmakuInfo(roomID: Int) async throws -> LiveDanmakuInfo {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.live.bilibili.com/xlive/web-room/v1/index/getDanmuInfo"
)
@@ -859,7 +873,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- let request = makeRequest(url: signedURL)
+ let request = makeRequest(account: account, url: signedURL)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -882,6 +896,7 @@ class BiliAPI {
}
func fetchLiveDanmakuHistory(roomID: Int) async throws -> [LiveDanmakuMessage] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory"
)
@@ -893,7 +908,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -948,6 +963,7 @@ class BiliAPI {
}
func fetchLiveRoomInfo(roomID: String) async throws -> LiveRoomInfo {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.live.bilibili.com/xlive/web-room/v1/index/getH5InfoByRoom"
)
@@ -959,7 +975,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -999,6 +1015,7 @@ class BiliAPI {
// MARK: - 获取视频相关推荐
func fetchRelatedVideos(bvid: String, limit: Int = 40) async throws -> [VideoItem] {
+ let account = LoginSession.shared.account(for: .recommendation)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/archive/related"
)
@@ -1010,7 +1027,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(RelatedVideosResponse.self, from: data)
@@ -1029,6 +1046,7 @@ class BiliAPI {
// MARK: - 获取App版推荐视频
func fetchAppRecommendVideos(idx: Int, flush: Int) async throws -> Data {
+ let account = LoginSession.shared.account(for: .recommendation)
// App 推荐数据的基准接口地址
let appRcmdHost = "https://app.bilibili.com/x/v2/feed/index"
@@ -1042,7 +1060,7 @@ class BiliAPI {
]
// 使用新封装的加签构造器创建请求
- guard var request = makeAppRequest(baseURLString: appRcmdHost, method: "GET", parameters: businessParams) else {
+ guard var request = makeAppRequest(account: account, baseURLString: appRcmdHost, method: "GET", parameters: businessParams) else {
throw APIError.invalidURL
}
@@ -1058,7 +1076,6 @@ class BiliAPI {
request.setValue("", forHTTPHeaderField: "x-bili-aurora-zone")
request.setValue("cronet", forHTTPHeaderField: "bili-http-engine")
- print(request.url)
let (data, response) = try await URLSession.shared.data(for: request)
@@ -1082,6 +1099,7 @@ class BiliAPI {
// MARK: - 获取个人空间信息(App)
func fetchUserSpace(mid: Int, fromViewAid: Int?) async throws -> UserSpaceData {
+ let account = LoginSession.shared.account(for: .main)
let urlString = "https://app.bilibili.com/x/v2/space"
var params = makeSpaceCommonParameters(mid: mid)
@@ -1089,7 +1107,7 @@ class BiliAPI {
params["from_view_aid"] = String(fromViewAid)
}
- guard let request = makeAppRequest(baseURLString: urlString, method: "GET", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "GET", parameters: params) else {
throw APIError.invalidURL
}
@@ -1115,6 +1133,7 @@ class BiliAPI {
// MARK: - 获取个人空间动态(Web)
func fetchUserSpaceDynamics(mid: Int, offset: String? = nil) async throws -> UserSpaceDynamicPageResult {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space")
var queryItems = [
URLQueryItem(name: "host_mid", value: String(mid)),
@@ -1126,7 +1145,7 @@ class BiliAPI {
components?.queryItems = queryItems
guard let url = components?.url else { throw APIError.invalidURL }
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- var request = makeRequest(url: signedURL)
+ var request = makeRequest(account: account, url: signedURL)
request.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15", forHTTPHeaderField: "User-Agent")
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue("web", forHTTPHeaderField: "Origin")
@@ -1143,6 +1162,7 @@ class BiliAPI {
// MARK: - 获取全部动态(Web)
func fetchAllDynamics(offset: String? = nil) async throws -> UserSpaceDynamicPageResult {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all")
var queryItems = [
URLQueryItem(name: "platform", value: "web"),
@@ -1156,7 +1176,7 @@ class BiliAPI {
guard let url = components?.url else { throw APIError.invalidURL }
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- var request = makeRequest(url: signedURL)
+ var request = makeRequest(account: account, url: signedURL)
request.setValue("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Version/18.0 Safari/605.1.15", forHTTPHeaderField: "User-Agent")
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue("web", forHTTPHeaderField: "Origin")
@@ -1184,6 +1204,7 @@ class BiliAPI {
ps: Int = 20,
qn: Int = 80
) async throws -> SpaceArchiveData {
+ let account = LoginSession.shared.account(for: .main)
let urlString = "https://app.biliapi.com/x/v2/space/archive/cursor"
var params = makeSpaceCommonParameters(mid: mid)
params["order"] = order.rawValue
@@ -1193,7 +1214,7 @@ class BiliAPI {
params["aid"] = String(aid)
}
- guard let request = makeAppRequest(baseURLString: urlString, method: "GET", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "GET", parameters: params) else {
throw APIError.invalidURL
}
@@ -1225,6 +1246,7 @@ class BiliAPI {
type: String = "archive",
ps: Int = 20
) async throws -> HistoryData {
+ let account = LoginSession.shared.account(for: .history)
var components = URLComponents(string: "https://api.bilibili.com/x/web-interface/history/cursor")
var queryItems: [URLQueryItem] = [
URLQueryItem(name: "type", value: type),
@@ -1247,7 +1269,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
@@ -1275,6 +1297,7 @@ class BiliAPI {
ps: Int = 50,
orderType: String? = nil
) async throws -> FollowingData {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/relation/followings")
var queryItems: [URLQueryItem] = [
URLQueryItem(name: "vmid", value: String(vmid)),
@@ -1292,7 +1315,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
@@ -1320,6 +1343,7 @@ class BiliAPI {
pn: Int = 1,
ps: Int = 50
) async throws -> FollowingData {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/relation/followings/search")
var queryItems: [URLQueryItem] = [
URLQueryItem(name: "vmid", value: String(vmid)),
@@ -1334,7 +1358,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
@@ -1357,6 +1381,7 @@ class BiliAPI {
// MARK: - 获取搜索热榜
func fetchSearchTrending(limit: Int = 10) async throws -> [SearchTrendingItem] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/v2/search/trending/ranking")
components?.queryItems = [
URLQueryItem(name: "limit", value: String(limit))
@@ -1366,7 +1391,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
@@ -1386,6 +1411,7 @@ class BiliAPI {
// MARK: - 获取搜索发现
func fetchSearchRecommend() async throws -> [SearchRecommendItem] {
+ let account = LoginSession.shared.account(for: .recommendation)
let urlString = "https://app.bilibili.com/x/v2/search/recommend"
let params: [String: String] = [
@@ -1397,13 +1423,12 @@ class BiliAPI {
"s_locale": "zh_CN"
]
- guard let request = makeAppRequest(baseURLString: urlString, method: "GET", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "GET", parameters: params) else {
throw APIError.invalidURL
}
let (data, response) = try await URLSession.shared.data(for: request)
- print(String(data: data, encoding: .utf8))
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -1422,6 +1447,7 @@ class BiliAPI {
// MARK: - 获取搜索联想
func fetchSearchSuggestions(term: String) async throws -> [SearchSuggestItem] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://s.search.bilibili.com/main/suggest")
components?.queryItems = [
URLQueryItem(name: "term", value: term),
@@ -1433,7 +1459,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- var request = makeRequest(url: url)
+ var request = makeRequest(account: account, url: url)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue(
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Mobile/15E148 Safari/604.1",
@@ -1459,6 +1485,7 @@ class BiliAPI {
// MARK: - 综合搜索
func fetchComprehensiveSearch(keyword: String) async throws -> [SearchComprehensiveModule] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/wbi/search/all/v2"
)
@@ -1471,7 +1498,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- var request = makeRequest(url: signedURL)
+ var request = makeRequest(account: account, url: signedURL)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue(
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Mobile/15E148 Safari/604.1",
@@ -1497,6 +1524,7 @@ class BiliAPI {
// MARK: - 分类搜索
func fetchTypedVideoSearch(keyword: String, page: Int = 1) async throws -> SearchTypedVideoData {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/wbi/search/type"
)
@@ -1511,7 +1539,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- var request = makeRequest(url: signedURL)
+ var request = makeRequest(account: account, url: signedURL)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue(
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Mobile/15E148 Safari/604.1",
@@ -1535,6 +1563,7 @@ class BiliAPI {
}
func fetchTypedUserSearch(keyword: String, page: Int = 1) async throws -> SearchTypedUserData {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/wbi/search/type"
)
@@ -1549,7 +1578,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- var request = makeRequest(url: signedURL)
+ var request = makeRequest(account: account, url: signedURL)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue(
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Mobile/15E148 Safari/604.1",
@@ -1594,10 +1623,11 @@ class BiliAPI {
isCancel: Bool,
type: Int = 1
) async throws {
- guard LoginSession.shared.isLogin else {
+ let account = LoginSession.shared.account(for: .main)
+ guard account != nil else {
throw APIError.responseError(-101)
}
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-111)
}
@@ -1609,7 +1639,7 @@ class BiliAPI {
"action": isCancel ? "0" : "1",
"access_key": accessKey
]
- guard let request = makeAppRequest(baseURLString: urlString, method: "POST", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "POST", parameters: params) else {
throw APIError.invalidURL
}
@@ -1632,10 +1662,11 @@ class BiliAPI {
isCancel: Bool,
type: Int = 1
) async throws {
- guard LoginSession.shared.isLogin else {
+ let account = LoginSession.shared.account(for: .main)
+ guard account != nil else {
throw APIError.responseError(-101)
}
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-111)
}
@@ -1647,7 +1678,7 @@ class BiliAPI {
"action": isCancel ? "0" : "1",
"access_key": accessKey
]
- guard let request = makeAppRequest(baseURLString: urlString, method: "POST", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "POST", parameters: params) else {
throw APIError.invalidURL
}
@@ -1667,10 +1698,11 @@ class BiliAPI {
// MARK: - 发表评论 / 上传评论图片
func uploadCommentImage(data: Data, fileName: String = "comment.jpg") async throws -> CommentImageUploadData {
- guard LoginSession.shared.isLogin else {
+ let account = LoginSession.shared.account(for: .main)
+ guard account != nil else {
throw APIError.responseError(-101)
}
- guard let csrf = LoginSession.shared.cookies?.bili_jct, !csrf.isEmpty else {
+ guard let csrf = account?.cookies.bili_jct, !csrf.isEmpty else {
throw APIError.responseError(-111)
}
@@ -1679,7 +1711,7 @@ class BiliAPI {
}
let boundary = "Boundary-\(UUID().uuidString)"
- var request = makeRequest(url: url)
+ var request = makeRequest(account: account, url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
@@ -1713,10 +1745,11 @@ class BiliAPI {
root: Int? = nil,
parent: Int? = nil
) async throws -> CommentAddResponseData {
- guard LoginSession.shared.isLogin else {
+ let account = LoginSession.shared.account(for: .main)
+ guard account != nil else {
throw APIError.responseError(-101)
}
- guard let csrf = LoginSession.shared.cookies?.bili_jct, !csrf.isEmpty else {
+ guard let csrf = account?.cookies.bili_jct, !csrf.isEmpty else {
throw APIError.responseError(-111)
}
@@ -1740,7 +1773,7 @@ class BiliAPI {
params["parent"] = String(parent)
}
- guard let request = makeAppRequest(baseURLString: urlString, method: "POST", parameters: params) else {
+ guard let request = makeAppRequest(account: account, baseURLString: urlString, method: "POST", parameters: params) else {
throw APIError.invalidURL
}
@@ -1787,6 +1820,7 @@ class BiliAPI {
}
func fetchUserReplyEmotePackages() async throws -> [ReplyEmotePackage] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/emote/user/panel/web")
components?.queryItems = [
URLQueryItem(name: "business", value: "reply")
@@ -1795,7 +1829,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -1906,8 +1940,9 @@ class BiliAPI {
// MARK: - 获取当前用户数据
func fetchMyInfo() async throws -> UserCard {
+ let account = LoginSession.shared.account(for: .main)
let url = URL(string: "https://api.bilibili.com/x/web-interface/nav")!
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
@@ -1922,8 +1957,9 @@ class BiliAPI {
// MARK: - 获取当前用户状态(动态/关注/粉丝)
func fetchMyStat() async throws -> MyStat {
+ let account = LoginSession.shared.account(for: .main)
let url = URL(string: "https://api.bilibili.com/x/web-interface/nav/stat")!
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
@@ -1938,6 +1974,7 @@ class BiliAPI {
// MARK: - 获取用户卡片
func fetchUserCardStats(mid: Int) async throws -> UserCardStats {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(string: "https://api.bilibili.com/x/web-interface/card")
components?.queryItems = [
URLQueryItem(name: "mid", value: String(mid))
@@ -1947,7 +1984,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -1969,6 +2006,7 @@ class BiliAPI {
// MARK: - 视频详情
func fetchVideoDetail(bvid: String) async throws -> VideoDetailData {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/view"
)
@@ -1980,7 +2018,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -1998,6 +2036,7 @@ class BiliAPI {
// MARK: - 视频实时在线人数
func fetchVideoOnlineTotal(bvid: String, cid: Int) async throws -> String {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/player/online/total"
)
@@ -2010,7 +2049,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(VideoOnlineTotalResponse.self, from: data)
@@ -2026,6 +2065,7 @@ class BiliAPI {
// MARK: - 视频关系(点赞/点踩/投币/收藏状态)
func fetchArchiveRelation(bvid: String) async throws -> ArchiveRelationData {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/web-interface/archive/relation"
)
@@ -2037,7 +2077,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -2059,6 +2099,7 @@ class BiliAPI {
// MARK: - 视频分P列表
func fetchVideoPageList(bvid: String) async throws -> [VideoPageListItem] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/player/pagelist"
)
@@ -2070,7 +2111,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -2088,10 +2129,11 @@ class BiliAPI {
// MARK: - 用户关系
func modifyUserRelation(fid: Int, act: Int) async throws {
+ let account = LoginSession.shared.account(for: .main)
guard act == 1 || act == 2 else {
throw APIError.requestFailed
}
- guard let csrf = LoginSession.shared.cookies?.bili_jct, !csrf.isEmpty else {
+ guard let csrf = account?.cookies.bili_jct, !csrf.isEmpty else {
throw APIError.responseError(-111)
}
@@ -2101,7 +2143,7 @@ class BiliAPI {
"csrf": csrf
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://api.bilibili.com/x/relation/modify",
parameters: parameters
) else {
@@ -2119,7 +2161,8 @@ class BiliAPI {
// MARK: - 点赞
func likeVideo(aid: Int, isCancel: Bool) async throws {
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-101)
}
@@ -2129,7 +2172,7 @@ class BiliAPI {
"like": isCancel ? "1" : "0"
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://app.bilibili.com/x/v2/view/like",
parameters: params
) else {
@@ -2149,7 +2192,8 @@ class BiliAPI {
// MARK: - 点踩
func dislikeVideo(aid: Int, isCancel: Bool) async throws {
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-101)
}
@@ -2159,7 +2203,7 @@ class BiliAPI {
"dislike": isCancel ? "1" : "0"
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://app.biliapi.net/x/v2/view/dislike",
parameters: params
) else {
@@ -2179,7 +2223,8 @@ class BiliAPI {
// MARK: - 一键三连
func tripleLikeVideo(aid: Int) async throws -> TripleLikeData {
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-101)
}
@@ -2188,7 +2233,7 @@ class BiliAPI {
"aid": String(aid)
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://app.bilibili.com/x/v2/view/like/triple",
parameters: parameters
) else {
@@ -2212,7 +2257,8 @@ class BiliAPI {
// MARK: - 投币
func coinVideo(aid: Int, multiply: Int) async throws {
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-101)
}
@@ -2223,7 +2269,7 @@ class BiliAPI {
"select_like": "0"
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://app.bilibili.com/x/v2/view/coin/add",
parameters: params
) else {
@@ -2246,6 +2292,7 @@ class BiliAPI {
upMid: Int64,
rid: Int64
) async throws -> [FavoriteFolderItem] {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/v3/fav/folder/created/list-all"
)
@@ -2258,7 +2305,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -2280,10 +2327,11 @@ class BiliAPI {
addMediaIds: [Int64],
delMediaIds: [Int64]
) async throws {
- guard let accessKey = LoginSession.shared.accessKey, !accessKey.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let accessKey = account?.accessKey, !accessKey.isEmpty else {
throw APIError.responseError(-101)
}
- guard let csrf = LoginSession.shared.cookies?.bili_jct, !csrf.isEmpty else {
+ guard let csrf = account?.cookies.bili_jct, !csrf.isEmpty else {
throw APIError.responseError(-111)
}
@@ -2300,7 +2348,7 @@ class BiliAPI {
params["del_media_ids"] = delMediaIds.map(String.init).joined(separator: ",")
}
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://api.bilibili.com/medialist/gateway/coll/resource/deal",
parameters: params
) else {
@@ -2320,10 +2368,11 @@ class BiliAPI {
// MARK: - 稍后再看(最多 100 个)
func addToWatchLater(bvid: String) async throws {
- guard let sessData = LoginSession.shared.cookies?.SESSDATA, !sessData.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let sessData = account?.cookies.SESSDATA, !sessData.isEmpty else {
throw APIError.responseError(-101)
}
- guard let csrf = LoginSession.shared.cookies?.bili_jct, !csrf.isEmpty else {
+ guard let csrf = account?.cookies.bili_jct, !csrf.isEmpty else {
throw APIError.responseError(-111)
}
@@ -2332,7 +2381,7 @@ class BiliAPI {
"csrf": csrf
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://api.bilibili.com/x/v2/history/toview/add",
parameters: params
) else {
@@ -2350,10 +2399,11 @@ class BiliAPI {
}
func removeFromWatchLater(aid: Int? = nil, bvid: String? = nil) async throws {
- guard let sessData = LoginSession.shared.cookies?.SESSDATA, !sessData.isEmpty else {
+ let account = LoginSession.shared.account(for: .main)
+ guard let sessData = account?.cookies.SESSDATA, !sessData.isEmpty else {
throw APIError.responseError(-101)
}
- guard let csrf = LoginSession.shared.cookies?.bili_jct, !csrf.isEmpty else {
+ guard let csrf = account?.cookies.bili_jct, !csrf.isEmpty else {
throw APIError.responseError(-111)
}
let resolvedAid: Int?
@@ -2374,7 +2424,7 @@ class BiliAPI {
"csrf": csrf
]
- guard let request = makePostFormRequest(
+ guard let request = makePostFormRequest(account: account,
urlString: "https://api.bilibili.com/x/v2/history/toview/del",
parameters: params
) else {
@@ -2392,11 +2442,12 @@ class BiliAPI {
}
func fetchWatchLaterList() async throws -> WatchLaterData {
+ let account = LoginSession.shared.account(for: .main)
guard let url = URL(string: "https://api.bilibili.com/x/v2/history/toview") else {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
@@ -2424,6 +2475,7 @@ class BiliAPI {
fnval: Int = 4048,
qn: Int = 127
) async throws -> PlayUrlResponse {
+ let account = LoginSession.shared.account(for: .playback)
var components = URLComponents(
string: "https://api.bilibili.com/x/player/wbi/playurl"
)
@@ -2440,7 +2492,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- let request = makeRequest(url: signedURL)
+ let request = makeRequest(account: account, url: signedURL)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -2459,8 +2511,10 @@ class BiliAPI {
func fetchPlayerWbiV2(
bvid: String,
- cid: Int
+ cid: Int,
+ role: AccountRole = .playback
) async throws -> PlayerWbiV2Response {
+ let account = LoginSession.shared.account(for: role)
var components = URLComponents(
string: "https://api.bilibili.com/x/player/wbi/v2"
)
@@ -2474,7 +2528,7 @@ class BiliAPI {
}
let signedURL = try await BiliWbiSigner.shared.sign(url: url)
- let request = makeRequest(url: signedURL)
+ let request = makeRequest(account: account, url: signedURL)
let (data, _) = try await URLSession.shared.data(for: request)
let response = try JSONDecoder().decode(
@@ -2495,6 +2549,7 @@ class BiliAPI {
bvid: String,
cid: Int
) async throws -> VideoShotPreviewMetadata {
+ let account = LoginSession.shared.account(for: .playback)
var components = URLComponents(
string: "https://api.bilibili.com/x/player/videoshot"
)
@@ -2508,7 +2563,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -2538,11 +2593,12 @@ class BiliAPI {
}
private func fetchVideoShotTimestamps(from rawURL: String) async throws -> [TimeInterval] {
+ let account = LoginSession.shared.account(for: .playback)
guard let url = normalizeBilibiliURL(rawURL) else {
throw APIError.invalidURL
}
- let request = makeRequest(url: url)
+ let request = makeRequest(account: account, url: url)
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode)
@@ -2596,23 +2652,9 @@ class BiliAPI {
cid: Int,
progress: Int
) async throws {
- var components = URLComponents(
- string: "https://api.bilibili.com/x/v2/history/report"
- )
- components?.queryItems = [
- URLQueryItem(name: "aid", value: String(aid)),
- URLQueryItem(name: "cid", value: String(cid)),
- URLQueryItem(name: "progress", value: String(progress)),
- URLQueryItem(name: "platform", value: "web"),
- URLQueryItem(name: "csrf", value: LoginSession.shared.cookies?.bili_jct ?? "")
- ]
-
- guard let url = components?.url else {
- throw APIError.invalidURL
- }
-
- var request = makeRequest(url: url)
- request.httpMethod = "POST"
+ guard let request = AccountRequest.historyRequest(
+ state: LoginSession.shared.snapshot, aid: aid, cid: cid, progress: progress
+ ) else { return }
let (_, response) = try await URLSession.shared.data(for: request)
@@ -2640,6 +2682,7 @@ class BiliAPI {
cid: Int,
segmentIndex: Int = 1
) async throws -> Data {
+ let account = LoginSession.shared.account(for: .main)
var components = URLComponents(
string: "https://api.bilibili.com/x/v2/dm/web/seg.so"
)
@@ -2653,7 +2696,7 @@ class BiliAPI {
throw APIError.invalidURL
}
- var request = makeRequest(url: url)
+ var request = makeRequest(account: account, url: url)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue(
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Mobile/15E148 Safari/604.1",
diff --git a/PiliPod/Services/BiliWbiSigner.swift b/PiliPod/Services/BiliWbiSigner.swift
index b55de35..1e56bd9 100644
--- a/PiliPod/Services/BiliWbiSigner.swift
+++ b/PiliPod/Services/BiliWbiSigner.swift
@@ -171,10 +171,8 @@ actor BiliWbiSigner {
forHTTPHeaderField: "User-Agent"
)
- let cookie = LoginSession.shared.cookieString
- if !cookie.isEmpty {
- request.setValue(cookie, forHTTPHeaderField: "Cookie")
- }
+ // WBI keys are public and must not borrow the main account's credentials.
+ request.httpShouldHandleCookies = false
let (data, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
diff --git a/PiliPod/Services/LiveDanmakuService.swift b/PiliPod/Services/LiveDanmakuService.swift
index 1c3c07e..5806030 100644
--- a/PiliPod/Services/LiveDanmakuService.swift
+++ b/PiliPod/Services/LiveDanmakuService.swift
@@ -127,6 +127,7 @@ final class LiveDanmakuService: NSObject {
var request = URLRequest(url: url)
request.timeoutInterval = 30
+ request.httpShouldHandleCookies = false
let cookie = LoginSession.shared.cookieString
if !cookie.isEmpty {
request.setValue(cookie, forHTTPHeaderField: "Cookie")
diff --git a/PiliPod/Services/MPVKitPlayer.swift b/PiliPod/Services/MPVKitPlayer.swift
index d08064d..3eff7a7 100644
--- a/PiliPod/Services/MPVKitPlayer.swift
+++ b/PiliPod/Services/MPVKitPlayer.swift
@@ -153,7 +153,7 @@ class MPVKitPlayer: NSObject {
override init() {
self.httpHeaders = [
- "Cookie": LoginSession.shared.cookieString,
+ "Cookie": LoginSession.shared.account(for: .playback)?.cookieString ?? "",
"User-Agent": "Mozilla/5.0 BiliIOS/1.0",
"Referer": "https://www.bilibili.com/",
"Origin": "https://www.bilibili.com"
diff --git a/PiliPod/Services/OfflineCacheService.swift b/PiliPod/Services/OfflineCacheService.swift
index efc145c..eb2d336 100644
--- a/PiliPod/Services/OfflineCacheService.swift
+++ b/PiliPod/Services/OfflineCacheService.swift
@@ -1311,7 +1311,7 @@ final class OfflineCacheManager: ObservableObject {
private func makeMediaRequest(url: URL) -> URLRequest {
var request = URLRequest(url: url)
- request.setValue(LoginSession.shared.cookieString, forHTTPHeaderField: "Cookie")
+ AccountRequest.apply(LoginSession.shared.account(for: .playback), to: &request)
request.setValue("https://www.bilibili.com", forHTTPHeaderField: "Referer")
request.setValue("Mozilla/5.0 BiliIOS/1.0", forHTTPHeaderField: "User-Agent")
return request
diff --git a/PiliPod/Services/SubtitleTrackLoader.swift b/PiliPod/Services/SubtitleTrackLoader.swift
index dc22cd8..4adfdca 100644
--- a/PiliPod/Services/SubtitleTrackLoader.swift
+++ b/PiliPod/Services/SubtitleTrackLoader.swift
@@ -52,7 +52,7 @@ final class SubtitleTrackLoader {
var request = URLRequest(url: url)
request.setValue("Mozilla/5.0 BiliIOS/1.0", forHTTPHeaderField: "User-Agent")
request.setValue("https://www.bilibili.com/", forHTTPHeaderField: "Referer")
- request.setValue(LoginSession.shared.cookieString, forHTTPHeaderField: "Cookie")
+ AccountRequest.apply(LoginSession.shared.account(for: .playback), to: &request)
let (data, response) = try await URLSession.shared.data(for: request)
guard loadingTrackID == trackID else { return }
guard let httpResponse = response as? HTTPURLResponse,
diff --git a/PiliPod/ViewModels/HistoryViewModel.swift b/PiliPod/ViewModels/HistoryViewModel.swift
index b1403b8..0059470 100644
--- a/PiliPod/ViewModels/HistoryViewModel.swift
+++ b/PiliPod/ViewModels/HistoryViewModel.swift
@@ -8,6 +8,7 @@ final class HistoryViewModel: ObservableObject {
@Published var errorMessage: String?
@Published var hasMore = true
+ private var loadedAccountID: String?
private var nextCursor: HistoryCursor?
private var hasLoadedOnce = false
private let pageSize = 20
@@ -30,12 +31,26 @@ final class HistoryViewModel: ObservableObject {
await Task.yield()
}
+ guard LoginSession.shared.account(for: .history) != nil else {
+ videos = []
+ nextCursor = nil
+ hasMore = false
+ errorMessage = "记录观看账号为匿名,请在账号与隐私设置中选择账号。"
+ return
+ }
+ let accountID = LoginSession.shared.selectedID(for: .history)
+ if loadedAccountID != accountID {
+ videos = []
+ nextCursor = nil
+ }
isLoading = true
errorMessage = nil
defer { isLoading = false }
do {
let page = try await BiliAPI.shared.fetchHistoryList(type: type, ps: pageSize)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .history) else { return }
+ loadedAccountID = accountID
let items = (page.list ?? []).filter { $0.history?.business == type }
videos = items.map { VideoItem(from: $0) }
nextCursor = page.cursor
@@ -61,6 +76,7 @@ final class HistoryViewModel: ObservableObject {
}
func loadMore() async {
+ let accountID = LoginSession.shared.selectedID(for: .history)
guard !isLoading, hasMore, let cursor = nextCursor else { return }
guard let max = cursor.max, let viewAt = cursor.viewAt else {
hasMore = false
@@ -78,6 +94,8 @@ final class HistoryViewModel: ObservableObject {
type: type,
ps: pageSize
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .history) else { return }
+ loadedAccountID = accountID
let items = (page.list ?? []).filter { $0.history?.business == type }
let moreVideos = items.map { VideoItem(from: $0) }
diff --git a/PiliPod/ViewModels/HomeViewModel.swift b/PiliPod/ViewModels/HomeViewModel.swift
index 9bf9b45..e87e4f7 100644
--- a/PiliPod/ViewModels/HomeViewModel.swift
+++ b/PiliPod/ViewModels/HomeViewModel.swift
@@ -69,10 +69,12 @@ class HomeViewModel {
private var appNextIdx: Int = 0
func loadUserIfNeeded() async {
+ let accountID = LoginSession.shared.selectedID(for: .main)
guard LoginSession.shared.isLogin else { return }
do {
let user = try await BiliAPI.shared.fetchMyInfo()
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .main) else { return }
userFace = user.face
} catch {
ErrorLogService.record(error, context: "加载账号头像")
@@ -81,6 +83,7 @@ class HomeViewModel {
}
func loadUnreadMessageCount(force: Bool = false) async {
+ let accountID = LoginSession.shared.selectedID(for: .main)
guard LoginSession.shared.isLogin else {
unreadMessageCount = 0
unreadReplyCount = 0
@@ -89,6 +92,16 @@ class HomeViewModel {
return
}
+ if force {
+ unreadMessageCount = 0
+ unreadReplyCount = 0
+ unreadAtCount = 0
+ unreadLikeCount = 0
+ while isLoadingUnreadMessageCount {
+ guard !Task.isCancelled else { return }
+ await Task.yield()
+ }
+ }
guard !isLoadingUnreadMessageCount else { return }
if !force,
let lastRequest = lastUnreadMessageRequestAt,
@@ -101,6 +114,7 @@ class HomeViewModel {
defer { isLoadingUnreadMessageCount = false }
do {
let counts = try await BiliAPI.shared.fetchUnreadMessageCounts()
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .main) else { return }
unreadMessageCount = counts.total
unreadReplyCount = counts.reply
unreadAtCount = counts.at
@@ -120,6 +134,19 @@ class HomeViewModel {
await loadUnreadMessageCount()
}
+ func reloadForAccountChange() async {
+ while isLoading {
+ guard !Task.isCancelled else { return }
+ await Task.yield()
+ }
+ guard !Task.isCancelled else { return }
+ sections = []
+ feedCards = []
+ refreshMarkerIndex = nil
+ hasLoaded = false
+ await loadInitialVideos()
+ }
+
// MARK: - 统一推荐入口
func loadInitialVideos() async {
@@ -135,6 +162,7 @@ class HomeViewModel {
}
func refreshVideos() async {
+ let accountID = LoginSession.shared.selectedID(for: .recommendation)
if isLoading { return }
let latestMode = RecommendSettingsStore.loadSource()
@@ -164,6 +192,7 @@ class HomeViewModel {
let newVideos = try await BiliAPI.shared.fetchRecommendVideos(
freshIdx: freshIdx, freshType: 3, brush: brush
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .recommendation) else { return }
// 下拉刷新:将新视频作为独立 section 插入顶部,旧内容放在下方
let newSection = VideoSection(title: "上次看到这", videos: newVideos)
sections.insert(newSection, at: 0)
@@ -177,6 +206,7 @@ class HomeViewModel {
let (cards, nextIdx) = try await BiliAPI.shared.fetchAppRecommendFeed(
idx: 0, flush: 1
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .recommendation) else { return }
// 下拉刷新:新内容插入到已有列表顶部
feedCards.insert(contentsOf: cards, at: 0)
refreshMarkerIndex = cards.count
@@ -189,6 +219,7 @@ class HomeViewModel {
}
func loadMoreVideos() async {
+ let accountID = LoginSession.shared.selectedID(for: .recommendation)
if isLoading { return }
isLoading = true
@@ -204,6 +235,7 @@ class HomeViewModel {
let moreVideos = try await BiliAPI.shared.fetchRecommendVideos(
freshIdx: freshIdx, freshType: 4, brush: brush
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .recommendation) else { return }
if let lastIndex = sections.indices.last {
sections[lastIndex].videos.append(contentsOf: moreVideos)
}
@@ -217,6 +249,7 @@ class HomeViewModel {
let (cards, nextIdx) = try await BiliAPI.shared.fetchAppRecommendFeed(
idx: appNextIdx, flush: 0
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .recommendation) else { return }
feedCards.append(contentsOf: cards)
appNextIdx = nextIdx
} catch {
@@ -237,12 +270,14 @@ class HomeViewModel {
}
private func fetchInitialVideosForCurrentMode() async {
+ let accountID = LoginSession.shared.selectedID(for: .recommendation)
switch apiMode {
case .web:
do {
let videos = try await BiliAPI.shared.fetchRecommendVideos(
freshIdx: freshIdx, freshType: 4, brush: brush
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .recommendation) else { return }
sections = [VideoSection(title: nil, videos: videos)]
feedCards = []
} catch {
@@ -255,6 +290,7 @@ class HomeViewModel {
let (cards, nextIdx) = try await BiliAPI.shared.fetchAppRecommendFeed(
idx: 0, flush: 1
)
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .recommendation) else { return }
feedCards = cards
sections = []
appNextIdx = nextIdx
diff --git a/PiliPod/ViewModels/LoginViewModel.swift b/PiliPod/ViewModels/LoginViewModel.swift
index 5e5e940..a83767d 100644
--- a/PiliPod/ViewModels/LoginViewModel.swift
+++ b/PiliPod/ViewModels/LoginViewModel.swift
@@ -10,7 +10,121 @@ import Foundation
@MainActor
final class LoginViewModel: ObservableObject {
- let authService = BiliAuthService()
+ let authService: BiliAuthService
+ init(authService: BiliAuthService = BiliAuthService()) { self.authService = authService }
+
+ enum Method: String, CaseIterable { case password = "密码", sms = "短信", qr = "扫码", cookie = "Cookie" }
+ @Published var method = Method.password
+ @Published var phone = ""
+ @Published var country = BiliLoginCountry.china
+ @Published var countries = [BiliLoginCountry.china]
+ @Published var smsCode = ""
+ @Published var cookieText = ""
+ @Published var qrURL: String?
+ @Published var qrMessage = ""
+ @Published var smsMessage = ""
+ @Published var resendAt = Date.distantPast
+ private var smsCredential: (phone: String, country: Int, key: String)?
+ private var smsCaptchaTarget: (phone: String, country: Int)?
+
+ func loadCountries() async {
+ if let loaded = try? await authService.countries(), !loaded.isEmpty { countries = loaded }
+ }
+
+ func runQRCode() async {
+ qrURL = nil
+ qrMessage = "正在获取二维码…"
+ errorMessage = nil
+ do {
+ let qr = try await authService.generateQRCode()
+ try Task.checkCancellation()
+ qrURL = qr.url
+ qrMessage = "请使用哔哩哔哩客户端扫码并确认登录"
+ let deadline = Date().addingTimeInterval(TimeInterval(qr.expiresIn))
+ while Date() < deadline {
+ try await Task.sleep(for: .seconds(2))
+ let status = try await authService.pollQRCode(qr.authCode)
+ try Task.checkCancellation()
+ switch status {
+ case .waiting(let message): qrMessage = message
+ case .expired: qrURL = nil; qrMessage = "二维码已过期,请刷新"; return
+ case .login(let result): await handleLoginStatus(result); qrURL = nil; return
+ }
+ }
+ qrURL = nil
+ qrMessage = "二维码已过期,请刷新"
+ } catch {
+ guard !Task.isCancelled else { return }
+ qrURL = nil
+ qrMessage = "获取二维码或查询状态失败,请刷新重试"
+ }
+ }
+
+ func sendLoginSMS(captcha: (GeetestValidateResult, String)? = nil) async {
+ guard !isLoading, Date() >= resendAt else { return }
+ let number = phone.trimmingCharacters(in: .whitespaces)
+ guard (5...20).contains(number.count), number.allSatisfy({ $0.isASCII && $0.isNumber }) else {
+ errorMessage = "请输入有效手机号"; return
+ }
+ let selectedCountry = country.callingCode
+ if captcha != nil, smsCaptchaTarget?.phone != number || smsCaptchaTarget?.country != selectedCountry {
+ errorMessage = "手机号或地区已变更,请重新获取验证码"; return
+ }
+ isLoading = true
+ errorMessage = nil
+ defer { isLoading = false }
+ do {
+ let status = try await authService.sendLoginSMS(phone: number, countryID: selectedCountry,
+ captcha: captcha.map { (result: $0.0, token: $0.1) })
+ guard !Task.isCancelled, phone.trimmingCharacters(in: .whitespaces) == number, country.callingCode == selectedCountry else { return }
+ switch status {
+ case .sent(let key):
+ smsCredential = (number, selectedCountry, key)
+ smsCaptchaTarget = nil
+ resendAt = Date().addingTimeInterval(60)
+ smsMessage = "验证码已发送"
+ case .captcha(let challenge):
+ smsCaptchaTarget = (number, selectedCountry)
+ geetestContext = GeetestContext(recaptchaToken: challenge.recaptchaToken,
+ gt: challenge.gt, challenge: challenge.challenge)
+ case .failed(let message): errorMessage = message
+ }
+ } catch { errorMessage = "发送验证码失败,请重试" }
+ }
+
+ func submitSMSCaptcha(_ result: GeetestValidateResult, token: String) async {
+ geetestContext = nil
+ await sendLoginSMS(captcha: (result, token))
+ }
+
+ func submitSelectedMethod() async {
+ guard !isLoading else { return }
+ switch method {
+ case .password: await executeLoginFlow()
+ case .qr: break
+ case .sms:
+ guard let credential = smsCredential,
+ credential.phone == phone.trimmingCharacters(in: .whitespaces), credential.country == country.callingCode,
+ !smsCode.isEmpty, smsCode.allSatisfy({ $0.isASCII && $0.isNumber }) else {
+ errorMessage = "请先为此手机号获取验证码并填写验证码"; return
+ }
+ isLoading = true
+ errorMessage = nil
+ defer { isLoading = false }
+ await handleLoginStatus(authService.loginBySMS(phone: credential.phone, countryID: credential.country,
+ code: smsCode, captchaKey: credential.key))
+ case .cookie:
+ isLoading = true
+ errorMessage = nil
+ defer { isLoading = false }
+ do {
+ let account = try await authService.validateCookie(cookieText.trimmingCharacters(in: .whitespacesAndNewlines))
+ try Task.checkCancellation()
+ try LoginSession.shared.add([account])
+ loginSucceeded = true
+ } catch { errorMessage = "Cookie 无效、已过期或无法保存到安全存储" }
+ }
+ }
@Published var username = ""
@Published var password = ""
@@ -53,6 +167,7 @@ final class LoginViewModel: ObservableObject {
}
func handleLoginStatus(_ status: BiliLoginStatus) async {
+ guard !Task.isCancelled else { return }
switch status {
case .success(let data):
let saved = authService.persistLogin(data: data)
@@ -60,15 +175,12 @@ final class LoginViewModel: ObservableObject {
loginSucceeded = true
print("登录成功并已保存登录状态")
} else {
- errorMessage = "登录成功,但解析登录凭证失败"
- print("登录成功但保存失败:\(data)")
+ errorMessage = "登录成功,但登录凭据无效或无法保存到安全存储"
+ print("登录成功但凭据解析或安全存储失败")
}
case .needGeetest(let recaptchaToken, let gt, let challenge):
print("触发人机验证风控!")
- print("recaptchaToken: \(recaptchaToken)")
- print("gt: \(gt)")
- print("challenge: \(challenge)")
geetestContext = GeetestContext(
recaptchaToken: recaptchaToken,
gt: gt,
diff --git a/PiliPod/ViewModels/MyViewModel.swift b/PiliPod/ViewModels/MyViewModel.swift
index d7eed18..89f0119 100644
--- a/PiliPod/ViewModels/MyViewModel.swift
+++ b/PiliPod/ViewModels/MyViewModel.swift
@@ -14,6 +14,7 @@ final class MyViewModel: ObservableObject {
@Published var stat: MyStat?
func loadUser() async {
+ let accountID = LoginSession.shared.selectedID(for: .main)
guard LoginSession.shared.isLogin else {
user = nil
stat = nil
@@ -24,8 +25,11 @@ final class MyViewModel: ObservableObject {
async let userInfo = BiliAPI.shared.fetchMyInfo()
async let userStat = BiliAPI.shared.fetchMyStat()
- user = try await userInfo
- stat = try await userStat
+ let loadedUser = try await userInfo
+ let loadedStat = try await userStat
+ guard !Task.isCancelled, accountID == LoginSession.shared.selectedID(for: .main) else { return }
+ user = loadedUser
+ stat = loadedStat
} catch {
ErrorLogService.record(error, context: "加载我的资料")
print(error)
diff --git a/PiliPod/ViewModels/VideoDetailViewModel.swift b/PiliPod/ViewModels/VideoDetailViewModel.swift
index f2d1a37..4cba1f0 100644
--- a/PiliPod/ViewModels/VideoDetailViewModel.swift
+++ b/PiliPod/ViewModels/VideoDetailViewModel.swift
@@ -98,6 +98,7 @@ class VideoDetailViewModel {
private var historyReportTimer: Timer?
private var historyReportStartTask: Task?
private var videoShotWarmTask: Task?
+ private var lastReportedAccountID: String?
private var lastReportedProgress = 0
private var playerRebuildToken = UUID()
private var isRebuildingPlayer = false
@@ -228,8 +229,17 @@ class VideoDetailViewModel {
cid: detail.cid
)
let playerInfoData = playerInfoResponse.data
- let lastPlayCID = playerInfoData?.lastPlayCid
- let lastPlayTimeMilliseconds = playerInfoData?.lastPlayTime
+ let session = LoginSession.shared
+ var historyInfo = playerInfoData
+ if !session.incognito, session.account(for: .history) != nil,
+ session.selectedID(for: .history) != session.selectedID(for: .playback) {
+ historyInfo = try? await BiliAPI.shared.fetchPlayerWbiV2(
+ bvid: bvid, cid: detail.cid, role: .history
+ ).data
+ }
+ let useHistory = !session.incognito && session.account(for: .history) != nil
+ let lastPlayCID = useHistory ? historyInfo?.lastPlayCid : nil
+ let lastPlayTimeMilliseconds = useHistory ? historyInfo?.lastPlayTime : nil
let resolvedInitialSeekTime: Double?
if let lastPlayTimeMilliseconds, lastPlayTimeMilliseconds > 0 {
let rawTime = Double(lastPlayTimeMilliseconds)
@@ -825,7 +835,7 @@ class VideoDetailViewModel {
@MainActor
func loadDanmakuSegment(cid: Int? = nil, segmentIndex: Int = 1) async {
- guard !isPlayingOfflineCache else { return }
+ guard !isPlayingOfflineCache, LoginSession.shared.shouldReportHistory else { return }
let targetCid = cid ?? self.cid
guard targetCid > 0 else {
danmakuError = "无效的 cid"
@@ -996,7 +1006,7 @@ class VideoDetailViewModel {
@MainActor
func preloadDanmakuIfNeeded(currentTime: Double) async {
- guard !isPlayingOfflineCache else { return }
+ guard !isPlayingOfflineCache, LoginSession.shared.shouldReportHistory else { return }
let targetCid = cid
guard targetCid > 0 else { return }
@@ -1358,11 +1368,13 @@ class VideoDetailViewModel {
}
private func reportHistoryIfNeeded(with player: MPVKitPlayer) {
- guard !isPlayingOfflineCache else { return }
+ guard !isPlayingOfflineCache, LoginSession.shared.shouldReportHistory else { return }
let currentProgress = Int(player.currentTime)
// 如果进度有改变,才上报
- if currentProgress != lastReportedProgress {
+ let accountID = LoginSession.shared.selectedID(for: .history)
+ if currentProgress != lastReportedProgress || lastReportedAccountID != accountID {
+ lastReportedAccountID = accountID
lastReportedProgress = currentProgress
Task {
@@ -1381,7 +1393,7 @@ class VideoDetailViewModel {
historyReportTimer?.invalidate()
historyReportTimer = nil
- guard !isPlayingOfflineCache else { return }
+ guard !isPlayingOfflineCache, LoginSession.shared.shouldReportHistory else { return }
// 退出时最后上报一次
let finalProgress = Int(player.currentTime)
diff --git a/PiliPod/Views/HistoryView.swift b/PiliPod/Views/HistoryView.swift
index 7311b0e..bf67af5 100644
--- a/PiliPod/Views/HistoryView.swift
+++ b/PiliPod/Views/HistoryView.swift
@@ -1,6 +1,7 @@
import SwiftUI
struct HistoryView: View {
+ @ObservedObject private var session = LoginSession.shared
@StateObject private var viewModel = HistoryViewModel()
@Namespace private var videoHeroNamespace
@State private var selectedVideo: VideoItem?
@@ -69,8 +70,8 @@ struct HistoryView: View {
)
}
}
- .task {
- await viewModel.refresh()
+ .task(id: session.selectedID(for: .history)) {
+ await viewModel.refresh(force: true)
}
}
}
diff --git a/PiliPod/Views/HomePage/HomeView.swift b/PiliPod/Views/HomePage/HomeView.swift
index 379784b..7c49d05 100644
--- a/PiliPod/Views/HomePage/HomeView.swift
+++ b/PiliPod/Views/HomePage/HomeView.swift
@@ -162,21 +162,15 @@ struct HomeView: View {
SearchView()
}
.navigationDestination(isPresented: $isMessageViewPresented) {
- MessageView(viewModel: viewModel)
+ MessageView(viewModel: viewModel).id(loginSession.selectedID(for: .main))
}
}
.task {
await viewModel.refreshUnreadMessageCountIfNeeded()
await viewModel.loadInitialVideos()
}
- .onReceive(loginSession.$isLogin) { isLogin in
- if isLogin {
- Task {
- await viewModel.loadUnreadMessageCount(force: true)
- }
- } else {
- viewModel.unreadMessageCount = 0
- }
+ .onChange(of: loginSession.selectedID(for: .recommendation)) {
+ liveHomeViewModel = LiveHomeViewModel()
}
.onReceive(NotificationCenter.default.publisher(for: .manualPictureInPictureRestoreOnHome)) { notification in
guard let route = notification.object as? ManualPictureInPictureRoute else { return }
@@ -235,6 +229,7 @@ struct HomeView: View {
private func tabPage(for tab: HomeTab, videoCardWidth: CGFloat) -> some View {
if tab == .live {
LiveHomeView(cardWidth: videoCardWidth, viewModel: liveHomeViewModel)
+ .id(loginSession.selectedID(for: .recommendation))
} else if tab == .popular {
PopularVideosPage(
namespace: videoHeroNamespace,
diff --git a/PiliPod/Views/LoginImportView.swift b/PiliPod/Views/LoginImportView.swift
index f2b87f0..fb068f2 100644
--- a/PiliPod/Views/LoginImportView.swift
+++ b/PiliPod/Views/LoginImportView.swift
@@ -13,31 +13,44 @@ struct LoginImportView: View {
let onImported: () -> Void
@State private var showImporter = false
+ @State private var importError: String?
+ @State private var imported = false
- init(title: String = "导入登录数据", onImported: @escaping () -> Void) {
+ init(title: String = "导入账号", onImported: @escaping () -> Void) {
self.title = title
self.onImported = onImported
}
var body: some View {
- Button(title) {
+ Button(title, systemImage: "square.and.arrow.down") {
showImporter = true
}
+ .alert("导入失败", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } })) {
+ Button("确定") { importError = nil }
+ } message: { Text(importError ?? "") }
+ .alert("账号已导入", isPresented: $imported) {
+ Button("确定", role: .cancel) {}
+ } message: {
+ Text("已保留文件中的功能分工。未指定用途的账号可在“账号与隐私”中选择。")
+ }
.fileImporter(
isPresented: $showImporter,
- allowedContentTypes: [.json]
+ // File providers may identify JSON exports as generic data or text.
+ // Validate the actual JSON and account schema after selection.
+ allowedContentTypes: [.data]
) { result in
switch result {
case .success(let url):
do {
try LoginImportService.importFrom(url: url)
+ imported = true
onImported()
} catch {
- print(error)
+ importError = error.localizedDescription
}
case .failure(let error):
- print(error)
+ importError = error.localizedDescription
}
}
}
diff --git a/PiliPod/Views/LoginPage/LoginPageView.swift b/PiliPod/Views/LoginPage/LoginPageView.swift
index 8198a81..e082caf 100644
--- a/PiliPod/Views/LoginPage/LoginPageView.swift
+++ b/PiliPod/Views/LoginPage/LoginPageView.swift
@@ -1,121 +1,141 @@
-//
-// LoginPageView.swift
-// PiliPod
-//
-// Created by co on 2026/5/27.
-//
-
import SwiftUI
+import CoreImage.CIFilterBuiltins
struct LoginPageView: View {
@Environment(\.dismiss) private var dismiss
@StateObject private var viewModel = LoginViewModel()
+ @State private var qrGeneration = UUID()
+ @State private var operation: Task?
var body: some View {
NavigationStack {
- VStack(spacing: 16) {
- HStack(spacing: 15) {
- Image(systemName: "person.fill")
- TextField("账号", text: $viewModel.username)
- .textInputAutocapitalization(.never)
- .autocorrectionDisabled()
- }
- .padding(.vertical, 10)
- .padding(.horizontal, 20)
- .glassEffect(.regular.interactive(), in: .capsule)
-
- HStack(spacing: 15) {
- Image(systemName: "lock.fill")
- SecureField("密码", text: $viewModel.password)
- .textInputAutocapitalization(.never)
- .autocorrectionDisabled()
- }
- .padding(.vertical, 10)
- .padding(.horizontal, 20)
- .glassEffect(.regular.interactive(), in: .capsule)
-
- Button {
- Task {
- await viewModel.executeLoginFlow()
+ ScrollView {
+ VStack(spacing: 20) {
+ Picker("登录方式", selection: $viewModel.method) {
+ ForEach(LoginViewModel.Method.allCases, id: \.self) { Text($0.rawValue).tag($0) }
}
- } label: {
- if viewModel.isLoading {
- ProgressView()
- .frame(maxWidth: .infinity)
- } else {
- Text("登录")
- .frame(maxWidth: .infinity)
- .foregroundStyle(.white)
- .padding(.vertical, 10)
+ .pickerStyle(.segmented)
+ .disabled(viewModel.isLoading)
+ loginFields
+ if viewModel.method != .qr { loginButton }
+ if let message = viewModel.errorMessage {
+ Text(message).font(.footnote).foregroundStyle(.red)
}
}
- .glassEffect(
- .regular.interactive().tint(.blue),
- in: .capsule
- )
- .disabled(viewModel.isLoading)
-
- if let message = viewModel.errorMessage, !message.isEmpty {
- Text(message)
- .font(.footnote)
- .foregroundStyle(.red)
- .frame(maxWidth: .infinity, alignment: .leading)
- }
-
- Spacer()
+ .padding()
}
- .padding()
.navigationTitle("登录")
- .toolbar {
- ToolbarItem(placement: .topBarTrailing) {
- Button("关闭") {
- dismiss()
- }
- }
- }
+ .toolbar { ToolbarItem(placement: .topBarTrailing) { Button("关闭") { dismiss() } } }
}
+ .task { await viewModel.loadCountries() }
+ .task(id: qrTaskID) {
+ if viewModel.method == .qr { await viewModel.runQRCode() }
+ }
+ .onChange(of: viewModel.method) { _, _ in viewModel.errorMessage = nil }
+ .onDisappear { operation?.cancel() }
.sheet(item: $viewModel.geetestContext) { context in
- GeetestCaptchaSheet(
- gt: context.gt,
- challenge: context.challenge
- ) { result in
- Task {
+ GeetestCaptchaSheet(gt: context.gt, challenge: context.challenge) { result in
+ operation = Task {
if viewModel.phoneVerifyContext != nil {
await viewModel.submitPhoneVerifyGeetest(result)
+ } else if viewModel.method == .sms {
+ await viewModel.submitSMSCaptcha(result, token: context.recaptchaToken)
} else {
- await viewModel.submitGeetestResult(
- result,
- recaptchaToken: context.recaptchaToken
- )
+ await viewModel.submitGeetestResult(result, recaptchaToken: context.recaptchaToken)
}
}
}
}
.sheet(item: $viewModel.phoneVerifyContext) { context in
- PhoneVerifySheet(
- phoneText: context.maskedTel,
- isLoading: viewModel.isLoading,
+ PhoneVerifySheet(phoneText: context.maskedTel, isLoading: viewModel.isLoading,
errorMessage: viewModel.phoneVerifyMessage,
- onSendCode: {
- Task {
- await viewModel.sendPhoneVerifySMS()
- }
- },
- onSubmitCode: { code in
- Task {
- await viewModel.submitPhoneVerifyCode(code)
+ onSendCode: { operation = Task { await viewModel.sendPhoneVerifySMS() } },
+ onSubmitCode: { code in operation = Task { await viewModel.submitPhoneVerifyCode(code) } })
+ }
+ .onReceive(viewModel.$loginSucceeded) { if $0 { dismiss() } }
+ }
+
+ private var qrTaskID: String { viewModel.method.rawValue + qrGeneration.uuidString }
+
+ @ViewBuilder private var loginFields: some View {
+ switch viewModel.method {
+ case .password: passwordFields
+ case .sms: smsFields
+ case .qr: qrFields
+ case .cookie: cookieFields
+ }
+ }
+
+ private var passwordFields: some View {
+ VStack(spacing: 16) {
+ TextField("账号", text: $viewModel.username).textContentType(.username)
+ SecureField("密码", text: $viewModel.password).textContentType(.password)
+ }
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .textFieldStyle(.roundedBorder).disabled(viewModel.isLoading)
+ }
+
+ private var smsFields: some View {
+ VStack(spacing: 16) {
+ HStack {
+ Picker("地区", selection: $viewModel.country) {
+ ForEach(viewModel.countries) { country in
+ Text("\(country.name) +\(country.dialCode)").tag(country)
}
}
- )
+ TextField("手机号", text: $viewModel.phone).keyboardType(.phonePad).textContentType(.telephoneNumber)
+ }
+ TextField("短信验证码", text: $viewModel.smsCode).keyboardType(.numberPad).textContentType(.oneTimeCode)
+ TimelineView(.periodic(from: .now, by: 1)) { context in
+ let remaining = max(0, Int(ceil(viewModel.resendAt.timeIntervalSince(context.date))))
+ Button(remaining > 0 ? "\(remaining) 秒后可重新发送" : "获取验证码") {
+ operation = Task { await viewModel.sendLoginSMS() }
+ }
+ .disabled(remaining > 0 || viewModel.isLoading)
+ }
+ Text(viewModel.smsMessage).font(.footnote).foregroundStyle(.secondary)
}
- .onReceive(viewModel.$loginSucceeded) { succeeded in
- if succeeded {
- dismiss()
+ .textFieldStyle(.roundedBorder).disabled(viewModel.isLoading)
+ }
+
+ private var qrFields: some View {
+ VStack(spacing: 16) {
+ if let url = viewModel.qrURL, let image = qrImage(url) {
+ Image(uiImage: image).interpolation(.none).resizable().scaledToFit()
+ .frame(width: 240, height: 240).padding(12).background(.white)
+ .accessibilityLabel("登录二维码,请使用哔哩哔哩扫码")
}
+ Text(viewModel.qrMessage).font(.callout)
+ Button("刷新二维码", systemImage: "arrow.clockwise") { qrGeneration = UUID() }
+ }
+ }
+
+ private var cookieFields: some View {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("粘贴 Cookie(需包含 SESSDATA、bili_jct 和 DedeUserID)").font(.callout)
+ TextEditor(text: $viewModel.cookieText).frame(minHeight: 160)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ .privacySensitive().overlay(RoundedRectangle(cornerRadius: 8).stroke(.secondary.opacity(0.3)))
+ Text("Cookie 登录不包含 App 令牌,部分 App 接口可能不可用。").font(.footnote).foregroundStyle(.secondary)
}
+ .disabled(viewModel.isLoading)
}
-}
-#Preview {
- LoginPageView()
-}
+ private var loginButton: some View {
+ Button { operation = Task { await viewModel.submitSelectedMethod() } } label: {
+ HStack { if viewModel.isLoading { ProgressView() }; Text("登录") }
+ .frame(maxWidth: .infinity).padding(.vertical, 10)
+ }
+ .buttonStyle(.borderedProminent).disabled(viewModel.isLoading)
+ }
+
+ private func qrImage(_ value: String) -> UIImage? {
+ let filter = CIFilter.qrCodeGenerator()
+ filter.message = Data(value.utf8)
+ filter.correctionLevel = "M"
+ guard let output = filter.outputImage,
+ let image = CIContext().createCGImage(output.transformed(by: CGAffineTransform(scaleX: 8, y: 8)),
+ from: output.extent.applying(CGAffineTransform(scaleX: 8, y: 8))) else { return nil }
+ return UIImage(cgImage: image)
+ }
+}
\ No newline at end of file
diff --git a/PiliPod/Views/MainTabView.swift b/PiliPod/Views/MainTabView.swift
index 6778161..91d17f6 100644
--- a/PiliPod/Views/MainTabView.swift
+++ b/PiliPod/Views/MainTabView.swift
@@ -29,7 +29,7 @@ struct MainTabView: View {
Text("首页")
}
- DynamicView()
+ DynamicView().id(loginSession.selectedID(for: .main))
.tag(MainTab.dynamic)
.tabItem {
Image("DynamicIcon")
@@ -45,8 +45,13 @@ struct MainTabView: View {
}
}
.toolbar(.visible, for: .tabBar)
- .task {
+ .task(id: loginSession.selectedID(for: .main)) {
+ homeViewModel.userFace = nil
await homeViewModel.loadUserIfNeeded()
+ await homeViewModel.loadUnreadMessageCount(force: true)
+ }
+ .task(id: loginSession.selectedID(for: .recommendation)) {
+ await homeViewModel.reloadForAccountChange()
}
.task(id: homeViewModel.userFace) {
guard let face = homeViewModel.userFace,
@@ -58,16 +63,7 @@ struct MainTabView: View {
}
profileTabAvatar = tabBarAvatar(from: image)
}
- .onReceive(loginSession.$isLogin) { isLogin in
- if isLogin {
- Task {
- await homeViewModel.loadUserIfNeeded()
- }
- } else {
- homeViewModel.userFace = nil
- profileTabAvatar = nil
- }
- }
+
.onChange(of: selectedTab) { newTab in
guard newTab == .home else { return }
Task {
diff --git a/PiliPod/Views/MyView.swift b/PiliPod/Views/MyView.swift
index 828b54f..c2fa5e3 100644
--- a/PiliPod/Views/MyView.swift
+++ b/PiliPod/Views/MyView.swift
@@ -21,6 +21,9 @@ struct MyView: View {
VStack(spacing: 20) {
// 顶部按钮
HStack {
+ NavigationLink { AccountSettingsView() } label: {
+ Label(loginSession.incognito ? "无痕模式" : "账号", systemImage: loginSession.incognito ? "eye.slash" : "person.2")
+ }
Spacer()
NavigationLink {
SettingsView()
@@ -43,21 +46,14 @@ struct MyView: View {
Spacer()
}
- .task {
+ .task(id: loginSession.selectedID(for: .main)) {
+ viewModel.user = nil
await viewModel.loadUser()
}
.fullScreenCover(isPresented: $showLoginSheet) {
LoginPageView()
}
- .onReceive(loginSession.$isLogin) { isLogin in
- if isLogin {
- Task {
- await viewModel.loadUser()
- }
- } else {
- viewModel.user = nil
- }
- }
+
.navigationDestination(isPresented: $showHistory) {
HistoryView()
}
@@ -65,7 +61,7 @@ struct MyView: View {
OfflineCacheView(initialPrefill: nil)
}
.navigationDestination(isPresented: $showWatchLater) {
- WatchLaterView()
+ WatchLaterView().id(loginSession.selectedID(for: .main))
}
.navigationDestination(item: $followingRoute) { route in
FollowingListView(mid: route.mid)
diff --git a/PiliPod/Views/SearchView.swift b/PiliPod/Views/SearchView.swift
index d82de95..5c325d0 100644
--- a/PiliPod/Views/SearchView.swift
+++ b/PiliPod/Views/SearchView.swift
@@ -846,10 +846,7 @@ struct SearchView: View {
}
private func recordSearchKeyword(_ keyword: String) {
- var updatedHistory = searchHistory.filter { $0 != keyword }
- updatedHistory.insert(keyword, at: 0)
- searchHistory = Array(updatedHistory.prefix(SearchHistoryStore.maximumCount))
- SearchHistoryStore.save(searchHistory)
+ searchHistory = SearchHistoryStore.record(keyword, in: searchHistory, incognito: LoginSession.shared.incognito)
}
private func deleteSearchHistoryItem(_ keyword: String) {
@@ -926,7 +923,13 @@ private struct SearchUserSpaceRoute: Identifiable, Hashable {
var id: Int { mid }
}
-private enum SearchHistoryStore {
+enum SearchHistoryStore {
+ static func record(_ keyword: String, in history: [String], incognito: Bool, defaults: UserDefaults = .standard) -> [String] {
+ guard !incognito else { return history }
+ let updated = Array(([keyword] + history.filter { $0 != keyword }).prefix(maximumCount))
+ defaults.set(updated, forKey: storageKey)
+ return updated
+ }
static let maximumCount = 30
private static let storageKey = "PiliPod.searchHistory"
diff --git a/PiliPod/Views/SettingsContext/AboutView.swift b/PiliPod/Views/SettingsContext/AboutView.swift
index 0cbaf1f..57ff1b2 100644
--- a/PiliPod/Views/SettingsContext/AboutView.swift
+++ b/PiliPod/Views/SettingsContext/AboutView.swift
@@ -69,18 +69,18 @@ struct AboutView: View {
}
}
- Section("登录数据") {
- Button("导入登录信息") {
+ Section("账号数据") {
+ Button("导入账号", systemImage: "square.and.arrow.down") {
activeImporter = .login
showImportSheet = true
}
.foregroundStyle(.primary)
- Button("导出登录信息") {
+ Button("导出账号", systemImage: "square.and.arrow.up") {
prepareLoginExport()
}
.foregroundStyle(.primary)
- .disabled(!loginSession.isLogin)
+ .disabled(loginSession.accounts.isEmpty)
}
Section {
@@ -103,7 +103,8 @@ struct AboutView: View {
.listStyle(.insetGrouped)
.fileImporter(
isPresented: $showImportSheet,
- allowedContentTypes: [.json]
+ // Account exports may be reported as generic data by file providers.
+ allowedContentTypes: activeImporter == .login ? [.data] : [.json]
) { result in
handleImportResult(result, for: activeImporter)
activeImporter = nil
@@ -127,7 +128,7 @@ struct AboutView: View {
} message: {
Text(exportErrorMessage ?? "未知错误")
}
- .alert("登录数据", isPresented: Binding(
+ .alert("账号数据", isPresented: Binding(
get: { loginTransferMessage != nil },
set: { if !$0 { loginTransferMessage = nil } }
)) {
@@ -174,38 +175,12 @@ struct AboutView: View {
}
private func prepareLoginExport() {
- guard let cookies = loginSession.cookies else { return }
-
- let uid = cookies.DedeUserID
- let loginType: [Int] = loginSession.type ?? [0, 1, 2, 3]
-
- let cookieDict: [String: String] = [
- "SESSDATA": cookies.SESSDATA,
- "bili_jct": cookies.bili_jct,
- "DedeUserID": cookies.DedeUserID,
- "DedeUserID__ckMd5": "",
- "sid": cookies.sid ?? "",
- "buvid3": cookies.buvid3 ?? ""
- ]
-
- let userDict: [String: Any] = [
- "cookies": cookieDict,
- "accessKey": loginSession.accessKey ?? "",
- "refresh": loginSession.refresh ?? "",
- "type": loginType
- ]
-
- let payload: [String: Any] = [
- uid: userDict
- ]
-
+ let state = loginSession.snapshot
+ guard !state.accounts.isEmpty else { return }
do {
- let data = try JSONSerialization.data(
- withJSONObject: payload,
- options: [.prettyPrinted, .sortedKeys]
- )
+ let data = try LoginImportService.encode(state)
exportDocument = JSONExportDocument(data: data)
- exportFilename = "bili_login_\(uid).json"
+ exportFilename = "pilipod_account.json"
showExportSheet = true
} catch {
ErrorLogService.record(error, context: "导出登录信息")
@@ -220,7 +195,7 @@ struct AboutView: View {
case let (.login, .success(url)):
do {
try LoginImportService.importFrom(url: url)
- loginTransferMessage = "登录信息已导入。"
+ loginTransferMessage = "账号已导入。"
} catch {
ErrorLogService.record(error, context: "导入登录信息")
loginTransferMessage = error.localizedDescription
@@ -281,7 +256,7 @@ private struct AppIconPreview: View {
#endif
}
-private struct JSONExportDocument: FileDocument {
+struct JSONExportDocument: FileDocument {
static var readableContentTypes: [UTType] { [.json] }
let data: Data
diff --git a/PiliPod/Views/SettingsContext/AccountSettingsView.swift b/PiliPod/Views/SettingsContext/AccountSettingsView.swift
new file mode 100644
index 0000000..cd3a3e2
--- /dev/null
+++ b/PiliPod/Views/SettingsContext/AccountSettingsView.swift
@@ -0,0 +1,119 @@
+import SwiftUI
+import UniformTypeIdentifiers
+
+struct AccountSettingsView: View {
+ @ObservedObject private var session = LoginSession.shared
+ @State private var showLogin = false
+ @State private var errorMessage: String?
+ @State private var pendingRemoval: String?
+ @State private var exportDocument = JSONExportDocument(data: Data())
+ @State private var showExport = false
+
+ var body: some View {
+ List {
+ privacySection
+ assignmentSection
+ accountsSection
+ if let storageError = session.storageError {
+ Section { Text(storageError).foregroundStyle(.red) }
+ }
+ }
+ .navigationTitle("账号与隐私")
+ .task(id: session.accounts.map(\.id)) { await refreshAccountNames() }
+ .fullScreenCover(isPresented: $showLogin) { LoginPageView() }
+ .fileExporter(isPresented: $showExport, document: exportDocument,
+ contentType: .json, defaultFilename: "pilipod_account.json") { result in
+ if case .failure(let error) = result { errorMessage = error.localizedDescription }
+ }
+ .alert("操作失败", isPresented: errorPresented) {
+ Button("确定") { errorMessage = nil }
+ } message: {
+ Text(errorMessage ?? "")
+ }
+ .confirmationDialog("移除此账号?使用该账号的功能将切换为匿名。",
+ isPresented: removalPresented, titleVisibility: .visible) {
+ Button("移除", role: .destructive) {
+ if let id = pendingRemoval { perform { try session.remove(id) } }
+ pendingRemoval = nil
+ }
+ }
+ }
+
+ private var privacySection: some View {
+ Section {
+ Toggle("无痕模式", isOn: Binding(get: { session.incognito }, set: { enabled in
+ perform { try session.setIncognito(enabled) }
+ }))
+ } footer: {
+ Text("开启后不再上报观看记录,也不保存新的搜索历史。取流账号和主动点赞、收藏等操作仍然有效;服务端仍可能识别访问。关闭后恢复原来的账号分工。")
+ }
+ }
+
+ private var assignmentSection: some View {
+ Section {
+ ForEach(AccountRole.allCases) { role in
+ Picker(role.title, selection: assignmentBinding(role)) {
+ Text("0(匿名)").tag("0")
+ ForEach(session.accounts) { account in Text(account.displayName).tag(account.id) }
+ }
+ }
+ Menu("快速统一切换") {
+ Button("0(匿名)") { perform { try session.assign("0") } }
+ ForEach(session.accounts) { account in
+ Button(account.displayName) { perform { try session.assign(account.id) } }
+ }
+ }
+ } footer: {
+ Text("主账号用于个人信息和互动;记录观看用于观看记录上报和历史列表,选择匿名时不上报;推荐用于推荐流;视频取流用于播放和缓存下载。")
+ }
+ }
+
+ private var accountsSection: some View {
+ Section("已登录账号") {
+ ForEach(session.accounts) { account in
+ HStack {
+ Label(account.displayName, systemImage: "person.crop.circle")
+ Spacer()
+ Button("移除", role: .destructive) { pendingRemoval = account.id }
+ .buttonStyle(.borderless)
+ }
+ }
+ Button("添加账号", systemImage: "person.badge.plus") { showLogin = true }
+ LoginImportView(onImported: {})
+ Button("导出账号", systemImage: "square.and.arrow.up") {
+ perform {
+ exportDocument = JSONExportDocument(data: try LoginImportService.encode(session.snapshot))
+ showExport = true
+ }
+ }
+ .disabled(session.accounts.isEmpty)
+ }
+ }
+ private var errorPresented: Binding {
+ Binding(get: { errorMessage != nil }, set: { if !$0 { errorMessage = nil } })
+ }
+ private var removalPresented: Binding {
+ Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } })
+ }
+ private func assignmentBinding(_ role: AccountRole) -> Binding {
+ Binding(get: { session.selectedID(for: role) }, set: { id in
+ perform { try session.assign(id, to: role) }
+ })
+ }
+ private func perform(_ action: () throws -> Void) {
+ do { try action() } catch { errorMessage = error.localizedDescription }
+ }
+ private func refreshAccountNames() async {
+ let auth = BiliAuthService()
+ for account in session.accounts {
+ guard !Task.isCancelled else { return }
+ do {
+ let name = try await auth.fetchAccountName(account)
+ try Task.checkCancellation()
+ try session.updateUsername(name, for: account)
+ } catch {
+ // Keep cached names (or the UID fallback) when offline or expired.
+ }
+ }
+ }
+}
diff --git a/PiliPod/Views/SettingsView.swift b/PiliPod/Views/SettingsView.swift
index 5b705ea..08c2845 100644
--- a/PiliPod/Views/SettingsView.swift
+++ b/PiliPod/Views/SettingsView.swift
@@ -3,8 +3,17 @@ import SwiftUI
struct SettingsView: View {
@ObservedObject private var loginSession = LoginSession.shared
+ @State private var accountError: String?
+
var body: some View {
List {
+ Section {
+ NavigationLink {
+ AccountSettingsView()
+ } label: {
+ SettingsCategoryRow(title: "账号与隐私", systemImage: "person.2.fill", tint: .purple)
+ }
+ }
Section {
NavigationLink {
RecommendSettingsView()
@@ -79,7 +88,8 @@ struct SettingsView: View {
Section {
Button {
- LoginImportService.clearLoginState()
+ do { try LoginImportService.clearLoginState() }
+ catch { accountError = error.localizedDescription }
} label: {
SettingsCategoryRow(
title: "退出登录",
@@ -91,6 +101,9 @@ struct SettingsView: View {
.disabled(!loginSession.isLogin)
}
}
+ .alert("操作失败", isPresented: Binding(get: { accountError != nil }, set: { if !$0 { accountError = nil } })) {
+ Button("确定") { accountError = nil }
+ } message: { Text(accountError ?? "") }
.navigationTitle("设置")
.navigationBarTitleDisplayMode(.inline)
.listStyle(.insetGrouped)
diff --git a/PiliPod/Views/VideoDetail/VideoDetailPage.swift b/PiliPod/Views/VideoDetail/VideoDetailPage.swift
index 722b461..a9beb8a 100644
--- a/PiliPod/Views/VideoDetail/VideoDetailPage.swift
+++ b/PiliPod/Views/VideoDetail/VideoDetailPage.swift
@@ -4138,10 +4138,7 @@ private actor VideoShotSpriteLoader {
forHTTPHeaderField: "User-Agent"
)
- let cookie = LoginSession.shared.cookieString
- if !cookie.isEmpty {
- request.setValue(cookie, forHTTPHeaderField: "Cookie")
- }
+ AccountRequest.apply(LoginSession.shared.account(for: .playback), to: &request)
guard let (data, response) = try? await URLSession.shared.data(for: request),
let httpResponse = response as? HTTPURLResponse,
diff --git a/PiliPodTests/AccountPrivacyTests.swift b/PiliPodTests/AccountPrivacyTests.swift
new file mode 100644
index 0000000..6bf8355
--- /dev/null
+++ b/PiliPodTests/AccountPrivacyTests.swift
@@ -0,0 +1,215 @@
+import Foundation
+import Testing
+@testable import PiliPod
+
+private final class MemoryAccountVault: AccountVault {
+ var data: Data?
+ var failSave = false
+ var failLoad = false
+ func load() throws -> Data? {
+ if failLoad { throw AccountStorageError.keychain(-1) }
+ return data
+ }
+ func save(_ data: Data) throws {
+ if failSave { throw AccountStorageError.keychain(-1) }
+ self.data = data
+ }
+}
+
+@MainActor
+struct AccountPrivacyTests {
+ @Test func usernamesPersistWithoutChangingAssignmentsOrCredentials() throws {
+ let vault = MemoryAccountVault()
+ let session = LoginSession(vault: vault)
+ let original = account("1")
+ try session.add([original, account("2")])
+ let assignments = session.snapshot.assignments
+ try session.updateUsername(" 用户名 ", for: original)
+ let restored = LoginSession(vault: vault)
+ restored.restore()
+ #expect(restored.accounts.first { $0.id == "1" }?.displayName == "用户名(1)")
+ #expect(restored.snapshot.assignments == assignments)
+ #expect(restored.accounts.first { $0.id == "1" }?.accessKey == original.accessKey)
+ #expect(restored.accounts.first { $0.id == "2" }?.displayName == "2")
+ }
+
+ @Test func usernameResponseCannotUpdateRemovedOrReauthenticatedAccount() throws {
+ let session = LoginSession(vault: MemoryAccountVault())
+ let old = account("1")
+ try session.add([old])
+ try session.remove("1")
+ try session.updateUsername("旧用户名", for: old)
+ #expect(session.accounts.isEmpty)
+ let replacement = BiliAccount(cookies: BiliCookie(SESSDATA: "new-session", bili_jct: "new-csrf",
+ DedeUserID: "1", sid: nil, buvid3: nil), accessKey: nil, refresh: nil, type: nil)
+ try session.add([replacement])
+ try session.updateUsername("旧用户名", for: old)
+ #expect(session.accounts.first?.username == nil)
+ }
+
+ private func account(_ id: String, type: [Int]? = nil) -> BiliAccount {
+ BiliAccount(cookies: BiliCookie(SESSDATA: "session-\(id)", bili_jct: "csrf-\(id)",
+ DedeUserID: id, sid: nil, buvid3: nil), accessKey: "token-\(id)", refresh: "refresh-\(id)", type: type)
+ }
+ @Test func roleAssignmentsRemainIndependentAndSurviveRestore() throws {
+ let vault = MemoryAccountVault()
+ let session = LoginSession(vault: vault)
+ try session.add([account("1")])
+ try session.add([account("2")])
+ try session.assign("2", to: .playback)
+ try session.assign("0", to: .recommendation)
+ let restored = LoginSession(vault: vault)
+ restored.restore()
+ #expect(restored.account(for: .main)?.id == "2")
+ #expect(restored.account(for: .history)?.id == "1")
+ #expect(restored.account(for: .recommendation) == nil)
+ #expect(restored.account(for: .playback)?.accessKey == "token-2")
+ }
+ @Test func incognitoPreservesAssignmentsAndStopsHistory() throws {
+ let session = LoginSession(vault: MemoryAccountVault())
+ try session.add([account("1")])
+ let assignments = session.snapshot.assignments
+ try session.setIncognito(true)
+ #expect(!session.shouldReportHistory)
+ #expect(session.account(for: .playback)?.id == "1")
+ #expect(session.snapshot.assignments == assignments)
+ try session.setIncognito(false)
+ #expect(session.shouldReportHistory)
+ try session.assign("0", to: .history)
+ #expect(!session.shouldReportHistory)
+ }
+ @Test func removalUsesAnonymousWithoutChangingOtherAccounts() throws {
+ let session = LoginSession(vault: MemoryAccountVault())
+ try session.add([account("1"), account("2")])
+ try session.assign("2", to: .playback)
+ try session.remove("1")
+ #expect(!session.isLogin)
+ #expect(!session.shouldReportHistory)
+ #expect(session.account(for: .playback)?.id == "2")
+ #expect(session.accounts.count == 1)
+ }
+ @Test func failedWriteLeavesWorkingSessionAndLegacyDataIntact() throws {
+ let vault = MemoryAccountVault()
+ let session = LoginSession(vault: vault)
+ try session.add([account("1")])
+ vault.failSave = true
+ #expect(throws: AccountStorageError.self) { try session.assign("0") }
+ #expect(session.account(for: .main)?.id == "1")
+ let suite = "PiliPod.Tests.\(UUID().uuidString)"
+ let defaults = try #require(UserDefaults(suiteName: suite))
+ defer { defaults.removePersistentDomain(forName: suite) }
+ defaults.set(try JSONEncoder().encode(account("2").cookies), forKey: "bili_cookie")
+ vault.data = nil
+ session.restore(defaults: defaults)
+ #expect(defaults.data(forKey: "bili_cookie") != nil)
+ #expect(session.storageError != nil)
+ }
+ @Test func legacyMigrationMovesAllCredentialsToVault() throws {
+ let suite = "PiliPod.Tests.\(UUID().uuidString)"
+ let defaults = try #require(UserDefaults(suiteName: suite))
+ defer { defaults.removePersistentDomain(forName: suite) }
+ defaults.set(try JSONEncoder().encode(account("1").cookies), forKey: "bili_cookie")
+ defaults.set("legacy-token", forKey: "bili_accessKey")
+ defaults.set("legacy-refresh", forKey: "bili_refresh")
+ let vault = MemoryAccountVault()
+ let session = LoginSession(vault: vault)
+ session.restore(defaults: defaults)
+ #expect(session.accessKey == "legacy-token")
+ #expect(session.refresh == "legacy-refresh")
+ #expect(defaults.data(forKey: "bili_cookie") == nil)
+ #expect(vault.data != nil)
+ for role in AccountRole.allCases { #expect(session.selectedID(for: role) == "1") }
+ }
+ @Test func importedRolesAndAllAccountsArePreserved() throws {
+ let payload: [String: Any] = [
+ "1": ["cookies": ["SESSDATA": "a", "bili_jct": "b", "DedeUserID": "1"], "type": [0, 1]],
+ "2": ["cookies": ["SESSDATA": "c", "bili_jct": "d", "DedeUserID": "2"], "type": [3]]
+ ]
+ let decoded = try LoginImportService.decode(JSONSerialization.data(withJSONObject: payload))
+ let session = LoginSession(vault: MemoryAccountVault())
+ try session.add(decoded)
+ #expect(session.accounts.count == 2)
+ #expect(session.account(for: .main)?.id == "1")
+ #expect(session.account(for: .history)?.id == "1")
+ #expect(session.account(for: .recommendation) == nil)
+ #expect(session.account(for: .playback)?.id == "2")
+ #expect(throws: AccountStorageError.self) {
+ try LoginImportService.decode(Data("{\"1\":{\"cookies\":{}}}".utf8))
+ }
+ }
+ @Test func anonymousRequestRemovesCookiesAndDisablesCookieJar() throws {
+ var request = URLRequest(url: try #require(URL(string: "https://api.bilibili.com/test")))
+ AccountRequest.apply(account("1"), to: &request)
+ #expect(request.value(forHTTPHeaderField: "Cookie")?.contains("session-1") == true)
+ AccountRequest.apply(nil, to: &request)
+ #expect(request.value(forHTTPHeaderField: "Cookie") == nil)
+ #expect(!request.httpShouldHandleCookies)
+ #expect(request.cachePolicy == .reloadIgnoringLocalCacheData)
+ }
+ @Test func capturedCredentialsDoNotChangeAfterSwitching() throws {
+ let session = LoginSession(vault: MemoryAccountVault())
+ try session.add([account("1"), account("2")])
+ let captured = try #require(session.account(for: .main))
+ try session.assign("2")
+ #expect(captured.cookies.bili_jct == "csrf-1")
+ #expect(captured.cookieString.contains("session-1"))
+ #expect(captured.accessKey == "token-1")
+ }
+ @Test func historyRequestUsesHistoryCSRFAndNeverExistsInIncognito() throws {
+ var state = AccountState()
+ state.add(account("1"), activate: true)
+ state.add(account("2"), activate: true)
+ let request = try #require(AccountRequest.historyRequest(state: state, aid: 3, cid: 4, progress: 5))
+ #expect(request.value(forHTTPHeaderField: "Cookie")?.contains("session-1") == true)
+ #expect(request.url?.query?.contains("csrf=csrf-1") == true)
+ #expect(request.httpMethod == "POST")
+ state.incognito = true
+ #expect(AccountRequest.historyRequest(state: state, aid: 3, cid: 4, progress: 5) == nil)
+ state.incognito = false
+ state.assignments[.history] = "0"
+ #expect(AccountRequest.historyRequest(state: state, aid: 3, cid: 4, progress: 5) == nil)
+ }
+ @Test func signedAppRequestsKeepTokenAndCookieFromTheSameAccount() throws {
+ let api = BiliAPI.shared
+ let request = try #require(api.makeAppRequest(account: account("2"),
+ baseURLString: "https://app.bilibili.com/x/v2/feed/index"))
+ #expect(request.url?.query?.contains("access_key=token-2") == true)
+ #expect(request.value(forHTTPHeaderField: "Cookie")?.contains("session-2") == true)
+ let anonymous = try #require(api.makeAppRequest(account: nil,
+ baseURLString: "https://app.bilibili.com/x/v2/feed/index", parameters: ["access_key": "stale-token"]))
+ #expect(anonymous.url?.query?.contains("access_key") == false)
+ #expect(anonymous.value(forHTTPHeaderField: "Cookie") == nil)
+ #expect(!anonymous.httpShouldHandleCookies)
+ }
+ @Test func incognitoSearchDoesNotPersistOrEraseExistingHistory() throws {
+ let suite = "PiliPod.Tests.\(UUID().uuidString)"
+ let defaults = try #require(UserDefaults(suiteName: suite))
+ defer { defaults.removePersistentDomain(forName: suite) }
+ let existing = SearchHistoryStore.record("old", in: [], incognito: false, defaults: defaults)
+ let result = SearchHistoryStore.record("private", in: existing, incognito: true, defaults: defaults)
+ #expect(result == ["old"])
+ #expect(defaults.stringArray(forKey: "PiliPod.searchHistory") == ["old"])
+ #expect(SearchHistoryStore.record("new", in: result, incognito: false, defaults: defaults) == ["new", "old"])
+ }
+
+ @Test func failedRestoreCannotOverwriteStoredAccounts() throws {
+ let vault = MemoryAccountVault()
+ let original = LoginSession(vault: vault)
+ try original.add([account("1")])
+ let saved = vault.data
+ vault.failLoad = true
+ let session = LoginSession(vault: vault)
+ session.restore()
+ #expect(throws: AccountStorageError.self) { try session.setIncognito(true) }
+ #expect(vault.data == saved)
+ vault.failLoad = false
+ try session.setIncognito(true)
+ #expect(session.account(for: .main)?.id == "1")
+ #expect(session.incognito)
+ let restored = LoginSession(vault: vault)
+ restored.restore()
+ #expect(restored.incognito)
+ #expect(!restored.shouldReportHistory)
+ }
+
+}
diff --git a/PiliPodTests/LoginMethodTests.swift b/PiliPodTests/LoginMethodTests.swift
new file mode 100644
index 0000000..0076d61
--- /dev/null
+++ b/PiliPodTests/LoginMethodTests.swift
@@ -0,0 +1,205 @@
+import Foundation
+import Security
+import Testing
+@testable import PiliPod
+
+private final class LoginMockProtocol: URLProtocol, @unchecked Sendable {
+ static var handler: ((URLRequest) throws -> (Int, [String: Any]))?
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func startLoading() {
+ do {
+ let handler = try #require(Self.handler)
+ let (status, payload) = try handler(request)
+ let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: try JSONSerialization.data(withJSONObject: payload))
+ client?.urlProtocolDidFinishLoading(self)
+ } catch { client?.urlProtocol(self, didFailWithError: error) }
+ }
+ override func stopLoading() {}
+}
+
+@Suite(.serialized)
+@MainActor
+struct LoginMethodTests {
+ private func service(_ handler: @escaping (URLRequest) throws -> (Int, [String: Any])) -> BiliAuthService {
+ LoginMockProtocol.handler = handler
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.protocolClasses = [LoginMockProtocol.self]
+ configuration.httpShouldSetCookies = false
+ return BiliAuthService(session: URLSession(configuration: configuration))
+ }
+ private func form(_ request: URLRequest) -> [String: String] {
+ var data = request.httpBody ?? Data()
+ if data.isEmpty, let stream = request.httpBodyStream {
+ stream.open()
+ defer { stream.close() }
+ var buffer = [UInt8](repeating: 0, count: 4096)
+ while stream.hasBytesAvailable {
+ let count = stream.read(&buffer, maxLength: buffer.count)
+ if count <= 0 { break }
+ data.append(contentsOf: buffer.prefix(count))
+ }
+ }
+ let raw = String(data: data, encoding: .utf8) ?? ""
+ return Dictionary(uniqueKeysWithValues: raw.split(separator: "&").map { part in
+ let pair = part.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
+ return (String(pair[0]), pair.count > 1 ? String(pair[1]).removingPercentEncoding ?? "" : "")
+ })
+ }
+
+ @Test func qrCodeUsesSignedAnonymousTVRequest() async throws {
+ let auth = service { request in
+ #expect(request.httpMethod == "POST")
+ #expect(!request.httpShouldHandleCookies)
+ #expect(request.value(forHTTPHeaderField: "Cookie") == nil)
+ let items = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)!.queryItems!
+ #expect(items.contains { $0.name == "local_id" && $0.value == "0" })
+ #expect(items.contains { $0.name == "sign" && $0.value?.count == 32 })
+ return (200, ["code": 0, "data": ["url": "https://passport.bilibili.com/test", "auth_code": "fake-code", "expires_in": 90]])
+ }
+ let qr = try await auth.generateQRCode()
+ #expect(qr.authCode == "fake-code")
+ #expect(qr.expiresIn == 90)
+ }
+ @Test func qrWaitingExpiryAndSuccessAreDistinct() async throws {
+ for code in [86039, 86090, 86038, 0] {
+ let auth = service { _ in (200, ["code": code, "message": "waiting", "data": [:]]) }
+ let status = try await auth.pollQRCode("fake-code")
+ switch (code, status) {
+ case (86039, .waiting), (86090, .waiting), (86038, .expired), (0, .login(.success)): break
+ default: Issue.record("Incorrect QR status")
+ }
+ }
+ }
+ @Test func unexpectedQRResponseIsAnError() async throws {
+ let auth = service { _ in (503, ["code": 0]) }
+ do { _ = try await auth.pollQRCode("fake"); Issue.record("Expected HTTP failure") } catch {}
+ }
+ @Test func smsUsesDialCodeAndCaptchaFields() async throws {
+ let auth = service { request in
+ let params = form(request)
+ #expect(params["cid"] == "86")
+ #expect(params["tel"] == "13800000000")
+ #expect(params["gee_validate"] == "fake-validate")
+ #expect(params["recaptcha_token"] == "fake-token")
+ #expect(params["login_session_id"]?.count == 32)
+ #expect(params["sign"]?.count == 32)
+ #expect(!request.httpShouldHandleCookies)
+ return (200, ["code": 0, "data": ["recaptcha_url": "", "captcha_key": "fake-key"]])
+ }
+ let result = GeetestValidateResult(validate: "fake-validate", challenge: "fake-challenge", seccode: "fake-seccode")
+ let status = try await auth.sendLoginSMS(phone: "13800000000", countryID: 86, captcha: (result, "fake-token"))
+ guard case .sent(let key) = status else { Issue.record("Expected SMS success"); return }
+ #expect(key == "fake-key")
+ }
+ @Test func smsChallengeDoesNotCountAsSent() async throws {
+ let auth = service { _ in (200, ["code": -105, "data": ["recaptcha_url":
+ "https://passport.bilibili.com/captcha?gee_gt=gt&gee_challenge=challenge&recaptcha_token=token"]]) }
+ let result = try await auth.sendLoginSMS(phone: "13800000000", countryID: 86)
+ guard case .captcha(let captcha) = result else { Issue.record("Expected captcha"); return }
+ #expect(captcha.gt == "gt")
+ #expect(captcha.recaptchaToken == "token")
+ }
+ @Test func countryIDsAreNotDialCodes() async throws {
+ let auth = service { _ in (200, ["code": 0, "data": ["common": [
+ ["id": 1, "cname": "中国大陆", "country_id": "86"],
+ ["id": 5, "cname": "中国香港特别行政区", "country_id": "852"]], "others": []]]) }
+ let countries = try await auth.countries()
+ #expect(countries[0].id == 1)
+ #expect(countries[0].callingCode == 86)
+ #expect(countries[1].callingCode == 852)
+ }
+ @Test func smsLoginSendsEncryptedDeviceAndReturnsTokens() async throws {
+ let privateKey = try #require(SecKeyCreateRandomKey([
+ kSecAttrKeyType: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits: 2048] as CFDictionary, nil))
+ let publicKey = try #require(SecKeyCopyPublicKey(privateKey))
+ let bytes = try #require(SecKeyCopyExternalRepresentation(publicKey, nil)) as Data
+ let pem = "-----BEGIN PUBLIC KEY-----\n" + bytes.base64EncodedString() + "\n-----END PUBLIC KEY-----"
+ let auth = service { request in
+ if request.url?.path == "/api/oauth2/getKey" {
+ return (200, ["code": 0, "data": ["hash": "fake-hash", "key": pem]])
+ }
+ #expect(request.url?.path == "/x/passport-login/login/sms")
+ let params = form(request)
+ #expect(params["cid"] == "852")
+ #expect(params["captcha_key"] == "fake-key")
+ #expect(params["code"] == "123456")
+ #expect(params["dt"]?.isEmpty == false)
+ return (200, ["code": 0, "data": ["token_info": ["access_token": "fake-token", "refresh_token": "fake-refresh"]]])
+ }
+ let status = await auth.loginBySMS(phone: "12345678", countryID: 852, code: "123456", captchaKey: "fake-key")
+ guard case .success(let data) = status else { Issue.record("Expected SMS login success"); return }
+ #expect((data["token_info"] as? [String: String])?["access_token"] == "fake-token")
+ }
+ @Test func cookieParsingPreservesEqualsAndAdditionalCookies() throws {
+ let account = try BiliAuthService.parseCookie("SESSDATA=fake==; bili_jct=csrf; DedeUserID=123; DedeUserID__ckMd5=checksum")
+ #expect(account.cookies.SESSDATA == "fake==")
+ #expect(account.cookies.dictionary["DedeUserID__ckMd5"] == "checksum")
+ #expect(account.accessKey == nil)
+ #expect(throws: AccountStorageError.self) { try BiliAuthService.parseCookie("SESSDATA=a; SESSDATA=b; bili_jct=c; DedeUserID=123") }
+ #expect(throws: AccountStorageError.self) { try BiliAuthService.parseCookie("SESSDATA=a\r\nInjected=x; bili_jct=c; DedeUserID=123") }
+ }
+ @Test func cookieValidationRejectsMismatchedUID() async throws {
+ let auth = service { request in
+ #expect(request.value(forHTTPHeaderField: "Cookie")?.contains("DedeUserID=123") == true)
+ #expect(!request.httpShouldHandleCookies)
+ return (200, ["code": 0, "data": ["isLogin": true, "mid": 456]])
+ }
+ do { _ = try await auth.validateCookie("SESSDATA=fake; bili_jct=csrf; DedeUserID=123"); Issue.record("Expected UID mismatch") } catch {}
+ }
+ @Test func cookieValidationAcceptsMatchingUID() async throws {
+ let auth = service { _ in (200, ["code": 0, "data": ["isLogin": true, "mid": 123, "uname": "测试用户"]]) }
+ let account = try await auth.validateCookie("SESSDATA=fake; bili_jct=csrf; DedeUserID=123")
+ #expect(account.id == "123")
+ #expect(account.displayName == "测试用户(123)")
+ }
+ @Test func compatibleJSONPreservesCredentialsAndEmptyAssignments() throws {
+ let cookies = ["SESSDATA": "fake-session", "bili_jct": "fake-csrf", "DedeUserID": "123",
+ "DedeUserID__ckMd5": "fake-checksum", "sid": "fake-sid", "buvid3": "fake-buvid"]
+ let fixture: [String: Any] = ["123": ["cookies": cookies, "accessKey": "fake-access", "refresh": "fake-refresh", "type": []]]
+ let accounts = try LoginImportService.decode(JSONSerialization.data(withJSONObject: fixture))
+ var state = AccountState()
+ state.accounts = accounts
+ let roundtrip = try LoginImportService.decode(LoginImportService.encode(state))
+ #expect(roundtrip[0].cookies.dictionary == cookies)
+ #expect(roundtrip[0].accessKey == "fake-access")
+ #expect(roundtrip[0].refresh == "fake-refresh")
+ #expect(roundtrip[0].type == [])
+ #expect(state.account(for: .main) == nil)
+ state.assignments[.playback] = "123"
+ #expect(try LoginImportService.decode(LoginImportService.encode(state))[0].type == [3])
+ }
+ @Test func oldStoredCookiesRemainDecodable() throws {
+ let old = Data("{\"SESSDATA\":\"fake\",\"bili_jct\":\"csrf\",\"DedeUserID\":\"123\"}".utf8)
+ let cookies = try JSONDecoder().decode(BiliCookie.self, from: old)
+ #expect(cookies.extraCookies == nil)
+ #expect(cookies.DedeUserID == "123")
+ }
+ @Test func cookieOnlyAccountExportsNullTokensAndAssignedRoles() throws {
+ let account = try BiliAuthService.parseCookie("SESSDATA=fake; bili_jct=csrf; DedeUserID=123")
+ var state = AccountState()
+ state.add(account, activate: true)
+ let data = try LoginImportService.encode(state)
+ let json = try #require(JSONSerialization.jsonObject(with: data) as? [String: [String: Any]])
+ #expect(json["123"]?["accessKey"] is NSNull)
+ #expect(json["123"]?["refresh"] is NSNull)
+ let restored = try LoginImportService.decode(data)
+ #expect(restored[0].accessKey == nil)
+ #expect(restored[0].type == [0, 1, 2, 3])
+ }
+ @Test func smsCredentialCannotBeUsedForAnotherPhone() async throws {
+ let auth = service { _ in (200, ["code": 0, "data": ["recaptcha_url": "", "captcha_key": "fake"]]) }
+ let model = LoginViewModel(authService: auth)
+ model.method = .sms
+ model.phone = "13800000000"
+ await model.sendLoginSMS()
+ #expect(model.resendAt > Date())
+ model.phone = "13900000000"
+ model.smsCode = "123456"
+ await model.submitSelectedMethod()
+ #expect(model.errorMessage != nil)
+ #expect(!model.loginSucceeded)
+ }
+}
diff --git a/README.md b/README.md
index 1a2abec..6718a54 100644
--- a/README.md
+++ b/README.md
@@ -51,6 +51,27 @@ iOS 26+ (测试平台为iOS27)
- [x] 弹幕
- [x] 缓存管理
+## 多账号与无痕模式
+
+在“我的 → 账号”或“设置 → 账号与隐私”中添加账号,并为四类功能分别选择账号或 `0(匿名)`:
+
+| 用途 | 对应功能 |
+| --- | --- |
+| 主账号 | 个人资料、动态、私信、关注、点赞、投币、收藏和评论 |
+| 记录观看 | 观看记录上报、历史列表和自动恢复观看进度;匿名时不上报 |
+| 推荐 | App/Web 推荐、相关视频、搜索推荐和直播推荐 |
+| 视频取流 | 视频及直播播放认证、字幕、视频预览和缓存下载 |
+
+“快速统一切换”可将四项设为同一个账号。新增账号会成为主账号,其余功能保留原分工。移除账号后,使用该账号的功能自动切换为匿名。
+
+无痕模式不会上报观看记录(包括退出播放时),也不会新增本地搜索历史;关闭后按原账号分工继续记录。已保存的搜索历史不会被删除,主动点赞、收藏等操作仍会使用主账号。无痕模式不代表网络匿名,取流账号仍可用于获取其有权限访问的内容。
+
+登录页支持密码、短信、扫码及 Cookie 四种方式。短信支持选择国际区号、极验验证和发送倒计时;扫码请使用哔哩哔哩客户端扫描并确认,过期后可刷新。Cookie 登录会校验是否有效及 UID 是否一致,但不包含 App 令牌,部分 App 接口可能不可用。
+
+登录凭据、账号分工及无痕开关保存在本设备 Keychain;首次升级会自动迁移原单账号凭据,迁移成功后移除 UserDefaults 中的旧凭据。“账号与隐私”和“关于”页可导入或导出所有账号,兼容 PiliPlus 的 UID 字典 JSON,保留额外 Cookie、访问令牌、刷新令牌,以及 `type` 表示的功能分工(0 主账号、1 记录观看、2 推荐、3 视频取流)。`type: []` 的账号导入后不负责任何功能,可在账号与隐私中选择分工。登录导出文件包含凭据,请妥善保管。
+
+开发分支的 `iOS Build and Tests` 工作流会编译未签名 iOS App、运行模拟器单元测试,并提供 `PiliPod-unsigned` IPA 和 `ios-validation` 诊断附件。安装 IPA 需要自行签名。
+
## 声明
此项目(PiliPod)是个人为了兴趣与swift学习而开发,仅用于学习和测试,请于下载后24小时内删除。所用API皆从官方网站收集,不提供任何破解内容。