Init commit

This commit is contained in:
世界
2023-07-15 15:03:45 +08:00
commit f441b89efb
122 changed files with 7355 additions and 0 deletions
+36
View File
@@ -0,0 +1,36 @@
import Foundation
import GRDB
class Database {
private static var writer: (any DatabaseWriter)?
static func sharedWriter() throws -> any DatabaseWriter {
if let writer {
return writer
}
let database = try DatabasePool(path: FilePath.sharedDirectory.appendingPathComponent("settings.db").relativePath)
var migrator = DatabaseMigrator().disablingDeferredForeignKeyChecks()
migrator.eraseDatabaseOnSchemaChange = true
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)
}
}
try migrator.migrate(database)
writer = database
return database
}
}
+16
View File
@@ -0,0 +1,16 @@
//
// Profile+Date.swift
// Library
//
// Created by on 2023/6/29.
//
import Foundation
public extension Profile {
var lastUpdatedString: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter.string(from: lastUpdated!)
}
}
+11
View File
@@ -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)
}
}
+31
View File
@@ -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)
}
}
}
+20
View File
@@ -0,0 +1,20 @@
import Foundation
import GRDB
import Libbox
public extension Profile {
func updateRemoteProfile() 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 ProfileManager.update(self)
}
}
+73
View File
@@ -0,0 +1,73 @@
import Foundation
import GRDB
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
public var lastUpdated: Date?
public init(id: Int64? = nil, name: String, order: UInt32 = 0, type: ProfileType, path: String, remoteURL: String? = nil) {
self.id = id
self.name = name
self.order = order
self.type = type
self.path = path
self.remoteURL = remoteURL
autoUpdate = false
lastUpdated = nil
if type == .remote {
lastUpdated = Date()
}
super.init()
}
override public class var databaseTableName: String {
"profiles"
}
enum Columns: String, ColumnExpression {
case id, name, order, type, path, remoteURL, autoUpdate, 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
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.lastUpdated] = lastUpdated
}
override public func didInsert(_ inserted: InsertionSuccess) {
super.didInsert(inserted)
id = inserted.rowID
}
}
public enum ProfileType: Int {
case local = 0, icloud, remote
}
+98
View File
@@ -0,0 +1,98 @@
import Foundation
import GRDB
public enum ProfileManager {
public static func create(_ profile: Profile) throws {
profile.order = try nextOrder()
try Database.sharedWriter().write { db in
try profile.insert(db, onConflict: .fail)
}
}
public static func get(_ profileID: Int64) throws -> Profile? {
try Database.sharedWriter().read { db in
try Profile.fetchOne(db, id: profileID)
}
}
public static func get(by profileName: String) throws -> Profile? {
try Database.sharedWriter().read { db in
try Profile.filter(Column("name") == profileName).fetchOne(db)
}
}
public static func delete(_ profile: Profile) throws {
_ = try Database.sharedWriter().write { db in
try profile.delete(db)
}
}
public static func delete(by id: Int64) throws {
_ = try Database.sharedWriter().write { db in
try Profile.deleteOne(db, id: id)
}
}
public static func delete(_ profileList: [Profile]) throws -> Int {
try Database.sharedWriter().write { db in
try Profile.deleteAll(db, keys: profileList.map {
["id": $0.id!]
})
}
}
public static func delete(by id: [Int64]) throws -> Int {
try Database.sharedWriter().write { db in
try Profile.deleteAll(db, ids: id)
}
}
public static func update(_ profile: Profile) throws {
_ = try Database.sharedWriter().write { db in
try profile.updateChanges(db)
}
}
public static func update(_ profileList: [Profile]) throws {
// TODO: batch update
try Database.sharedWriter().write { db in
for profile in profileList {
try profile.updateChanges(db)
}
}
}
public static func list() throws -> [Profile] {
try Database.sharedWriter().read { db in
try Profile.all().order(Column("order").asc).fetchAll(db)
}
}
public static func listRemote() throws -> [Profile] {
try Database.sharedWriter().read { db in
try Profile.filter(Column("type") == ProfileType.remote.rawValue).order(Column("order").asc).fetchAll(db)
}
}
public static func listAutoUpdateEnabled() throws -> [Profile] {
try Database.sharedWriter().read { db in
try Profile.filter(Column("autoUpdate") == true).order(Column("order").asc).fetchAll(db)
}
}
public static func nextID() throws -> Int64 {
try 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 static func nextOrder() throws -> UInt32 {
try Database.sharedWriter().read { db in
try UInt32(Profile.fetchCount(db))
}
}
}
@@ -0,0 +1,116 @@
import BinaryCodable
import Foundation
import GRDB
extension SharedPreferences {
@propertyWrapper 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 var wrappedValue: T {
get {
do {
return try SharedPreferences.read(name) ?? defaultValue
} catch {
NSLog("read preferences error: \(error)")
return defaultValue
}
}
set {
do {
try SharedPreferences.write(name, newValue)
} catch {
NSLog("write preferences error: \(error)")
}
}
}
}
@propertyWrapper public class NullablePreference<T: Codable> {
private let name: String
init(_ name: String) {
self.name = name
}
public var wrappedValue: T? {
get {
do {
return try SharedPreferences.read(name)
} catch {
NSLog("read preferences error: \(error)")
return nil
}
}
set {
do {
try SharedPreferences.write(name, newValue)
} catch {
NSLog("write preferences error: \(error)")
}
}
}
}
private static func read<T: Codable>(_ name: String) throws -> T? {
guard let item = try (Database.sharedWriter().read { db in
try Item.fetchOne(db, id: name)
})
else {
return nil
}
return try BinaryDecoder().decode(from: item.data)
}
private static func write(_ name: String, _ value: (some Codable)?) throws {
if value == nil {
_ = try Database.sharedWriter().write { db in
try Item.deleteOne(db, id: name)
}
} else {
let data = try BinaryEncoder().encode(value)
try 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
}
}
+19
View File
@@ -0,0 +1,19 @@
import Foundation
public enum SharedPreferences {
@Preference<Int64>("selected_profile_id", defaultValue: -1) public static var selectedProfileID
#if os(macOS)
private static let disableMemoryLimitByDefault = true
#else
private static let disableMemoryLimitByDefault = false
#endif
@Preference<Bool>("disable_memory_limit", defaultValue: disableMemoryLimitByDefault) public static var disableMemoryLimit
@Preference<Int>("max_log_lines", defaultValue: 300) public static var maxLogLines
#if os(macOS)
@Preference<Bool>("show_menu_bar_extra", defaultValue: true) public static var showMenuBarExtra
@Preference<Bool>("started_by_user", defaultValue: false) public static var startedByUser
#endif
}
+3
View File
@@ -0,0 +1,3 @@
import Foundation
public class Library {}
+70
View File
@@ -0,0 +1,70 @@
import Foundation
import NetworkExtension
public class ExtensionProfile: ObservableObject {
private let manager: NEVPNManager
private var connection: NEVPNConnection
private var observer: Any?
@Published public var status: NEVPNStatus
public init(_ manager: NEVPNManager) {
self.manager = manager
connection = manager.connection
status = manager.connection.status
}
deinit {
unregister()
}
public func register() {
observer = NotificationCenter.default.addObserver(
forName: NSNotification.Name.NEVPNStatusDidChange,
object: manager.connection,
queue: .main
) { [weak self] notification in
guard let self else {
return
}
self.connection = notification.object as! NEVPNConnection
self.status = self.connection.status
}
}
private func unregister() {
if let observer {
NotificationCenter.default.removeObserver(observer)
}
}
public func start() async throws {
manager.isEnabled = true
try await manager.saveToPreferences()
try manager.connection.startVPNTunnel()
}
public func stop() {
manager.connection.stopVPNTunnel()
}
public static func load() async throws -> ExtensionProfile? {
let managers = try await NETunnelProviderManager.loadAllFromPreferences()
if managers.isEmpty {
return nil
}
let profile = ExtensionProfile(managers[0])
return profile
}
public static func install() async throws {
let manager = NETunnelProviderManager()
manager.localizedDescription = "utun interface"
let tunnelProtocol = NETunnelProviderProtocol()
tunnelProtocol.providerBundleIdentifier = "\(FilePath.packageName).extension"
tunnelProtocol.serverAddress = "sing-box"
manager.protocolConfiguration = tunnelProtocol
manager.isEnabled = true
try await manager.saveToPreferences()
}
}
+40
View File
@@ -0,0 +1,40 @@
import Foundation
import Libbox
public class HTTPClient {
private static var userAgent: String {
var userAgent = FilePath.httpClientName
userAgent += "/"
userAgent += Bundle.main.version
userAgent += " (Build "
userAgent += Bundle.main.versionNumber
userAgent += "; sing-box "
userAgent += LibboxVersion()
userAgent += ")"
return userAgent
}
private let client: any LibboxHTTPClientProtocol
public init() {
client = LibboxNewHTTPClient()!
client.modernTLS()
}
public func getString(_ url: String?) throws -> String {
let request = client.newRequest()!
request.setUserAgent(HTTPClient.userAgent)
try request.setURL(url)
let response = try request.execute()
var error: NSError?
let contentString = response.getContentString(&error)
if let error {
throw error
}
return contentString
}
deinit {
client.close()
}
}
@@ -0,0 +1,40 @@
import Foundation
import NetworkExtension
public extension NEVPNStatus {
var isEnabled: Bool {
switch self {
case .connected, .disconnected, .reasserting:
return true
default:
return false
}
}
var isSwitchable: Bool {
switch self {
case .connected, .disconnected:
return true
default:
return false
}
}
var isConnected: Bool {
switch self {
case .connecting, .connected, .disconnecting, .reasserting:
return true
default:
return false
}
}
var isConnectedStrict: Bool {
switch self {
case .connected, .reasserting:
return true
default:
return false
}
}
}
+11
View File
@@ -0,0 +1,11 @@
import Foundation
extension Bundle {
var version: String {
infoDictionary?["CFBundleShortVersionString"] as? String ?? "unknown"
}
var versionNumber: String {
infoDictionary?["CFBundleVersion"] as? String ?? "unknown"
}
}
+34
View File
@@ -0,0 +1,34 @@
import Foundation
public enum FilePath {
public static let packageName = "io.nekohasekai.sfa"
#if os(iOS)
public static let httpClientName = "SFI"
#elseif os(macOS)
public static let httpClientName = "SFM"
#endif
}
public extension FilePath {
static let groupName = "group.\(packageName)"
static let sharedDirectory: URL! = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupName)
static let cacheDirectory = sharedDirectory
.appendingPathComponent("Library", isDirectory: true)
.appendingPathComponent("Caches", isDirectory: true)
static let workingDirectory = cacheDirectory.appendingPathComponent("Working", isDirectory: true)
static let iCloudDirectory = FileManager.default.url(forUbiquityContainerIdentifier: nil)!.appendingPathComponent("Documents", isDirectory: true)
}
public extension URL {
var fileName: String {
var path = relativePath
if let index = path.lastIndex(of: "/") {
path = String(path[path.index(index, offsetBy: 1)...])
}
return path
}
}
+46
View File
@@ -0,0 +1,46 @@
import Foundation
import UserNotifications
public enum ServiceNotification {
private static let delegate = Delegate()
public static func register() {
UNUserNotificationCenter.current().delegate = delegate
UNUserNotificationCenter.current().requestAuthorization(options: [.alert]) {
_, _ in
}
}
private static var listener: ((UNNotificationContent) -> Void)?
public static func setServiceNotificationListener(listener: @escaping (UNNotificationContent) -> Void) {
ServiceNotification.listener = listener
}
public static func removeServiceNotificationListener() {
ServiceNotification.listener = nil
}
public static func postServiceNotification(content: UNNotificationContent) {
UNUserNotificationCenter.current().add(UNNotificationRequest(identifier: "service-notification", content: content, trigger: nil))
}
public static func postServiceNotification(title: String, message: String) {
let content = UNMutableNotificationContent()
content.title = title
content.body = message
postServiceNotification(content: content)
}
private class Delegate: NSObject, UNUserNotificationCenterDelegate {
func userNotificationCenter(_: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions {
NSLog("userNotificationCenter")
if let listener = ServiceNotification.listener {
listener(notification.request.content)
return []
} else {
return [.alert]
}
}
}
}