mirror of
https://github.com/sudosylabs/vnidrop.git
synced 2026-08-05 02:29:55 +02:00
Merge origin/master into feat/apple-typed-resources-and-fixes
Brings in custom relays, relay connection policies, storage cache clearing, and receiver-failure reporting. Apple-side conflict resolutions: - CoreRepository: keep CoreDispatcher, adopt master's relay factory + network transition guard, drop the now-unused serial queue. - TransferDetailsView: keep the toolbar-share layout; adopt master's invitationPresentation-based QR panel and the new .failed receiver case (typed). - SettingsModel/SettingsScreen: typed L10n titleKey with master's .network case; relay controls and the Free up space / storage redesign coexist. - Add the missing transfer_receiver_failed localization key. - Regenerate l10n from the merged strings.json; keep the Apple catalog untracked. - Drop the notificationsEnabled test assertion (notifications preference was intentionally removed on this branch).
This commit is contained in:
@@ -20,6 +20,18 @@ final class AppModelTests: XCTestCase {
|
||||
_ = makeModel(core, preferences: Fixtures.preferences())
|
||||
await waitUntil { core.state.isInitialized }
|
||||
XCTAssertTrue(core.state.isInitialized)
|
||||
XCTAssertEqual(core.initializedNetworkConfigurations, [.automatic])
|
||||
}
|
||||
|
||||
func testInitializesCoreWithSavedCustomRelayConfiguration() async {
|
||||
let core = FakeCoreGateway()
|
||||
let preferences = Fixtures.preferences()
|
||||
let configuration = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"])
|
||||
preferences.setRelayConfiguration(configuration)
|
||||
_ = makeModel(core, preferences: preferences)
|
||||
|
||||
await waitUntil { core.state.isInitialized }
|
||||
XCTAssertEqual(core.initializedNetworkConfigurations, [configuration])
|
||||
}
|
||||
|
||||
func testSelectDestination() {
|
||||
|
||||
@@ -15,10 +15,11 @@ final class AppPreferencesRepositoryTests: XCTestCase {
|
||||
)
|
||||
}
|
||||
|
||||
func testFallbacksWhenEmpty() {
|
||||
func testMissingRelayProfileDefaultsToAutomatic() {
|
||||
let repo = AppPreferencesRepository(defaults: defaults(), fallback: fallback())
|
||||
XCTAssertEqual(repo.preferences.username, "Default")
|
||||
XCTAssertEqual(repo.preferences.themeMode, .system)
|
||||
XCTAssertEqual(repo.preferences.relayConfiguration, .automatic)
|
||||
}
|
||||
|
||||
func testValuesPersistAndReload() {
|
||||
@@ -28,6 +29,10 @@ final class AppPreferencesRepositoryTests: XCTestCase {
|
||||
repo.setUsername("Bob")
|
||||
repo.setThemeMode(.dark)
|
||||
repo.setReceiveFolder(ReceiveFolder(kind: .iosSecurityScopedUrl, value: "file:///x", displayName: "Custom"))
|
||||
repo.setRelayConfiguration(RelayConfiguration(
|
||||
mode: .strictCustom,
|
||||
relayURLs: ["https://relay-one.example", "https://relay-two.example:443"]
|
||||
))
|
||||
|
||||
// A fresh repository over the same store reflects the persisted values.
|
||||
let reloaded = AppPreferencesRepository(defaults: store, fallback: fb)
|
||||
@@ -35,6 +40,40 @@ final class AppPreferencesRepositoryTests: XCTestCase {
|
||||
XCTAssertEqual(reloaded.preferences.themeMode, .dark)
|
||||
XCTAssertEqual(reloaded.preferences.receiveFolder.displayName, "Custom")
|
||||
XCTAssertEqual(reloaded.preferences.receiveFolder.kind, .iosSecurityScopedUrl)
|
||||
XCTAssertEqual(reloaded.preferences.relayConfiguration, RelayConfiguration(
|
||||
mode: .strictCustom,
|
||||
relayURLs: ["https://relay-one.example", "https://relay-two.example:443"]
|
||||
))
|
||||
XCTAssertNotNil(store.data(forKey: "relay_configuration"))
|
||||
XCTAssertNil(store.object(forKey: "relay_mode"))
|
||||
XCTAssertNil(store.object(forKey: "relay_urls"))
|
||||
}
|
||||
|
||||
func testCorruptedRelayProfileFailsClosed() {
|
||||
let store = defaults()
|
||||
store.set(Data("{".utf8), forKey: "relay_configuration")
|
||||
|
||||
let repo = AppPreferencesRepository(defaults: store, fallback: fallback())
|
||||
|
||||
XCTAssertEqual(
|
||||
repo.preferences.relayConfiguration,
|
||||
RelayConfiguration(mode: .strictCustom, relayURLs: [])
|
||||
)
|
||||
}
|
||||
|
||||
func testUnknownRelayModeFailsClosed() {
|
||||
let store = defaults()
|
||||
store.set(
|
||||
Data(#"{"mode":"future-mode","relayURLs":["https://relay.example"]}"#.utf8),
|
||||
forKey: "relay_configuration"
|
||||
)
|
||||
|
||||
let repo = AppPreferencesRepository(defaults: store, fallback: fallback())
|
||||
|
||||
XCTAssertEqual(
|
||||
repo.preferences.relayConfiguration,
|
||||
RelayConfiguration(mode: .strictCustom, relayURLs: [])
|
||||
)
|
||||
}
|
||||
|
||||
func testResetReceiveFolderRestoresFallback() {
|
||||
|
||||
131
apple/Tests/CoreRepositoryLifecycleTests.swift
Normal file
131
apple/Tests/CoreRepositoryLifecycleTests.swift
Normal file
@@ -0,0 +1,131 @@
|
||||
import Foundation
|
||||
import XCTest
|
||||
@preconcurrency import VnidropCore
|
||||
@testable import VniDrop
|
||||
|
||||
private enum BlockingCoreFactoryError: Error {
|
||||
case stopped
|
||||
}
|
||||
|
||||
private final class BlockingCoreBindingFactory: CoreBindingFactory, @unchecked Sendable {
|
||||
private let release = DispatchSemaphore(value: 0)
|
||||
private let lock = NSLock()
|
||||
private var initializeCallCount = 0
|
||||
private var initializationStarted = false
|
||||
private var startWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
|
||||
var callCount: Int {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return initializeCallCount
|
||||
}
|
||||
|
||||
func initialize(
|
||||
appDataDir: String,
|
||||
eventSink: CoreEventSink,
|
||||
networkConfiguration: RelayConfiguration
|
||||
) throws -> VnidropCore {
|
||||
lock.lock()
|
||||
initializeCallCount += 1
|
||||
let call = initializeCallCount
|
||||
initializationStarted = true
|
||||
let waiters = startWaiters
|
||||
startWaiters.removeAll()
|
||||
lock.unlock()
|
||||
waiters.forEach { $0.resume() }
|
||||
|
||||
if call == 1 {
|
||||
release.wait()
|
||||
}
|
||||
throw BlockingCoreFactoryError.stopped
|
||||
}
|
||||
|
||||
func waitUntilInitializationStarts() async {
|
||||
await withCheckedContinuation { continuation in
|
||||
lock.lock()
|
||||
if initializationStarted {
|
||||
lock.unlock()
|
||||
continuation.resume()
|
||||
} else {
|
||||
startWaiters.append(continuation)
|
||||
lock.unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func unblockInitialization() {
|
||||
release.signal()
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
final class CoreRepositoryLifecycleTests: XCTestCase {
|
||||
func testIdleRequirementRejectsTransfersAndShares() throws {
|
||||
XCTAssertNoThrow(try CoreNetworkLifecycle.requireIdle(activeTransfers: 0, activeShares: 0))
|
||||
XCTAssertThrowsError(
|
||||
try CoreNetworkLifecycle.requireIdle(activeTransfers: 1, activeShares: 0)
|
||||
) { error in
|
||||
XCTAssertEqual(error as? CoreNetworkLifecycleError, .activeNetworkWork)
|
||||
}
|
||||
XCTAssertThrowsError(
|
||||
try CoreNetworkLifecycle.requireIdle(activeTransfers: 0, activeShares: 1)
|
||||
) { error in
|
||||
XCTAssertEqual(error as? CoreNetworkLifecycleError, .activeNetworkWork)
|
||||
}
|
||||
}
|
||||
|
||||
func testRestartSerializesInitializationAndRejectsNewNetworkWork() async {
|
||||
let factory = BlockingCoreBindingFactory()
|
||||
let repository = CoreRepository(coreFactory: factory)
|
||||
let firstInitialization = Task {
|
||||
await repository.initialize(appDataDir: "/tmp/first", networkConfiguration: .automatic)
|
||||
}
|
||||
await factory.waitUntilInitializationStarts()
|
||||
|
||||
let safetyRelease = Task.detached {
|
||||
try? await Task.sleep(nanoseconds: 1_000_000_000)
|
||||
guard !Task.isCancelled else { return }
|
||||
factory.unblockInitialization()
|
||||
}
|
||||
defer {
|
||||
safetyRelease.cancel()
|
||||
factory.unblockInitialization()
|
||||
}
|
||||
|
||||
let concurrentInitialization = await repository.initialize(
|
||||
appDataDir: "/tmp/second",
|
||||
networkConfiguration: RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"])
|
||||
)
|
||||
assertLifecycleFailure(concurrentInitialization, equals: .transitionInProgress)
|
||||
|
||||
let share = await repository.shareSources(
|
||||
[],
|
||||
transferName: "Blocked",
|
||||
senderName: "Tester",
|
||||
accessPolicy: .requireApproval
|
||||
)
|
||||
assertLifecycleFailure(share, equals: .transitionInProgress)
|
||||
|
||||
let receive = await repository.receive(ticket: "ticket", outputDir: "/tmp", receiverName: "Tester")
|
||||
assertLifecycleFailure(receive, equals: .transitionInProgress)
|
||||
XCTAssertEqual(factory.callCount, 1)
|
||||
|
||||
factory.unblockInitialization()
|
||||
guard case .failure(let error) = await firstInitialization.value else {
|
||||
return XCTFail("The blocking factory should fail the first initialization")
|
||||
}
|
||||
XCTAssertTrue(error is BlockingCoreFactoryError)
|
||||
}
|
||||
|
||||
private func assertLifecycleFailure<T>(
|
||||
_ result: Result<T, Error>,
|
||||
equals expected: CoreNetworkLifecycleError,
|
||||
file: StaticString = #filePath,
|
||||
line: UInt = #line
|
||||
) {
|
||||
guard case .failure(let error) = result else {
|
||||
return XCTFail("Expected lifecycle failure \(expected)", file: file, line: line)
|
||||
}
|
||||
XCTAssertEqual(error as? CoreNetworkLifecycleError, expected, file: file, line: line)
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,8 @@ final class FakeCoreGateway: CoreGateway {
|
||||
var cancelResult: Result<Void, Error> = .success(())
|
||||
var deleteResult: Result<Void, Error> = .success(())
|
||||
var clearReceiveHistoryResult: Result<UInt64, Error> = .success(0)
|
||||
var initializeResult: Result<Void, Error> = .success(())
|
||||
var initializeResults: [Result<Void, Error>] = []
|
||||
|
||||
// Recorded calls
|
||||
private(set) var responses: [(id: String, accepted: Bool, reason: String?)] = []
|
||||
@@ -35,11 +37,18 @@ final class FakeCoreGateway: CoreGateway {
|
||||
private(set) var lastReceiveTicket: String?
|
||||
private(set) var lastReceiveReceiverName: String?
|
||||
private(set) var lastShareAccessPolicy: ShareAccessPolicy?
|
||||
private(set) var initializedNetworkConfigurations: [RelayConfiguration] = []
|
||||
|
||||
func setState(_ state: CoreState) { stateSubject.send(state) }
|
||||
func emit(_ signal: CoreSignal) { signalsSubject.send(signal) }
|
||||
|
||||
func initialize(appDataDir: String) async -> Result<Void, Error> {
|
||||
func initialize(
|
||||
appDataDir: String,
|
||||
networkConfiguration: RelayConfiguration
|
||||
) async -> Result<Void, Error> {
|
||||
initializedNetworkConfigurations.append(networkConfiguration)
|
||||
let result = initializeResults.isEmpty ? initializeResult : initializeResults.removeFirst()
|
||||
guard case .success = result else { return result }
|
||||
var s = stateSubject.value
|
||||
s.isInitialized = true
|
||||
stateSubject.send(s)
|
||||
|
||||
121
apple/Tests/RelayConfigurationTests.swift
Normal file
121
apple/Tests/RelayConfigurationTests.swift
Normal file
@@ -0,0 +1,121 @@
|
||||
import XCTest
|
||||
@testable import VniDrop
|
||||
|
||||
final class RelayConfigurationTests: XCTestCase {
|
||||
func testCustomFallbackValidatesAndPreservesItsMode() throws {
|
||||
let result = try RelayConfigurationValidator.validate(
|
||||
mode: .customWithDirectFallback,
|
||||
relayURLs: ["https://relay.example/"]
|
||||
)
|
||||
|
||||
XCTAssertEqual(
|
||||
result,
|
||||
RelayConfiguration(
|
||||
mode: .customWithDirectFallback,
|
||||
relayURLs: ["https://relay.example"]
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
func testLocalOnlyRetainsPreviouslySavedRelayURLs() throws {
|
||||
let retained = ["https://relay.example"]
|
||||
let result = try RelayConfigurationValidator.validate(
|
||||
mode: .localOnly,
|
||||
relayURLs: ["not a URL"],
|
||||
retainedRelayURLs: retained
|
||||
)
|
||||
|
||||
XCTAssertEqual(result, RelayConfiguration(mode: .localOnly, relayURLs: retained))
|
||||
}
|
||||
|
||||
func testAutomaticModeIgnoresRelayDrafts() throws {
|
||||
let result = try RelayConfigurationValidator.validate(
|
||||
mode: .automatic,
|
||||
relayURLs: ["not a URL"]
|
||||
)
|
||||
XCTAssertEqual(result, .automatic)
|
||||
}
|
||||
|
||||
func testAutomaticModeRetainsPreviouslySavedRelayURLs() throws {
|
||||
let result = try RelayConfigurationValidator.validate(
|
||||
mode: .automatic,
|
||||
relayURLs: ["not a URL"],
|
||||
retainedRelayURLs: ["https://relay.example"]
|
||||
)
|
||||
XCTAssertEqual(result, RelayConfiguration(
|
||||
mode: .automatic,
|
||||
relayURLs: ["https://relay.example"]
|
||||
))
|
||||
}
|
||||
|
||||
func testCustomModeTrimsValidHTTPSRelayURLs() throws {
|
||||
let result = try RelayConfigurationValidator.validate(
|
||||
mode: .strictCustom,
|
||||
relayURLs: [" https://relay.example/ ", "https://backup.example:443"]
|
||||
)
|
||||
XCTAssertEqual(result, RelayConfiguration(
|
||||
mode: .strictCustom,
|
||||
relayURLs: ["https://relay.example", "https://backup.example"]
|
||||
))
|
||||
}
|
||||
|
||||
func testCustomModeIgnoresEmptyURLRows() throws {
|
||||
let result = try RelayConfigurationValidator.validate(
|
||||
mode: .strictCustom,
|
||||
relayURLs: ["", " ", "https://relay.example"]
|
||||
)
|
||||
XCTAssertEqual(result.relayURLs, ["https://relay.example"])
|
||||
}
|
||||
|
||||
func testCustomModeRequiresAtLeastOneRelay() {
|
||||
XCTAssertThrowsError(try RelayConfigurationValidator.validate(mode: .strictCustom, relayURLs: [])) { error in
|
||||
XCTAssertEqual(error as? RelayConfigurationValidationError, .missingURL)
|
||||
}
|
||||
}
|
||||
|
||||
func testCustomModeRequiresHTTPS() {
|
||||
XCTAssertThrowsError(try RelayConfigurationValidator.validate(
|
||||
mode: .strictCustom,
|
||||
relayURLs: ["http://relay.example"]
|
||||
)) { error in
|
||||
XCTAssertEqual(error as? RelayConfigurationValidationError, .httpsRequired(index: 0))
|
||||
}
|
||||
}
|
||||
|
||||
func testCustomModeRejectsCredentialsQueryFragmentAndPath() {
|
||||
let invalidURLs = [
|
||||
"https://user:password@relay.example",
|
||||
"https://relay.example?token=secret",
|
||||
"https://relay.example#fragment",
|
||||
"https://relay.example/custom/path",
|
||||
"https://relay.example:0",
|
||||
"https://relay.example:99999",
|
||||
]
|
||||
for relayURL in invalidURLs {
|
||||
XCTAssertThrowsError(
|
||||
try RelayConfigurationValidator.validate(mode: .strictCustom, relayURLs: [relayURL]),
|
||||
"Expected \(relayURL) to be rejected"
|
||||
) { error in
|
||||
XCTAssertEqual(error as? RelayConfigurationValidationError, .invalidURL(index: 0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testCustomModeRejectsNormalizedDuplicate() {
|
||||
XCTAssertThrowsError(try RelayConfigurationValidator.validate(
|
||||
mode: .strictCustom,
|
||||
relayURLs: ["https://relay.example", "https://RELAY.example:443/"]
|
||||
)) { error in
|
||||
XCTAssertEqual(error as? RelayConfigurationValidationError, .duplicateURL(index: 1))
|
||||
}
|
||||
}
|
||||
|
||||
func testCustomModeRejectsMoreThanEightRelays() {
|
||||
let relayURLs = (0...RelayConfigurationValidator.maximumRelayCount).map {
|
||||
"https://relay-\($0).example"
|
||||
}
|
||||
XCTAssertThrowsError(try RelayConfigurationValidator.validate(mode: .strictCustom, relayURLs: relayURLs)) { error in
|
||||
XCTAssertEqual(error as? RelayConfigurationValidationError, .tooManyURLs)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,4 +58,25 @@ final class SendModelTests: XCTestCase {
|
||||
let response = core.responses.first { $0.id == "req-1" }
|
||||
XCTAssertEqual(response?.accepted, false)
|
||||
}
|
||||
|
||||
func testOnlyActiveShareExposesStoredInvitationTicket() {
|
||||
XCTAssertEqual(
|
||||
Fixtures.transfer(id: 1, direction: .send, status: .sharing).invitationPresentation,
|
||||
.ready("ticket")
|
||||
)
|
||||
XCTAssertEqual(
|
||||
Fixtures.transfer(id: 2, direction: .send, status: .importing).invitationPresentation,
|
||||
.preparing
|
||||
)
|
||||
for status in [TransferStatus.stopped, .failed, .cancelled, .done] {
|
||||
XCTAssertEqual(
|
||||
Fixtures.transfer(id: 3, direction: .send, status: status).invitationPresentation,
|
||||
.unavailable
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func testOversizedInvitationReportsQRCodeUnavailable() {
|
||||
XCTAssertNil(QRCode.generate(from: String(repeating: "x", count: 10_000)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,4 +42,107 @@ final class SettingsModelTests: XCTestCase {
|
||||
await waitUntil { core.deletedTransfers.count == 2 }
|
||||
XCTAssertEqual(Set(core.deletedTransfers), [2, 3])
|
||||
}
|
||||
|
||||
func testNetworkSettingsExposeCurrentEndpointId() {
|
||||
let core = FakeCoreGateway()
|
||||
let model = makeModel(core, preferences: Fixtures.preferences())
|
||||
|
||||
core.setState(CoreState(
|
||||
isInitialized: true,
|
||||
status: CoreStatus(endpointId: "endpoint-for-allowlist", activeTransfers: 0, activeShares: 0)
|
||||
))
|
||||
|
||||
XCTAssertEqual(model.state.endpointId, "endpoint-for-allowlist")
|
||||
}
|
||||
|
||||
func testApplyCustomRelayRestartsCoreThenPersistsConfiguration() async {
|
||||
let core = FakeCoreGateway()
|
||||
let preferences = Fixtures.preferences()
|
||||
let model = makeModel(core, preferences: preferences)
|
||||
model.setRelayMode(.strictCustom)
|
||||
model.setRelayURL(" https://relay.example/ ", at: 0)
|
||||
|
||||
model.applyRelayConfiguration()
|
||||
|
||||
await waitUntil { preferences.preferences.relayConfiguration.mode == .strictCustom }
|
||||
let expected = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"])
|
||||
XCTAssertEqual(preferences.preferences.relayConfiguration, expected)
|
||||
XCTAssertEqual(core.initializedNetworkConfigurations, [expected])
|
||||
XCTAssertFalse(model.state.relayConfigurationIsDirty)
|
||||
}
|
||||
|
||||
func testApplyingAutomaticRetainsLastCustomRelayURLs() async {
|
||||
let core = FakeCoreGateway()
|
||||
let preferences = Fixtures.preferences()
|
||||
let relayURLs = ["https://relay.example", "https://backup.example"]
|
||||
preferences.setRelayConfiguration(RelayConfiguration(mode: .strictCustom, relayURLs: relayURLs))
|
||||
let model = makeModel(core, preferences: preferences)
|
||||
|
||||
model.setRelayMode(.automatic)
|
||||
model.applyRelayConfiguration()
|
||||
|
||||
await waitUntil { preferences.preferences.relayConfiguration.mode == .automatic }
|
||||
XCTAssertEqual(preferences.preferences.relayConfiguration.relayURLs, relayURLs)
|
||||
XCTAssertEqual(core.initializedNetworkConfigurations, [
|
||||
RelayConfiguration(mode: .automatic, relayURLs: relayURLs),
|
||||
])
|
||||
model.setRelayMode(.strictCustom)
|
||||
XCTAssertEqual(model.state.relayURLs, relayURLs)
|
||||
}
|
||||
|
||||
func testApplyRelayIsBlockedWhileShareIsActive() async {
|
||||
let core = FakeCoreGateway()
|
||||
let preferences = Fixtures.preferences()
|
||||
let model = makeModel(core, preferences: preferences)
|
||||
core.setState(CoreState(
|
||||
isInitialized: true,
|
||||
status: CoreStatus(endpointId: "endpoint", activeTransfers: 0, activeShares: 1)
|
||||
))
|
||||
model.setRelayMode(.strictCustom)
|
||||
model.setRelayURL("https://relay.example", at: 0)
|
||||
|
||||
model.applyRelayConfiguration()
|
||||
await Task.yield()
|
||||
|
||||
XCTAssertTrue(core.initializedNetworkConfigurations.isEmpty)
|
||||
XCTAssertEqual(preferences.preferences.relayConfiguration, .automatic)
|
||||
XCTAssertEqual(model.state.relayApplyErrorKey, "relay_apply_active_transfers")
|
||||
}
|
||||
|
||||
func testRepositoryActiveWorkRejectionDoesNotAttemptRollback() async {
|
||||
let core = FakeCoreGateway()
|
||||
core.initializeResult = .failure(CoreNetworkLifecycleError.activeNetworkWork)
|
||||
let preferences = Fixtures.preferences()
|
||||
let model = makeModel(core, preferences: preferences)
|
||||
let attempted = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"])
|
||||
model.setRelayMode(.strictCustom)
|
||||
model.setRelayURL(attempted.relayURLs[0], at: 0)
|
||||
|
||||
model.applyRelayConfiguration()
|
||||
await waitUntil {
|
||||
core.initializedNetworkConfigurations.count == 1 && !model.state.isApplyingRelayConfiguration
|
||||
}
|
||||
|
||||
XCTAssertEqual(core.initializedNetworkConfigurations, [attempted])
|
||||
XCTAssertEqual(preferences.preferences.relayConfiguration, .automatic)
|
||||
XCTAssertTrue(model.state.hasActiveNetworkWork)
|
||||
XCTAssertEqual(model.state.relayApplyErrorKey, "relay_apply_active_transfers")
|
||||
}
|
||||
|
||||
func testFailedRelayApplyRollsBackWithoutPersisting() async {
|
||||
let core = FakeCoreGateway()
|
||||
core.initializeResults = [.failure(TestError.unimplemented), .success(())]
|
||||
let preferences = Fixtures.preferences()
|
||||
let model = makeModel(core, preferences: preferences)
|
||||
let attempted = RelayConfiguration(mode: .strictCustom, relayURLs: ["https://relay.example"])
|
||||
model.setRelayMode(.strictCustom)
|
||||
model.setRelayURL(attempted.relayURLs[0], at: 0)
|
||||
|
||||
model.applyRelayConfiguration()
|
||||
await waitUntil { core.initializedNetworkConfigurations.count == 2 }
|
||||
|
||||
XCTAssertEqual(core.initializedNetworkConfigurations, [attempted, .automatic])
|
||||
XCTAssertEqual(preferences.preferences.relayConfiguration, .automatic)
|
||||
XCTAssertEqual(model.state.relayApplyErrorKey, "relay_apply_failed")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,101 @@ enum FolderAccessStatus {
|
||||
case unavailable
|
||||
}
|
||||
|
||||
enum RelayPreferenceMode: String, Codable, CaseIterable, Sendable {
|
||||
case automatic
|
||||
case strictCustom = "custom"
|
||||
case customWithDirectFallback = "custom-with-direct-fallback"
|
||||
case localOnly = "local-only"
|
||||
|
||||
var usesCustomRelayURLs: Bool {
|
||||
self == .strictCustom || self == .customWithDirectFallback
|
||||
}
|
||||
}
|
||||
|
||||
struct RelayConfiguration: Equatable, Codable, Sendable {
|
||||
var mode: RelayPreferenceMode
|
||||
var relayURLs: [String]
|
||||
|
||||
static let automatic = RelayConfiguration(mode: .automatic, relayURLs: [])
|
||||
}
|
||||
|
||||
enum RelayConfigurationValidationError: Error, Equatable, Sendable {
|
||||
case missingURL
|
||||
case tooManyURLs
|
||||
case httpsRequired(index: Int)
|
||||
case invalidURL(index: Int)
|
||||
case duplicateURL(index: Int)
|
||||
|
||||
var urlIndex: Int? {
|
||||
switch self {
|
||||
case .httpsRequired(let index), .invalidURL(let index), .duplicateURL(let index): return index
|
||||
case .missingURL, .tooManyURLs: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum RelayConfigurationValidator {
|
||||
static let maximumRelayCount = 8
|
||||
static let maximumRelayURLBytes = 2_048
|
||||
|
||||
static func validate(
|
||||
mode: RelayPreferenceMode,
|
||||
relayURLs: [String],
|
||||
retainedRelayURLs: [String] = []
|
||||
) throws -> RelayConfiguration {
|
||||
guard mode.usesCustomRelayURLs else {
|
||||
return RelayConfiguration(mode: mode, relayURLs: retainedRelayURLs)
|
||||
}
|
||||
|
||||
let relayEntries = relayURLs.enumerated().compactMap { index, value -> (Int, String)? in
|
||||
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : (index, trimmed)
|
||||
}
|
||||
guard !relayEntries.isEmpty else {
|
||||
throw RelayConfigurationValidationError.missingURL
|
||||
}
|
||||
guard relayEntries.count <= maximumRelayCount else {
|
||||
throw RelayConfigurationValidationError.tooManyURLs
|
||||
}
|
||||
|
||||
var seen = Set<String>()
|
||||
var normalizedURLs: [String] = []
|
||||
for (index, relayURL) in relayEntries {
|
||||
guard relayURL.lengthOfBytes(using: .utf8) <= maximumRelayURLBytes,
|
||||
relayURL.rangeOfCharacter(from: .whitespacesAndNewlines.union(.controlCharacters)) == nil,
|
||||
var components = URLComponents(string: relayURL) else {
|
||||
throw RelayConfigurationValidationError.invalidURL(index: index)
|
||||
}
|
||||
guard components.scheme?.lowercased() == "https" else {
|
||||
throw RelayConfigurationValidationError.httpsRequired(index: index)
|
||||
}
|
||||
guard
|
||||
let host = components.host,
|
||||
!host.isEmpty,
|
||||
components.port.map({ (1...65_535).contains($0) }) ?? true,
|
||||
components.user == nil,
|
||||
components.password == nil,
|
||||
components.query == nil,
|
||||
components.fragment == nil,
|
||||
components.path.isEmpty || components.path == "/"
|
||||
else {
|
||||
throw RelayConfigurationValidationError.invalidURL(index: index)
|
||||
}
|
||||
|
||||
components.scheme = "https"
|
||||
components.host = host.lowercased()
|
||||
if components.port == 443 { components.port = nil }
|
||||
if components.path == "/" { components.path = "" }
|
||||
guard let canonicalURL = components.string, seen.insert(canonicalURL).inserted else {
|
||||
throw RelayConfigurationValidationError.duplicateURL(index: index)
|
||||
}
|
||||
normalizedURLs.append(canonicalURL)
|
||||
}
|
||||
|
||||
return RelayConfiguration(mode: mode, relayURLs: normalizedURLs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Persisted app preferences, ported from `preferences/AppPreferencesRepository.kt`.
|
||||
/// Backed by `UserDefaults` instead of DataStore; keys and semantics match.
|
||||
struct AppPreferences: Equatable {
|
||||
@@ -27,6 +122,7 @@ struct AppPreferences: Equatable {
|
||||
var themeMode: ThemeMode
|
||||
var diagnosticsEnabled: Bool
|
||||
var diagnosticsInstallId: String
|
||||
var relayConfiguration: RelayConfiguration
|
||||
}
|
||||
|
||||
struct AppPreferencesDefaults {
|
||||
@@ -51,6 +147,7 @@ final class AppPreferencesRepository: ObservableObject {
|
||||
static let themeMode = "theme_mode"
|
||||
static let diagnosticsEnabled = "diagnostics_enabled"
|
||||
static let diagnosticsInstallId = "diagnostics_install_id"
|
||||
static let relayConfiguration = "relay_configuration"
|
||||
}
|
||||
|
||||
init(defaults: UserDefaults = .standard, fallback: AppPreferencesDefaults) {
|
||||
@@ -70,10 +167,24 @@ final class AppPreferencesRepository: ObservableObject {
|
||||
receiveFolder: folder,
|
||||
themeMode: themeMode,
|
||||
diagnosticsEnabled: diagnostics,
|
||||
diagnosticsInstallId: installId
|
||||
diagnosticsInstallId: installId,
|
||||
relayConfiguration: resolveRelayConfiguration(defaults)
|
||||
)
|
||||
}
|
||||
|
||||
private static func resolveRelayConfiguration(_ defaults: UserDefaults) -> RelayConfiguration {
|
||||
guard defaults.object(forKey: Key.relayConfiguration) != nil else { return .automatic }
|
||||
guard
|
||||
let data = defaults.data(forKey: Key.relayConfiguration),
|
||||
let configuration = try? JSONDecoder().decode(RelayConfiguration.self, from: data)
|
||||
else {
|
||||
// A stored profile must never silently fall back to public relays. Strict
|
||||
// custom with no URLs makes startup fail closed until Settings repairs it.
|
||||
return RelayConfiguration(mode: .strictCustom, relayURLs: [])
|
||||
}
|
||||
return configuration
|
||||
}
|
||||
|
||||
private static func resolveReceiveFolder(_ defaults: UserDefaults, fallback: ReceiveFolder) -> ReceiveFolder {
|
||||
let kind = defaults.string(forKey: Key.receiveFolderKind)
|
||||
.flatMap(ReceiveFolderKind.init(rawValue:)) ?? fallback.kind
|
||||
@@ -113,6 +224,12 @@ final class AppPreferencesRepository: ObservableObject {
|
||||
reload()
|
||||
}
|
||||
|
||||
func setRelayConfiguration(_ configuration: RelayConfiguration) {
|
||||
guard let encoded = try? JSONEncoder().encode(configuration) else { return }
|
||||
defaults.set(encoded, forKey: Key.relayConfiguration)
|
||||
reload()
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
func ensureDiagnosticsInstallId() -> String {
|
||||
let existing = preferences.diagnosticsInstallId
|
||||
|
||||
@@ -24,7 +24,7 @@ protocol CoreGateway: AnyObject {
|
||||
/// Coalesced change hints emitted by the event sink.
|
||||
var signals: AnyPublisher<CoreSignal, Never> { get }
|
||||
|
||||
func initialize(appDataDir: String) async -> Result<Void, Error>
|
||||
func initialize(appDataDir: String, networkConfiguration: RelayConfiguration) async -> Result<Void, Error>
|
||||
func shutdown()
|
||||
func shareSources(
|
||||
_ sources: [ShareSource],
|
||||
|
||||
@@ -134,6 +134,7 @@ enum ReceiverDeliveryStatus: Equatable, Sendable {
|
||||
case refused
|
||||
case expired
|
||||
case completed
|
||||
case failed
|
||||
case unknown
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,65 @@ import Foundation
|
||||
import Combine
|
||||
@preconcurrency import VnidropCore
|
||||
|
||||
enum CoreNetworkLifecycleError: Error, Equatable, LocalizedError, Sendable {
|
||||
case transitionInProgress
|
||||
case activeNetworkWork
|
||||
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .transitionInProgress: return "A network restart is already in progress."
|
||||
case .activeNetworkWork: return "Stop active transfers and shares before restarting the network."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum CoreNetworkLifecycle {
|
||||
nonisolated static func requireIdle(activeTransfers: UInt64, activeShares: UInt64) throws {
|
||||
guard activeTransfers == 0, activeShares == 0 else {
|
||||
throw CoreNetworkLifecycleError.activeNetworkWork
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protocol CoreBindingFactory: Sendable {
|
||||
func initialize(
|
||||
appDataDir: String,
|
||||
eventSink: CoreEventSink,
|
||||
networkConfiguration: RelayConfiguration
|
||||
) throws -> VnidropCore
|
||||
}
|
||||
|
||||
struct NativeCoreBindingFactory: CoreBindingFactory {
|
||||
func initialize(
|
||||
appDataDir: String,
|
||||
eventSink: CoreEventSink,
|
||||
networkConfiguration: RelayConfiguration
|
||||
) throws -> VnidropCore {
|
||||
let nativeConfiguration: CoreNetworkConfig
|
||||
switch networkConfiguration.mode {
|
||||
case .automatic:
|
||||
nativeConfiguration = defaultCoreNetworkConfig()
|
||||
case .strictCustom:
|
||||
nativeConfiguration = CoreNetworkConfig(
|
||||
mode: .strictCustom,
|
||||
relayUrls: networkConfiguration.relayURLs
|
||||
)
|
||||
case .customWithDirectFallback:
|
||||
nativeConfiguration = CoreNetworkConfig(
|
||||
mode: .customWithDirectFallback,
|
||||
relayUrls: networkConfiguration.relayURLs
|
||||
)
|
||||
case .localOnly:
|
||||
nativeConfiguration = CoreNetworkConfig(mode: .localOnly, relayUrls: [])
|
||||
}
|
||||
return try VnidropCore.initializeWithNetworkConfig(
|
||||
appDataDir: appDataDir,
|
||||
eventSink: eventSink,
|
||||
networkConfig: nativeConfiguration
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift port of `core/CoreRepository.kt`. Owns the `VnidropCore` handle, maps the
|
||||
/// generated UniFFI records into app domain models, publishes an observable
|
||||
/// `CoreState`, and emits coalesced `CoreSignal`s from the event sink.
|
||||
@@ -17,28 +76,65 @@ final class CoreRepository: ObservableObject, CoreGateway {
|
||||
/// Coalesced change hints; subscribe to react to approval/history/transfer changes.
|
||||
var signals: AnyPublisher<CoreSignal, Never> { signalsSubject.eraseToAnyPublisher() }
|
||||
|
||||
// Set on the main actor (initialize/shutdown) but read from `queue` inside
|
||||
// `runCore`; the underlying core is internally synchronized, so this crossing
|
||||
// is safe. `nonisolated(unsafe)` documents that contract for Swift 6.
|
||||
// Initialization swaps happen on `queue`; shutdown and snapshot reads may also
|
||||
// access the handle from the main actor. The underlying core is internally
|
||||
// synchronized, and `nonisolated(unsafe)` documents that crossing for Swift 6.
|
||||
private nonisolated(unsafe) var core: VnidropCore?
|
||||
// Core calls run through `dispatcher` (see runCore/runInterrupt); the factory
|
||||
// and transition flag drive relay-aware (re)initialization.
|
||||
private let dispatcher = CoreDispatcher()
|
||||
private let coreFactory: any CoreBindingFactory
|
||||
private var isNetworkTransitionInProgress = false
|
||||
private lazy var sink = RepositoryEventSink { [weak self] event in
|
||||
Task { @MainActor in self?.handle(event: event) }
|
||||
}
|
||||
|
||||
private nonisolated static let maxEvents = 200
|
||||
|
||||
init(coreFactory: any CoreBindingFactory = NativeCoreBindingFactory()) {
|
||||
self.coreFactory = coreFactory
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
func initialize(appDataDir: String) async -> Result<Void, Error> {
|
||||
await runCore { [sink] in
|
||||
self.core?.shutdown()
|
||||
let created = try VnidropCore.initialize(appDataDir: appDataDir, eventSink: sink)
|
||||
return created
|
||||
}.map { created in
|
||||
func initialize(
|
||||
appDataDir: String,
|
||||
networkConfiguration: RelayConfiguration
|
||||
) async -> Result<Void, Error> {
|
||||
guard !isNetworkTransitionInProgress else {
|
||||
return .failure(CoreNetworkLifecycleError.transitionInProgress)
|
||||
}
|
||||
isNetworkTransitionInProgress = true
|
||||
defer { isNetworkTransitionInProgress = false }
|
||||
|
||||
let result = await runCore { [sink] in
|
||||
if let existing = self.core {
|
||||
let status = existing.status()
|
||||
try CoreNetworkLifecycle.requireIdle(
|
||||
activeTransfers: status.activeTransfers,
|
||||
activeShares: status.activeShares
|
||||
)
|
||||
existing.shutdown()
|
||||
self.core = nil
|
||||
}
|
||||
let created = try self.coreFactory.initialize(
|
||||
appDataDir: appDataDir,
|
||||
eventSink: sink,
|
||||
networkConfiguration: networkConfiguration
|
||||
)
|
||||
self.core = created
|
||||
return created
|
||||
}
|
||||
switch result {
|
||||
case .success:
|
||||
self.refreshSnapshot()
|
||||
self.state.isInitialized = true
|
||||
return .success(())
|
||||
case .failure(let error):
|
||||
if error as? CoreNetworkLifecycleError != .activeNetworkWork {
|
||||
self.state = CoreState()
|
||||
}
|
||||
return .failure(error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,6 +152,9 @@ final class CoreRepository: ObservableObject, CoreGateway {
|
||||
senderName: String,
|
||||
accessPolicy: ShareAccessPolicy
|
||||
) async -> Result<Share, Error> {
|
||||
guard !isNetworkTransitionInProgress else {
|
||||
return .failure(CoreNetworkLifecycleError.transitionInProgress)
|
||||
}
|
||||
guard !sources.isEmpty else {
|
||||
return .failure(InvitationError.message("Select at least one file to share"))
|
||||
}
|
||||
@@ -89,7 +188,10 @@ final class CoreRepository: ObservableObject, CoreGateway {
|
||||
}
|
||||
|
||||
func receive(ticket: String, outputDir: String, receiverName: String) async -> Result<Void, Error> {
|
||||
await runCore {
|
||||
guard !isNetworkTransitionInProgress else {
|
||||
return .failure(CoreNetworkLifecycleError.transitionInProgress)
|
||||
}
|
||||
return await runCore {
|
||||
try self.requireCore().receive(
|
||||
ticket: ticket,
|
||||
outputDir: outputDir,
|
||||
@@ -105,7 +207,10 @@ final class CoreRepository: ObservableObject, CoreGateway {
|
||||
outputDirectoryUrl: String,
|
||||
receiverName: String
|
||||
) async -> Result<Void, Error> {
|
||||
await runCore {
|
||||
guard !isNetworkTransitionInProgress else {
|
||||
return .failure(CoreNetworkLifecycleError.transitionInProgress)
|
||||
}
|
||||
return await runCore {
|
||||
try withSecurityScopedAccess(pathOrUrl: outputDirectoryUrl) {
|
||||
try self.requireCore().receive(
|
||||
ticket: ticket,
|
||||
@@ -409,6 +514,7 @@ private extension ReceiverRequest {
|
||||
case "refused": return .refused
|
||||
case "expired": return .expired
|
||||
case "completed": return .completed
|
||||
case "failed": return .failed
|
||||
default: return .unknown
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,10 @@ final class AppModel: ObservableObject {
|
||||
AppLogger.info("lifecycle", "app started", ["platform": environment.name])
|
||||
|
||||
Task {
|
||||
let result = await repository.initialize(appDataDir: environment.defaultCoreDataDir)
|
||||
let result = await repository.initialize(
|
||||
appDataDir: environment.defaultCoreDataDir,
|
||||
networkConfiguration: preferences.preferences.relayConfiguration
|
||||
)
|
||||
if case .failure(let error) = result { messages.error(error) }
|
||||
}
|
||||
|
||||
|
||||
@@ -236,6 +236,7 @@ private struct ReceiverRow: View {
|
||||
let name = receiver.receiverName ?? receiver.receiverDeviceName ?? String(localized: L10n.Transfer.nearbyDevice)
|
||||
let showLive = sendProgress != nil && receiver.status != .completed
|
||||
&& receiver.status != .refused && receiver.status != .expired
|
||||
&& receiver.status != .failed
|
||||
HStack(alignment: .top, spacing: 12) {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text(name).font(VniType.bodyLarge).lineLimit(1)
|
||||
@@ -277,24 +278,39 @@ struct TransferSharePanel: View {
|
||||
|
||||
var body: some View {
|
||||
PanelContainer(title: String(localized: L10n.Transfer.shareTitle)) {
|
||||
if let ticket = transfer.ticket {
|
||||
qrCard(ticket: ticket)
|
||||
Text(String(localized: L10n.Transfer.scanQr))
|
||||
.font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter)
|
||||
.frame(maxWidth: .infinity)
|
||||
switch transfer.invitationPresentation {
|
||||
case .ready(let ticket):
|
||||
let qrImage = QRCode.generate(from: ticket)
|
||||
qrCard(image: qrImage)
|
||||
if qrImage != nil {
|
||||
Text(String(localized: L10n.Transfer.scanQr))
|
||||
.font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter)
|
||||
.frame(maxWidth: .infinity)
|
||||
}
|
||||
ShareActionsView(model: model, transfer: transfer, ticket: ticket)
|
||||
} else {
|
||||
case .preparing:
|
||||
Text(String(localized: L10n.Transfer.eventPreparing)).foregroundStyle(colors.foregroundLighter)
|
||||
case .unavailable:
|
||||
Text(String(localized: transfer.status == .failed ? L10n.Transfer.eventFailed : L10n.Transfer.eventStopped))
|
||||
.foregroundStyle(colors.foregroundLighter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func qrCard(ticket: String) -> some View {
|
||||
private func qrCard(image: Image?) -> some View {
|
||||
ZStack {
|
||||
if let qr = QRCode.generate(from: ticket) {
|
||||
qr.interpolation(.none).resizable().scaledToFit().padding(14)
|
||||
if let image {
|
||||
image.interpolation(.none).resizable().scaledToFit().padding(14)
|
||||
} else {
|
||||
ProgressView()
|
||||
VStack(spacing: 10) {
|
||||
Image(systemName: "qrcode")
|
||||
.font(.system(size: 36, weight: .medium))
|
||||
Text(LocalizedStringKey("transfer_qr_unavailable"))
|
||||
.font(VniType.bodySmall)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
.foregroundStyle(.black.opacity(0.72))
|
||||
.padding(22)
|
||||
}
|
||||
}
|
||||
.frame(width: 268, height: 268)
|
||||
@@ -303,6 +319,26 @@ struct TransferSharePanel: View {
|
||||
}
|
||||
}
|
||||
|
||||
enum TransferInvitationPresentation: Equatable {
|
||||
case preparing
|
||||
case ready(String)
|
||||
case unavailable
|
||||
}
|
||||
|
||||
extension Transfer {
|
||||
var invitationPresentation: TransferInvitationPresentation {
|
||||
switch status {
|
||||
case .importing:
|
||||
return .preparing
|
||||
case .sharing:
|
||||
guard let ticket, !ticket.isEmpty else { return .preparing }
|
||||
return .ready(ticket)
|
||||
case .receiving, .done, .failed, .cancelled, .stopped:
|
||||
return .unavailable
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - QR generation (CoreImage)
|
||||
|
||||
enum QRCode {
|
||||
@@ -359,6 +395,7 @@ extension ReceiverDeliveryStatus {
|
||||
case .refused: return L10n.Transfer.receiverRefused
|
||||
case .expired: return L10n.Transfer.receiverExpired
|
||||
case .completed: return L10n.Transfer.receiverCompleted
|
||||
case .failed: return L10n.Transfer.receiverFailed
|
||||
case .unknown: return L10n.Transfer.receiverUnknown
|
||||
}
|
||||
}
|
||||
@@ -366,7 +403,7 @@ extension ReceiverDeliveryStatus {
|
||||
func statusColor(_ colors: VniDropColors) -> Color {
|
||||
switch self {
|
||||
case .completed: return colors.brandDefault
|
||||
case .refused, .expired: return colors.destructiveDefault
|
||||
case .refused, .expired, .failed: return colors.destructiveDefault
|
||||
default: return colors.foregroundLighter
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ enum SettingsSection: Hashable {
|
||||
case preferences
|
||||
case appearance
|
||||
case notifications
|
||||
case network
|
||||
case storage
|
||||
case about
|
||||
case bugReport
|
||||
@@ -17,6 +18,7 @@ enum SettingsSection: Hashable {
|
||||
case .preferences: return L10n.Preferences.title
|
||||
case .appearance: return L10n.Appearance.title
|
||||
case .notifications: return L10n.Notifications.title
|
||||
case .network: return L10n.Settings.networkTitle
|
||||
case .storage: return L10n.Storage.title
|
||||
case .about: return L10n.About.title
|
||||
case .bugReport: return L10n.About.bugReport
|
||||
@@ -43,6 +45,14 @@ struct SettingsState: Equatable {
|
||||
var themeMode: ThemeMode = .system
|
||||
var notificationPermission: NotificationPermission = .notDetermined
|
||||
var diagnosticsEnabled = false
|
||||
var relayMode: RelayPreferenceMode = .automatic
|
||||
var relayURLs: [String] = []
|
||||
var relayValidationError: RelayConfigurationValidationError?
|
||||
var relayConfigurationIsDirty = false
|
||||
var isApplyingRelayConfiguration = false
|
||||
var hasActiveNetworkWork = false
|
||||
var endpointId: String?
|
||||
var relayApplyErrorKey: String?
|
||||
var deviceInfo: DeviceInfo?
|
||||
var appVersion = ""
|
||||
var isLoadingDeviceInfo = false
|
||||
@@ -67,6 +77,13 @@ struct SettingsState: Equatable {
|
||||
&& lhs.themeMode == rhs.themeMode
|
||||
&& lhs.notificationPermission == rhs.notificationPermission
|
||||
&& lhs.diagnosticsEnabled == rhs.diagnosticsEnabled && lhs.appVersion == rhs.appVersion
|
||||
&& lhs.relayMode == rhs.relayMode && lhs.relayURLs == rhs.relayURLs
|
||||
&& lhs.relayValidationError == rhs.relayValidationError
|
||||
&& lhs.relayConfigurationIsDirty == rhs.relayConfigurationIsDirty
|
||||
&& lhs.isApplyingRelayConfiguration == rhs.isApplyingRelayConfiguration
|
||||
&& lhs.hasActiveNetworkWork == rhs.hasActiveNetworkWork
|
||||
&& lhs.endpointId == rhs.endpointId
|
||||
&& lhs.relayApplyErrorKey == rhs.relayApplyErrorKey
|
||||
&& lhs.isLoadingDeviceInfo == rhs.isLoadingDeviceInfo
|
||||
&& lhs.bugWhatHappened == rhs.bugWhatHappened && lhs.bugExpected == rhs.bugExpected
|
||||
&& lhs.bugSteps == rhs.bugSteps && lhs.bugContact == rhs.bugContact
|
||||
@@ -98,6 +115,7 @@ final class SettingsModel: ObservableObject {
|
||||
|
||||
private var usernamePersistTask: Task<Void, Never>?
|
||||
private var hasLocalUsernameDraft = false
|
||||
private var hasRelayConfigurationDraft = false
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
|
||||
init(
|
||||
@@ -134,10 +152,29 @@ final class SettingsModel: ObservableObject {
|
||||
self.state.receiveFolder = folder
|
||||
self.state.themeMode = prefs.themeMode
|
||||
self.state.diagnosticsEnabled = prefs.diagnosticsEnabled
|
||||
if !self.hasRelayConfigurationDraft {
|
||||
self.state.relayMode = prefs.relayConfiguration.mode
|
||||
self.state.relayURLs = prefs.relayConfiguration.relayURLs
|
||||
self.state.relayConfigurationIsDirty = false
|
||||
}
|
||||
if folder != previousFolder { Task { await self.validateFolder(folder) } }
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
repository.statePublisher
|
||||
.sink { [weak self] coreState in
|
||||
guard let self else { return }
|
||||
let hasActiveWork = (coreState.status?.activeTransfers ?? 0) > 0
|
||||
|| (coreState.status?.activeShares ?? 0) > 0
|
||||
|| coreState.transfers.contains(where: { $0.status.isActiveTransfer })
|
||||
self.state.hasActiveNetworkWork = hasActiveWork
|
||||
self.state.endpointId = coreState.status?.endpointId
|
||||
if !hasActiveWork && self.state.relayApplyErrorKey == "relay_apply_active_transfers" {
|
||||
self.state.relayApplyErrorKey = nil
|
||||
}
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
refreshNotificationPermission()
|
||||
loadDeviceInfo()
|
||||
}
|
||||
@@ -204,6 +241,119 @@ final class SettingsModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Network
|
||||
|
||||
func setRelayMode(_ mode: RelayPreferenceMode) {
|
||||
hasRelayConfigurationDraft = true
|
||||
state.relayMode = mode
|
||||
if mode.usesCustomRelayURLs && state.relayURLs.isEmpty { state.relayURLs = [""] }
|
||||
updateRelayConfigurationDraft()
|
||||
}
|
||||
|
||||
func setRelayURL(_ value: String, at index: Int) {
|
||||
guard state.relayURLs.indices.contains(index) else { return }
|
||||
hasRelayConfigurationDraft = true
|
||||
state.relayURLs[index] = value
|
||||
updateRelayConfigurationDraft()
|
||||
}
|
||||
|
||||
func addRelayURL() {
|
||||
guard state.relayURLs.count < RelayConfigurationValidator.maximumRelayCount else { return }
|
||||
hasRelayConfigurationDraft = true
|
||||
state.relayURLs.append("")
|
||||
updateRelayConfigurationDraft()
|
||||
}
|
||||
|
||||
func removeRelayURL(at index: Int) {
|
||||
guard state.relayURLs.indices.contains(index) else { return }
|
||||
hasRelayConfigurationDraft = true
|
||||
state.relayURLs.remove(at: index)
|
||||
if state.relayURLs.isEmpty { state.relayURLs = [""] }
|
||||
updateRelayConfigurationDraft()
|
||||
}
|
||||
|
||||
func applyRelayConfiguration() {
|
||||
guard !state.isApplyingRelayConfiguration, state.relayConfigurationIsDirty else { return }
|
||||
|
||||
let configuration: RelayConfiguration
|
||||
do {
|
||||
configuration = try RelayConfigurationValidator.validate(
|
||||
mode: state.relayMode,
|
||||
relayURLs: state.relayURLs,
|
||||
retainedRelayURLs: preferences.preferences.relayConfiguration.relayURLs
|
||||
)
|
||||
} catch let error as RelayConfigurationValidationError {
|
||||
state.relayValidationError = error
|
||||
state.relayApplyErrorKey = nil
|
||||
return
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
|
||||
let coreState = repository.state
|
||||
let hasActiveWork = (coreState.status?.activeTransfers ?? 0) > 0
|
||||
|| (coreState.status?.activeShares ?? 0) > 0
|
||||
|| coreState.transfers.contains(where: { $0.status.isActiveTransfer })
|
||||
guard !hasActiveWork else {
|
||||
state.hasActiveNetworkWork = true
|
||||
state.relayApplyErrorKey = "relay_apply_active_transfers"
|
||||
messages.show(UiMessage(text: .resource("relay_apply_active_transfers"), tone: .warning))
|
||||
return
|
||||
}
|
||||
|
||||
let previousConfiguration = preferences.preferences.relayConfiguration
|
||||
state.relayValidationError = nil
|
||||
state.relayApplyErrorKey = nil
|
||||
state.isApplyingRelayConfiguration = true
|
||||
Task {
|
||||
let applyResult = await repository.initialize(
|
||||
appDataDir: environment.defaultCoreDataDir,
|
||||
networkConfiguration: configuration
|
||||
)
|
||||
switch applyResult {
|
||||
case .success:
|
||||
hasRelayConfigurationDraft = false
|
||||
preferences.setRelayConfiguration(configuration)
|
||||
state.isApplyingRelayConfiguration = false
|
||||
state.relayConfigurationIsDirty = false
|
||||
messages.show(UiMessage(text: .resource("relay_settings_applied"), tone: .success))
|
||||
case .failure(let error):
|
||||
if let lifecycleError = error as? CoreNetworkLifecycleError {
|
||||
state.isApplyingRelayConfiguration = false
|
||||
switch lifecycleError {
|
||||
case .activeNetworkWork:
|
||||
state.hasActiveNetworkWork = true
|
||||
state.relayApplyErrorKey = "relay_apply_active_transfers"
|
||||
case .transitionInProgress:
|
||||
state.relayApplyErrorKey = "relay_apply_failed"
|
||||
}
|
||||
return
|
||||
}
|
||||
let rollbackResult = await repository.initialize(
|
||||
appDataDir: environment.defaultCoreDataDir,
|
||||
networkConfiguration: previousConfiguration
|
||||
)
|
||||
state.isApplyingRelayConfiguration = false
|
||||
if case .success = rollbackResult {
|
||||
state.relayApplyErrorKey = "relay_apply_failed"
|
||||
messages.show(UiMessage(text: .resource("relay_apply_failed"), tone: .error))
|
||||
} else {
|
||||
state.relayApplyErrorKey = "relay_restore_failed"
|
||||
messages.show(UiMessage(text: .resource("relay_restore_failed"), tone: .error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func updateRelayConfigurationDraft() {
|
||||
state.relayValidationError = nil
|
||||
state.relayApplyErrorKey = nil
|
||||
let saved = preferences.preferences.relayConfiguration
|
||||
let draftURLs = state.relayMode.usesCustomRelayURLs ? state.relayURLs : saved.relayURLs
|
||||
state.relayConfigurationIsDirty = saved != RelayConfiguration(mode: state.relayMode, relayURLs: draftURLs)
|
||||
hasRelayConfigurationDraft = state.relayConfigurationIsDirty
|
||||
}
|
||||
|
||||
func setBugWhatHappened(_ value: String) { state.bugWhatHappened = value }
|
||||
func setBugExpected(_ value: String) { state.bugExpected = value }
|
||||
func setBugSteps(_ value: String) { state.bugSteps = value }
|
||||
|
||||
@@ -39,6 +39,17 @@ struct SettingsScreen: View {
|
||||
NavigationLink(value: SettingsSection.storage) {
|
||||
SettingsRow(icon: .internaldrive, title: String(localized: L10n.Storage.title), value: nil)
|
||||
}
|
||||
}
|
||||
Section(String(localized: L10n.Settings.advancedTitle)) {
|
||||
NavigationLink(value: SettingsSection.network) {
|
||||
SettingsRow(
|
||||
icon: .network,
|
||||
title: String(localized: L10n.Settings.networkTitle),
|
||||
value: relayModeLabel(model.state.relayMode)
|
||||
)
|
||||
}
|
||||
}
|
||||
Section {
|
||||
NavigationLink(value: SettingsSection.about) {
|
||||
SettingsRow(icon: .infoCircle, title: String(localized: L10n.About.title), value: nil)
|
||||
}
|
||||
@@ -100,6 +111,8 @@ private struct SettingsSectionContent: View {
|
||||
AppearanceSettings(model: model)
|
||||
case .notifications:
|
||||
NotificationSettings(model: model)
|
||||
case .network:
|
||||
NetworkSettings(model: model)
|
||||
case .storage:
|
||||
StorageSettings(model: model)
|
||||
case .about:
|
||||
@@ -110,6 +123,24 @@ private struct SettingsSectionContent: View {
|
||||
}
|
||||
}
|
||||
|
||||
func relayModeLabel(_ mode: RelayPreferenceMode) -> String {
|
||||
switch mode {
|
||||
case .automatic: return String(localized: "relay_mode_automatic")
|
||||
case .strictCustom: return String(localized: "relay_mode_custom")
|
||||
case .customWithDirectFallback: return String(localized: "relay_mode_custom_direct_fallback")
|
||||
case .localOnly: return String(localized: "relay_mode_local_only")
|
||||
}
|
||||
}
|
||||
|
||||
func relayModeDescriptionKey(_ mode: RelayPreferenceMode) -> String {
|
||||
switch mode {
|
||||
case .automatic: return "relay_mode_automatic_description"
|
||||
case .strictCustom: return "relay_mode_custom_description"
|
||||
case .customWithDirectFallback: return "relay_mode_custom_direct_fallback_description"
|
||||
case .localOnly: return "relay_mode_local_only_description"
|
||||
}
|
||||
}
|
||||
|
||||
struct SettingsRow: View {
|
||||
let icon: SFSymbol
|
||||
let title: String
|
||||
|
||||
@@ -74,6 +74,175 @@ struct NotificationSettings: View {
|
||||
}
|
||||
}
|
||||
|
||||
struct NetworkSettings: View {
|
||||
@ObservedObject var model: SettingsModel
|
||||
|
||||
var body: some View {
|
||||
Section {
|
||||
Picker(
|
||||
String(localized: "settings_network_title"),
|
||||
selection: Binding(get: { model.state.relayMode }, set: { model.setRelayMode($0) })
|
||||
) {
|
||||
ForEach(RelayPreferenceMode.allCases, id: \.self) { mode in
|
||||
Text(relayModeLabel(mode)).tag(mode)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.inline)
|
||||
.disabled(model.state.isApplyingRelayConfiguration)
|
||||
} footer: {
|
||||
Text(LocalizedStringKey(relayModeDescriptionKey(model.state.relayMode)))
|
||||
}
|
||||
|
||||
Section {
|
||||
Label {
|
||||
Text(LocalizedStringKey("relay_privacy_description"))
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
} icon: {
|
||||
Image(systemName: "lock.shield")
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
if let endpointId = model.state.endpointId, !endpointId.isEmpty {
|
||||
Section {
|
||||
Text(String(format: String(localized: "approval_endpoint_id"), endpointId))
|
||||
.font(.footnote.monospaced())
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
}
|
||||
|
||||
if model.state.relayMode.usesCustomRelayURLs {
|
||||
Section {
|
||||
if model.state.relayMode == .strictCustom {
|
||||
Label {
|
||||
Text(LocalizedStringKey("relay_strict_warning"))
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
} icon: {
|
||||
Image(systemName: "exclamationmark.shield.fill")
|
||||
}
|
||||
.foregroundStyle(.orange)
|
||||
}
|
||||
|
||||
ForEach(Array(model.state.relayURLs.indices), id: \.self) { index in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
TextField(
|
||||
"https://relay.example.com",
|
||||
text: Binding(
|
||||
get: {
|
||||
model.state.relayURLs.indices.contains(index)
|
||||
? model.state.relayURLs[index]
|
||||
: ""
|
||||
},
|
||||
set: { model.setRelayURL($0, at: index) }
|
||||
)
|
||||
)
|
||||
#if os(iOS)
|
||||
.keyboardType(.URL)
|
||||
.textInputAutocapitalization(.never)
|
||||
#endif
|
||||
.autocorrectionDisabled()
|
||||
.disabled(model.state.isApplyingRelayConfiguration)
|
||||
|
||||
Button(role: .destructive) {
|
||||
model.removeRelayURL(at: index)
|
||||
} label: {
|
||||
Image(systemName: "minus.circle.fill")
|
||||
}
|
||||
.buttonStyle(.borderless)
|
||||
.accessibilityLabel(Text(LocalizedStringKey("relay_remove_url")))
|
||||
.disabled(model.state.isApplyingRelayConfiguration)
|
||||
}
|
||||
|
||||
if let error = model.state.relayValidationError, error.urlIndex == index {
|
||||
Text(relayValidationMessage(error))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Button(action: model.addRelayURL) {
|
||||
Label(String(localized: "relay_add_url"), systemImage: "plus.circle")
|
||||
}
|
||||
.disabled(
|
||||
model.state.relayURLs.count >= RelayConfigurationValidator.maximumRelayCount
|
||||
|| model.state.isApplyingRelayConfiguration
|
||||
)
|
||||
} header: {
|
||||
Text(LocalizedStringKey("relay_custom_urls_label"))
|
||||
} footer: {
|
||||
Text(LocalizedStringKey("relay_custom_urls_help"))
|
||||
}
|
||||
}
|
||||
|
||||
if let error = model.state.relayValidationError, error.urlIndex == nil {
|
||||
Section {
|
||||
Label {
|
||||
Text(relayValidationMessage(error))
|
||||
} icon: {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
}
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
}
|
||||
|
||||
if model.state.hasActiveNetworkWork || model.state.relayApplyErrorKey != nil {
|
||||
Section {
|
||||
Label {
|
||||
Text(LocalizedStringKey(
|
||||
model.state.hasActiveNetworkWork
|
||||
? "relay_apply_active_transfers"
|
||||
: model.state.relayApplyErrorKey ?? "relay_apply_failed"
|
||||
))
|
||||
} icon: {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
}
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
}
|
||||
|
||||
Section {
|
||||
Button(action: model.applyRelayConfiguration) {
|
||||
HStack {
|
||||
Text(LocalizedStringKey(
|
||||
model.state.isApplyingRelayConfiguration ? "relay_applying" : "relay_apply"
|
||||
))
|
||||
if model.state.isApplyingRelayConfiguration {
|
||||
Spacer()
|
||||
ProgressView()
|
||||
}
|
||||
}
|
||||
}
|
||||
.disabled(
|
||||
!model.state.relayConfigurationIsDirty
|
||||
|| model.state.isApplyingRelayConfiguration
|
||||
|| model.state.hasActiveNetworkWork
|
||||
)
|
||||
} footer: {
|
||||
Text(LocalizedStringKey("relay_apply_restart_description"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func relayValidationMessage(_ error: RelayConfigurationValidationError) -> String {
|
||||
switch error {
|
||||
case .missingURL:
|
||||
return String(localized: "relay_validation_missing_url")
|
||||
case .tooManyURLs:
|
||||
return String(
|
||||
format: String(localized: "relay_validation_too_many_urls"),
|
||||
RelayConfigurationValidator.maximumRelayCount
|
||||
)
|
||||
case .httpsRequired(let index):
|
||||
return String(format: String(localized: "relay_validation_https_required"), index + 1)
|
||||
case .invalidURL(let index):
|
||||
return String(format: String(localized: "relay_validation_invalid_url"), index + 1)
|
||||
case .duplicateURL(let index):
|
||||
return String(format: String(localized: "relay_validation_duplicate_url"), index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct StorageSettings: View {
|
||||
@ObservedObject var model: SettingsModel
|
||||
@State private var showDeleteConfirmation = false
|
||||
|
||||
Reference in New Issue
Block a user