4 Commits
Author SHA1 Message Date
JinJiangHuang dc1a010e05 fix bug 2026-03-02 12:53:16 +08:00
JinJiangHuang e58322339f fix search 2026-03-01 22:57:20 +08:00
JinJiangHuang ee8c71dcd4 增加注解 2026-03-01 22:23:38 +08:00
JinJiangHuang 99a8cc799b fix bug 2026-03-01 21:43:02 +08:00
27 changed files with 1085 additions and 72 deletions
+28
View File
@@ -214,3 +214,31 @@ struct AppConfigData: Codable {
var script: [String]?
}
}
extension AppConfigData {
///
/// AppConfigData JSON
///
var hasUsableContent: Bool {
let hasSites = !(sites?.isEmpty ?? true)
let hasLives = !(lives?.isEmpty ?? true)
let hasParses = !(parses?.isEmpty ?? true)
return hasSites || hasLives || hasParses
}
}
/// tvboxmulti.json
struct MultiRepoConfigData: Codable {
var urls: [Entry]?
struct Entry: Codable {
var name: String?
var url: String?
}
var candidateUrls: [String] {
(urls ?? [])
.compactMap { $0.url?.trimmingCharacters(in: .whitespacesAndNewlines) }
.filter { !$0.isEmpty }
}
}
+22 -2
View File
@@ -4,10 +4,15 @@ import Foundation
///
struct LiveChannelGroup: Codable, Identifiable, Hashable {
/// 便 SwiftUI diff
var id: String { groupName }
///
var groupName: String = ""
///
var groupIndex: Int = 0
///
var channels: [LiveChannelItem] = []
///
var isPassword: Bool = false
init(groupName: String = "", groupIndex: Int = 0) {
@@ -18,12 +23,19 @@ struct LiveChannelGroup: Codable, Identifiable, Hashable {
///
struct LiveChannelItem: Codable, Identifiable, Hashable {
/// +
var id: String { "\(channelName)_\(channelIndex)" }
///
var channelName: String = ""
///
var channelIndex: Int = 0
/// 线
var channelUrls: [String] = []
/// 线
var sourceIndex: Int = 0
/// 线
var sourceNum: Int { channelUrls.count }
///
var logo: String = ""
init(channelName: String = "", channelIndex: Int = 0) {
@@ -31,11 +43,14 @@ struct LiveChannelItem: Codable, Identifiable, Hashable {
self.channelIndex = channelIndex
}
/// 线
/// 线
var currentUrl: String? {
guard sourceIndex >= 0, sourceIndex < channelUrls.count else { return channelUrls.first }
return channelUrls[sourceIndex]
}
/// 线
mutating func nextSource() {
if channelUrls.count > 0 {
sourceIndex = (sourceIndex + 1) % channelUrls.count
@@ -51,6 +66,7 @@ struct Epginfo: Codable, Identifiable, Hashable {
var endTime: String = ""
var index: Int = 0
/// `HH:mm`
var isLive: Bool {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
@@ -65,8 +81,12 @@ struct Epginfo: Codable, Identifiable, Hashable {
/// EPG
struct LiveEpgDate: Codable, Identifiable, Hashable {
var id: String { datePresent }
var datePresent: String = "" //
var date: String = "" //
/// UI
var datePresent: String = ""
///
var date: String = ""
///
var index: Int = 0
/// UI
var isSelected: Bool = false
}
+27 -7
View File
@@ -2,28 +2,47 @@ import Foundation
/// / - Android Movie.java
struct Movie: Codable {
///
var videoList: [Video] = []
///
var pagecount: Int = 0
///
var page: Int = 0
///
var total: Int = 0
///
var limit: Int = 0
///
struct Video: Codable, Identifiable, Hashable {
/// ID Int String
var id: String
///
var name: String = ""
///
var pic: String = ""
var note: String = "" // "20"
/// 20
var note: String = ""
///
var year: String = ""
///
var area: String = ""
var type: String = "" // /
/// /
var type: String = ""
///
var director: String = ""
///
var actor: String = ""
var des: String = "" //
var sourceKey: String = "" // key
var tid: String = "" // ID
var last: String = "" //
var dt: String = "" //
///
var des: String = ""
/// key
var sourceKey: String = ""
/// ID
var tid: String = ""
///
var last: String = ""
///
var dt: String = ""
init(id: String = UUID().uuidString, name: String = "", pic: String = "",
note: String = "", sourceKey: String = "") {
@@ -51,6 +70,7 @@ struct Movie: Codable {
case sourceKey
}
/// `vod_id` / `type_id` Int String
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
// String Int id
+14 -2
View File
@@ -2,13 +2,18 @@ import Foundation
/// - Android MovieSort.java
struct MovieSort: Codable {
///
var sortList: [SortData] = []
///
struct SortData: Codable, Identifiable, Hashable {
/// type_id
var id: String
///
var name: String = ""
/// /
var flag: String = ""
///
var filters: [SortFilter] = []
init(id: String = "", name: String = "", flag: String = "") {
@@ -17,6 +22,8 @@ struct MovieSort: Codable {
self.flag = flag
}
///
///
static func home() -> SortData {
SortData(id: "home", name: "推荐", flag: "1")
}
@@ -24,13 +31,18 @@ struct MovieSort: Codable {
///
struct SortFilter: Codable, Hashable {
/// `year``area`
var key: String = ""
/// UI
var name: String = ""
///
var values: [SortFilterValue] = []
struct SortFilterValue: Codable, Hashable {
var n: String = "" //
var v: String = "" //
///
var n: String = ""
///
var v: String = ""
}
}
}
+18
View File
@@ -2,11 +2,14 @@ import Foundation
///
enum PlayerEngine: Int, CaseIterable, Identifiable {
/// AVPlayer
case system = 0
/// VLC VLCKitSPM
case vlc = 10
var id: Int { rawValue }
/// UI
var title: String {
switch self {
case .system:
@@ -16,6 +19,7 @@ enum PlayerEngine: Int, CaseIterable, Identifiable {
}
}
/// VLC
static var isVLCAvailable: Bool {
#if canImport(VLCKitSPM)
return true
@@ -24,6 +28,8 @@ enum PlayerEngine: Int, CaseIterable, Identifiable {
#endif
}
///
/// VLC
static var availableEngines: [PlayerEngine] {
var engines: [PlayerEngine] = [.system]
if isVLCAvailable {
@@ -32,6 +38,7 @@ enum PlayerEngine: Int, CaseIterable, Identifiable {
return engines
}
///
static func fromStoredValue(_ rawValue: Int) -> PlayerEngine {
guard let engine = PlayerEngine(rawValue: rawValue) else {
return .system
@@ -47,8 +54,11 @@ enum PlayerEngine: Int, CaseIterable, Identifiable {
///
enum VideoDecodeMode: Int, CaseIterable, Identifiable {
///
case auto = 0
///
case hardware = 1
///
case software = 2
var id: Int { rawValue }
@@ -69,6 +79,7 @@ enum VideoDecodeMode: Int, CaseIterable, Identifiable {
}
/// VLC
/// `avcodec-hw`
var vlcHardwareDecodeOption: String? {
switch self {
case .auto:
@@ -84,8 +95,11 @@ enum VideoDecodeMode: Int, CaseIterable, Identifiable {
/// VLC
enum VLCBufferMode: Int, CaseIterable, Identifiable {
///
case lowLatency = 0
///
case balanced = 1
///
case smooth = 2
var id: Int { rawValue }
@@ -111,6 +125,10 @@ enum VLCBufferMode: Int, CaseIterable, Identifiable {
self == .lowLatency
}
/// /
/// - Parameters:
/// - isLive:
/// - Returns: network/live/file
func cacheConfig(isLive: Bool) -> (network: Int, live: Int, file: Int) {
switch self {
case .lowLatency:
+18 -5
View File
@@ -2,25 +2,37 @@ import Foundation
/// - Android SourceBean.java
struct SourceBean: Codable, Identifiable, Hashable {
/// key
var id: String { key }
///
let key: String
///
let name: String
///
let api: String
let searchable: Int // 0: 1:
let filterable: Int // 0: 1:
let playerType: Int // 0: 1:IJK 2:EXO
let type: Int // 0:xml 1:json 3:jar 4:remote
/// 0 1
let searchable: Int
/// 0 1
let filterable: Int
/// 0 1 remote quick
let quickSearch: Int
/// Swift
let playerType: Int
/// 0 XML1 JSON3 JAR4 Remote
let type: Int
/// remote
let ext: String?
init(key: String = "", name: String = "", api: String = "",
searchable: Int = 1, filterable: Int = 1,
searchable: Int = 1, filterable: Int = 1, quickSearch: Int = 0,
playerType: Int = 0, type: Int = 1, ext: String? = nil) {
self.key = key
self.name = name
self.api = api
self.searchable = searchable
self.filterable = filterable
self.quickSearch = quickSearch
self.playerType = playerType
self.type = type
self.ext = ext
@@ -28,6 +40,7 @@ struct SourceBean: Codable, Identifiable, Hashable {
var isSearchable: Bool { searchable == 1 }
var isFilterable: Bool { filterable == 1 }
var isQuickSearchEnabled: Bool { quickSearch == 1 }
/// Swift type=3 JAR/Spider Java
var isSupportedInSwift: Bool {
+20 -3
View File
@@ -2,16 +2,27 @@ import Foundation
/// - Android VodInfo.java
struct VodInfo: Codable, Identifiable {
/// ID
var id: String
///
var name: String = ""
///
var pic: String = ""
///
var note: String = ""
///
var year: String = ""
///
var area: String = ""
///
var typeName: String = ""
///
var director: String = ""
///
var actor: String = ""
///
var des: String = ""
/// key
var sourceKey: String = ""
/// 线
@@ -19,13 +30,17 @@ struct VodInfo: Codable, Identifiable {
/// key: flag, value:
var playUrlMap: [String: [Episode]] = [:]
var playFlag: String = "" // 线
var playIndex: Int = 0 //
/// 线
var playFlag: String = ""
///
var playIndex: Int = 0
///
struct Episode: Codable, Identifiable, Hashable {
var id: String { name }
///
let name: String
///
let url: String
init(name: String, url: String) {
@@ -48,7 +63,7 @@ struct VodInfo: Codable, Identifiable {
info.des = video.des.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression)
info.sourceKey = video.sourceKey
//
//
// playFrom : "线1$$$线2$$$线3"
// playUrl : "1$url1#2$url2$$$1$url3#2$url4"
let flags = playFrom.components(separatedBy: "$$$").filter { !$0.isEmpty }
@@ -73,10 +88,12 @@ struct VodInfo: Codable, Identifiable {
return info
}
/// 线
var currentEpisodes: [Episode] {
playUrlMap[playFlag] ?? []
}
/// 线 +
var currentEpisode: Episode? {
let eps = currentEpisodes
guard playIndex >= 0, playIndex < eps.count else { return nil }
+24 -2
View File
@@ -5,18 +5,26 @@ import SwiftData
///
struct VodPlaybackState: Codable {
/// 线
var flag: String
///
var episodeIndex: Int
///
var progressSeconds: Double
}
///
@Model
final class VodCollect {
/// ID sourceKey
var vodId: String = ""
///
var vodName: String = ""
///
var vodPic: String = ""
/// key
var sourceKey: String = ""
/// /
var updateTime: Date = Date()
init(vodId: String, vodName: String, vodPic: String, sourceKey: String) {
@@ -31,12 +39,19 @@ final class VodCollect {
///
@Model
final class VodRecord {
/// ID
var vodId: String = ""
///
var vodName: String = ""
///
var vodPic: String = ""
/// key
var sourceKey: String = ""
var playNote: String = "" // "5 03:45"
var dataJson: String = "" // JSONVodPlaybackState
/// 5 03:45
var playNote: String = ""
/// JSON`VodPlaybackState`
var dataJson: String = ""
///
var updateTime: Date = Date()
init(vodId: String, vodName: String, vodPic: String, sourceKey: String, playNote: String = "") {
@@ -52,8 +67,11 @@ final class VodRecord {
///
@Model
final class CacheItem {
///
@Attribute(.unique) var key: String = ""
///
var value: String = ""
///
var updateTime: Date = Date()
init(key: String, value: String) {
@@ -95,6 +113,7 @@ actor CacheStore {
@MainActor
func removeCollect(vodId: String, sourceKey: String, context: ModelContext) {
// (vodId, sourceKey)
let predicate = #Predicate<VodCollect> { item in
item.vodId == vodId && item.sourceKey == sourceKey
}
@@ -151,6 +170,7 @@ actor CacheStore {
try? context.save()
}
/// JSON `nil`
@MainActor
func getPlaybackState(vodId: String, sourceKey: String, context: ModelContext) -> VodPlaybackState? {
guard let record = fetchRecord(vodId: vodId, sourceKey: sourceKey, context: context) else {
@@ -171,6 +191,7 @@ actor CacheStore {
@MainActor
private func fetchRecord(vodId: String, sourceKey: String, context: ModelContext) -> VodRecord? {
// (vodId, sourceKey)
let predicate = #Predicate<VodRecord> { item in
item.vodId == vodId && item.sourceKey == sourceKey
}
@@ -185,6 +206,7 @@ actor CacheStore {
return String(data: data, encoding: .utf8)
}
/// JSON
private nonisolated static func decodePlaybackState(_ json: String) -> VodPlaybackState? {
guard let data = json.data(using: .utf8) else { return nil }
return try? JSONDecoder().decode(VodPlaybackState.self, from: data)
+387 -9
View File
@@ -5,6 +5,15 @@ import Foundation
@MainActor
class ApiConfig: ObservableObject {
static let shared = ApiConfig()
private static let maxConfigResolveDepth = 6
private static let maxRedirectCandidates = 20
struct MultiRepoOption: Identifiable, Equatable {
let name: String
let url: String
var id: String { url.lowercased() }
}
@Published var sourceBeanList: [SourceBean] = []
@Published var homeSourceBean: SourceBean?
@@ -38,21 +47,65 @@ class ApiConfig: ObservableObject {
self.liveConfigUrl = resolvedLive
if trimmedVod == resolvedLive {
let config = try await fetchConfig(from: trimmedVod)
parseConfig(config, apiUrl: trimmedVod, includeSources: true, includeLive: true)
let configResult = try await fetchConfig(from: trimmedVod)
parseConfig(
configResult.config,
apiUrl: configResult.loadedFrom,
includeSources: true,
includeLive: true
)
} else {
let vodConfig = try await fetchConfig(from: trimmedVod)
parseConfig(vodConfig, apiUrl: trimmedVod, includeSources: true, includeLive: false)
parseConfig(
vodConfig.config,
apiUrl: vodConfig.loadedFrom,
includeSources: true,
includeLive: false
)
let liveConfig = try await fetchConfig(from: resolvedLive)
parseConfig(liveConfig, apiUrl: resolvedLive, includeSources: false, includeLive: true)
parseConfig(
liveConfig.config,
apiUrl: liveConfig.loadedFrom,
includeSources: false,
includeLive: true
)
}
self.isLoaded = true
}
private func fetchConfig(from apiUrl: String) async throws -> AppConfigData {
let jsonStr = try await network.getString(from: apiUrl)
private func fetchConfig(from apiUrl: String) async throws -> (config: AppConfigData, loadedFrom: String) {
try await fetchConfig(
from: apiUrl,
visitedUrls: Set<String>(),
depth: 0
)
}
private func fetchConfig(
from apiUrl: String,
visitedUrls: Set<String>,
depth: Int
) async throws -> (config: AppConfigData, loadedFrom: String) {
guard depth <= Self.maxConfigResolveDepth else {
throw ConfigError.parseError("配置跳转层级过深(超过 \(Self.maxConfigResolveDepth) 层)")
}
let normalizedUrl = Self.normalizeConfigUrl(apiUrl)
guard !normalizedUrl.isEmpty else {
throw ConfigError.parseError("配置地址为空")
}
let visitKey = normalizedUrl.lowercased()
guard !visitedUrls.contains(visitKey) else {
throw ConfigError.parseError("检测到循环引用的配置地址: \(normalizedUrl)")
}
var nextVisited = visitedUrls
nextVisited.insert(visitKey)
let jsonStr = try await network.getString(from: normalizedUrl)
// JSONAndroid Gson Swift
let cleanedJson = Self.stripJsonComments(jsonStr)
@@ -61,7 +114,283 @@ class ApiConfig: ObservableObject {
throw ConfigError.parseError("无法解析配置数据")
}
return try JSONDecoder().decode(AppConfigData.self, from: data)
let decoder = JSONDecoder()
let decodedConfig = try? decoder.decode(AppConfigData.self, from: data)
if let config = decodedConfig, config.hasUsableContent {
return (config, normalizedUrl)
}
if let multiRepo = try? decoder.decode(MultiRepoConfigData.self, from: data) {
let candidateUrls = Self.uniqueUrlsInOrder(
multiRepo.candidateUrls.map(Self.normalizeConfigUrl)
)
var lastError: Error?
for candidateUrl in candidateUrls {
do {
return try await fetchConfig(
from: candidateUrl,
visitedUrls: nextVisited,
depth: depth + 1
)
} catch {
lastError = error
}
}
if let lastError {
throw ConfigError.parseError("多仓库配置中没有可用地址,最后错误: \(lastError.localizedDescription)")
}
throw ConfigError.parseError("多仓库配置中没有可用地址")
}
let redirectCandidates = Self.extractConfigRedirectCandidates(from: cleanedJson)
.filter { $0.lowercased() != visitKey && !nextVisited.contains($0.lowercased()) }
if !redirectCandidates.isEmpty {
var lastError: Error?
for candidate in redirectCandidates {
do {
return try await fetchConfig(
from: candidate,
visitedUrls: nextVisited,
depth: depth + 1
)
} catch {
lastError = error
}
}
if let lastError {
throw ConfigError.parseError("页面跳转配置解析失败,最后错误: \(lastError.localizedDescription)")
}
}
if decodedConfig != nil {
throw ConfigError.parseError("配置缺少可用站点(sites / lives / parses")
}
throw ConfigError.parseError("配置格式不受支持")
}
private static func uniqueUrlsInOrder(_ urls: [String]) -> [String] {
var seen: Set<String> = []
var result: [String] = []
for url in urls {
let trimmed = url.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { continue }
let key = trimmed.lowercased()
guard !seen.contains(key) else { continue }
seen.insert(key)
result.append(trimmed)
}
return result
}
/// /
/// - URL
/// - data-clipboard-text
/// - JSON url
private static func extractConfigRedirectCandidates(from content: String) -> [String] {
let trimmed = content.trimmingCharacters(in: .whitespacesAndNewlines)
var rawCandidates: [String] = []
if (trimmed.hasPrefix("http://") || trimmed.hasPrefix("https://")) && !trimmed.contains("\n") {
rawCandidates.append(trimmed)
}
rawCandidates.append(contentsOf: matchCaptureGroup(
pattern: #"data-clipboard-text\s*=\s*["']([^"']+)["']"#,
in: content
))
rawCandidates.append(contentsOf: matchCaptureGroup(
pattern: #""url"\s*:\s*"([^"]+)""#,
in: content
))
rawCandidates.append(contentsOf: matchCaptureGroup(
pattern: #"(https?://[^\s"'<>\\]+)"#,
in: content
))
let normalized = rawCandidates
.map(sanitizeExtractedUrl)
.map(normalizeConfigUrl)
.filter { !$0.isEmpty }
.filter(isLikelyConfigPointerUrl)
.filter { !isLikelyBinaryAssetUrl($0) }
return Array(uniqueUrlsInOrder(normalized).prefix(maxRedirectCandidates))
}
private static func matchCaptureGroup(pattern: String, in content: String) -> [String] {
guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {
return []
}
let range = NSRange(content.startIndex..<content.endIndex, in: content)
let matches = regex.matches(in: content, options: [], range: range)
return matches.compactMap { match in
guard match.numberOfRanges >= 2,
let subRange = Range(match.range(at: 1), in: content) else {
return nil
}
return String(content[subRange])
}
}
private static func sanitizeExtractedUrl(_ value: String) -> String {
var result = value.trimmingCharacters(in: .whitespacesAndNewlines)
result = result.replacingOccurrences(of: "&amp;", with: "&")
result = result.replacingOccurrences(of: "\\/", with: "/")
while let last = result.last, [".", ",", ";", ")", "]", "}", "\"", "'"].contains(last) {
result.removeLast()
}
while let first = result.first, ["\"", "'", "(", "[", "{"].contains(first) {
result.removeFirst()
}
return result.trimmingCharacters(in: .whitespacesAndNewlines)
}
private static func isLikelyBinaryAssetUrl(_ urlString: String) -> Bool {
guard let components = URLComponents(string: urlString) else { return false }
let path = components.path.lowercased()
return path.hasSuffix(".png")
|| path.hasSuffix(".jpg")
|| path.hasSuffix(".jpeg")
|| path.hasSuffix(".webp")
|| path.hasSuffix(".gif")
|| path.hasSuffix(".svg")
|| path.hasSuffix(".ico")
|| path.hasSuffix(".css")
|| path.hasSuffix(".woff")
|| path.hasSuffix(".woff2")
|| path.hasSuffix(".ttf")
}
private static func isLikelyConfigPointerUrl(_ urlString: String) -> Bool {
guard let components = URLComponents(string: urlString) else { return false }
let host = (components.host ?? "").lowercased()
let path = components.path.lowercased()
let query = (components.percentEncodedQuery ?? "").lowercased()
if host.contains("raw.githubusercontent.com") || host.contains("githubusercontent.com") {
return true
}
if path.contains(".json")
|| path.hasSuffix("/tv")
|| path.hasSuffix("/tv/")
|| path.hasSuffix("/m")
|| path.hasSuffix("/m/")
|| path.contains("tvbox")
|| path.contains("box")
|| query.contains("json")
|| query.contains("config")
|| query.contains("url=") {
return true
}
return false
}
/// URL
/// 1) https:/xxx
/// 2) github.com/.../blob/... raw.githubusercontent.com/...
/// 3) gh-proxy + github/blob
static func normalizeConfigUrl(_ rawUrl: String) -> String {
let trimmed = rawUrl.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return trimmed }
let fixedScheme = fixMalformedSchemeIfNeeded(trimmed)
if let normalizedProxy = normalizeGhProxyWrappedUrl(fixedScheme) {
return normalizedProxy
}
if let githubRaw = convertGitHubBlobUrlToRaw(fixedScheme) {
return githubRaw
}
return fixedScheme
}
private static func fixMalformedSchemeIfNeeded(_ urlString: String) -> String {
let fixedHttps = urlString.replacingOccurrences(
of: #"^https:/(?!/)"#,
with: "https://",
options: .regularExpression
)
return fixedHttps.replacingOccurrences(
of: #"^http:/(?!/)"#,
with: "http://",
options: .regularExpression
)
}
private static func normalizeGhProxyWrappedUrl(_ urlString: String) -> String? {
guard let components = URLComponents(string: urlString),
let host = components.host?.lowercased(),
host.contains("gh-proxy") else {
return nil
}
let path = components.percentEncodedPath.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
guard !path.isEmpty else { return nil }
let decodedPath = path.removingPercentEncoding ?? path
let fixedEmbedded = fixMalformedSchemeIfNeeded(decodedPath)
guard fixedEmbedded.hasPrefix("http://") || fixedEmbedded.hasPrefix("https://") else {
return nil
}
let normalizedEmbedded = convertGitHubBlobUrlToRaw(fixedEmbedded) ?? fixedEmbedded
let scheme = components.scheme ?? "https"
let portSuffix = components.port.map { ":\($0)" } ?? ""
var rebuilt = "\(scheme)://\(host)\(portSuffix)/\(normalizedEmbedded)"
if let query = components.percentEncodedQuery, !query.isEmpty {
rebuilt += "?\(query)"
}
if let fragment = components.percentEncodedFragment, !fragment.isEmpty {
rebuilt += "#\(fragment)"
}
return rebuilt
}
private static func convertGitHubBlobUrlToRaw(_ urlString: String) -> String? {
guard let components = URLComponents(string: urlString),
let host = components.host?.lowercased(),
host == "github.com" || host == "www.github.com" else {
return nil
}
let parts = components.path.split(separator: "/", omittingEmptySubsequences: true)
guard parts.count >= 5, parts[2] == "blob" else {
return nil
}
let owner = String(parts[0])
let repo = String(parts[1])
let branch = String(parts[3])
let filePath = parts.dropFirst(4).joined(separator: "/")
guard !filePath.isEmpty else {
return nil
}
var rawUrl = "https://raw.githubusercontent.com/\(owner)/\(repo)/\(branch)/\(filePath)"
if let query = components.percentEncodedQuery, !query.isEmpty {
rawUrl += "?\(query)"
}
if let fragment = components.percentEncodedFragment, !fragment.isEmpty {
rawUrl += "#\(fragment)"
}
return rawUrl
}
/// JSON // TVBox
@@ -124,6 +453,54 @@ class ApiConfig: ObservableObject {
return line
}
///
/// nil
func fetchMultiRepoOptions(from apiUrl: String) async throws -> [MultiRepoOption]? {
let normalizedUrl = Self.normalizeConfigUrl(apiUrl)
let jsonStr = try await network.getString(from: normalizedUrl)
let cleanedJson = Self.stripJsonComments(jsonStr)
guard let data = cleanedJson.data(using: .utf8) else {
throw ConfigError.parseError("无法解析配置数据")
}
let decoder = JSONDecoder()
if let config = try? decoder.decode(AppConfigData.self, from: data), config.hasUsableContent {
return nil
}
guard let multiRepo = try? decoder.decode(MultiRepoConfigData.self, from: data) else {
return nil
}
let normalizedCandidates = Self.uniqueUrlsInOrder(
multiRepo.candidateUrls.map(Self.normalizeConfigUrl)
)
var options: [MultiRepoOption] = []
for candidate in normalizedCandidates {
let matchedEntry = multiRepo.urls?.first(where: {
Self.normalizeConfigUrl($0.url ?? "") == candidate
})
let displayName = matchedEntry?.name?.trimmingCharacters(in: .whitespacesAndNewlines)
let fallbackName = URL(string: candidate)?.host ?? candidate
let resolvedName: String
if let displayName, !displayName.isEmpty {
resolvedName = displayName
} else {
resolvedName = fallbackName
}
options.append(
MultiRepoOption(
name: resolvedName,
url: candidate
)
)
}
return options
}
///
private func parseConfig(
_ config: AppConfigData,
@@ -142,6 +519,7 @@ class ApiConfig: ObservableObject {
api: site.api ?? "",
searchable: site.searchable?.value ?? 1,
filterable: site.filterable?.value ?? 1,
quickSearch: site.quickSearch?.value ?? 0,
playerType: site.playerType?.value ?? 0,
type: site.type?.value ?? 1,
ext: site.ext?.stringValue
@@ -389,13 +767,13 @@ class ApiConfig: ObservableObject {
let trimmed = urlString.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return trimmed }
if let url = URL(string: trimmed), url.scheme != nil {
return trimmed
return Self.normalizeConfigUrl(trimmed)
}
guard let baseUrl = URL(string: baseConfigUrl),
let resolved = URL(string: trimmed, relativeTo: baseUrl)?.absoluteURL else {
return trimmed
}
return resolved.absoluteString
return Self.normalizeConfigUrl(resolved.absoluteString)
}
private static func uniqueLiveUrls(_ urls: [String]) -> [String] {
+79 -2
View File
@@ -2,11 +2,42 @@ import Foundation
/// - Android OkGo
class NetworkManager {
///
static let shared = NetworkManager()
///
private static let fallbackCharsetNames: [String] = [
"utf-8",
"gb18030",
"gbk",
"gb2312",
"utf-16",
"utf-16le",
"utf-16be",
"utf-32",
"windows-1252",
"iso-8859-1"
]
///
private static let fallbackStringEncodings: [String.Encoding] = [
.utf8,
.utf16,
.utf16LittleEndian,
.utf16BigEndian,
.utf32,
.utf32LittleEndian,
.utf32BigEndian,
.windowsCP1252,
.isoLatin1
]
///
private let session: URLSession
/// JSON
private let decoder = JSONDecoder()
///
private init() {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15
@@ -35,8 +66,9 @@ class NetworkManager {
throw NetworkError.httpError(httpResponse.statusCode)
}
guard let str = String(data: data, encoding: .utf8) else {
throw NetworkError.decodingError("UTF-8 解码失败")
// +
guard let str = Self.decodeString(data: data, response: httpResponse) else {
throw NetworkError.decodingError("文本解码失败")
}
return str
@@ -59,14 +91,59 @@ class NetworkManager {
let (data, _) = try await session.data(from: url)
return data
}
///
/// 1)
/// 2)
/// 3) UTF-8
private static func decodeString(data: Data, response: HTTPURLResponse) -> String? {
// 使 gbk / gb2312 / gb18030
if let charset = response.textEncodingName,
let declaredEncoding = encoding(fromIANACharset: charset),
let value = String(data: data, encoding: declaredEncoding) {
return value
}
for charset in fallbackCharsetNames {
if let encoding = encoding(fromIANACharset: charset),
let value = String(data: data, encoding: encoding) {
return value
}
}
for encoding in fallbackStringEncodings {
if let value = String(data: data, encoding: encoding) {
return value
}
}
//
if !data.isEmpty {
return String(decoding: data, as: UTF8.self)
}
return nil
}
/// IANA `String.Encoding`
private static func encoding(fromIANACharset charset: String) -> String.Encoding? {
let cfEncoding = CFStringConvertIANACharSetNameToEncoding(charset as CFString)
guard cfEncoding != kCFStringEncodingInvalidId else {
return nil
}
let nsEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding)
return String.Encoding(rawValue: nsEncoding)
}
}
///
enum NetworkError: LocalizedError {
case invalidURL(String)
case invalidResponse
case httpError(Int)
case decodingError(String)
/// UI/
var errorDescription: String? {
switch self {
case .invalidURL(let url): return "无效的URL: \(url)"
+42 -3
View File
@@ -325,9 +325,10 @@ class SourceService {
url = "\(api)?wd=\(encodedKeyword)"
} else if sourceBean.type == 4 {
// Type 4:
let quickValue = sourceBean.isQuickSearchEnabled ? "true" : "false"
url = api.contains("?")
? "\(api)&wd=\(encodedKeyword)&ac=detail&quick=false"
: "\(api)?wd=\(encodedKeyword)&ac=detail&quick=false"
? "\(api)&wd=\(encodedKeyword)&ac=detail&quick=\(quickValue)"
: "\(api)?wd=\(encodedKeyword)&ac=detail&quick=\(quickValue)"
// extend
if let ext = sourceBean.ext, !ext.isEmpty {
@@ -345,7 +346,8 @@ class SourceService {
}
let jsonStr = try await network.getString(from: url)
return try parseVideoList(jsonStr, sourceKey: sourceBean.key, type: sourceBean.type)
let videos = try parseVideoList(jsonStr, sourceKey: sourceBean.key, type: sourceBean.type)
return filterSearchResults(videos, keyword: keyword)
}
///
@@ -374,6 +376,43 @@ class SourceService {
}
}
/// /
private func filterSearchResults(_ videos: [Movie.Video], keyword: String) -> [Movie.Video] {
let tokens = keyword
.split(whereSeparator: \.isWhitespace)
.map { normalizeSearchText(String($0)) }
.filter { !$0.isEmpty }
guard !tokens.isEmpty else { return videos }
return videos.filter { video in
let searchableText = normalizeSearchText([
video.name,
video.note,
video.actor,
video.director,
video.type,
video.area,
video.year
].joined(separator: " "))
guard !searchableText.isEmpty else { return false }
return tokens.allSatisfy { searchableText.contains($0) }
}
}
private func normalizeSearchText(_ text: String) -> String {
let folded = text.folding(
options: [.caseInsensitive, .diacriticInsensitive, .widthInsensitive],
locale: .current
)
let scalars = folded.unicodeScalars.filter { scalar in
!CharacterSet.whitespacesAndNewlines.contains(scalar) &&
!CharacterSet.punctuationCharacters.contains(scalar) &&
!CharacterSet.symbols.contains(scalar)
}
return String(String.UnicodeScalarView(scalars)).lowercased()
}
// MARK: - Extend
/// extend Android getFixUrl
+33
View File
@@ -2,9 +2,13 @@ import Foundation
import SwiftUI
struct PlaybackQualityOption: Identifiable, Hashable {
///
static let autoIdentifier = "auto"
/// 使 auto id
let id: String
/// UI 1080p / 720p /
let name: String
///
let url: String
var isAuto: Bool {
@@ -19,23 +23,39 @@ struct PlaybackQualityOption: Identifiable, Hashable {
/// ViewModel
@MainActor
class DetailViewModel: ObservableObject {
///
@Published var vodInfo: VodInfo?
///
@Published var isLoading = false
///
@Published var errorMessage: String?
/// 线
@Published var selectedFlag: String = ""
///
@Published var selectedEpisodeIndex: Int = 0
///
@Published var isPlaying = false
///
@Published var playUrl: String?
///
@Published var resumeSeconds: Double = 0
///
@Published var qualityOptions: [PlaybackQualityOption] = []
/// id
@Published var selectedQualityId: String = PlaybackQualityOption.autoIdentifier
/// UI
private var realtimeProgressSeconds: Double = 0
///
private let sourceService = SourceService.shared
private let network = NetworkManager.shared
///
private var qualityBaseEpisodeURL: String = ""
/// key URL
private var qualityOptionCache: [String: [PlaybackQualityOption]] = [:]
///
private var qualityResolveTask: Task<Void, Never>?
///
private var qualityResolveToken = UUID()
///
@@ -105,6 +125,7 @@ class DetailViewModel: ObservableObject {
realtimeProgressSeconds = 0
if let episode = vodInfo?.currentEpisode {
// URL
let shouldResetQuality = qualityBaseEpisodeURL != episode.url
updateQualityOptions(for: episode.url, resetSelection: shouldResetQuality)
playUrl = selectedPlayableURL(fallback: episode.url)
@@ -144,6 +165,7 @@ class DetailViewModel: ObservableObject {
selectedQualityId = option.id
guard isPlaying else { return }
// 使使
let targetURL = option.url.isEmpty ? qualityBaseEpisodeURL : option.url
guard !targetURL.isEmpty, playUrl != targetURL else { return }
@@ -208,6 +230,7 @@ class DetailViewModel: ObservableObject {
}
private func selectedPlayableURL(fallback: String) -> String {
// URL使退
let selected = qualityOptions.first(where: { $0.id == selectedQualityId })?.url
if let selected, !selected.isEmpty {
return selected
@@ -215,6 +238,7 @@ class DetailViewModel: ObservableObject {
return fallback
}
///
private func resetQualityState() {
qualityResolveTask?.cancel()
qualityResolveTask = nil
@@ -231,6 +255,7 @@ class DetailViewModel: ObservableObject {
return
}
//
qualityResolveTask?.cancel()
qualityResolveTask = nil
@@ -245,6 +270,7 @@ class DetailViewModel: ObservableObject {
qualityOptions = [autoOption]
if let cached = qualityOptionCache[trimmedEpisodeURL] {
//
qualityOptions = cached
if resetSelection || !cached.contains(where: { $0.id == selectedQualityId }) {
selectedQualityId = PlaybackQualityOption.autoIdentifier
@@ -277,12 +303,14 @@ class DetailViewModel: ObservableObject {
}
}
/// HLS
private func resolveQualityOptions(for episodeURL: String) async -> [PlaybackQualityOption] {
guard let url = URL(string: episodeURL), Self.looksLikeHLSURL(url) else { return [] }
guard let playlist = try? await network.getString(from: episodeURL) else { return [] }
return Self.parseMasterPlaylist(playlist, masterURL: url)
}
/// HLS
private struct HLSVariant {
let url: String
let name: String?
@@ -290,6 +318,7 @@ class DetailViewModel: ObservableObject {
let bandwidth: Int?
}
/// URL HLS
private static func looksLikeHLSURL(_ url: URL) -> Bool {
let lowercased = url.absoluteString.lowercased()
if lowercased.contains(".m3u8") { return true }
@@ -297,6 +326,8 @@ class DetailViewModel: ObservableObject {
return ext == "m3u8" || ext == "m3u"
}
/// HLS
/// 2
private static func parseMasterPlaylist(_ content: String, masterURL: URL) -> [PlaybackQualityOption] {
guard content.localizedCaseInsensitiveContains("#EXT-X-STREAM-INF") else { return [] }
@@ -407,6 +438,7 @@ class DetailViewModel: ObservableObject {
return merged
}
/// `EXT-X-STREAM-INF`
private static func parseAttributeMap(_ raw: String) -> [String: String] {
var result: [String: String] = [:]
let pairs = splitAttributes(raw)
@@ -426,6 +458,7 @@ class DetailViewModel: ObservableObject {
return result
}
///
private static func splitAttributes(_ raw: String) -> [String] {
var parts: [String] = []
var buffer = ""
+14 -1
View File
@@ -4,15 +4,24 @@ import SwiftUI
/// ViewModel
@MainActor
class HomeViewModel: ObservableObject {
///
@Published var sorts: [MovieSort.SortData] = []
///
@Published var selectedSort: MovieSort.SortData?
///
@Published var homeVideos: [Movie.Video] = []
///
@Published var categoryVideos: [Movie.Video] = []
///
@Published var isLoading = false
///
@Published var currentPage = 1
///
@Published var hasMore = true
///
@Published var errorMessage: String?
/// 访
private let sourceService = SourceService.shared
///
@@ -24,7 +33,7 @@ class HomeViewModel: ObservableObject {
do {
let result = try await sourceService.getSort(sourceBean: source)
// ""
// UI Android
var allSorts = [MovieSort.SortData.home()]
allSorts.append(contentsOf: result.sorts)
@@ -43,6 +52,7 @@ class HomeViewModel: ObservableObject {
///
func selectSort(_ sort: MovieSort.SortData) {
//
selectedSort = sort
errorMessage = nil
categoryVideos = []
@@ -62,6 +72,7 @@ class HomeViewModel: ObservableObject {
private func loadCategoryVideos(page: Int, sort: MovieSort.SortData) async {
guard sort.id != "home" else { return }
guard let source = ApiConfig.shared.homeSourceBean else { return }
//
guard !isLoading else { return }
isLoading = true
@@ -78,6 +89,7 @@ class HomeViewModel: ObservableObject {
} else {
categoryVideos.append(contentsOf: videos)
}
//
currentPage = page
hasMore = !videos.isEmpty
} catch {
@@ -105,6 +117,7 @@ class HomeViewModel: ObservableObject {
///
func refresh() async {
//
currentPage = 1
hasMore = true
categoryVideos = []
+11 -1
View File
@@ -4,12 +4,19 @@ import SwiftUI
/// ViewModel
@MainActor
class LiveViewModel: ObservableObject {
///
@Published var channelGroups: [LiveChannelGroup] = []
///
@Published var selectedGroupIndex: Int = 0
///
@Published var selectedChannelIndex: Int = 0
///
@Published var currentChannel: LiveChannelItem?
///
@Published var epgList: [Epginfo] = []
/// 便 EPG
@Published var isLoading = false
/// TV
@Published var showChannelList = false
///
@@ -67,6 +74,7 @@ class LiveViewModel: ObservableObject {
/// 线
func switchSource() {
// `currentChannel` mutating @Published
currentChannel?.nextSource()
}
@@ -78,13 +86,15 @@ class LiveViewModel: ObservableObject {
/// EPG
private func loadEPG(for channel: LiveChannelItem) {
// EPG -
// / ID EPG
//
epgList = []
}
}
// 访
extension Collection {
/// `nil`
subscript(safe index: Index) -> Element? {
indices.contains(index) ? self[index] : nil
}
+23 -1
View File
@@ -4,14 +4,23 @@ import SwiftUI
/// ViewModel
@MainActor
class SearchViewModel: ObservableObject {
///
@Published var keyword: String = ""
///
@Published var results: [Movie.Video] = []
///
@Published var isSearching = false
///
@Published var searchHistory: [String] = []
///
@Published var errorMessage: String?
///
private let sourceService = SourceService.shared
///
private var latestSearchRequestId: UUID = UUID()
///
init() {
loadSearchHistory()
}
@@ -20,15 +29,19 @@ class SearchViewModel: ObservableObject {
func search() async {
let trimmed = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
let requestId = UUID()
latestSearchRequestId = requestId
isSearching = true
errorMessage = nil
results = []
//
//
addToHistory(trimmed)
//
let videos = await sourceService.searchAll(keyword: trimmed)
guard requestId == latestSearchRequestId else { return }
self.results = videos
if videos.isEmpty {
@@ -42,13 +55,18 @@ class SearchViewModel: ObservableObject {
func searchInSource(_ source: SourceBean) async {
let trimmed = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
let requestId = UUID()
latestSearchRequestId = requestId
isSearching = true
errorMessage = nil
do {
let videos = try await sourceService.search(sourceBean: source, keyword: trimmed)
guard requestId == latestSearchRequestId else { return }
self.results = videos
} catch {
guard requestId == latestSearchRequestId else { return }
errorMessage = error.localizedDescription
}
@@ -57,10 +75,12 @@ class SearchViewModel: ObservableObject {
// MARK: -
///
private func loadSearchHistory() {
searchHistory = UserDefaults.standard.stringArray(forKey: HawkConfig.SEARCH_HISTORY) ?? []
}
/// 20
private func addToHistory(_ keyword: String) {
searchHistory.removeAll { $0 == keyword }
searchHistory.insert(keyword, at: 0)
@@ -70,11 +90,13 @@ class SearchViewModel: ObservableObject {
UserDefaults.standard.set(searchHistory, forKey: HawkConfig.SEARCH_HISTORY)
}
///
func clearHistory() {
searchHistory = []
UserDefaults.standard.removeObject(forKey: HawkConfig.SEARCH_HISTORY)
}
///
func removeFromHistory(_ keyword: String) {
searchHistory.removeAll { $0 == keyword }
UserDefaults.standard.set(searchHistory, forKey: HawkConfig.SEARCH_HISTORY)
+130
View File
@@ -4,24 +4,70 @@ import SwiftUI
/// ViewModel
@MainActor
class SettingsViewModel: ObservableObject {
///
struct PendingMultiRepoSelection: Identifiable {
///
enum Target {
case vod
case live
var title: String {
switch self {
case .vod: return "点播"
case .live: return "直播"
}
}
}
let id = UUID()
///
let target: Target
/// live
let sourceUrl: String
///
let options: [ApiConfig.MultiRepoOption]
}
///
@Published var vodApiUrl: String = ""
///
@Published var liveApiUrl: String = ""
///
@Published var isLoadingConfig = false
///
@Published var configError: String?
/// UI /
@Published var configSuccess = false
/// nil
@Published var pendingMultiRepoSelection: PendingMultiRepoSelection?
/// API
@Published var apiHistory: [String] = []
///
@Published var vodPlayerEngine: PlayerEngine = .system
///
@Published var livePlayerEngine: PlayerEngine = .system
///
@Published var decodeMode: VideoDecodeMode = .auto
/// VLC
@Published var vlcBufferMode: VLCBufferMode = .defaultMode
/// /退
@Published var playTimeStep: Int = 10
///
@Published var cacheSizeString: String = "0 KB"
///
let playTimeStepOptions: [Int] = [5, 10, 15, 30, 60]
///
let playerEngineOptions: [PlayerEngine] = PlayerEngine.availableEngines
///
let decodeModeOptions: [VideoDecodeMode] = VideoDecodeMode.allCases
/// VLC
let vlcBufferModeOptions: [VLCBufferMode] = VLCBufferMode.allCases
///
/// 1)
/// 2)
/// 3) /
init() {
let defaults = UserDefaults.standard
let savedVod = defaults.string(forKey: HawkConfig.API_URL) ?? ""
@@ -74,10 +120,23 @@ class SettingsViewModel: ObservableObject {
isLoadingConfig = true
configError = nil
configSuccess = false
pendingMultiRepoSelection = nil
do {
let resolvedLive = trimmedLive.isEmpty ? trimmedVod : trimmedLive
//
if let pending = try await detectPendingMultiRepoSelection(
vodUrl: trimmedVod,
liveUrl: resolvedLive
) {
pendingMultiRepoSelection = pending
isLoadingConfig = false
return
}
try await ApiConfig.shared.loadConfigs(vodApiUrl: trimmedVod, liveApiUrl: resolvedLive)
// live
UserDefaults.standard.set(trimmedVod, forKey: HawkConfig.API_URL)
UserDefaults.standard.set(trimmedLive, forKey: HawkConfig.LIVE_API_URL)
vodApiUrl = trimmedVod
@@ -92,12 +151,80 @@ class SettingsViewModel: ObservableObject {
isLoadingConfig = false
}
///
func selectPendingMultiRepoOption(_ option: ApiConfig.MultiRepoOption) async {
guard let pending = pendingMultiRepoSelection else { return }
let normalizedSource = ApiConfig.normalizeConfigUrl(pending.sourceUrl)
switch pending.target {
case .vod:
let normalizedLive = ApiConfig.normalizeConfigUrl(liveApiUrl)
// live vod
let shouldSyncLive = !liveApiUrl.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
&& normalizedLive == normalizedSource
vodApiUrl = option.url
if shouldSyncLive {
liveApiUrl = option.url
}
case .live:
liveApiUrl = option.url
}
pendingMultiRepoSelection = nil
await loadConfig()
}
///
func cancelPendingMultiRepoSelection() {
pendingMultiRepoSelection = nil
isLoadingConfig = false
}
///
/// - Returns: `nil`
private func detectPendingMultiRepoSelection(
vodUrl: String,
liveUrl: String
) async throws -> PendingMultiRepoSelection? {
if let vodOptions = try await ApiConfig.shared.fetchMultiRepoOptions(from: vodUrl) {
guard !vodOptions.isEmpty else {
throw ConfigError.parseError("点播多仓库配置中没有可用地址")
}
return PendingMultiRepoSelection(
target: .vod,
sourceUrl: vodUrl,
options: vodOptions
)
}
let normalizedVod = ApiConfig.normalizeConfigUrl(vodUrl)
let normalizedLive = ApiConfig.normalizeConfigUrl(liveUrl)
guard normalizedLive != normalizedVod else {
return nil
}
if let liveOptions = try await ApiConfig.shared.fetchMultiRepoOptions(from: liveUrl) {
guard !liveOptions.isEmpty else {
throw ConfigError.parseError("直播多仓库配置中没有可用地址")
}
return PendingMultiRepoSelection(
target: .live,
sourceUrl: liveUrl,
options: liveOptions
)
}
return nil
}
// MARK: - API
/// API
private func loadApiHistory() {
apiHistory = UserDefaults.standard.stringArray(forKey: "api_history") ?? []
}
/// 10
private func addToApiHistory(_ url: String) {
apiHistory.removeAll { $0 == url }
apiHistory.insert(url, at: 0)
@@ -107,6 +234,7 @@ class SettingsViewModel: ObservableObject {
UserDefaults.standard.set(apiHistory, forKey: "api_history")
}
/// API
func removeApiHistory(_ url: String) {
apiHistory.removeAll { $0 == url }
UserDefaults.standard.set(apiHistory, forKey: "api_history")
@@ -155,12 +283,14 @@ class SettingsViewModel: ObservableObject {
UserDefaults.standard.set(mode.rawValue, forKey: HawkConfig.PLAY_VLC_BUFFER_MODE)
}
/// +
private func refreshCacheSize() {
let sharedDisk = URLCache.shared.currentDiskUsage
let imageDisk = ImageLoader.shared.cacheUsage.disk
cacheSizeString = Self.formatSize(bytes: sharedDisk + imageDisk)
}
///
private static func formatSize(bytes: Int) -> String {
let size = max(0, bytes)
if size < 1024 * 1024 {
+7
View File
@@ -1,8 +1,13 @@
import SwiftUI
///
///
struct EmptyStateView: View {
/// SF Symbol
let icon: String
///
let title: String
///
var message: String? = nil
var body: some View {
@@ -23,11 +28,13 @@ struct EmptyStateView: View {
}
.padding(.bottom, 8)
//
Text(title)
.font(.title3.bold())
.foregroundColor(.white.opacity(0.9))
.tracking(1)
//
if let message = message {
Text(message)
.font(.callout)
+36
View File
@@ -2,15 +2,21 @@ import SwiftUI
/// - Android HomeActivity TabView
struct ContentView: View {
/// 使
private enum ApiInputTarget {
case vod
case live
}
///
@EnvironmentObject var appState: AppState
/// ViewModel
@StateObject private var settingsVM = SettingsViewModel()
///
@State private var selectedTab = 0
/// `appState.isConfigLoaded`
@State private var showSetup = false
///
@State private var setupInputTarget: ApiInputTarget = .vod
var body: some View {
@@ -21,6 +27,7 @@ struct ContentView: View {
setupView
}
}
.overlay(multiRepoSelectionOverlay)
.preferredColorScheme(.dark)
.onAppear {
//
@@ -28,6 +35,7 @@ struct ContentView: View {
let savedVodUrl = defaults.string(forKey: HawkConfig.API_URL) ?? ""
let savedLiveUrl = defaults.string(forKey: HawkConfig.LIVE_API_URL) ?? ""
if !savedVodUrl.isEmpty {
//
Task {
await appState.loadConfig(vodUrl: savedVodUrl, liveUrl: savedLiveUrl)
}
@@ -35,8 +43,34 @@ struct ContentView: View {
}
}
@ViewBuilder
private var multiRepoSelectionOverlay: some View {
//
if let pending = settingsVM.pendingMultiRepoSelection {
SelectionModal(
title: "选择\(pending.target.title)仓库",
icon: "list.bullet.rectangle.portrait.fill",
items: pending.options,
selectedItem: nil,
itemTitle: { $0.name },
onSelect: { option in
Task {
await settingsVM.selectPendingMultiRepoOption(option)
if settingsVM.configSuccess {
appState.applyLoadedConfigState()
}
}
},
onCancel: {
settingsVM.cancelPendingMultiRepoSelection()
}
)
}
}
// MARK: -
/// iOS 使 TabViewmacOS 使 NavigationSplitView
private var mainTabView: some View {
#if os(iOS)
TabView(selection: $selectedTab) {
@@ -105,6 +139,7 @@ struct ContentView: View {
// MARK: -
///
private var setupView: some View {
ZStack {
//
@@ -321,6 +356,7 @@ struct ContentView: View {
#if os(iOS)
UIPasteboard.general.string
#else
// macOS NSPasteboard
NSPasteboard.general.string(forType: .string)
#endif
}
+2 -1
View File
@@ -1 +1,2 @@
// This file has been moved to tvbox/Utils/Extensions.swift to ensure compatibility across targets.
// `tvbox/Utils/Extensions.swift`
//
+39 -33
View File
@@ -2,17 +2,26 @@ import SwiftUI
/// - Android SeriesAdapter
struct EpisodeListView: View {
/// 线
let episodes: [VodInfo.Episode]
///
let selectedIndex: Int
///
let onSelect: (Int) -> Void
/// 50
@State private var currentGroup = 0
///
private let groupSize = 50
///
private let gridColumns = [GridItem(.adaptive(minimum: 78), spacing: 10)]
/// 1 0
private var groupCount: Int {
max(1, (episodes.count + groupSize - 1) / groupSize)
}
///
private var currentEpisodes: [VodInfo.Episode] {
let start = currentGroup * groupSize
let end = min(start + groupSize, episodes.count)
@@ -56,43 +65,40 @@ struct EpisodeListView: View {
}
}
//
ScrollView(.horizontal, showsIndicators: false) {
LazyHGrid(rows: [
GridItem(.fixed(44)),
GridItem(.fixed(44))
], spacing: 10) {
ForEach(Array(currentEpisodes.enumerated()), id: \.offset) { index, episode in
let actualIndex = currentGroup * groupSize + index
Button {
onSelect(actualIndex)
} label: {
Text(episode.name)
.font(.system(size: 13, weight: actualIndex == selectedIndex ? .bold : .medium))
.foregroundColor(actualIndex == selectedIndex ? .white : .white.opacity(0.7))
.frame(minWidth: 70)
.frame(height: 44)
.background(
ZStack {
if actualIndex == selectedIndex {
AppTheme.accentGradient
} else {
Color.white.opacity(0.05)
}
//
LazyVGrid(columns: gridColumns, alignment: .leading, spacing: 10) {
// 使 + 便
ForEach(Array(currentEpisodes.enumerated()), id: \.offset) { index, episode in
let actualIndex = currentGroup * groupSize + index
Button {
onSelect(actualIndex)
} label: {
Text(episode.name)
.font(.system(size: 13, weight: actualIndex == selectedIndex ? .bold : .medium))
.foregroundColor(actualIndex == selectedIndex ? .white : .white.opacity(0.7))
.lineLimit(1)
.minimumScaleFactor(0.85)
.frame(maxWidth: .infinity)
.frame(height: 44)
.background(
ZStack {
if actualIndex == selectedIndex {
AppTheme.accentGradient
} else {
Color.white.opacity(0.05)
}
)
.clipShape(RoundedRectangle(cornerRadius: 10))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(actualIndex == selectedIndex ? Color.clear : Color.white.opacity(0.1), lineWidth: 0.5)
)
}
.buttonStyle(.plain)
}
)
.clipShape(RoundedRectangle(cornerRadius: 10))
.overlay(
RoundedRectangle(cornerRadius: 10)
.stroke(actualIndex == selectedIndex ? Color.clear : Color.white.opacity(0.1), lineWidth: 0.5)
)
}
.buttonStyle(.plain)
}
.padding(.horizontal, 20)
}
.frame(height: 100)
.padding(.horizontal, 20)
}
}
}
+10
View File
@@ -3,15 +3,19 @@ import SwiftData
/// - Android CollectActivity
struct FavoritesView: View {
/// /
@Query(sort: \VodCollect.updateTime, order: .reverse)
private var favorites: [VodCollect]
/// SwiftData
@Environment(\.modelContext) private var modelContext
#if os(iOS)
/// iOS
private let columns = [
GridItem(.adaptive(minimum: 120, maximum: 160), spacing: 12)
]
#else
/// macOS
private let columns = [
GridItem(.adaptive(minimum: 140, maximum: 180), spacing: 16)
]
@@ -25,6 +29,7 @@ struct FavoritesView: View {
} else {
ScrollView {
LazyVGrid(columns: columns, spacing: 16) {
//
ForEach(favorites) { item in
NavigationLink(value: movieVideo(from: item)) {
favoriteCard(item)
@@ -50,12 +55,14 @@ struct FavoritesView: View {
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
// Movie.Video /
.navigationDestination(for: Movie.Video.self) { video in
DetailView(video: video)
}
}
}
///
private var emptyState: some View {
EmptyStateView(
icon: "heart.text.square",
@@ -65,6 +72,8 @@ struct FavoritesView: View {
.padding(40)
}
///
///
private func favoriteCard(_ item: VodCollect) -> some View {
VStack(alignment: .leading, spacing: 6) {
CachedAsyncImage(url: URL.posterURL(from: item.vodPic)) { image in
@@ -83,6 +92,7 @@ struct FavoritesView: View {
}
}
///
private func movieVideo(from item: VodCollect) -> Movie.Video {
Movie.Video(id: item.vodId, name: item.vodName, pic: item.vodPic, sourceKey: item.sourceKey)
}
+11
View File
@@ -3,15 +3,19 @@ import SwiftData
/// - Android HistoryActivity
struct HistoryView: View {
///
@Query(sort: \VodRecord.updateTime, order: .reverse)
private var records: [VodRecord]
/// SwiftData
@Environment(\.modelContext) private var modelContext
#if os(iOS)
/// iOS
private let columns = [
GridItem(.adaptive(minimum: 120, maximum: 160), spacing: 12)
]
#else
/// macOS
private let columns = [
GridItem(.adaptive(minimum: 140, maximum: 180), spacing: 16)
]
@@ -25,6 +29,7 @@ struct HistoryView: View {
} else {
ScrollView {
LazyVGrid(columns: columns, spacing: 16) {
//
ForEach(records) { item in
NavigationLink(value: movieVideo(from: item)) {
recordCard(item)
@@ -53,6 +58,7 @@ struct HistoryView: View {
.toolbar {
if !records.isEmpty {
ToolbarItem(placement: .automatic) {
// 使
Button {
Task {
CacheStore.shared.clearHistory(context: modelContext)
@@ -64,12 +70,14 @@ struct HistoryView: View {
}
}
}
// //
.navigationDestination(for: Movie.Video.self) { video in
DetailView(video: video)
}
}
}
///
private var emptyState: some View {
EmptyStateView(
icon: "clock.arrow.circlepath",
@@ -79,6 +87,8 @@ struct HistoryView: View {
.padding(40)
}
///
/// 便
private func recordCard(_ item: VodRecord) -> some View {
VStack(alignment: .leading, spacing: 6) {
ZStack(alignment: .bottomLeading) {
@@ -115,6 +125,7 @@ struct HistoryView: View {
}
}
///
private func movieVideo(from item: VodRecord) -> Movie.Video {
Movie.Video(id: item.vodId, name: item.vodName, pic: item.vodPic, sourceKey: item.sourceKey)
}
+4
View File
@@ -2,7 +2,9 @@ import SwiftUI
///
struct VodCardView: View {
///
let video: Movie.Video
/// macOS
@State private var isHovered = false
var body: some View {
@@ -44,6 +46,7 @@ struct VodCardView: View {
.padding(8)
}
}
//
.scaleEffect(isHovered ? 1.05 : 1.0)
.animation(.spring(response: 0.3, dampingFraction: 0.6), value: isHovered)
.onHover { hovering in
@@ -67,6 +70,7 @@ struct VodCardView: View {
}
}
///
private var placeholderImage: some View {
RoundedRectangle(cornerRadius: AppTheme.cardRadius)
.fill(Color.white.opacity(0.05))
+27
View File
@@ -6,24 +6,43 @@ import AppKit
/// - Android LivePlayActivity
struct LiveView: View {
///
@StateObject private var viewModel = LiveViewModel()
/// macOS
@EnvironmentObject var appState: AppState
/// 使
@State private var avPlayer: AVPlayer?
///
@AppStorage(HawkConfig.PLAY_TYPE_LIVE) private var livePlayTypeRaw = -1
///
@AppStorage(HawkConfig.PLAY_TYPE) private var legacyPlayTypeRaw = PlayerEngine.system.rawValue
///
@State private var showChannelDrawer = true
///
@State private var isWindowFullScreen = false
///
private let currentChannelInfoMaxWidth: CGFloat = 600
/// AVPlayer
@State private var itemStatusObserver: NSKeyValueObservation?
///
@State private var playbackFailedObserver: NSObjectProtocol?
///
@State private var playbackStalledObserver: NSObjectProtocol?
/// 线线
@State private var failedSourceIndices: Set<Int> = []
/// ID
@State private var trackedChannelId: String = ""
///
@State private var showCurrentChannelInfo = true
///
@State private var channelInfoTimer: Timer?
///
private let channelInfoAutoHideDelay: TimeInterval = 3.0
/// VLC
@State private var vlcInteractionToken = 0
///
/// 退使
private var selectedEngine: PlayerEngine {
let defaults = UserDefaults.standard
let rawValue: Int
@@ -80,6 +99,7 @@ struct LiveView: View {
.navigationBarTitleDisplayMode(.inline)
#endif
.onAppear {
//
viewModel.loadChannels()
wakeUpCurrentChannelInfo()
}
@@ -92,6 +112,7 @@ struct LiveView: View {
wakeUpCurrentChannelInfo()
}
.onChange(of: viewModel.currentChannel?.id) { _, _ in
// 线
resetFailureTracking(for: viewModel.currentChannel)
wakeUpCurrentChannelInfo()
}
@@ -364,6 +385,7 @@ struct LiveView: View {
}
private func reportUserActivity() {
// VLC
wakeUpCurrentChannelInfo()
vlcInteractionToken &+= 1
}
@@ -459,6 +481,7 @@ struct LiveView: View {
}
private func cleanupPlayer() {
//
if let observer = playbackFailedObserver {
NotificationCenter.default.removeObserver(observer)
playbackFailedObserver = nil
@@ -475,6 +498,7 @@ struct LiveView: View {
}
private func observePlaybackFailure(for item: AVPlayerItem) {
// KVO item
itemStatusObserver = item.observe(\.status, options: [.new]) { observedItem, _ in
if observedItem.status == .failed {
DispatchQueue.main.async {
@@ -483,6 +507,7 @@ struct LiveView: View {
}
}
//
playbackFailedObserver = NotificationCenter.default.addObserver(
forName: .AVPlayerItemFailedToPlayToEndTime,
object: item,
@@ -491,6 +516,7 @@ struct LiveView: View {
handlePlaybackFailure(trigger: "item_failed")
}
//
playbackStalledObserver = NotificationCenter.default.addObserver(
forName: .AVPlayerItemPlaybackStalled,
object: item,
@@ -526,6 +552,7 @@ struct LiveView: View {
private func switchToNextAvailableSource(totalSources: Int) -> Bool {
guard failedSourceIndices.count < totalSources else { return false }
// `totalSources` 线
for _ in 0..<totalSources {
viewModel.switchSource()
guard let nextIndex = viewModel.currentChannel?.sourceIndex else { return false }
+11
View File
@@ -2,13 +2,16 @@ import SwiftUI
/// - Android SearchActivity
struct SearchView: View {
///
@StateObject private var viewModel = SearchViewModel()
#if os(iOS)
/// iOS
private let columns = [
GridItem(.adaptive(minimum: 120, maximum: 160), spacing: 12)
]
#else
/// macOS
private let columns = [
GridItem(.adaptive(minimum: 140, maximum: 180), spacing: 16)
]
@@ -29,6 +32,7 @@ struct SearchView: View {
} else if !viewModel.results.isEmpty {
searchResults
} else if viewModel.keyword.isEmpty {
//
searchHistorySection
} else if let error = viewModel.errorMessage {
Spacer()
@@ -53,6 +57,7 @@ struct SearchView: View {
// MARK: -
///
private var searchBar: some View {
HStack(spacing: 12) {
HStack(spacing: 10) {
@@ -114,6 +119,7 @@ struct SearchView: View {
// MARK: -
///
private var searchResults: some View {
ScrollView {
LazyVGrid(columns: columns, spacing: 16) {
@@ -134,6 +140,7 @@ struct SearchView: View {
// MARK: -
///
private var searchHistorySection: some View {
VStack(alignment: .leading, spacing: 12) {
if !viewModel.searchHistory.isEmpty {
@@ -183,13 +190,16 @@ struct SearchView: View {
///
struct FlowLayout: Layout {
///
var spacing: CGFloat = 8
///
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let result = arrangement(proposal: proposal, subviews: subviews)
return result.size
}
///
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let result = arrangement(proposal: ProposedViewSize(width: bounds.width, height: bounds.height), subviews: subviews)
for (index, position) in result.positions.enumerated() {
@@ -197,6 +207,7 @@ struct FlowLayout: Layout {
}
}
///
private func arrangement(proposal: ProposedViewSize, subviews: Subviews) -> (size: CGSize, positions: [CGPoint]) {
let maxWidth = proposal.width ?? .infinity
var positions: [CGPoint] = []
+26
View File
@@ -335,11 +335,37 @@ struct SettingsView: View {
}
}
}
.overlay(multiRepoSelectionOverlay)
#if os(iOS)
.presentationDetents([.medium, .large])
#endif
}
@ViewBuilder
private var multiRepoSelectionOverlay: some View {
if let pending = viewModel.pendingMultiRepoSelection {
SelectionModal(
title: "选择\(pending.target.title)仓库",
icon: "list.bullet.rectangle.portrait.fill",
items: pending.options,
selectedItem: nil,
itemTitle: { $0.name },
onSelect: { option in
Task {
await viewModel.selectPendingMultiRepoOption(option)
if viewModel.configSuccess {
appState.applyLoadedConfigState()
showApiInput = false
}
}
},
onCancel: {
viewModel.cancelPendingMultiRepoSelection()
}
)
}
}
private var currentApiBinding: Binding<String> {
switch editingApiType {
case .vod:
+22
View File
@@ -1,10 +1,15 @@
import SwiftUI
import SwiftData
///
/// SwiftData `AppState`
@main
struct tvboxApp: App {
///
@StateObject private var appState = AppState()
/// SwiftData
/// Schema//使
var sharedModelContainer: ModelContainer = {
let schema = Schema([
VodCollect.self,
@@ -19,6 +24,7 @@ struct tvboxApp: App {
}
}()
///
var body: some Scene {
WindowGroup {
ContentView()
@@ -31,20 +37,32 @@ struct tvboxApp: App {
}
}
///
///
@MainActor
class AppState: ObservableObject {
/// ViewModel 使
@Published var apiConfig = ApiConfig.shared
/// `ContentView`
@Published var isConfigLoaded = false
/// key
@Published var currentSourceKey: String = ""
#if os(macOS)
/// macOS //
@Published var splitViewVisibility: NavigationSplitViewVisibility = .all
/// 退
private var splitViewVisibilityBeforePlayerFullScreen: NavigationSplitViewVisibility?
#endif
///
func loadConfig(url: String) async {
await loadConfig(vodUrl: url, liveUrl: nil)
}
///
/// - Parameters:
/// - vodUrl:
/// - liveUrl: 退
func loadConfig(vodUrl: String, liveUrl: String?) async {
let trimmedVod = vodUrl.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedLive = (liveUrl ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
@@ -59,12 +77,15 @@ class AppState: ObservableObject {
}
}
///
///
func applyLoadedConfigState() {
isConfigLoaded = true
currentSourceKey = ApiConfig.shared.homeSourceBean?.key ?? ""
}
#if os(macOS)
///
func enterPlayerFullScreen() {
if splitViewVisibilityBeforePlayerFullScreen == nil {
splitViewVisibilityBeforePlayerFullScreen = splitViewVisibility
@@ -72,6 +93,7 @@ class AppState: ObservableObject {
splitViewVisibility = .detailOnly
}
/// 退
func exitPlayerFullScreen() {
guard let previous = splitViewVisibilityBeforePlayerFullScreen else { return }
splitViewVisibility = previous