Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion apple/Omnitun/App.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,15 @@ func editMenu() -> NSMenu {
edit.addItem(withTitle: String(localized: "Select All"), action: #selector(NSText.selectAll(_:)), keyEquivalent: "a")
let close = NSMenu(title: String(localized: "Window"))
close.addItem(withTitle: String(localized: "Close"), action: #selector(NSWindow.performClose(_:)), keyEquivalent: "w")
// Shown while a window makes the app a regular one (⌘-Tab).
let app = NSMenu(title: brand.product)
app.addItem(withTitle: String(localized: "Hide \(brand.product)"), action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h")
app.addItem(.separator())
app.addItem(withTitle: String(localized: "Quit \(brand.product)"), action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q")
let main = NSMenu()
for menu in [NSMenu(title: brand.product), edit, close] {
for menu in [app, edit, close] {
let item = NSMenuItem()
item.submenu = menu
main.addItem(item)
Expand Down
109 changes: 109 additions & 0 deletions apple/Omnitun/ManageView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,7 @@ struct ProfileEditor: View {
NetworkTab(form: $form, others: model.profiles.filter { $0.id != original }.map { ($0.id, $0.name) },
announced: original.flatMap(Settings.announced(for:)))
.tabItem { Text("Network") }
ScheduleTab(form: $form).tabItem { Text("Schedule") }
}
.padding(.horizontal)
footer
Expand Down Expand Up @@ -2147,3 +2148,111 @@ private struct NetworkTab: View {
}
}


/// Automatic disconnection: a switch for the whole, then each limit, the
/// first one reached disconnecting. Limits switched off are kept.
private struct ScheduleTab: View {
@Binding var form: ProfileForm

var body: some View {
Form {
Section {
Toggle("Disconnect automatically", isOn: $form.disconnectEnabled)
caption("Even with the app closed: the service disconnects. You are warned 5 minutes before and can postpone.")
}
Section("Limits") {
limit("After being connected for", text: $form.disconnectAfter, initial: "8:00") {
DurationField(text: $form.disconnectAfter)
}
caption("Reconnections after a drop do not start the time again. Postponing starts it again.")
limit("After no keyboard or mouse activity for", text: $form.disconnectIdle, initial: "1:00") {
DurationField(text: $form.disconnectIdle)
}
caption("Network traffic does not count: it never stops. Using the computer again keeps the VPN up.")
limit("At", text: $form.disconnectAt, initial: "19:00") {
DatePicker("At", selection: timeOfDay, displayedComponents: .hourAndMinute).labelsHidden()
}
caption("The first time after connecting. Postponing moves it an hour later.")
if form.disconnectEnabled && noLimit {
Label("Choose at least one limit.", systemImage: "exclamationmark.triangle")
.font(.caption).foregroundStyle(.orange)
}
}
.disabled(!form.disconnectEnabled)
}
.formStyle(.grouped)
}

private var noLimit: Bool {
form.disconnectAfter.isEmpty && form.disconnectIdle.isEmpty && form.disconnectAt.isEmpty
}

/// A limit's checkbox, and its value once checked; unchecked, the
/// limit is removed.
private func limit(_ title: LocalizedStringKey, text: Binding<String>, initial: String,
@ViewBuilder value: () -> some View) -> some View {
let on = Binding(get: { !text.wrappedValue.trimmingCharacters(in: .whitespaces).isEmpty },
set: { text.wrappedValue = $0 ? initial : "" })
return HStack {
Toggle(title, isOn: on).toggleStyle(.checkbox)
Spacer()
if on.wrappedValue { value() }
}
}

/// The time of day of `disconnectAt`, as today's date for the picker.
private var timeOfDay: Binding<Date> {
Binding(get: {
let (h, m) = HourMinute.parse(form.disconnectAt) ?? (19, 0)
return Calendar.current.date(bySettingHour: h, minute: m, second: 0, of: Date()) ?? Date()
}, set: { date in
let c = Calendar.current.dateComponents([.hour, .minute], from: date)
form.disconnectAt = HourMinute.text(c.hour ?? 0, c.minute ?? 0)
})
}

private func caption(_ text: LocalizedStringKey) -> some View {
Text(text).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
}
}

/// `H:MM` text, as the profile writes it.
private enum HourMinute {
static func parse(_ text: String) -> (Int, Int)? {
let parts = text.trimmingCharacters(in: .whitespaces).split(separator: ":")
guard parts.count == 2, let h = Int(parts[0]), let m = Int(parts[1]) else { return nil }
return (h, m)
}

static func text(_ hours: Int, _ minutes: Int) -> String {
String(format: "%d:%02d", hours, minutes)
}
}

/// A duration in hours and minutes, never empty.
private struct DurationField: View {
@Binding var text: String

private var parts: (Int, Int) { HourMinute.parse(text) ?? (0, 0) }

private var hours: Binding<Int> {
Binding(get: { parts.0 }, set: { text = HourMinute.text(min(max($0, 0), 999), parts.1) })
}

private var minutes: Binding<Int> {
Binding(get: { parts.1 }, set: { text = HourMinute.text(parts.0, min(max($0, 0), 59)) })
}

var body: some View {
HStack(spacing: 4) {
TextField("Hours", value: hours, format: .number).labelsHidden().frame(width: 44)
.multilineTextAlignment(.trailing)
Stepper("Hours", value: hours, in: 0...999).labelsHidden()
Text("h")
TextField("Minutes", value: minutes, format: .number).labelsHidden().frame(width: 36)
.multilineTextAlignment(.trailing)
Stepper("Minutes", value: minutes, in: 0...59, step: 5).labelsHidden()
Text("min")
}
}
}
57 changes: 56 additions & 1 deletion apple/Omnitun/Model.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ final class AppModel: ObservableObject {
func profile(_ id: String) -> ProfileSummary? { profiles.first { $0.id == id } }

func start() {
Notifier.shared.onPostpone = { [weak self] id in self?.postpone(id) }
Notifier.shared.setUp()
reloadProfiles()
resuming = Self.toResume(Settings.upSessions, version: Self.version, now: Date())
Expand Down Expand Up @@ -171,6 +172,14 @@ final class AppModel: ObservableObject {

fileprivate func changed(_ change: StateChange) {
retries[change.id] = change.retry
if [.disconnected, .failed].contains(change.state) { Notifier.shared.removeExpiring(id: change.id) }
// Ended by the service, not by the user: its profile's limit.
if change.state == .disconnected, change.detail != nil {
let planned = sessions[change.id]?.autoDisconnect
Notifier.shared.post(title: String(localized: "\(displayName(change.id)) disconnected automatically"),
body: planned.map(Self.reason) ?? change.detail ?? "")
return
}
if change.state == .connecting || change.state == .connected { failures[change.id] = nil }
// An interactive connection reports its own outcome.
guard flows[change.id] == nil else { return }
Expand All @@ -191,6 +200,42 @@ final class AppModel: ObservableObject {
}
}

/// Warns that `id` disconnects soon, as its profile says.
fileprivate func expiring(_ id: String, _ planned: PlannedDisconnect) {
let time = Date(timeIntervalSince1970: TimeInterval(planned.at)).formatted(date: .omitted, time: .shortened)
let body = switch planned.criterion {
case .after: String(localized: "Connected for \(planned.limit): it disconnects at \(time).")
case .at: String(localized: "It disconnects at \(time), as planned.")
case .idle: String(localized: "No activity for a while: it disconnects at \(time) unless you use the computer.")
}
Notifier.shared.postExpiring(id: id, title: String(localized: "\(displayName(id)) disconnects soon"),
body: body, canPostpone: planned.criterion != .idle)
objectWillChange.send()
}

/// Why a session was disconnected automatically, for people.
nonisolated static func reason(_ planned: PlannedDisconnect) -> String {
switch planned.criterion {
case .after: String(localized: "Connected for \(planned.limit), as its settings say.")
case .idle: String(localized: "No activity for \(planned.limit), as its settings say.")
case .at: String(localized: "It is \(planned.limit), as its settings say.")
}
}

/// Puts off `id`'s automatic disconnection.
func postpone(_ id: String) {
Notifier.shared.removeExpiring(id: id)
Task {
do {
try await client.postpone(id: id)
} catch {
Notifier.shared.post(title: String(localized: "\(displayName(id)) disconnects as planned"),
body: describe(error))
}
pollSessions()
}
}

fileprivate func stopped(_ error: ClientError?) {
subscription = nil
sessions = [:]
Expand All @@ -209,7 +254,13 @@ final class AppModel: ObservableObject {

// MARK: Reconnecting after an update

private static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String
/// Version and build: a package of the same version built again (a
/// test build) is an update too.
private static let version: String? = {
let info = Bundle.main.infoDictionary
guard let short = info?["CFBundleShortVersionString"] as? String else { return nil }
return (info?["CFBundleVersion"] as? String).map { "\(short) (\($0))" } ?? short
}()

/// What to connect again at launch: the VPNs a previous version saw up
/// shortly before it stopped. A crash or a quit without an update
Expand Down Expand Up @@ -519,6 +570,10 @@ private final class Observer: SessionObserver, @unchecked Sendable {
DispatchQueue.main.async { MainActor.assumeIsolated { self.model?.holdRecord() } }
}

func expiring(id: String, planned: PlannedDisconnect) {
DispatchQueue.main.async { MainActor.assumeIsolated { self.model?.expiring(id, planned) } }
}

func stopped(error: ClientError?) {
DispatchQueue.main.async { MainActor.assumeIsolated { self.model?.stopped(error) } }
}
Expand Down
53 changes: 52 additions & 1 deletion apple/Omnitun/Notifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,29 @@ import UserNotifications
/// User notifications; silently off when the app runs outside its bundle
/// (`swift run`), where the notification center is not available.
@MainActor
final class Notifier {
final class Notifier: NSObject, UNUserNotificationCenterDelegate {
static let shared = Notifier()
private var center: UNUserNotificationCenter? {
Bundle.main.bundleIdentifier == nil ? nil : UNUserNotificationCenter.current()
}

/// A disconnection to come, with a button to put it off.
private nonisolated static let expiringCategory = "expiring"
private nonisolated static let postponeAction = "postpone"

/// Called with the profile id when the user asks to put off its
/// automatic disconnection from a notification.
var onPostpone: (String) -> Void = { _ in }

func setUp() {
if let center {
center.delegate = self
let postpone = UNNotificationAction(identifier: Self.postponeAction,
title: String(localized: "Postpone"), options: [])
center.setNotificationCategories([
UNNotificationCategory(identifier: Self.expiringCategory, actions: [postpone], intentIdentifiers: []),
])
}
Task {
if await status() == .notDetermined { await requestAuthorization() }
}
Expand Down Expand Up @@ -39,4 +55,39 @@ final class Notifier {
content.body = body
center.add(UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil))
}

/// `id`'s disconnection to come; one at a time per VPN, replaced by
/// the next. `canPostpone`: with the Postpone button.
func postExpiring(id: String, title: String, body: String, canPostpone: Bool) {
guard let center else { return }
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
content.userInfo = ["id": id]
if canPostpone { content.categoryIdentifier = Self.expiringCategory }
center.add(UNNotificationRequest(identifier: Self.expiringIdentifier(id), content: content, trigger: nil))
}

/// Takes back `id`'s warning: postponed, or already disconnected.
func removeExpiring(id: String) {
center?.removeDeliveredNotifications(withIdentifiers: [Self.expiringIdentifier(id)])
}

private static func expiringIdentifier(_ id: String) -> String { "expiring-\(id)" }

// MARK: UNUserNotificationCenterDelegate

/// Shown as banners even though the menu bar app is always active.
nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification)
async -> UNNotificationPresentationOptions {
[.banner, .list, .sound]
}

nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse) async {
guard response.actionIdentifier == Self.postponeAction,
let id = response.notification.request.content.userInfo["id"] as? String else { return }
await MainActor.run { onPostpone(id) }
}
}
Loading
Loading