add swiftUI code

This commit is contained in:
zeus
2025-01-22 14:09:10 +08:00
parent 68e7b7347c
commit 8a99853829
2531 changed files with 486215 additions and 0 deletions
@@ -0,0 +1,39 @@
import Foundation
import GRDB
enum Database {
static let sharedWriter = makeShared()
private static func makeShared() -> any DatabaseWriter {
do {
try FileManager.default.createDirectory(at: FilePath.sharedDirectory, withIntermediateDirectories: true)
let database = try DatabasePool(path: FilePath.sharedDirectory.appendingPathComponent("settings.db").relativePath)
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
migrator.registerMigration("initialize") { db in
try db.create(table: "profiles") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("order", .integer).notNull()
t.column("type", .integer).notNull().defaults(to: ProfileType.local.rawValue)
t.column("path", .text).notNull()
t.column("remoteURL", .text)
t.column("autoUpdate", .boolean).notNull().defaults(to: false)
t.column("lastUpdated", .datetime)
}
try db.create(table: "preferences") { t in
t.primaryKey("name", .text, onConflict: .replace).notNull()
t.column("data", .blob)
}
}
migrator.registerMigration("add_auto_update_interval") { db in
try db.alter(table: "profiles") { t in
t.add(column: "autoUpdateInterval", .integer).notNull().defaults(to: 0)
}
}
try migrator.migrate(database)
return database
} catch {
fatalError(error.localizedDescription)
}
}
}
@@ -0,0 +1,9 @@
import Foundation
public extension Profile {
var lastUpdatedString: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: lastUpdated!)
}
}
@@ -0,0 +1,11 @@
import Foundation
extension Profile: Hashable {
public static func == (lhs: Profile, rhs: Profile) -> Bool {
lhs.id == rhs.id
}
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
@@ -0,0 +1,31 @@
import Foundation
public extension Profile {
func read() throws -> String {
switch type {
case .local, .remote:
return try String(contentsOfFile: path)
case .icloud:
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
return try String(contentsOf: saveURL)
}
}
func write(_ content: String) throws {
switch type {
case .local, .remote:
try content.write(toFile: path, atomically: true, encoding: .utf8)
case .icloud:
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
try content.write(to: saveURL, atomically: true, encoding: .utf8)
}
}
}
@@ -0,0 +1,8 @@
import Foundation
import Libbox
public extension Profile {
var shareLink: URL {
URL(string: LibboxGenerateRemoteProfileImportLink(name, remoteURL!))!
}
}
@@ -0,0 +1,106 @@
import Foundation
import Libbox
import SwiftUI
import UniformTypeIdentifiers
public extension Profile {
func toContent() throws -> LibboxProfileContent {
let content = LibboxProfileContent()
content.name = name
content.type = Int32(type.rawValue)
content.config = try read()
if type != .local {
content.remotePath = remoteURL!
}
if type == .remote {
content.autoUpdate = autoUpdate
content.autoUpdateInterval = autoUpdateInterval
if let lastUpdated {
content.lastUpdated = Int64(lastUpdated.timeIntervalSince1970)
}
}
return content
}
}
@available(iOS 16.0, macOS 13.0, *)
extension Profile: Transferable {
public static var transferRepresentation: some TransferRepresentation {
ProxyRepresentation { profile in
try TypedProfile(profile.toContent())
}
}
}
public extension LibboxProfileContent {
static func from(_ data: Data) throws -> LibboxProfileContent {
var error: NSError?
let content = LibboxDecodeProfileContent(data, &error)
if let error {
throw error
}
return content!
}
func importProfile() async throws {
let nextProfileID = try await ProfileManager.nextID()
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
try config.write(to: profileConfig, atomically: true, encoding: .utf8)
var lastUpdatedAt: Date?
if lastUpdated > 0 {
lastUpdatedAt = Date(timeIntervalSince1970: Double(lastUpdated))
}
try await ProfileManager.create(Profile(name: name, type: ProfileType(rawValue: Int(type))!, path: profileConfig.relativePath, remoteURL: remotePath, autoUpdate: autoUpdate, autoUpdateInterval: autoUpdateInterval, lastUpdated: lastUpdatedAt))
}
func generateShareFile() throws -> URL {
let shareDirectory = FilePath.cacheDirectory.appendingPathComponent("share", isDirectory: true)
try FileManager.default.createDirectory(at: shareDirectory, withIntermediateDirectories: true)
let shareFile = shareDirectory.appendingPathComponent("\(name).bpf")
try encode()!.write(to: shareFile)
return shareFile
}
}
public extension String {
func generateShareFile(name: String) throws -> URL {
let shareDirectory = FilePath.cacheDirectory.appendingPathComponent("share", isDirectory: true)
try FileManager.default.createDirectory(at: shareDirectory, withIntermediateDirectories: true)
let shareFile = shareDirectory.appendingPathComponent(name)
try write(to: shareFile, atomically: true, encoding: .utf8)
return shareFile
}
}
@available(iOS 16.0, macOS 13.0, *)
public struct TypedProfile: Transferable, Codable {
public let content: LibboxProfileContent
public init(_ content: LibboxProfileContent) {
self.content = content
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let data = try container.decode(Data.self)
try self.init(.from(data))
}
public static var transferRepresentation: some TransferRepresentation {
FileRepresentation(contentType: .profile) { typed in
try SentTransferredFile(typed.content.generateShareFile(), allowAccessingOriginalFile: true)
} importing: { received in
try TypedProfile(.from(Data(contentsOf: received.file)))
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(content.encode()!)
}
}
public extension UTType {
static var profile: UTType { .init(exportedAs: "com.uuvpn.apple.profile") }
}
@@ -0,0 +1,20 @@
import Foundation
import GRDB
import Libbox
public extension Profile {
nonisolated func updateRemoteProfile() async throws {
if type != .remote {
return
}
let remoteContent = try HTTPClient().getString(remoteURL)
var error: NSError?
LibboxCheckConfig(remoteContent, &error)
if let error {
throw error
}
try write(remoteContent)
lastUpdated = Date()
try await ProfileManager.update(self)
}
}
@@ -0,0 +1,100 @@
import Foundation
import GRDB
import Network
public class Profile: Record, Identifiable, ObservableObject {
public var id: Int64?
public var mustID: Int64 {
id!
}
@Published public var name: String
public var order: UInt32
public var type: ProfileType
public var path: String
@Published public var remoteURL: String?
@Published public var autoUpdate: Bool
@Published public var autoUpdateInterval: Int32
public var lastUpdated: Date?
public init(id: Int64? = nil, name: String, order: UInt32 = 0, type: ProfileType, path: String, remoteURL: String? = nil, autoUpdate: Bool = false, autoUpdateInterval: Int32 = 0, lastUpdated: Date? = nil) {
self.id = id
self.name = name
self.order = order
self.type = type
self.path = path
self.remoteURL = remoteURL
self.autoUpdate = autoUpdate
self.autoUpdateInterval = autoUpdateInterval
self.lastUpdated = lastUpdated
super.init()
}
override public class var databaseTableName: String {
"profiles"
}
enum Columns: String, ColumnExpression {
case id, name, order, type, path, remoteURL, autoUpdate, autoUpdateInterval, lastUpdated, userAgent
}
required init(row: Row) throws {
id = row[Columns.id]
name = row[Columns.name] ?? ""
order = row[Columns.order] ?? 0
type = ProfileType(rawValue: row[Columns.type] ?? ProfileType.local.rawValue)!
path = row[Columns.path] ?? ""
remoteURL = row[Columns.remoteURL] ?? ""
autoUpdate = row[Columns.autoUpdate] ?? false
autoUpdateInterval = row[Columns.autoUpdateInterval] ?? 0
lastUpdated = row[Columns.lastUpdated] ?? Date()
try super.init(row: row)
}
override public func encode(to container: inout PersistenceContainer) throws {
container[Columns.id] = id
container[Columns.name] = name
container[Columns.order] = order
container[Columns.type] = type.rawValue
container[Columns.path] = path
container[Columns.remoteURL] = remoteURL
container[Columns.autoUpdate] = autoUpdate
container[Columns.autoUpdateInterval] = autoUpdateInterval
container[Columns.lastUpdated] = lastUpdated
}
override public func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
public struct ProfilePreview: Identifiable, Hashable {
public let id: Int64
public let name: String
public var order: UInt32
public let type: ProfileType
public let path: String
public let remoteURL: String?
public let autoUpdate: Bool
public let autoUpdateInterval: Int32
public let lastUpdated: Date?
public let origin: Profile
public init(_ profile: Profile) {
id = profile.mustID
name = profile.name
order = profile.order
type = profile.type
path = profile.path
remoteURL = profile.remoteURL
autoUpdate = profile.autoUpdate
autoUpdateInterval = profile.autoUpdateInterval
lastUpdated = profile.lastUpdated
origin = profile
}
}
public enum ProfileType: Int {
case local = 0, icloud, remote
}
@@ -0,0 +1,98 @@
import Foundation
import GRDB
public enum ProfileManager {
public nonisolated static func create(_ profile: Profile) async throws {
profile.order = try await nextOrder()
try await Database.sharedWriter.write { db in
try profile.insert(db, onConflict: .fail)
}
}
public nonisolated static func get(_ profileID: Int64) async throws -> Profile? {
try await Database.sharedWriter.read { db in
try Profile.fetchOne(db, id: profileID)
}
}
public nonisolated static func get(by profileName: String) async throws -> Profile? {
try await Database.sharedWriter.read { db in
try Profile.filter(Column("name") == profileName).fetchOne(db)
}
}
public nonisolated static func delete(_ profile: Profile) async throws {
_ = try await Database.sharedWriter.write { db in
try profile.delete(db)
}
}
public nonisolated static func delete(by id: Int64) async throws {
_ = try await Database.sharedWriter.write { db in
try Profile.deleteOne(db, id: id)
}
}
public nonisolated static func delete(_ profileList: [Profile]) async throws -> Int {
try await Database.sharedWriter.write { db in
try Profile.deleteAll(db, keys: profileList.map {
["id": $0.id!]
})
}
}
public nonisolated static func delete(by id: [Int64]) async throws -> Int {
try await Database.sharedWriter.write { db in
try Profile.deleteAll(db, ids: id)
}
}
public nonisolated static func update(_ profile: Profile) async throws {
_ = try await Database.sharedWriter.write { db in
try profile.updateChanges(db)
}
}
public nonisolated static func update(_ profileList: [Profile]) async throws {
// TODO: batch update
try await Database.sharedWriter.write { db in
for profile in profileList {
try profile.updateChanges(db)
}
}
}
public nonisolated static func list() async throws -> [Profile] {
try await Database.sharedWriter.read { db in
try Profile.all().order(Column("order").asc).fetchAll(db)
}
}
public nonisolated static func listRemote() async throws -> [Profile] {
try await Database.sharedWriter.read { db in
try Profile.filter(Column("type") == ProfileType.remote.rawValue).order(Column("order").asc).fetchAll(db)
}
}
public nonisolated static func listAutoUpdateEnabled() async throws -> [Profile] {
try await Database.sharedWriter.read { db in
try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db)
}
}
public nonisolated static func nextID() async throws -> Int64 {
try await Database.sharedWriter.read { db in
if let lastProfile = try Profile.select(Column("id")).order(Column("id").desc).fetchOne(db) {
return lastProfile.id! + 1
} else {
return 1
}
}
}
private nonisolated static func nextOrder() async throws -> UInt32 {
try await Database.sharedWriter.read { db in
try UInt32(Profile.fetchCount(db))
}
}
}
@@ -0,0 +1,95 @@
import BinaryCodable
import Foundation
import GRDB
extension SharedPreferences {
public class Preference<T: Codable> {
private let name: String
private let defaultValue: T
init(_ name: String, defaultValue: T) {
self.name = name
self.defaultValue = defaultValue
}
public nonisolated func get() async -> T {
do {
return try await SharedPreferences.read(name) ?? defaultValue
} catch {
NSLog("read preferences error: \(error)")
return defaultValue
}
}
public func getBlocking() -> T {
runBlocking { [self] in
await get()
}
}
public nonisolated func set(_ newValue: T?) async {
do {
try await SharedPreferences.write(name, newValue)
} catch {
NSLog("write preferences error: \(error)")
}
}
}
private nonisolated static func read<T: Codable>(_ name: String) async throws -> T? {
guard let item = try await (Database.sharedWriter.read { db in
try Item.fetchOne(db, id: name)
})
else {
return nil
}
return try BinaryDecoder().decode(from: item.data)
}
private nonisolated static func write(_ name: String, _ value: (some Codable)?) async throws {
if value == nil {
_ = try await Database.sharedWriter.write { db in
try Item.deleteOne(db, id: name)
}
} else {
let data = try BinaryEncoder().encode(value)
try await Database.sharedWriter.write { db in
try Item(name: name, data: data).insert(db)
}
}
}
}
private class Item: Record, Identifiable {
public var id: String {
name
}
public var name: String
public var data: Data
init(name: String, data: Data) {
self.name = name
self.data = data
super.init()
}
override public class var databaseTableName: String {
"preferences"
}
enum Columns: String, ColumnExpression {
case name, data
}
required init(row: Row) throws {
name = row[Columns.name]
data = row[Columns.data]
try super.init(row: row)
}
override public func encode(to container: inout PersistenceContainer) throws {
container[Columns.name] = name
container[Columns.data] = data
}
}
@@ -0,0 +1,84 @@
import Foundation
public enum SharedPreferences {
public static let selectedProfileID = Preference<Int64>("selected_profile_id", defaultValue: -1)
#if os(macOS)
private static let ignoreMemoryLimitByDefault = true
#else
private static let ignoreMemoryLimitByDefault = false
#endif
public static let ignoreMemoryLimit = Preference<Bool>("ignore_memory_limit", defaultValue: ignoreMemoryLimitByDefault)
#if os(iOS)
public static let excludeLocalNetworksByDefault = true
#elseif os(macOS)
public static let excludeLocalNetworksByDefault = false
#endif
#if !os(tvOS)
public static let includeAllNetworks = Preference<Bool>("include_all_networks", defaultValue: false)
public static let excludeAPNs = Preference<Bool>("exclude_apns", defaultValue: true)
public static let excludeLocalNetworks = Preference<Bool>("exclude_local_networks", defaultValue: excludeLocalNetworksByDefault)
public static let excludeCellularServices = Preference<Bool>("exclude_celluar_services", defaultValue: true)
public static let enforceRoutes = Preference<Bool>("enforce_routes", defaultValue: false)
#endif
public static func resetPacketTunnel() async {
await ignoreMemoryLimit.set(nil)
#if !os(tvOS)
await includeAllNetworks.set(nil)
await excludeAPNs.set(nil)
await excludeLocalNetworks.set(nil)
await excludeCellularServices.set(nil)
await enforceRoutes.set(nil)
#endif
}
public static let maxLogLines = Preference<Int>("max_log_lines", defaultValue: 300)
#if os(macOS)
public static let showMenuBarExtra = Preference<Bool>("show_menu_bar_extra", defaultValue: true)
public static let menuBarExtraInBackground = Preference<Bool>("menu_bar_extra_in_background", defaultValue: false)
public static let startedByUser = Preference<Bool>("started_by_user", defaultValue: false)
public static func resetMacOS() async {
await showMenuBarExtra.set(nil)
await menuBarExtraInBackground.set(nil)
}
#endif
#if os(iOS)
public static let networkPermissionRequested = Preference<Bool>("network_permission_requested", defaultValue: false)
#endif
public static let systemProxyEnabled = Preference<Bool>("system_proxy_enabled", defaultValue: true)
// Profile Override
public static let excludeDefaultRoute = Preference<Bool>("exclude_default_route", defaultValue: false)
public static let autoRouteUseSubRangesByDefault = Preference<Bool>("auto_route_use_sub_ranges_by_default", defaultValue: false)
public static let excludeAPNsRoute = Preference<Bool>("exclude_apple_push_notification_services", defaultValue: false)
public static func resetProfileOverride() async {
await excludeDefaultRoute.set(nil)
await autoRouteUseSubRangesByDefault.set(nil)
await excludeAPNsRoute.set(nil)
}
// On Demand Rules
public static let alwaysOn = Preference<Bool>("always_on", defaultValue: false)
public static func resetOnDemandRules() async {
await alwaysOn.set(nil)
}
#if DEBUG
public static let inDebug = true
#else
public static let inDebug = false
#endif
}