content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
//\n// String+FuzzyMatch.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-04-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension String {\n func fuzzyMatch(_ needle: String) -> Bool {\n guard !needle.isEmpty else { return false }\n\n let haystack = lowercased()\n let needle = needle.lowercased()\n\n var indices: [Index] = []\n var remainder = needle[...].utf8\n\n for index in haystack.utf8.indices {\n let character = haystack.utf8[index]\n\n if character == remainder[remainder.startIndex] {\n indices.append(index)\n remainder.removeFirst()\n\n if remainder.isEmpty {\n return !indices.isEmpty\n }\n }\n }\n\n return false\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\String+FuzzyMatch.swift | String+FuzzyMatch.swift | Swift | 840 | 0.95 | 0.083333 | 0.25 | python-kit | 667 | 2025-01-20T10:14:04.128510 | GPL-3.0 | false | 688a4ff9136b39ffab1d16ce4226ffe8 |
//\n// String+Helpers.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/03/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension String {\n /// Returns the array of the longest possible subsequences of the given length.\n func split(every length: Int) -> [Substring] {\n guard length > 0 else { return [prefix(upTo: endIndex)] }\n\n let resultCount = Int((Float(count) / Float(length)).rounded(.up))\n\n return (0 ..< resultCount)\n .map { dropFirst($0 * length).prefix(length) }\n }\n\n func width(using font: UIFont) -> CGFloat {\n let fontAttributes = [NSAttributedString.Key.font: font]\n return self.size(withAttributes: fontAttributes).width\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\String+Helpers.swift | String+Helpers.swift | Swift | 745 | 0.95 | 0 | 0.380952 | node-utils | 185 | 2024-06-17T23:18:47.421144 | BSD-3-Clause | false | 5011f22c2c1aef3c56db21753a901c54 |
//\n// UIBackgroundConfiguration+Extensions.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIBackgroundConfiguration {\n /// Type of cell selection used in Mullvad UI.\n enum CellSelectionType {\n /// Dimmed blue.\n case dimmed\n /// Bright green.\n case green\n }\n\n /// Returns a plain cell background configuration adapted for Mullvad UI.\n /// - Returns: a background configuration\n static func mullvadListPlainCell() -> UIBackgroundConfiguration {\n var config = listPlainCell()\n config.backgroundColor = UIColor.Cell.Background.normal\n return config\n }\n\n /// Returns the corresponding grouped cell background configuration adapted for Mullvad UI.\n /// - Returns: a background configuration\n static func mullvadListGroupedCell() -> UIBackgroundConfiguration {\n var config = listGroupedCell()\n config.backgroundColor = UIColor.Cell.Background.normal\n return config\n }\n\n /// Adapt background configuration for the cell state and selection type.\n ///\n /// - Parameters:\n /// - state: a cell state.\n /// - selectionType: a desired selecton type.\n /// - Returns: new background configuration.\n func adapted(\n for state: UICellConfigurationState,\n selectionType: CellSelectionType\n ) -> UIBackgroundConfiguration {\n var config = self\n config.backgroundColor = state.mullvadCellBackgroundColor(selectionType: selectionType)\n return config\n }\n}\n\nextension UICellConfigurationState {\n /// Produce background color for the given state and cell selection type.\n ///\n /// - Parameter selectionType: cell selection type.\n /// - Returns: a background color to apply to cell.\n func mullvadCellBackgroundColor(selectionType: UIBackgroundConfiguration.CellSelectionType) -> UIColor {\n switch selectionType {\n case .dimmed:\n if isSelected || isHighlighted {\n UIColor.Cell.Background.selectedAlt\n } else if isDisabled {\n UIColor.Cell.Background.disabled\n } else {\n UIColor.Cell.Background.normal\n }\n\n case .green:\n if isSelected || isHighlighted {\n UIColor.Cell.Background.selected\n } else if isDisabled {\n UIColor.Cell.Background.disabled\n } else {\n UIColor.Cell.Background.normal\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIBackgroundConfiguration+Extensions.swift | UIBackgroundConfiguration+Extensions.swift | Swift | 2,566 | 0.95 | 0.128205 | 0.338028 | awesome-app | 72 | 2024-08-30T11:27:28.360450 | GPL-3.0 | false | 47b1d8d37c5eb405af2bbb82492a578f |
//\n// UIBarButtonItem+KeyboardNavigation.swift\n// MullvadVPN\n//\n// Created by pronebird on 24/02/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIBarButtonItem {\n enum KeyboardNavigationItemType {\n case previous, next\n\n fileprivate var localizedTitle: String {\n switch self {\n case .previous:\n return NSLocalizedString(\n "PREVIOUS_BUTTON_TITLE",\n tableName: "KeyboardNavigation",\n value: "Previous",\n comment: "Previous button"\n )\n case .next:\n return NSLocalizedString(\n "NEXT_BUTTON_TITLE",\n tableName: "KeyboardNavigation",\n value: "Next",\n comment: "Next button"\n )\n }\n }\n\n fileprivate var systemImage: UIImage? {\n switch self {\n case .previous:\n return UIImage(systemName: "chevron.up")\n case .next:\n return UIImage(systemName: "chevron.down")\n }\n }\n }\n\n convenience init(\n keyboardNavigationItemType: KeyboardNavigationItemType,\n target: Any?,\n action: Selector?\n ) {\n self.init(\n image: keyboardNavigationItemType.systemImage,\n style: .plain,\n target: target,\n action: action\n )\n\n accessibilityLabel = keyboardNavigationItemType.localizedTitle\n }\n\n static func makeKeyboardNavigationItems(_ configurationBlock: (\n _ prevItem: UIBarButtonItem,\n _ nextItem: UIBarButtonItem\n ) -> Void) -> [UIBarButtonItem] {\n let prevButton = UIBarButtonItem(keyboardNavigationItemType: .previous, target: nil, action: nil)\n let nextButton = UIBarButtonItem(keyboardNavigationItemType: .next, target: nil, action: nil)\n\n configurationBlock(prevButton, nextButton)\n\n let spacer = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)\n spacer.width = 8\n\n return [prevButton, spacer, nextButton]\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIBarButtonItem+KeyboardNavigation.swift | UIBarButtonItem+KeyboardNavigation.swift | Swift | 2,189 | 0.95 | 0.027397 | 0.111111 | react-lib | 449 | 2023-11-22T11:25:05.296715 | Apache-2.0 | false | 3662eaa76d41f64ba71213530338cba9 |
//\n// UIColor+Helpers.swift\n// MullvadVPN\n//\n// Created by pronebird on 06/05/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension UIColor {\n var color: Color {\n Color(self)\n }\n\n /// Returns the color lighter by the given percent (in range from 0..1)\n func lightened(by percent: CGFloat) -> UIColor? {\n darkened(by: -percent)\n }\n\n /// Returns the color darker by the given percent (in range from 0..1)\n func darkened(by percent: CGFloat) -> UIColor? {\n var r = CGFloat.zero, g = CGFloat.zero, b = CGFloat.zero, a = CGFloat.zero\n let factor = 1.0 - percent\n\n if getRed(&r, green: &g, blue: &b, alpha: &a) {\n return UIColor(\n red: clampColorComponent(r * factor),\n green: clampColorComponent(g * factor),\n blue: clampColorComponent(b * factor),\n alpha: a\n )\n }\n\n return nil\n }\n}\n\nprivate func clampColorComponent(_ value: CGFloat) -> CGFloat {\n min(1.0, max(value, 0.0))\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIColor+Helpers.swift | UIColor+Helpers.swift | Swift | 1,074 | 0.95 | 0.02439 | 0.264706 | awesome-app | 649 | 2025-04-07T16:12:05.194600 | MIT | false | df9746109aa39102abd6ca20516a93bc |
//\n// UIFont+Weight.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-05-23.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIFont {\n static func preferredFont(forTextStyle style: TextStyle, weight: Weight) -> UIFont {\n let descriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style)\n .addingAttributes([\n .traits: [UIFontDescriptor.TraitKey.weight: weight],\n ])\n\n return UIFont(descriptor: descriptor, size: 0)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIFont+Weight.swift | UIFont+Weight.swift | Swift | 542 | 0.95 | 0 | 0.411765 | awesome-app | 603 | 2023-11-19T20:23:56.414474 | Apache-2.0 | false | 8760a33d1a103cb1d3b9e1781608a57f |
//\n// UIImage+Assets.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2025-03-06.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIImage {\n enum Buttons {\n static var account: UIImage {\n UIImage(named: "IconAccount")!\n }\n\n static var alert: UIImage {\n UIImage(named: "IconAlert")!\n }\n\n static var info: UIImage {\n UIImage(named: "IconInfo")!\n }\n\n static var settings: UIImage {\n UIImage(named: "IconSettings")!\n }\n\n static var back: UIImage {\n UIImage(named: "IconBack")!\n }\n\n static var copy: UIImage {\n UIImage(named: "IconCopy")!\n }\n\n static var hide: UIImage {\n UIImage(named: "IconObscure")!\n }\n\n static var reload: UIImage {\n UIImage(named: "IconReload")!\n }\n\n static var rightArrow: UIImage {\n UIImage(named: "IconArrow")!\n }\n\n static var show: UIImage {\n UIImage(named: "IconUnobscure")!\n }\n\n // The close button, which we consume in two sizes, both of which come from the same asset.\n\n static var closeSmall: UIImage {\n UIImage(named: "IconClose")!\n .resized(to: CGSize(width: 18, height: 18))\n }\n\n static var close: UIImage {\n UIImage(named: "IconClose")!\n .resized(to: CGSize(width: 24, height: 24))\n }\n }\n\n enum CellDecoration {\n static var chevronRight: UIImage {\n UIImage(named: "IconChevron")!\n }\n\n static var chevronDown: UIImage {\n UIImage(named: "IconChevronDown")!\n }\n\n static var chevronUp: UIImage {\n UIImage(named: "IconChevronUp")!\n }\n\n static var externalLink: UIImage {\n UIImage(named: "IconExtlink")!\n }\n\n static var tick: UIImage {\n UIImage(named: "IconTickSml")!\n }\n }\n\n enum Status {\n static var failure: UIImage { UIImage(named: "IconFail")! }\n static var success: UIImage { UIImage(named: "IconSuccess")! }\n }\n\n // miscellaneous images\n static var backTransitionMask: UIImage {\n UIImage(named: "IconBackTransitionMask")!\n }\n\n static var spinner: UIImage {\n UIImage(named: "IconSpinner")!\n }\n\n static var tick: UIImage {\n UIImage(named: "IconTickSml")!\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIImage+Assets.swift | UIImage+Assets.swift | Swift | 2,472 | 0.95 | 0 | 0.109756 | vue-tools | 329 | 2025-06-02T09:49:12.117237 | MIT | false | fbd65ef73c9341d992042fb22dc3a9fa |
//\n// UIImage+Helpers.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2024-10-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIImage {\n // Function to resize image while keeping aspect ratio\n // if `trimmingBorder` is specified, that number of pixels will be trimmed off each side before the remaining area is rendered to the new image\n func resized(to: CGSize, trimmingBorder border: CGFloat = 0) -> UIImage {\n let sourceSize = CGSize(width: size.width - 2 * border, height: size.height - 2 * border)\n let widthRatio = to.width / sourceSize.width\n let heightRatio = to.height / sourceSize.height\n let scaleFactor = min(widthRatio, heightRatio)\n let scaledBorder = border * scaleFactor\n\n // Calculate new size based on the scale factor\n let newSize = CGSize(width: sourceSize.width * scaleFactor, height: sourceSize.height * scaleFactor)\n let renderer = UIGraphicsImageRenderer(size: newSize)\n\n // Render the new image\n let resizedImage = renderer.image { _ in\n draw(\n in: CGRect(\n origin: .init(x: -scaledBorder, y: -scaledBorder),\n size: .init(width: newSize.width + 2 * scaledBorder, height: newSize.height + 2 * scaledBorder)\n )\n )\n }\n\n return resizedImage.withRenderingMode(renderingMode)\n }\n\n func withAlpha(_ alpha: CGFloat) -> UIImage? {\n return UIGraphicsImageRenderer(size: size, format: imageRendererFormat).image { _ in\n draw(in: CGRect(origin: .zero, size: size), blendMode: .normal, alpha: alpha)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIImage+Helpers.swift | UIImage+Helpers.swift | Swift | 1,682 | 0.95 | 0.046512 | 0.297297 | node-utils | 786 | 2024-03-13T09:22:42.709410 | GPL-3.0 | false | 9bd1bdf90de4445fafd644aae5f0c1c1 |
//\n// UIListContentConfiguration+Extensions.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIListContentConfiguration {\n /// Returns cell configured with default text attribute used in Mullvad UI.\n static func mullvadCell(tableStyle: UITableView.Style, isEnabled: Bool = true) -> UIListContentConfiguration {\n var configuration = cell()\n configuration.textProperties.font = .systemFont(ofSize: 17)\n configuration.textProperties.color = .Cell.titleTextColor.withAlphaComponent(isEnabled ? 1 : 0.8)\n\n applyMargins(to: &configuration, tableStyle: tableStyle)\n\n return configuration\n }\n\n /// Returns value cell configured with default text attribute used in Mullvad UI.\n static func mullvadValueCell(tableStyle: UITableView.Style, isEnabled: Bool = true) -> UIListContentConfiguration {\n var configuration = valueCell()\n configuration.textProperties.font = .systemFont(ofSize: 17)\n configuration.textProperties.color = .Cell.titleTextColor.withAlphaComponent(isEnabled ? 1 : 0.8)\n configuration.secondaryTextProperties.color = .Cell.detailTextColor.withAlphaComponent(0.8)\n configuration.secondaryTextProperties.font = .systemFont(ofSize: 17)\n\n applyMargins(to: &configuration, tableStyle: tableStyle)\n\n return configuration\n }\n\n /// Returns grouped header configured with default text attribute used in Mullvad UI.\n static func mullvadGroupedHeader(tableStyle: UITableView.Style) -> UIListContentConfiguration {\n var configuration = groupedHeader()\n configuration.textProperties.color = .TableSection.headerTextColor\n configuration.textProperties.font = .systemFont(ofSize: 13)\n\n applyMargins(to: &configuration, tableStyle: tableStyle)\n\n return configuration\n }\n\n /// Returns grouped footer configured with default text attribute used in Mullvad UI.\n static func mullvadGroupedFooter(tableStyle: UITableView.Style) -> UIListContentConfiguration {\n var configuration = groupedFooter()\n configuration.textProperties.color = .TableSection.footerTextColor\n configuration.textProperties.font = .systemFont(ofSize: 13)\n\n applyMargins(to: &configuration, tableStyle: tableStyle)\n\n return configuration\n }\n\n private static func applyMargins(\n to configuration: inout UIListContentConfiguration,\n tableStyle: UITableView.Style\n ) {\n configuration.axesPreservingSuperviewLayoutMargins = .vertical\n configuration.directionalLayoutMargins = tableStyle.directionalLayoutMarginsForCell\n }\n}\n\nextension UITableView.Style {\n var directionalLayoutMarginsForCell: NSDirectionalEdgeInsets {\n switch self {\n case .plain, .grouped:\n UIMetrics.SettingsCell.apiAccessLayoutMargins\n case .insetGrouped:\n UIMetrics.SettingsCell.apiAccessInsetLayoutMargins\n @unknown default:\n UIMetrics.SettingsCell.apiAccessLayoutMargins\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIListContentConfiguration+Extensions.swift | UIListContentConfiguration+Extensions.swift | Swift | 3,109 | 0.95 | 0.012821 | 0.174603 | vue-tools | 160 | 2024-07-06T11:30:01.095016 | MIT | false | 893eda36819d1ff09875c4b01eb8e715 |
//\n// UITableView+ReuseIdentifier.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/11/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/**\n Type describing cell identifier.\n\n Example:\n\n ```\n enum MyCellIdentifier: CaseIterable, String, CellIdentifierProtocol {\n case primary, secondary\n\n var cellClass: AnyClass {\n switch self {\n case .primary:\n return MyPrimaryCell.self\n case .secondary:\n return MySecondaryCell.self\n }\n }\n }\n\n // Register all cells\n tableView.registerReusableViews(from: MyCellIdentifier.self)\n\n // Dequeue cell\n let cell = tableView.dequeueReusableView(withIdentifier: MyCellIdentifier.primary, for: IndexPath(row: 0, section: 0)))\n ```\n */\nprotocol CellIdentifierProtocol: CaseIterable, RawRepresentable where RawValue == String {\n var cellClass: AnyClass { get }\n}\n\n/**\n Type describing header footer view identifier.\n\n Example:\n\n ```\n enum MyHeaderFooterIdentifier: CaseIterable, String, HeaderFooterIdentifierProtocol {\n case primary, secondary\n\n var headerFooterClass: AnyClass {\n switch self {\n case .primary:\n return MyPrimaryHeaderFooterView.self\n case .secondary:\n return MySecondaryHeaderFooterView.self\n }\n }\n }\n\n // Register all cells\n tableView.registerReusableViews(from: MyHeaderFooterIdentifier.self)\n\n // Dequeue header footer view\n let headerFooterView = tableView.dequeueReusableView(withIdentifier: MyHeaderFooterIdentifier.primary)\n ```\n */\nprotocol HeaderFooterIdentifierProtocol: CaseIterable, RawRepresentable where RawValue == String {\n var headerFooterClass: AnyClass { get }\n}\n\nextension UITableView {\n /// Register all cell identifiers in the table view.\n /// - Parameter cellIdentifierType: a type conforming to the ``CellIdentifierProtocol`` protocol.\n func registerReusableViews<T: CellIdentifierProtocol>(from cellIdentifierType: T.Type) {\n cellIdentifierType.allCases.forEach { identifier in\n register(identifier.cellClass, forCellReuseIdentifier: identifier.rawValue)\n }\n }\n\n /// Register header footer view identifiers in the table view.\n /// - Parameter headerFooterIdentifierType: a type conforming to the ``HeaderFooterIdentifierProtocol`` protocol.\n func registerReusableViews<T: HeaderFooterIdentifierProtocol>(from headerFooterIdentifierType: T.Type) {\n headerFooterIdentifierType.allCases.forEach { identifier in\n register(identifier.headerFooterClass, forHeaderFooterViewReuseIdentifier: identifier.rawValue)\n }\n }\n}\n\nextension UITableView {\n /// Convenience method to dequeue a cell by identifier conforming to ``CellIdentifierProtocol``.\n /// - Parameters:\n /// - identifier: cell identifier.\n /// - indexPath: index path\n /// - Returns: table cell.\n func dequeueReusableView(\n withIdentifier identifier: some CellIdentifierProtocol,\n for indexPath: IndexPath\n ) -> UITableViewCell {\n dequeueReusableCell(withIdentifier: identifier.rawValue, for: indexPath)\n }\n\n /// Convenience method to dequeue a header footer view by identifier conforming to ``HeaderFooterIdentifierProtocol``.\n /// - Parameter identifier: header footer view identifier.\n /// - Returns: table header footer view.\n func dequeueReusableView(withIdentifier identifier: some HeaderFooterIdentifierProtocol)\n -> UITableViewHeaderFooterView? {\n dequeueReusableHeaderFooterView(withIdentifier: identifier.rawValue)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UITableView+ReuseIdentifier.swift | UITableView+ReuseIdentifier.swift | Swift | 3,599 | 0.95 | 0.045872 | 0.293478 | react-lib | 665 | 2024-12-27T20:16:00.069413 | Apache-2.0 | false | a0d4b9a57f3012ce8a3498ea12412897 |
//\n// UITableViewCell+Disable.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-01-05.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UITableViewCell {\n func setDisabled(_ disabled: Bool) {\n isUserInteractionEnabled = !disabled\n contentView.alpha = disabled ? 0.8 : 1\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UITableViewCell+Disable.swift | UITableViewCell+Disable.swift | Swift | 345 | 0.95 | 0 | 0.5 | python-kit | 488 | 2025-01-31T23:14:37.580820 | MIT | false | c1d83c9d20ffa8efc76fad08f77abbf0 |
//\n// UITextField+Appearance.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-04-04.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UITextField {\n @MainActor\n struct SearchTextFieldAppearance {\n let placeholderTextColor: UIColor\n let textColor: UIColor\n let backgroundColor: UIColor\n let leftViewTintColor: UIColor\n\n static var active: SearchTextFieldAppearance {\n SearchTextFieldAppearance(\n placeholderTextColor: .SearchTextField.placeholderTextColor,\n textColor: .SearchTextField.textColor,\n backgroundColor: .SearchTextField.backgroundColor,\n leftViewTintColor: .SearchTextField.leftViewTintColor\n )\n }\n\n static var inactive: SearchTextFieldAppearance {\n SearchTextFieldAppearance(\n placeholderTextColor: .SearchTextField.inactivePlaceholderTextColor,\n textColor: .SearchTextField.inactiveTextColor,\n backgroundColor: .SearchTextField.inactiveBackgroundColor,\n leftViewTintColor: .SearchTextField.inactiveLeftViewTintColor\n )\n }\n\n func apply(to searchBar: UISearchBar) {\n searchBar.setImage(\n UIImage.Buttons.closeSmall.withTintColor(leftViewTintColor),\n for: .clear,\n state: .normal\n )\n\n apply(to: searchBar.searchTextField)\n }\n\n func apply(to textField: UITextField) {\n textField.leftView?.tintColor = leftViewTintColor\n textField.tintColor = textColor\n textField.textColor = textColor\n textField.backgroundColor = backgroundColor\n\n if let customTextField = textField as? CustomTextField {\n customTextField.placeholderTextColor = placeholderTextColor\n } else {\n textField.attributedPlaceholder = NSAttributedString(\n string: textField.placeholder ?? "",\n attributes: [.foregroundColor: placeholderTextColor]\n )\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UITextField+Appearance.swift | UITextField+Appearance.swift | Swift | 2,176 | 0.95 | 0.031746 | 0.127273 | python-kit | 202 | 2024-03-07T15:52:25.773209 | GPL-3.0 | false | fffb1194d1a6133e8b64b9b8f06c39ac |
//\n// UIView+AutoLayoutBuilder.swift\n// MullvadVPN\n//\n// Created by pronebird on 24/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/**\n Protocol that describes common AutoLayout properties of `UIView` and `UILayoutGuide` and helps to remove distinction\n between two of them when creating constraints.\n */\nprotocol AutoLayoutAnchorsProtocol {\n var topAnchor: NSLayoutYAxisAnchor { get }\n var bottomAnchor: NSLayoutYAxisAnchor { get }\n var leadingAnchor: NSLayoutXAxisAnchor { get }\n var trailingAnchor: NSLayoutXAxisAnchor { get }\n}\n\nextension UIView: @preconcurrency AutoLayoutAnchorsProtocol {}\nextension UILayoutGuide: @preconcurrency AutoLayoutAnchorsProtocol {}\n\nextension UIView {\n /**\n Pin all edges to edges of other view.\n */\n func pinEdgesTo(_ other: AutoLayoutAnchorsProtocol) -> [NSLayoutConstraint] {\n pinEdges(.all(), to: other)\n }\n\n /**\n Pin edges to edges of other view.\n */\n func pinEdges(_ edges: PinnableEdges, to other: AutoLayoutAnchorsProtocol) -> [NSLayoutConstraint] {\n edges.makeConstraints(firstView: self, secondView: other)\n }\n\n /**\n Pin edges to superview edges.\n */\n func pinEdgesToSuperview(_ edges: PinnableEdges = .all()) -> [NSLayoutConstraint] {\n guard let superview else { return [] }\n\n return pinEdges(edges, to: superview)\n }\n\n /**\n Pin edges to superview margins.\n */\n func pinEdgesToSuperviewMargins(_ edges: PinnableEdges = .all()) -> [NSLayoutConstraint] {\n guard let superview else { return [] }\n\n return pinEdges(edges, to: superview.layoutMarginsGuide)\n }\n\n /**\n Pin single edge to superview edge.\n */\n func pinEdgeToSuperview(_ edge: PinnableEdges.Edge) -> [NSLayoutConstraint] {\n guard let superview else { return [] }\n\n return pinEdges(PinnableEdges([edge]), to: superview)\n }\n\n /**\n Pin single edge to superview margin edge.\n */\n func pinEdgeToSuperviewMargin(_ edge: PinnableEdges.Edge) -> [NSLayoutConstraint] {\n guard let superview else { return [] }\n\n return pinEdges(PinnableEdges([edge]), to: superview.layoutMarginsGuide)\n }\n}\n\n/**\n AutoLayout builder.\n\n Use it in conjunction with `NSLayoutConstraint.activate()`, for example:\n\n ```\n let view = UIView()\n let subview = UIView()\n\n subview.translatesAutoresizingMaskIntoConstraints = false\n\n view.addSubview(subview)\n\n NSLayoutConstraint.activate {\n // Pin top, leading and trailing edges to superview.\n subview.pinEdgesToSuperview(.init([.top(8), .leading(16), .trailing(8)]))\n\n // Pin bottom to safe area layout guide.\n subview.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)\n }\n ```\n */\n@resultBuilder enum AutoLayoutBuilder {\n static func buildBlock(_ components: [NSLayoutConstraint]...) -> [NSLayoutConstraint] {\n components.flatMap { $0 }\n }\n\n static func buildExpression(_ expression: NSLayoutConstraint) -> [NSLayoutConstraint] {\n [expression]\n }\n\n static func buildExpression(_ expression: [NSLayoutConstraint]) -> [NSLayoutConstraint] {\n expression\n }\n\n static func buildOptional(_ components: [NSLayoutConstraint]?) -> [NSLayoutConstraint] {\n components ?? []\n }\n\n static func buildEither(first components: [NSLayoutConstraint]) -> [NSLayoutConstraint] {\n components\n }\n\n static func buildEither(second components: [NSLayoutConstraint]) -> [NSLayoutConstraint] {\n components\n }\n\n static func buildArray(_ components: [[NSLayoutConstraint]]) -> [NSLayoutConstraint] {\n components.flatMap { $0 }\n }\n}\n\nextension NSLayoutConstraint {\n /**\n Activate constraints produced by a builder.\n */\n static func activate(@AutoLayoutBuilder builder: () -> [NSLayoutConstraint]) {\n activate(builder())\n }\n}\n\nextension UIView {\n /**\n Add subviews using AutoLayout and configure constraints.\n */\n @MainActor\n func addConstrainedSubviews(\n _ subviews: [UIView],\n @AutoLayoutBuilder builder: () -> [NSLayoutConstraint]\n ) {\n for subview in subviews {\n subview.configureForAutoLayout()\n addSubview(subview)\n }\n\n NSLayoutConstraint.activate(builder())\n }\n\n /**\n Add subviews using AutoLayout without configuring constraints.\n */\n func addConstrainedSubviews(_ subviews: [UIView]) {\n addConstrainedSubviews(subviews) {}\n }\n\n /**\n Configure view for AutoLayout by disabling automatic autoresizing mask translation into\n constraints.\n */\n func configureForAutoLayout() {\n translatesAutoresizingMaskIntoConstraints = false\n }\n}\n\n/**\n Struct describing a relationship between AutoLayout anchors.\n */\nstruct PinnableEdges {\n /**\n Enum describing each inidividual edge with associated inset value.\n */\n enum Edge: Hashable {\n case top(CGFloat)\n case bottom(CGFloat)\n case leading(CGFloat)\n case trailing(CGFloat)\n\n var rectEdge: NSDirectionalRectEdge {\n switch self {\n case .top:\n return .top\n case .bottom:\n return .bottom\n case .leading:\n return .leading\n case .trailing:\n return .trailing\n }\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(rectEdge.rawValue)\n }\n\n static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.rectEdge == rhs.rectEdge\n }\n\n @MainActor\n func makeConstraint(\n firstView: AutoLayoutAnchorsProtocol,\n secondView: AutoLayoutAnchorsProtocol\n ) -> NSLayoutConstraint {\n switch self {\n case let .top(inset):\n return firstView.topAnchor.constraint(equalTo: secondView.topAnchor, constant: inset)\n\n case let .bottom(inset):\n return firstView.bottomAnchor.constraint(equalTo: secondView.bottomAnchor, constant: -inset)\n\n case let .leading(inset):\n return firstView.leadingAnchor.constraint(equalTo: secondView.leadingAnchor, constant: inset)\n\n case let .trailing(inset):\n return firstView.trailingAnchor.constraint(equalTo: secondView.trailingAnchor, constant: -inset)\n }\n }\n }\n\n /**\n Inner set of `Edge` objects.\n */\n var inner: Set<Edge>\n\n /**\n Designated initializer.\n */\n init(_ edges: Set<Edge>) {\n inner = edges\n }\n\n /**\n Returns new `PinnableEdges` with the given edge(s) excluded.\n */\n func excluding(_ excludeEdges: NSDirectionalRectEdge) -> Self {\n Self(inner.filter { !excludeEdges.contains($0.rectEdge) })\n }\n\n /**\n Returns new `PinnableEdges` initialized with four edges and corresponding insets from\n `NSDirectionalEdgeInsets`.\n */\n static func all(_ directionalEdgeInsets: NSDirectionalEdgeInsets = .zero) -> Self {\n Self([\n .top(directionalEdgeInsets.top),\n .bottom(directionalEdgeInsets.bottom),\n .leading(directionalEdgeInsets.leading),\n .trailing(directionalEdgeInsets.trailing),\n ])\n }\n\n /**\n Returns new constraints pinning edges of the corresponding views.\n */\n @MainActor\n func makeConstraints(\n firstView: AutoLayoutAnchorsProtocol,\n secondView: AutoLayoutAnchorsProtocol\n ) -> [NSLayoutConstraint] {\n inner.map { $0.makeConstraint(firstView: firstView, secondView: secondView) }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\UIView+AutoLayoutBuilder.swift | UIView+AutoLayoutBuilder.swift | Swift | 7,628 | 0.95 | 0.018657 | 0.209821 | react-lib | 301 | 2025-04-05T05:23:07.166073 | Apache-2.0 | false | 0d03bbd3d9ffdf1ab85d975ca56567c9 |
//\n// URL+Scoping.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-02-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nextension URL {\n func securelyScoped(_ completionHandler: (Self?) -> Void) {\n if startAccessingSecurityScopedResource() {\n completionHandler(self)\n stopAccessingSecurityScopedResource()\n } else {\n completionHandler(nil)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\URL+Scoping.swift | URL+Scoping.swift | Swift | 457 | 0.95 | 0.05 | 0.388889 | awesome-app | 622 | 2024-05-06T18:09:17.949865 | BSD-3-Clause | false | 8781c47917ecacb1278779469095898b |
//\n// View+Conditionals.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2025-01-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension View {\n @ViewBuilder func `if`<Content: View>(\n _ conditional: Bool,\n @ViewBuilder _ content: (Self) -> Content\n ) -> some View {\n if conditional {\n content(self)\n } else {\n self\n }\n }\n\n @ViewBuilder func ifLet<Content: View, T>(\n _ conditional: T?,\n @ViewBuilder _ content: (Self, _ value: T) -> Content\n ) -> some View {\n if let value = conditional {\n content(self, value)\n } else {\n self\n }\n }\n\n @ViewBuilder func showIf(_ conditional: Bool) -> some View {\n if conditional {\n self\n } else {\n EmptyView()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\View+Conditionals.swift | View+Conditionals.swift | Swift | 878 | 0.95 | 0.097561 | 0.189189 | python-kit | 677 | 2024-12-19T03:22:15.300546 | GPL-3.0 | false | bede9858948b9aca59382cc754e564ca |
//\n// View+Modifier.swift\n// MullvadVPN\n//\n// Created by Steffen Ernst on 2025-01-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension View {\n /**\n A view modifier that can be used to conditionally apply other view modifiers.\n # Example #\n ```\n .apply {\n if #available(iOS 16.4, *) {\n $0.scrollBounceBehavior(.basedOnSize)\n } else {\n $0\n }\n }\n ```\n */\n func apply<V: View>(@ViewBuilder _ block: (Self) -> V) -> V { block(self) }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\View+Modifier.swift | View+Modifier.swift | Swift | 553 | 0.95 | 0.038462 | 0.416667 | vue-tools | 975 | 2024-04-08T00:10:30.261722 | BSD-3-Clause | false | 933f6fec2d00e55d6696d39e4e9af6bc |
//\n// View+Size.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-14.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension View {\n /// Measures view size.\n func sizeOfView(_ onSizeChange: @escaping ((CGSize) -> Void)) -> some View {\n return self\n .background {\n GeometryReader { proxy in\n Color.clear\n .preference(key: ViewSizeKey.self, value: proxy.size)\n .onPreferenceChange(ViewSizeKey.self) { size in\n onSizeChange(size)\n }\n }\n }\n }\n}\n\nprivate struct ViewSizeKey: PreferenceKey, Sendable {\n nonisolated(unsafe) static var defaultValue: CGSize = .zero\n\n static func reduce(value: inout CGSize, nextValue: () -> CGSize) {\n value = nextValue()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\View+Size.swift | View+Size.swift | Swift | 900 | 0.95 | 0 | 0.275862 | awesome-app | 156 | 2024-08-05T05:45:26.733373 | MIT | false | 632d4ba2421d0e103514d6b82599f340 |
//\n// View+TapAreaSize.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-11-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\n\nextension View {\n /// Adjusts tappable area to at least minimum (default) size without changing\n /// actual view size.\n func adjustingTapAreaSize() -> some View {\n modifier(TappablePadding())\n }\n}\n\nprivate struct TappablePadding: ViewModifier {\n @State private var actualViewSize: CGSize = .zero\n private let tappableViewSize = UIMetrics.Button.minimumTappableAreaSize\n\n func body(content: Content) -> some View {\n content\n .sizeOfView { actualViewSize = $0 }\n .frame(\n width: max(actualViewSize.width, tappableViewSize.width),\n height: max(actualViewSize.height, tappableViewSize.height)\n )\n .contentShape(Rectangle())\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Extensions\View+TapAreaSize.swift | View+TapAreaSize.swift | Swift | 908 | 0.95 | 0 | 0.321429 | python-kit | 606 | 2025-05-21T10:44:16.612240 | GPL-3.0 | false | b5bb399e2b5580da64d73209a694c67c |
//\n// OutgoingConnectionData.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-11-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Network\n\ntypealias IPV4ConnectionData = OutgoingConnectionData<IPv4Address>\ntypealias IPV6ConnectionData = OutgoingConnectionData<IPv6Address>\n\n// MARK: - OutgoingConnectionData\n\nstruct OutgoingConnectionData<T: Codable & IPAddress>: Codable, Equatable {\n let ip: T\n let exitIP: Bool\n\n enum CodingKeys: String, CodingKey {\n case ip, exitIP = "mullvad_exit_ip"\n }\n\n static func == (lhs: Self, rhs: Self) -> Bool {\n lhs.ip.rawValue == rhs.ip.rawValue && lhs.exitIP == rhs.exitIP\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\GeneralAPIs\OutgoingConnectionData.swift | OutgoingConnectionData.swift | Swift | 693 | 0.95 | 0 | 0.363636 | python-kit | 307 | 2024-02-05T13:09:34.902081 | Apache-2.0 | false | a368f9715d8716937aa229344710ee0c |
//\n// OutgoingConnectionProxy.swift\n// MullvadREST\n//\n// Created by Mojgan on 2023-10-24.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport Network\n\nprotocol OutgoingConnectionHandling {\n func getIPV6(retryStrategy: REST.RetryStrategy) async throws -> IPV6ConnectionData\n func getIPV4(retryStrategy: REST.RetryStrategy) async throws -> IPV4ConnectionData\n}\n\nfinal class OutgoingConnectionProxy: OutgoingConnectionHandling {\n enum ExitIPVersion: String {\n case v4 = "ipv4", v6 = "ipv6"\n\n func host(hostname: String) -> String {\n "\(rawValue).am.i.\(hostname)"\n }\n }\n\n let urlSession: URLSessionProtocol\n let hostname: String\n\n init(urlSession: URLSessionProtocol, hostname: String) {\n self.urlSession = urlSession\n self.hostname = hostname\n }\n\n func getIPV6(retryStrategy: REST.RetryStrategy) async throws -> IPV6ConnectionData {\n try await perform(retryStrategy: retryStrategy, version: .v6)\n }\n\n func getIPV4(retryStrategy: REST.RetryStrategy) async throws -> IPV4ConnectionData {\n try await perform(retryStrategy: retryStrategy, version: .v4)\n }\n\n private func perform<T: Decodable>(retryStrategy: REST.RetryStrategy, version: ExitIPVersion) async throws -> T {\n let delayIterator = retryStrategy.makeDelayIterator()\n for _ in 0 ..< retryStrategy.maxRetryCount {\n do {\n return try await perform(host: version.host(hostname: hostname))\n } catch {\n // ignore if request is cancelled\n if case URLError.cancelled = error {\n throw error\n } else {\n // retry with the delay\n guard let delay = delayIterator.next() else { throw error }\n let mills = UInt64(max(0, delay.milliseconds))\n let nanos = mills.saturatingMultiplication(1_000_000)\n try await Task.sleep(nanoseconds: nanos)\n }\n }\n }\n return try await perform(host: version.host(hostname: hostname))\n }\n\n private func perform<T: Decodable>(host: String) async throws -> T {\n var urlComponents = URLComponents()\n urlComponents.scheme = "https"\n urlComponents.host = host\n urlComponents.path = "/json"\n\n guard let url = urlComponents.url else {\n throw REST.Error.network(URLError(.badURL))\n }\n let request = URLRequest(\n url: url,\n cachePolicy: .useProtocolCachePolicy,\n timeoutInterval: REST.defaultAPINetworkTimeout.timeInterval\n )\n let (data, response) = try await data(for: request)\n guard let httpResponse = response as? HTTPURLResponse else {\n throw REST.Error.network(URLError(.badServerResponse))\n }\n let decoder = JSONDecoder()\n guard (200 ..< 300).contains(httpResponse.statusCode) else {\n throw REST.Error.unhandledResponse(\n httpResponse.statusCode,\n try? decoder.decode(\n REST.ServerErrorResponse.self,\n from: data\n )\n )\n }\n let connectionData = try decoder.decode(T.self, from: data)\n return connectionData\n }\n}\n\nextension OutgoingConnectionProxy: URLSessionProtocol {\n func data(for request: URLRequest) async throws -> (Data, URLResponse) {\n return try await urlSession.data(for: request)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\GeneralAPIs\OutgoingConnectionProxy.swift | OutgoingConnectionProxy.swift | Swift | 3,581 | 0.95 | 0.166667 | 0.1 | python-kit | 919 | 2024-02-19T19:01:51.923983 | MIT | false | 2152d2a361616a872b4215acef04cf48 |
//\n// InAppNotificationDescriptor.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit.UIImage\n\n/// Struct describing in-app notification.\nstruct InAppNotificationDescriptor: Equatable {\n /// Notification identifier.\n var identifier: NotificationProviderIdentifier\n\n /// Notification banner style.\n var style: NotificationBannerStyle\n\n /// Notification title.\n var title: String\n\n /// Notification body.\n var body: NSAttributedString\n\n /// Notification action.\n var button: InAppNotificationAction?\n\n /// Notification tap action (optional).\n var tapAction: InAppNotificationAction?\n}\n\n/// Type describing a specific in-app notification action.\nstruct InAppNotificationAction: Equatable {\n /// Image assigned to action button.\n var image: UIImage?\n\n /// Action handler for button.\n var handler: (() -> Void)?\n\n static func == (lhs: InAppNotificationAction, rhs: InAppNotificationAction) -> Bool {\n lhs.image == rhs.image\n }\n}\n\nenum NotificationBannerStyle {\n case success, warning, error\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\InAppNotificationDescriptor.swift | InAppNotificationDescriptor.swift | Swift | 1,159 | 0.95 | 0.020833 | 0.459459 | vue-tools | 389 | 2025-04-23T01:46:09.225646 | MIT | false | b8c4685defa6e62e297da49e8c233291 |
//\n// InAppNotificationProvider.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Protocol describing in-app notification provider.\nprotocol InAppNotificationProvider: NotificationProviderProtocol {\n /// In-app notification descriptor.\n var notificationDescriptor: InAppNotificationDescriptor? { get }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\InAppNotificationProvider.swift | InAppNotificationProvider.swift | Swift | 411 | 0.95 | 0 | 0.692308 | vue-tools | 425 | 2024-03-18T17:33:47.843638 | GPL-3.0 | false | b0da8083aa5bf8e690a6744b63036b62 |
//\n// NotificationManager.swift\n// MullvadVPN\n//\n// Created by pronebird on 31/05/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport UserNotifications\n\nfinal class NotificationManager: NotificationProviderDelegate {\n private lazy var logger = Logger(label: "NotificationManager")\n private var _notificationProviders: [NotificationProvider] = []\n private var inAppNotificationDescriptors: [InAppNotificationDescriptor] = []\n\n var notificationProviders: [NotificationProvider] {\n get {\n _notificationProviders\n }\n set(newNotificationProviders) {\n dispatchPrecondition(condition: .onQueue(.main))\n\n for oldNotificationProvider in _notificationProviders {\n oldNotificationProvider.delegate = nil\n }\n\n for newNotificationProvider in newNotificationProviders {\n newNotificationProvider.delegate = self\n }\n\n _notificationProviders = newNotificationProviders.sorted { $0.priority > $1.priority }\n }\n }\n\n weak var delegate: NotificationManagerDelegate? {\n didSet {\n dispatchPrecondition(condition: .onQueue(.main))\n\n // Pump in-app notifications when changing delegate.\n if !inAppNotificationDescriptors.isEmpty {\n delegate?.notificationManagerDidUpdateInAppNotifications(\n self,\n notifications: inAppNotificationDescriptors\n )\n }\n }\n }\n\n nonisolated(unsafe) static let shared = NotificationManager()\n\n private init() {}\n\n func updateNotifications() {\n dispatchPrecondition(condition: .onQueue(.main))\n\n var newSystemNotificationRequests = [UNNotificationRequest]()\n var newInAppNotificationDescriptors = [InAppNotificationDescriptor]()\n var pendingRequestIdentifiersToRemove = [String]()\n var deliveredRequestIdentifiersToRemove = [String]()\n\n for notificationProvider in notificationProviders {\n if let notificationProvider = notificationProvider as? SystemNotificationProvider {\n if notificationProvider.shouldRemovePendingRequests {\n pendingRequestIdentifiersToRemove.append(notificationProvider.identifier.domainIdentifier)\n }\n\n if notificationProvider.shouldRemoveDeliveredRequests {\n deliveredRequestIdentifiersToRemove.append(notificationProvider.identifier.domainIdentifier)\n }\n\n if let request = notificationProvider.notificationRequest {\n newSystemNotificationRequests.append(request)\n }\n }\n\n if let notificationProvider = notificationProvider as? InAppNotificationProvider {\n if let descriptor = notificationProvider.notificationDescriptor {\n newInAppNotificationDescriptors.append(descriptor)\n }\n }\n }\n\n let notificationCenter = UNUserNotificationCenter.current()\n\n notificationCenter.removePendingNotificationRequests(\n withIdentifiers: pendingRequestIdentifiersToRemove\n )\n notificationCenter.removeDeliveredNotifications(\n withIdentifiers: deliveredRequestIdentifiersToRemove\n )\n\n requestNotificationPermissions { granted in\n guard granted else { return }\n\n for newRequest in newSystemNotificationRequests {\n notificationCenter.add(newRequest) { error in\n guard let error else { return }\n\n self.logger.error(\n error: error,\n message: "Failed to add notification request with identifier \(newRequest.identifier)."\n )\n }\n }\n }\n\n inAppNotificationDescriptors = newInAppNotificationDescriptors\n\n delegate?.notificationManagerDidUpdateInAppNotifications(\n self,\n notifications: newInAppNotificationDescriptors\n )\n }\n\n func handleSystemNotificationResponse(_ response: UNNotificationResponse) {\n dispatchPrecondition(condition: .onQueue(.main))\n\n guard let sourceProvider = notificationProviders.first(where: { notificationProvider in\n guard let notificationProvider = notificationProvider as? SystemNotificationProvider else { return false }\n\n return response.notification.request.identifier == notificationProvider.identifier.domainIdentifier\n }) else {\n logger.warning(\n "Received response with request identifier: \(response.notification.request.identifier) that didn't map to any notification provider"\n )\n return\n }\n\n let notificationResponse = NotificationResponse(\n providerIdentifier: sourceProvider.identifier,\n actionIdentifier: response.actionIdentifier,\n systemResponse: response\n )\n\n delegate?.notificationManager(self, didReceiveResponse: notificationResponse)\n }\n\n // MARK: - Private\n\n private func requestNotificationPermissions(completion: @escaping (Bool) -> Void) {\n let authorizationOptions: UNAuthorizationOptions = [.alert, .sound, .provisional]\n let userNotificationCenter = UNUserNotificationCenter.current()\n\n userNotificationCenter.getNotificationSettings { notificationSettings in\n switch notificationSettings.authorizationStatus {\n case .notDetermined:\n userNotificationCenter.requestAuthorization(options: authorizationOptions) { granted, error in\n if let error {\n self.logger.error(\n error: error,\n message: "Failed to obtain user notifications authorization"\n )\n }\n completion(granted)\n }\n\n case .authorized, .provisional:\n completion(true)\n\n case .denied, .ephemeral:\n fallthrough\n\n @unknown default:\n completion(false)\n }\n }\n }\n\n // MARK: - NotificationProviderDelegate\n\n func notificationProviderDidInvalidate(_ notificationProvider: NotificationProvider) {\n dispatchPrecondition(condition: .onQueue(.main))\n\n // Invalidate system notification\n if let notificationProvider = notificationProvider as? SystemNotificationProvider {\n let notificationCenter = UNUserNotificationCenter.current()\n\n if notificationProvider.shouldRemovePendingRequests {\n notificationCenter.removePendingNotificationRequests(withIdentifiers: [\n notificationProvider.identifier.domainIdentifier,\n ])\n }\n\n if notificationProvider.shouldRemoveDeliveredRequests {\n notificationCenter.removeDeliveredNotifications(withIdentifiers: [\n notificationProvider.identifier.domainIdentifier,\n ])\n }\n\n if let request = notificationProvider.notificationRequest {\n requestNotificationPermissions { granted in\n guard granted else { return }\n\n notificationCenter.add(request) { error in\n if let error {\n self.logger.error(\n """\n Failed to add notification request with identifier \\n \(request.identifier). Error: \(error.localizedDescription)\n """\n )\n }\n }\n }\n }\n }\n\n invalidateInAppNotification(notificationProvider)\n }\n\n private func invalidateInAppNotification(_ notificationProvider: NotificationProvider) {\n if let notificationProvider = notificationProvider as? InAppNotificationProvider {\n var newNotificationDescriptors = inAppNotificationDescriptors\n\n if let replaceNotificationDescriptor = notificationProvider.notificationDescriptor {\n newNotificationDescriptors = notificationProviders\n .compactMap { notificationProvider -> InAppNotificationDescriptor? in\n if replaceNotificationDescriptor.identifier == notificationProvider.identifier {\n return replaceNotificationDescriptor\n } else {\n return inAppNotificationDescriptors.first { descriptor in\n descriptor.identifier == notificationProvider.identifier\n }\n }\n }\n } else {\n newNotificationDescriptors.removeAll { descriptor in\n descriptor.identifier == notificationProvider.identifier\n }\n }\n\n inAppNotificationDescriptors = newNotificationDescriptors\n\n delegate?.notificationManagerDidUpdateInAppNotifications(\n self,\n notifications: inAppNotificationDescriptors\n )\n }\n }\n\n func notificationProvider(_ notificationProvider: NotificationProvider, didReceiveAction actionIdentifier: String) {\n dispatchPrecondition(condition: .onQueue(.main))\n\n let notificationResponse = NotificationResponse(\n providerIdentifier: notificationProvider.identifier,\n actionIdentifier: actionIdentifier\n )\n\n delegate?.notificationManager(self, didReceiveResponse: notificationResponse)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\NotificationManager.swift | NotificationManager.swift | Swift | 9,845 | 0.95 | 0.086957 | 0.053922 | python-kit | 466 | 2023-12-10T10:13:46.206729 | GPL-3.0 | false | f67ad3e1853c6db3b1c90a4b85849c84 |
//\n// NotificationManagerDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol NotificationManagerDelegate: AnyObject {\n func notificationManagerDidUpdateInAppNotifications(\n _ manager: NotificationManager,\n notifications: [InAppNotificationDescriptor]\n )\n\n func notificationManager(_ manager: NotificationManager, didReceiveResponse: NotificationResponse)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\NotificationManagerDelegate.swift | NotificationManagerDelegate.swift | Swift | 493 | 0.95 | 0 | 0.466667 | awesome-app | 916 | 2024-10-21T21:31:26.712105 | GPL-3.0 | false | f265d812e02d712162f1f1c1cbfdaf2c |
//\n// NotificationProvider.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UserNotifications\n\n/// Notification provider delegate primarily used by `NotificationManager`.\nprotocol NotificationProviderDelegate: AnyObject {\n func notificationProviderDidInvalidate(_ notificationProvider: NotificationProvider)\n func notificationProvider(_ notificationProvider: NotificationProvider, didReceiveAction actionIdentifier: String)\n}\n\n/// Base class for all notification providers.\nclass NotificationProvider: NotificationProviderProtocol, @unchecked Sendable {\n weak var delegate: NotificationProviderDelegate?\n\n /**\n Provider identifier.\n\n Override in subclasses and make sure each provider has unique identifier. It's preferred that identifiers use\n reverse domain name, for instance: `com.example.app.ProviderName`.\n */\n var identifier: NotificationProviderIdentifier {\n .default\n }\n\n /**\n Default implementation for the priority property, setting it to `.low`.\n */\n var priority: NotificationPriority {\n .low\n }\n\n /**\n Send action to notification manager delegate.\n\n Usually in response to user interacting with notification banner, i.e by tapping a button. Use different action\n identifiers if notification offers more than one action that user can perform.\n */\n func sendAction(_ actionIdentifier: String = UNNotificationDefaultActionIdentifier) {\n dispatchOnMain {\n self.delegate?.notificationProvider(self, didReceiveAction: actionIdentifier)\n }\n }\n\n /**\n This method tells notification manager to re-evalute the notification content.\n Call this method when notification provider wants to change the content it presents.\n */\n func invalidate() {\n dispatchOnMain {\n self.delegate?.notificationProviderDidInvalidate(self)\n }\n }\n\n private func dispatchOnMain(_ block: @escaping @Sendable () -> Void) {\n if Thread.isMainThread {\n block()\n } else {\n DispatchQueue.main.async(execute: block)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\NotificationProvider.swift | NotificationProvider.swift | Swift | 2,209 | 0.95 | 0.102941 | 0.293103 | node-utils | 788 | 2024-03-13T22:23:02.935710 | Apache-2.0 | false | fb2d2df20f0ceb64248ccc175505a671 |
//\n// NotificationProviderIdentifier.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-05-10.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nenum NotificationPriority: Int, Comparable {\n case low = 1\n case medium = 2\n case high = 3\n case critical = 4\n\n static func < (lhs: NotificationPriority, rhs: NotificationPriority) -> Bool {\n return lhs.rawValue < rhs.rawValue\n }\n}\n\nenum NotificationProviderIdentifier: String {\n case accountExpirySystemNotification = "AccountExpiryNotification"\n case accountExpiryInAppNotification = "AccountExpiryInAppNotification"\n case registeredDeviceInAppNotification = "RegisteredDeviceInAppNotification"\n case tunnelStatusNotificationProvider = "TunnelStatusNotificationProvider"\n case latestChangesInAppNotificationProvider = "LatestChangesInAppNotificationProvider"\n case `default` = "default"\n\n var domainIdentifier: String {\n "net.mullvad.MullvadVPN.\(rawValue)"\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\NotificationProviderIdentifier.swift | NotificationProviderIdentifier.swift | Swift | 1,001 | 0.95 | 0 | 0.25 | react-lib | 305 | 2023-09-28T12:04:03.937701 | GPL-3.0 | false | f38f185045573a93ace9fdd5e397c1e6 |
//\n// NotificationProviderProtocol.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\n/// Base protocol for notification providers.\nprotocol NotificationProviderProtocol {\n /// Unique provider identifier used to identify notification providers and notifications\n /// produced by them.\n var identifier: NotificationProviderIdentifier { get }\n\n /// The priority level of the notification, used to determine the order in which notifications\n /// should be displayed. Higher priority notifications are displayed first.\n var priority: NotificationPriority { get }\n\n /// Tell notification manager to update the associated notification.\n func invalidate()\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\NotificationProviderProtocol.swift | NotificationProviderProtocol.swift | Swift | 771 | 0.95 | 0.043478 | 0.684211 | awesome-app | 893 | 2023-12-23T05:29:00.946133 | GPL-3.0 | false | 5e1c97a7f7369fa36b2d351a586438fb |
//\n// NotificationResponse.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/05/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UserNotifications\n\n/**\n Struct holding system or in-app notification response.\n */\nstruct NotificationResponse {\n /// Provider identifier.\n var providerIdentifier: NotificationProviderIdentifier\n\n /// Action identifier, i.e UNNotificationDefaultActionIdentifier or any custom.\n var actionIdentifier: String\n\n /// System notification response. Unset for in-app notifications.\n var systemResponse: UNNotificationResponse?\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\NotificationResponse.swift | NotificationResponse.swift | Swift | 620 | 0.95 | 0.041667 | 0.6 | node-utils | 259 | 2024-07-20T21:47:14.426110 | BSD-3-Clause | false | 167c773d6c6483fc7af521a8e67b2d11 |
//\n// SystemNotificationProvider.swift\n// MullvadVPN\n//\n// Created by pronebird on 09/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UserNotifications\n\n/// Protocol describing a system notification provider.\nprotocol SystemNotificationProvider: NotificationProviderProtocol {\n /// Notification request if available, otherwise `nil`.\n var notificationRequest: UNNotificationRequest? { get }\n\n /// Whether any pending requests should be removed.\n var shouldRemovePendingRequests: Bool { get }\n\n /// Whether any delivered requests should be removed.\n var shouldRemoveDeliveredRequests: Bool { get }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\SystemNotificationProvider.swift | SystemNotificationProvider.swift | Swift | 669 | 0.95 | 0.045455 | 0.611111 | vue-tools | 481 | 2024-01-30T18:59:16.942419 | GPL-3.0 | false | ab01e3f770fd8652fadaf5b2be58825a |
//\n// AccountExpiry.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-11-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nstruct AccountExpiry {\n enum Trigger {\n case system, inApp\n\n var dateIntervals: [Int] {\n switch self {\n case .system:\n NotificationConfiguration.closeToExpirySystemTriggerIntervals\n case .inApp:\n NotificationConfiguration.closeToExpiryInAppTriggerIntervals\n }\n }\n }\n\n private let calendar = Calendar.current\n\n var expiryDate: Date?\n\n func nextTriggerDate(for trigger: Trigger) -> Date? {\n let now = Date().secondsPrecision\n let triggerDates = triggerDates(for: trigger)\n\n // Get earliest trigger date and remove one day. Since we want to count whole days, If first\n // notification should trigger 3 days before account expiry, we need to start checking when\n // there's (less than) 4 days left.\n guard\n let expiryDate,\n let earliestDate = triggerDates.min(),\n let earliestTriggerDate = calendar.date(byAdding: .day, value: -1, to: earliestDate),\n now <= expiryDate.secondsPrecision,\n now > earliestTriggerDate.secondsPrecision\n else { return nil }\n\n let datesByTimeToTrigger = triggerDates.filter { date in\n now.secondsPrecision <= date.secondsPrecision // Ignore dates that have passed.\n }.sorted { date1, date2 in\n abs(date1.timeIntervalSince(now)) < abs(date2.timeIntervalSince(now))\n }\n\n return datesByTimeToTrigger.first\n }\n\n func daysRemaining(for trigger: Trigger) -> DateComponents? {\n let nextTriggerDate = nextTriggerDate(for: trigger)\n guard let expiryDate, let nextTriggerDate else { return nil }\n\n let dateComponents = calendar.dateComponents(\n [.day],\n from: Date().secondsPrecision,\n to: max(nextTriggerDate, expiryDate).secondsPrecision\n )\n\n return dateComponents\n }\n\n func triggerDates(for trigger: Trigger) -> [Date] {\n guard let expiryDate else { return [] }\n\n let dates = trigger.dateIntervals.compactMap {\n calendar.date(\n byAdding: .day,\n value: -$0,\n to: expiryDate\n )\n }\n\n return dates\n }\n}\n\nprivate extension Date {\n // Used to compare dates with a precision of a minimum of seconds.\n var secondsPrecision: Date {\n let dateComponents = Calendar.current.dateComponents(\n [.second, .minute, .hour, .day, .month, .year, .calendar],\n from: self\n )\n\n return dateComponents.date ?? self\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\Notification Providers\AccountExpiry.swift | AccountExpiry.swift | Swift | 2,796 | 0.95 | 0.065217 | 0.146667 | node-utils | 763 | 2024-01-11T16:26:05.380072 | MIT | false | 61beaa6053ca5991c173d4ce2e44abff |
//\n// AccountExpiryInAppNotificationProvider.swift\n// MullvadVPN\n//\n// Created by pronebird on 12/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n\nfinal class AccountExpiryInAppNotificationProvider: NotificationProvider, InAppNotificationProvider,\n @unchecked Sendable {\n private var accountExpiry = AccountExpiry()\n private var tunnelObserver: TunnelBlockObserver?\n private var timer: DispatchSourceTimer?\n\n init(tunnelManager: TunnelManager) {\n super.init()\n\n let tunnelObserver = TunnelBlockObserver(\n didLoadConfiguration: { [weak self] tunnelManager in\n self?.invalidate(deviceState: tunnelManager.deviceState)\n },\n didUpdateTunnelStatus: { [weak self] tunnelManager, _ in\n self?.invalidate(deviceState: tunnelManager.deviceState)\n },\n didUpdateDeviceState: { [weak self] _, deviceState, _ in\n self?.invalidate(deviceState: deviceState)\n }\n )\n self.tunnelObserver = tunnelObserver\n\n tunnelManager.addObserver(tunnelObserver)\n }\n\n override var identifier: NotificationProviderIdentifier {\n .accountExpiryInAppNotification\n }\n\n override var priority: NotificationPriority {\n .high\n }\n\n // MARK: - InAppNotificationProvider\n\n var notificationDescriptor: InAppNotificationDescriptor? {\n guard let durationText = remainingDaysText else {\n return nil\n }\n\n return InAppNotificationDescriptor(\n identifier: identifier,\n style: .warning,\n title: durationText,\n body: NSAttributedString(string: NSLocalizedString(\n "ACCOUNT_EXPIRY_IN_APP_NOTIFICATION_BODY",\n value: "You can add more time via the account view or website to continue using the VPN.",\n comment: "Title for in-app notification, displayed within the last X days until account expiry."\n ))\n )\n }\n\n // MARK: - Private\n\n private func invalidate(deviceState: DeviceState) {\n accountExpiry.expiryDate = deviceState.accountData?.expiry\n updateTimer()\n invalidate()\n }\n\n private func updateTimer() {\n timer?.cancel()\n\n guard let triggerDate = accountExpiry.nextTriggerDate(for: .inApp) else {\n return\n }\n\n let now = Date()\n let fireDate = max(now, triggerDate)\n\n let timer = DispatchSource.makeTimerSource(queue: .main)\n timer.setEventHandler { [weak self] in\n self?.timerDidFire()\n }\n timer.schedule(\n wallDeadline: .now() + fireDate.timeIntervalSince(now),\n repeating: .seconds(NotificationConfiguration.closeToExpiryInAppNotificationRefreshInterval)\n )\n timer.activate()\n\n self.timer = timer\n }\n\n private func timerDidFire() {\n let shouldCancelTimer = accountExpiry.expiryDate.map { $0 <= Date() } ?? true\n\n if shouldCancelTimer {\n timer?.cancel()\n }\n\n invalidate()\n }\n}\n\nextension AccountExpiryInAppNotificationProvider {\n private var remainingDaysText: String? {\n guard\n let expiryDate = accountExpiry.expiryDate,\n let nextTriggerDate = accountExpiry.nextTriggerDate(for: .inApp),\n let duration = CustomDateComponentsFormatting.localizedString(\n from: nextTriggerDate,\n to: expiryDate,\n unitsStyle: .full\n )\n else { return nil }\n\n return String(format: NSLocalizedString(\n "ACCOUNT_EXPIRY_IN_APP_NOTIFICATION_TITLE",\n tableName: "AccountExpiry",\n value: "%@ left on this account",\n comment: "Message for in-app notification, displayed within the last X days until account expiry."\n ), duration).uppercased()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\Notification Providers\AccountExpiryInAppNotificationProvider.swift | AccountExpiryInAppNotificationProvider.swift | Swift | 3,971 | 0.95 | 0.047619 | 0.086538 | awesome-app | 392 | 2025-06-25T18:15:43.124003 | GPL-3.0 | false | e93129ca7916a080c6d6c0480be1cae4 |
//\n// AccountExpirySystemNotificationProvider.swift\n// MullvadVPN\n//\n// Created by pronebird on 03/06/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport UserNotifications\n\nfinal class AccountExpirySystemNotificationProvider: NotificationProvider, SystemNotificationProvider,\n @unchecked Sendable {\n private var accountExpiry = AccountExpiry()\n private var tunnelObserver: TunnelBlockObserver?\n private var accountHasExpired = false\n\n init(tunnelManager: TunnelManager) {\n super.init()\n\n let tunnelObserver = TunnelBlockObserver(\n didLoadConfiguration: { [weak self] tunnelManager in\n self?.invalidate(deviceState: tunnelManager.deviceState)\n },\n didUpdateTunnelStatus: { [weak self] tunnelManager, _ in\n self?.checkAccountExpiry(\n tunnelStatus: tunnelManager.tunnelStatus,\n deviceState: tunnelManager.deviceState\n )\n },\n didUpdateDeviceState: { [weak self] _, deviceState, _ in\n if self?.accountHasExpired == false {\n self?.invalidate(deviceState: deviceState)\n }\n }\n )\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n }\n\n override var identifier: NotificationProviderIdentifier {\n .accountExpirySystemNotification\n }\n\n override var priority: NotificationPriority {\n .high\n }\n\n // MARK: - SystemNotificationProvider\n\n var notificationRequest: UNNotificationRequest? {\n let trigger = accountHasExpired ? triggerExpiry : triggerCloseToExpiry\n\n guard let trigger, let formattedRemainingDurationBody else {\n return nil\n }\n\n let content = UNMutableNotificationContent()\n content.title = formattedRemainingDurationTitle\n content.body = formattedRemainingDurationBody\n content.sound = .default\n\n return UNNotificationRequest(\n identifier: identifier.domainIdentifier,\n content: content,\n trigger: trigger\n )\n }\n\n var shouldRemovePendingRequests: Bool {\n // Remove pending notifications when account expiry is not set (user logged out)\n shouldRemovePendingOrDeliveredRequests\n }\n\n var shouldRemoveDeliveredRequests: Bool {\n // Remove delivered notifications when account expiry is not set (user logged out)\n shouldRemovePendingOrDeliveredRequests\n }\n\n // MARK: - Private\n\n private var triggerCloseToExpiry: UNNotificationTrigger? {\n guard let triggerDate = accountExpiry.nextTriggerDate(for: .system) else { return nil }\n\n let dateComponents = Calendar.current.dateComponents(\n [.second, .minute, .hour, .day, .month, .year],\n from: triggerDate\n )\n\n return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)\n }\n\n private var triggerExpiry: UNNotificationTrigger {\n // When scheduling a user notification we need to make sure that the date has not passed\n // when it's actually added to the system. Giving it a one second leeway lets us be sure\n // that this is the case.\n let dateComponents = Calendar.current.dateComponents(\n [.second, .minute, .hour, .day, .month, .year],\n from: Date().addingTimeInterval(1)\n )\n\n return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)\n }\n\n private var shouldRemovePendingOrDeliveredRequests: Bool {\n return accountExpiry.expiryDate == nil\n }\n\n private func checkAccountExpiry(tunnelStatus: TunnelStatus, deviceState: DeviceState) {\n if !accountHasExpired {\n if case .accountExpired = tunnelStatus.observedState.blockedState?.reason {\n accountHasExpired = true\n }\n\n if accountHasExpired {\n invalidate(deviceState: deviceState)\n }\n }\n }\n\n private func invalidate(deviceState: DeviceState) {\n accountExpiry.expiryDate = deviceState.accountData?.expiry\n invalidate()\n }\n}\n\nextension AccountExpirySystemNotificationProvider {\n private var formattedRemainingDurationTitle: String {\n accountHasExpired\n ? NSLocalizedString(\n "ACCOUNT_EXPIRY_SYSTEM_NOTIFICATION_TITLE",\n tableName: "AccountExpiry",\n value: "Account credit has expired",\n comment: "Title for system account expiry notification, fired on account expiry."\n )\n : NSLocalizedString(\n "ACCOUNT_EXPIRY_SYSTEM_NOTIFICATION_TITLE",\n tableName: "AccountExpiry",\n value: "Account credit expires soon",\n comment: "Title for system account expiry notification, fired X days prior to account expiry."\n )\n }\n\n private var formattedRemainingDurationBody: String? {\n guard !accountHasExpired else { return expiredText }\n\n switch accountExpiry.daysRemaining(for: .system)?.day {\n case .none:\n return nil\n case 1:\n return singleDayText\n default:\n return multipleDaysText\n }\n }\n\n private var expiredText: String {\n NSLocalizedString(\n "ACCOUNT_EXPIRY_SYSTEM_NOTIFICATION_BODY",\n tableName: "AccountExpiry",\n value: """\n Blocking internet: Your time on this account has expired. To continue using the internet, \\n please add more time or disconnect the VPN.\n """,\n comment: "Message for in-app notification, displayed on account expiry while connected to VPN."\n )\n }\n\n private var singleDayText: String {\n NSLocalizedString(\n "ACCOUNT_EXPIRY_SYSTEM_NOTIFICATION_BODY",\n tableName: "AccountExpiry",\n value: "You have one day left on this account. Please add more time to continue using the VPN.",\n comment: "Message for in-app notification, displayed within the last 1 day until account expiry."\n )\n }\n\n private var multipleDaysText: String? {\n guard\n let expiryDate = accountExpiry.expiryDate,\n let nextTriggerDate = accountExpiry.nextTriggerDate(for: .system),\n let duration = CustomDateComponentsFormatting.localizedString(\n from: nextTriggerDate,\n to: expiryDate,\n unitsStyle: .full\n )\n else { return nil }\n\n return String(format: NSLocalizedString(\n "ACCOUNT_EXPIRY_SYSTEM_NOTIFICATION_BODY",\n tableName: "AccountExpiry",\n value: "You have %@ left on this account.",\n comment: "Message for in-app notification, displayed within the last X days until account expiry."\n ), duration.lowercased())\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\Notification Providers\AccountExpirySystemNotificationProvider.swift | AccountExpirySystemNotificationProvider.swift | Swift | 7,001 | 0.95 | 0.075377 | 0.083832 | awesome-app | 527 | 2023-11-06T13:52:54.994727 | MIT | false | 44a09b26dd2131c6ee6ef3be731dc8d9 |
//\n// NewDeviceNotificationProvider.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-04-21.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport UIKit.UIColor\nimport UIKit.UIFont\n\nfinal class NewDeviceNotificationProvider: NotificationProvider,\n InAppNotificationProvider, @unchecked Sendable {\n // MARK: - private properties\n\n private let tunnelManager: TunnelManager\n\n private var storedDeviceData: StoredDeviceData? {\n tunnelManager.deviceState.deviceData\n }\n\n private var tunnelObserver: TunnelBlockObserver?\n private var isNewDeviceRegistered = false\n\n private var attributedBody: NSAttributedString {\n let formattedString = NSLocalizedString(\n "ACCOUNT_CREATION_INAPP_NOTIFICATION_BODY",\n value: "Welcome, this device is now called **%@**. For more details see the info button in Account.",\n comment: ""\n )\n let deviceName = storedDeviceData?.capitalizedName ?? ""\n let string = String(format: formattedString, deviceName)\n\n let stylingOptions = MarkdownStylingOptions(font: .systemFont(ofSize: 14.0))\n\n return NSAttributedString(markdownString: string, options: stylingOptions) { markdownType, _ in\n if case .bold = markdownType {\n return [.foregroundColor: UIColor.InAppNotificationBanner.titleColor]\n } else {\n return [:]\n }\n }\n }\n\n // MARK: - public properties\n\n var notificationDescriptor: InAppNotificationDescriptor? {\n guard isNewDeviceRegistered else { return nil }\n return InAppNotificationDescriptor(\n identifier: identifier,\n style: .success,\n title: NSLocalizedString(\n "ACCOUNT_CREATION_INAPP_NOTIFICATION_TITLE",\n value: "NEW DEVICE CREATED",\n comment: ""\n ),\n body: attributedBody,\n button: InAppNotificationAction(\n image: UIImage.Buttons.closeSmall,\n handler: { [weak self] in\n guard let self else { return }\n isNewDeviceRegistered = false\n sendAction()\n invalidate()\n }\n )\n )\n }\n\n // MARK: - initialize\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n super.init()\n addObservers()\n }\n\n override var identifier: NotificationProviderIdentifier {\n .registeredDeviceInAppNotification\n }\n\n override var priority: NotificationPriority {\n .medium\n }\n\n private func addObservers() {\n tunnelObserver =\n TunnelBlockObserver(didUpdateDeviceState: { [weak self] _, deviceState, previousDeviceState in\n if previousDeviceState == .loggedOut,\n case .loggedIn = deviceState {\n self?.isNewDeviceRegistered = true\n DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1)) { [weak self] in\n self?.invalidate()\n }\n\n } else if case .loggedIn = previousDeviceState,\n deviceState == .loggedOut || deviceState == .revoked {\n self?.isNewDeviceRegistered = false\n self?.invalidate()\n }\n })\n tunnelObserver.flatMap { tunnelManager.addObserver($0) }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\Notification Providers\NewDeviceNotificationProvider.swift | NewDeviceNotificationProvider.swift | Swift | 3,504 | 0.95 | 0.037736 | 0.111111 | python-kit | 587 | 2024-04-29T02:10:00.114483 | MIT | false | ae884e43b57136a10c7c51bbfa1435a5 |
//\n// NotificationConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 27/04/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nenum NotificationConfiguration {\n /**\n Duration measured in days, before the account expiry, when a system notification is scheduled to remind user\n to add more time on account.\n */\n static let closeToExpirySystemTriggerIntervals = [3, 1]\n\n /**\n Duration measured in days, before the account expiry, when an in-app notification is scheduled to remind user\n to add more time on account.\n */\n static let closeToExpiryInAppTriggerIntervals: [Int] = [3, 2, 1, 0]\n\n /**\n Time interval measured in seconds at which to refresh account expiry in-app notification, which reformats\n the duration until account expiry over time.\n */\n static let closeToExpiryInAppNotificationRefreshInterval = 60\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\Notification Providers\NotificationConfiguration.swift | NotificationConfiguration.swift | Swift | 920 | 0.95 | 0 | 0.52 | vue-tools | 394 | 2024-03-11T12:41:34.515120 | Apache-2.0 | false | 22d8e7200d1582b4b3c7ac813c5b821a |
//\n// TunnelStatusNotificationProvider.swift\n// TunnelStatusNotificationProvider\n//\n// Created by pronebird on 20/08/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport PacketTunnelCore\n\nfinal class TunnelStatusNotificationProvider: NotificationProvider, InAppNotificationProvider, @unchecked Sendable {\n private var isWaitingForConnectivity = false\n private var noNetwork = false\n private var packetTunnelError: BlockedStateReason?\n private var tunnelManagerError: Error?\n private var tunnelObserver: TunnelBlockObserver?\n\n override var identifier: NotificationProviderIdentifier {\n .tunnelStatusNotificationProvider\n }\n\n override var priority: NotificationPriority {\n .critical\n }\n\n var notificationDescriptor: InAppNotificationDescriptor? {\n if let packetTunnelError {\n return notificationDescription(for: packetTunnelError)\n } else if let tunnelManagerError {\n return notificationDescription(for: tunnelManagerError)\n } else if isWaitingForConnectivity {\n return connectivityNotificationDescription()\n } else if noNetwork {\n return noNetworkNotificationDescription()\n } else {\n return nil\n }\n }\n\n init(tunnelManager: TunnelManager) {\n super.init()\n\n let tunnelObserver = TunnelBlockObserver(\n didLoadConfiguration: { [weak self] tunnelManager in\n self?.handleTunnelStatus(tunnelManager.tunnelStatus)\n },\n didUpdateTunnelStatus: { [weak self] _, tunnelStatus in\n self?.handleTunnelStatus(tunnelStatus)\n },\n didFailWithError: { [weak self] _, error in\n self?.tunnelManagerError = error\n }\n )\n self.tunnelObserver = tunnelObserver\n\n tunnelManager.addObserver(tunnelObserver)\n }\n\n // MARK: - Private\n\n private func handleTunnelStatus(_ tunnelStatus: TunnelStatus) {\n let invalidateForTunnelError = updateLastTunnelError(tunnelStatus.state)\n let invalidateForManagerError = updateTunnelManagerError(tunnelStatus.state)\n let invalidateForConnectivity = updateConnectivity(tunnelStatus.state)\n let invalidateForNetwork = updateNetwork(tunnelStatus.state)\n\n if invalidateForTunnelError || invalidateForManagerError || invalidateForConnectivity || invalidateForNetwork {\n invalidate()\n }\n }\n\n private func updateLastTunnelError(_ tunnelState: TunnelState) -> Bool {\n let lastTunnelError = tunnelError(from: tunnelState)\n\n if packetTunnelError != lastTunnelError {\n packetTunnelError = lastTunnelError\n\n return true\n }\n\n return false\n }\n\n private func updateConnectivity(_ tunnelState: TunnelState) -> Bool {\n let isWaitingState = tunnelState == .waitingForConnectivity(.noConnection)\n\n if isWaitingForConnectivity != isWaitingState {\n isWaitingForConnectivity = isWaitingState\n return true\n }\n\n return false\n }\n\n private func updateNetwork(_ tunnelState: TunnelState) -> Bool {\n let isWaitingState = tunnelState == .waitingForConnectivity(.noNetwork)\n\n if noNetwork != isWaitingState {\n noNetwork = isWaitingState\n return true\n }\n\n return false\n }\n\n private func updateTunnelManagerError(_ tunnelState: TunnelState) -> Bool {\n switch tunnelState {\n case .connecting, .connected, .reconnecting:\n // As of now, tunnel manager error can be received only when starting or stopping\n // the tunnel. Make sure to reset it on each connection attempt.\n if tunnelManagerError != nil {\n tunnelManagerError = nil\n return true\n }\n\n default:\n break\n }\n\n return false\n }\n\n // Extracts the blocked state reason from tunnel state with a few exceptions.\n // We already have dedicated screens for .accountExpired and .deviceRevoked,\n // so no need to show banners as well.\n private func tunnelError(from tunnelState: TunnelState) -> BlockedStateReason? {\n let errorsToIgnore: [BlockedStateReason] = [.accountExpired, .deviceRevoked]\n\n if case let .error(blockedStateReason) = tunnelState, !errorsToIgnore.contains(blockedStateReason) {\n return blockedStateReason\n }\n\n return nil\n }\n\n private func notificationDescription(for packetTunnelError: BlockedStateReason) -> InAppNotificationDescriptor {\n InAppNotificationDescriptor(\n identifier: identifier,\n style: .error,\n title: NSLocalizedString(\n "TUNNEL_BLOCKED_INAPP_NOTIFICATION_TITLE",\n value: "BLOCKING INTERNET",\n comment: ""\n ),\n body: .init(string: String(\n format: NSLocalizedString(\n "TUNNEL_BLOCKED_INAPP_NOTIFICATION_BODY",\n value: localizedReasonForBlockedStateError(packetTunnelError),\n comment: ""\n )\n ))\n )\n }\n\n private func notificationDescription(for error: Error) -> InAppNotificationDescriptor {\n let body: String\n\n if let startError = error as? StartTunnelError {\n body = String(\n format: NSLocalizedString(\n "START_TUNNEL_ERROR_INAPP_NOTIFICATION_BODY",\n value: "Failed to start the tunnel: %@.",\n comment: ""\n ),\n startError.underlyingError?.localizedDescription ?? ""\n )\n } else if let stopError = error as? StopTunnelError {\n body = String(\n format: NSLocalizedString(\n "STOP_TUNNEL_ERROR_INAPP_NOTIFICATION_BODY",\n value: "Failed to stop the tunnel: %@.",\n comment: ""\n ),\n stopError.underlyingError?.localizedDescription ?? ""\n )\n } else {\n body = error.localizedDescription\n }\n\n return InAppNotificationDescriptor(\n identifier: identifier,\n style: .error,\n title: NSLocalizedString(\n "TUNNEL_MANAGER_ERROR_INAPP_NOTIFICATION_TITLE",\n value: "TUNNEL ERROR",\n comment: ""\n ),\n body: .init(string: body)\n )\n }\n\n private func connectivityNotificationDescription() -> InAppNotificationDescriptor {\n InAppNotificationDescriptor(\n identifier: identifier,\n style: .warning,\n title: NSLocalizedString(\n "TUNNEL_NO_CONNECTIVITY_INAPP_NOTIFICATION_TITLE",\n value: "NETWORK ISSUES",\n comment: ""\n ),\n body: .init(\n string: NSLocalizedString(\n "TUNNEL_NO_CONNECTIVITY_INAPP_NOTIFICATION_BODY",\n value: """\n Your device is offline. The tunnel will automatically connect once \\n your device is back online.\n """,\n comment: ""\n )\n )\n )\n }\n\n private func noNetworkNotificationDescription() -> InAppNotificationDescriptor {\n InAppNotificationDescriptor(\n identifier: identifier,\n style: .warning,\n title: NSLocalizedString(\n "TUNNEL_NO_NETWORK_INAPP_NOTIFICATION_TITLE",\n value: "NETWORK ISSUES",\n comment: ""\n ),\n body: .init(\n string: NSLocalizedString(\n "TUNNEL_NO_NETWORK_INAPP_NOTIFICATION_BODY",\n value: """\n Your device is offline. Try connecting again when the device \\n has access to Internet.\n """,\n comment: ""\n )\n )\n )\n }\n\n private func localizedReasonForBlockedStateError(_ error: BlockedStateReason) -> String {\n let errorString: String\n\n switch error {\n case .outdatedSchema:\n errorString = "Unable to start tunnel connection after update. Please disconnect and reconnect."\n case .noRelaysSatisfyingFilterConstraints:\n errorString = "No servers match your location filter. Try changing filter settings."\n case .multihopEntryEqualsExit:\n errorString = "The entry and exit servers cannot be the same. Try changing one to a new server or location."\n case .noRelaysSatisfyingDaitaConstraints:\n errorString = "No DAITA compatible servers match your location settings. Try changing location."\n case .noRelaysSatisfyingConstraints:\n errorString = "No servers match your settings, try changing server or other settings."\n case .invalidAccount:\n errorString = "You are logged in with an invalid account number. Please log out and try another one."\n case .deviceLoggedOut:\n errorString = "Unable to authenticate account. Please log out and log back in."\n default:\n errorString = "Unable to start tunnel connection. Please send a problem report."\n }\n\n return NSLocalizedString(\n "BLOCKED_STATE_ERROR_TITLE",\n tableName: "Main",\n value: errorString,\n comment: ""\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\Notification Providers\TunnelStatusNotificationProvider.swift | TunnelStatusNotificationProvider.swift | Swift | 9,571 | 0.95 | 0.082707 | 0.056522 | node-utils | 681 | 2023-07-21T20:21:01.396309 | GPL-3.0 | false | d840368b8ae06070d734ba4374daba2b |
//\n// NotificationBannerView.swift\n// MullvadVPN\n//\n// Created by pronebird on 01/06/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nfinal class NotificationBannerView: UIView {\n private let backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))\n\n private let titleLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17, weight: .bold)\n textLabel.textColor = UIColor.InAppNotificationBanner.titleColor\n textLabel.numberOfLines = 0\n textLabel.lineBreakMode = .byWordWrapping\n textLabel.lineBreakStrategy = []\n return textLabel\n }()\n\n private let bodyLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.systemFont(ofSize: 17)\n textLabel.textColor = UIColor.InAppNotificationBanner.bodyColor\n textLabel.numberOfLines = 0\n textLabel.lineBreakMode = .byWordWrapping\n textLabel.lineBreakStrategy = []\n return textLabel\n }()\n\n private let indicatorView: UIView = {\n let view = UIView()\n view.backgroundColor = .dangerColor\n view.layer.cornerRadius = UIMetrics.InAppBannerNotification.indicatorSize.width * 0.5\n view.layer.cornerCurve = .circular\n return view\n }()\n\n private let wrapperView: UIView = {\n let view = UIView()\n view.directionalLayoutMargins = UIMetrics.InAppBannerNotification.layoutMargins\n return view\n }()\n\n private lazy var bodyStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [titleLabel, bodyLabel])\n stackView.alignment = .top\n stackView.distribution = .fill\n stackView.axis = .vertical\n stackView.spacing = UIStackView.spacingUseSystem\n return stackView\n }()\n\n private lazy var contentStackView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [bodyStackView, actionButton])\n stackView.spacing = UIStackView.spacingUseSystem\n stackView.alignment = .center\n return stackView\n }()\n\n private let actionButton: IncreasedHitButton = {\n let button = IncreasedHitButton(type: .system)\n button.tintColor = UIColor.InAppNotificationBanner.actionButtonColor\n return button\n }()\n\n var title: String? {\n didSet {\n titleLabel.text = title\n }\n }\n\n var body: NSAttributedString? {\n didSet {\n bodyLabel.attributedText = body\n }\n }\n\n var style: NotificationBannerStyle = .error {\n didSet {\n indicatorView.backgroundColor = style.color\n }\n }\n\n var action: InAppNotificationAction? {\n didSet {\n let image = action?.image\n let showsAction = image != nil\n\n actionButton.setBackgroundImage(image, for: .normal)\n actionButton.widthAnchor.constraint(equalToConstant: 24).isActive = true\n actionButton.heightAnchor.constraint(equalTo: actionButton.widthAnchor).isActive = true\n actionButton.isHidden = !showsAction\n }\n }\n\n var tapAction: InAppNotificationAction?\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n addSubviews()\n addTapHandler()\n addActionHandlers()\n addConstraints()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n private func addTapHandler() {\n let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))\n addGestureRecognizer(tapGesture)\n }\n\n private func addActionHandlers() {\n actionButton.addTarget(self, action: #selector(handleActionTap), for: .touchUpInside)\n }\n\n @objc\n private func handleTap() {\n tapAction?.handler?()\n }\n\n private func addSubviews() {\n wrapperView.addConstrainedSubviews([indicatorView, contentStackView])\n backgroundView.contentView.addConstrainedSubviews([wrapperView]) {\n wrapperView.pinEdgesToSuperview()\n }\n addConstrainedSubviews([backgroundView]) {\n backgroundView.pinEdgesToSuperview()\n }\n }\n\n private func addConstraints() {\n NSLayoutConstraint.activate([\n indicatorView.bottomAnchor.constraint(equalTo: titleLabel.firstBaselineAnchor),\n indicatorView.leadingAnchor.constraint(equalTo: wrapperView.layoutMarginsGuide.leadingAnchor),\n indicatorView.widthAnchor\n .constraint(equalToConstant: UIMetrics.InAppBannerNotification.indicatorSize.width),\n indicatorView.heightAnchor\n .constraint(equalToConstant: UIMetrics.InAppBannerNotification.indicatorSize.height),\n\n contentStackView.topAnchor.constraint(equalTo: wrapperView.layoutMarginsGuide.topAnchor),\n contentStackView.leadingAnchor.constraint(\n equalToSystemSpacingAfter: indicatorView.trailingAnchor,\n multiplier: 1\n ),\n contentStackView.trailingAnchor.constraint(equalTo: wrapperView.layoutMarginsGuide.trailingAnchor),\n contentStackView.bottomAnchor.constraint(equalTo: wrapperView.layoutMarginsGuide.bottomAnchor),\n ])\n }\n\n @objc private func handleActionTap() {\n action?.handler?()\n }\n}\n\nprivate extension NotificationBannerStyle {\n var color: UIColor {\n switch self {\n case .success:\n return UIColor.InAppNotificationBanner.successIndicatorColor\n case .warning:\n return UIColor.InAppNotificationBanner.warningIndicatorColor\n case .error:\n return UIColor.InAppNotificationBanner.errorIndicatorColor\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\UI\NotificationBannerView.swift | NotificationBannerView.swift | Swift | 5,746 | 0.95 | 0.023121 | 0.047297 | node-utils | 90 | 2024-05-26T14:55:01.101655 | BSD-3-Clause | false | 01ea8e50ae3c034583935542f03773f6 |
//\n// NotificationContainerView.swift\n// MullvadVPN\n//\n// Created by pronebird on 03/06/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nfinal class NotificationContainerView: UIView {\n override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {\n let hitView = super.hitTest(point, with: event)\n\n // Pass through taps if no subview was touched\n if hitView == self {\n return nil\n } else {\n return hitView\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\UI\NotificationContainerView.swift | NotificationContainerView.swift | Swift | 527 | 0.95 | 0.136364 | 0.421053 | node-utils | 621 | 2025-05-03T19:45:06.893474 | MIT | false | 72e3f7c152c4fb543219ccf38ba90426 |
//\n// NotificationController.swift\n// MullvadVPN\n//\n// Created by pronebird on 01/06/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nfinal class NotificationController: UIViewController {\n let bannerView: NotificationBannerView = {\n let bannerView = NotificationBannerView()\n bannerView.translatesAutoresizingMaskIntoConstraints = false\n bannerView.isAccessibilityElement = true\n return bannerView\n }()\n\n private var showBannerConstraint: NSLayoutConstraint?\n private var hideBannerConstraint: NSLayoutConstraint?\n\n private(set) var showsBanner = false\n private var lastNotification: InAppNotificationDescriptor?\n\n override func loadView() {\n view = NotificationContainerView(frame: UIScreen.main.bounds)\n view.clipsToBounds = true\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n showBannerConstraint = bannerView.topAnchor.constraint(equalTo: view.topAnchor)\n hideBannerConstraint = bannerView.bottomAnchor.constraint(equalTo: view.topAnchor)\n\n view.addSubview(bannerView)\n\n let verticalConstraint = showsBanner ? showBannerConstraint : hideBannerConstraint\n NSLayoutConstraint.activate([\n verticalConstraint!,\n bannerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\n bannerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\n ])\n }\n\n override func viewDidLayoutSubviews() {\n super.viewDidLayoutSubviews()\n\n updateAccessibilityFrame()\n }\n\n func toggleBanner(show: Bool, animated: Bool, completion: (() -> Void)? = nil) {\n guard showsBanner != show else {\n completion?()\n return\n }\n\n showsBanner = show\n\n if show {\n // Make sure to lay out the banner before animating its appearance to\n // avoid undesired horizontal expansion animation.\n view.layoutIfNeeded()\n\n hideBannerConstraint?.isActive = false\n showBannerConstraint?.isActive = true\n } else {\n showBannerConstraint?.isActive = false\n hideBannerConstraint?.isActive = true\n }\n\n if animated {\n let timing = UISpringTimingParameters(\n dampingRatio: 0.7,\n initialVelocity: CGVector(dx: 0, dy: 1)\n )\n let animator = UIViewPropertyAnimator(duration: 0.8, timingParameters: timing)\n animator.isInterruptible = false\n animator.addAnimations {\n self.view.layoutIfNeeded()\n }\n animator.addCompletion { _ in\n completion?()\n }\n animator.startAnimation()\n } else {\n view.layoutIfNeeded()\n completion?()\n }\n }\n\n func setNotification(_ notification: InAppNotificationDescriptor, animated: Bool) {\n guard lastNotification != notification else { return }\n\n lastNotification = notification\n\n bannerView.title = notification.title\n bannerView.body = notification.body\n bannerView.style = notification.style\n bannerView.action = notification.button\n bannerView.tapAction = notification.tapAction\n bannerView.accessibilityLabel = "\(notification.title)\n\(notification.body.string)"\n\n // Do not emit the .layoutChanged unless the banner is focused to avoid capturing\n // the voice over focus.\n if bannerView.accessibilityElementIsFocused() {\n UIAccessibility.post(notification: .layoutChanged, argument: bannerView)\n }\n }\n\n func setNotifications(_ notifications: [InAppNotificationDescriptor], animated: Bool) {\n let nextNotification = notifications.first\n\n if let notification = nextNotification {\n setNotification(notification, animated: showsBanner)\n toggleBanner(show: true, animated: true)\n } else {\n lastNotification = nil\n toggleBanner(show: false, animated: animated)\n }\n }\n\n private func updateAccessibilityFrame() {\n let layoutFrame = bannerView.layoutMarginsGuide.layoutFrame\n bannerView.accessibilityFrame = UIAccessibility.convertToScreenCoordinates(\n layoutFrame,\n in: view\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Notifications\UI\NotificationController.swift | NotificationController.swift | Swift | 4,353 | 0.95 | 0.038462 | 0.102804 | awesome-app | 704 | 2025-03-22T13:31:30.283481 | BSD-3-Clause | false | ba8e45aa87cdc7c2104e32771fd1c1cb |
//\n// ProductsRequestOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 02/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport Operations\nimport StoreKit\n\nfinal class ProductsRequestOperation: ResultOperation<SKProductsResponse>,\n SKProductsRequestDelegate, @unchecked Sendable {\n private let productIdentifiers: Set<String>\n\n private let maxRetryCount = 10\n private let retryDelay: Duration = .seconds(2)\n\n private var retryCount = 0\n private var retryTimer: DispatchSourceTimer?\n private var request: SKProductsRequest?\n\n init(productIdentifiers: Set<String>, completionHandler: @escaping CompletionHandler) {\n self.productIdentifiers = productIdentifiers\n\n super.init(\n dispatchQueue: .main,\n completionQueue: .main,\n completionHandler: completionHandler\n )\n }\n\n override func main() {\n startRequest()\n }\n\n override func operationDidCancel() {\n request?.cancel()\n retryTimer?.cancel()\n }\n\n // - MARK: SKProductsRequestDelegate\n\n func requestDidFinish(_ request: SKRequest) {\n // no-op\n }\n\n func request(_ request: SKRequest, didFailWithError error: Error) {\n dispatchQueue.async {\n if self.retryCount < self.maxRetryCount, !self.isCancelled {\n self.retryCount += 1\n self.retry(error: error)\n } else {\n self.finish(result: .failure(error))\n }\n }\n }\n\n func productsRequest(\n _ request: SKProductsRequest,\n didReceive response: SKProductsResponse\n ) {\n finish(result: .success(response))\n }\n\n // MARK: - Private\n\n private func startRequest() {\n request = SKProductsRequest(productIdentifiers: productIdentifiers)\n request?.delegate = self\n request?.start()\n }\n\n private func retry(error: Error) {\n retryTimer = DispatchSource.makeTimerSource(flags: [], queue: .main)\n\n retryTimer?.setEventHandler { [weak self] in\n self?.startRequest()\n }\n\n retryTimer?.setCancelHandler { [weak self] in\n self?.finish(result: .failure(error))\n }\n\n retryTimer?.schedule(wallDeadline: .now() + retryDelay)\n retryTimer?.activate()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Operations\ProductsRequestOperation.swift | ProductsRequestOperation.swift | Swift | 2,340 | 0.95 | 0.022472 | 0.140845 | react-lib | 777 | 2025-01-14T03:46:44.096357 | BSD-3-Clause | false | da3b561515ed34a20bb2a26f9689c565 |
//\n// FormSheetPresentationController.swift\n// MullvadVPN\n//\n// Created by pronebird on 18/02/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport UIKit\nstruct FormSheetPresentationOptions {\n /**\n Indicates whether the presentation controller should use a fullscreen presentation when in a compact width environment\n */\n var useFullScreenPresentationInCompactWidth = false\n\n /**\n Indicates whether the presentation controller should handle keyboard notifications\n */\n var adjustViewWhenKeyboardAppears = false\n}\n\n/**\n Custom implementation of a formsheet presentation controller.\n */\nclass FormSheetPresentationController: UIPresentationController {\n /**\n Name of notification posted when fullscreen presentation changes, including during initial presentation.\n */\n static let willChangeFullScreenPresentation = Notification\n .Name(rawValue: "FormSheetPresentationControllerWillChangeFullScreenPresentation")\n\n /**\n User info key passed along with `willChangeFullScreenPresentation` notification that contains boolean value that\n indicates if presentation controller is using fullscreen presentation.\n */\n static let isFullScreenUserInfoKey = "isFullScreen"\n\n /**\n Last known presentation style used to prevent emitting duplicate `willChangeFullScreenPresentation` notifications.\n */\n private var lastKnownIsInFullScreen: Bool?\n\n /**\n Change the position of `presentedView` if `FormSheetPresentationOptions.adjustViewWhenKeyboardAppears` is `true`\n */\n private var keyboardResponder: AutomaticKeyboardResponder?\n\n private let dimmingView: UIView = {\n let dimmingView = UIView()\n dimmingView.backgroundColor = UIMetrics.DimmingView.backgroundColor\n return dimmingView\n }()\n\n override var shouldRemovePresentersView: Bool {\n false\n }\n\n /**\n Returns `true` if presentation controller is in fullscreen presentation.\n */\n var isInFullScreenPresentation: Bool {\n options.useFullScreenPresentationInCompactWidth &&\n traitCollection.horizontalSizeClass == .compact\n }\n\n private let options: FormSheetPresentationOptions\n\n init(\n presentedViewController: UIViewController,\n presenting presentingViewController: UIViewController?,\n options: FormSheetPresentationOptions\n ) {\n self.options = options\n super.init(presentedViewController: presentedViewController, presenting: presentingViewController)\n addKeyboardResponderIfNeeded()\n }\n\n override var frameOfPresentedViewInContainerView: CGRect {\n guard let containerView else {\n return super.frameOfPresentedViewInContainerView\n }\n\n if isInFullScreenPresentation {\n return containerView.bounds\n }\n\n let preferredContentSize = presentedViewController.preferredContentSize\n\n assert(preferredContentSize.width > 0 && preferredContentSize.height > 0)\n\n return CGRect(\n origin: CGPoint(\n x: containerView.bounds.midX - preferredContentSize.width * 0.5,\n y: containerView.bounds.midY - preferredContentSize.height * 0.5\n ),\n size: preferredContentSize\n )\n }\n\n override func containerViewWillLayoutSubviews() {\n dimmingView.frame = containerView?.bounds ?? .zero\n presentedView?.frame = frameOfPresentedViewInContainerView\n }\n\n override func presentationTransitionWillBegin() {\n dimmingView.alpha = 0\n containerView?.addSubview(dimmingView)\n\n presentedView?.layer.cornerRadius = UIMetrics.DimmingView.cornerRadius\n presentedView?.clipsToBounds = true\n\n let revealDimmingView = {\n self.dimmingView.alpha = UIMetrics.DimmingView.opacity\n }\n\n if let transitionCoordinator = presentingViewController.transitionCoordinator {\n transitionCoordinator.animate { _ in\n revealDimmingView()\n }\n } else {\n revealDimmingView()\n }\n\n postFullscreenPresentationWillChangeIfNeeded()\n }\n\n override func presentationTransitionDidEnd(_ completed: Bool) {\n if !completed {\n dimmingView.removeFromSuperview()\n }\n }\n\n override func dismissalTransitionWillBegin() {\n let fadeDimmingView = {\n self.dimmingView.alpha = 0\n }\n\n if let transitionCoordinator = presentingViewController.transitionCoordinator {\n transitionCoordinator.animate { _ in\n fadeDimmingView()\n }\n } else {\n fadeDimmingView()\n }\n }\n\n override func dismissalTransitionDidEnd(_ completed: Bool) {\n if completed {\n dimmingView.removeFromSuperview()\n }\n }\n\n override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {\n super.traitCollectionDidChange(previousTraitCollection)\n\n postFullscreenPresentationWillChangeIfNeeded()\n }\n\n private func postFullscreenPresentationWillChangeIfNeeded() {\n let currentIsInFullScreen = isInFullScreenPresentation\n\n guard lastKnownIsInFullScreen != currentIsInFullScreen else { return }\n\n lastKnownIsInFullScreen = currentIsInFullScreen\n\n NotificationCenter.default.post(\n name: Self.willChangeFullScreenPresentation,\n object: presentedViewController,\n userInfo: [Self.isFullScreenUserInfoKey: NSNumber(value: currentIsInFullScreen)]\n )\n }\n\n private func addKeyboardResponderIfNeeded() {\n guard options.adjustViewWhenKeyboardAppears,\n let presentedView else { return }\n keyboardResponder = AutomaticKeyboardResponder(\n targetView: presentedView,\n handler: { [weak self] view, adjustment in\n guard let self,\n let containerView,\n !isInFullScreenPresentation else { return }\n let frame = view.frame\n let bottomMarginFromKeyboard = adjustment > 0 ? UIMetrics.TableView.sectionSpacing : 0\n view.frame = CGRect(\n origin: CGPoint(\n x: frame.origin.x,\n y: containerView.bounds.midY - presentedViewController.preferredContentSize\n .height * 0.5 - adjustment - bottomMarginFromKeyboard\n ),\n size: frame.size\n )\n view.layoutIfNeeded()\n }\n )\n }\n}\n\nclass FormSheetTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate {\n let options: FormSheetPresentationOptions\n\n init(options: FormSheetPresentationOptions = FormSheetPresentationOptions()) {\n self.options = options\n }\n\n func animationController(\n forPresented presented: UIViewController,\n presenting: UIViewController,\n source: UIViewController\n ) -> UIViewControllerAnimatedTransitioning? {\n FormSheetPresentationAnimator()\n }\n\n func animationController(forDismissed dismissed: UIViewController)\n -> UIViewControllerAnimatedTransitioning? {\n FormSheetPresentationAnimator()\n }\n\n func presentationController(\n forPresented presented: UIViewController,\n presenting: UIViewController?,\n source: UIViewController\n ) -> UIPresentationController? {\n FormSheetPresentationController(\n presentedViewController: presented,\n presenting: source,\n options: options\n )\n }\n}\n\nclass FormSheetPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning {\n func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?)\n -> TimeInterval {\n (transitionContext?.isAnimated ?? true) ? UIMetrics.FormSheetTransition.duration.timeInterval : 0\n }\n\n func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {\n let destination = transitionContext.viewController(forKey: .to)\n\n if destination?.isBeingPresented ?? false {\n animatePresentation(transitionContext)\n } else {\n animateDismissal(transitionContext)\n }\n }\n\n private func animatePresentation(_ transitionContext: UIViewControllerContextTransitioning) {\n let duration = transitionDuration(using: transitionContext)\n let containerView = transitionContext.containerView\n let destinationView = transitionContext.view(forKey: .to)!\n let destinationController = transitionContext.viewController(forKey: .to)!\n\n containerView.addSubview(destinationView)\n\n var initialFrame = transitionContext.finalFrame(for: destinationController)\n initialFrame.origin.y = containerView.bounds.maxY\n destinationView.frame = initialFrame\n\n if transitionContext.isAnimated {\n UIView.animate(\n withDuration: duration,\n delay: UIMetrics.FormSheetTransition.delay.timeInterval,\n options: UIMetrics.FormSheetTransition.animationOptions,\n animations: {\n destinationView.frame = transitionContext.finalFrame(for: destinationController)\n },\n completion: { _ in\n transitionContext.completeTransition(true)\n }\n )\n } else {\n destinationView.frame = transitionContext.finalFrame(for: destinationController)\n }\n }\n\n private func animateDismissal(_ transitionContext: UIViewControllerContextTransitioning) {\n let duration = transitionDuration(using: transitionContext)\n let containerView = transitionContext.containerView\n let sourceView = transitionContext.view(forKey: .from)!\n let sourceController = transitionContext.viewController(forKey: .from)!\n\n var initialFrame = transitionContext.finalFrame(for: sourceController)\n initialFrame.origin.y = containerView.bounds.maxY\n\n if transitionContext.isAnimated {\n UIView.animate(\n withDuration: duration,\n delay: UIMetrics.FormSheetTransition.delay.timeInterval,\n options: UIMetrics.FormSheetTransition.animationOptions,\n animations: {\n sourceView.frame = initialFrame\n },\n completion: { _ in\n transitionContext.completeTransition(true)\n }\n )\n } else {\n sourceView.frame = initialFrame\n transitionContext.completeTransition(true)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Presentation controllers\FormsheetPresentationController.swift | FormsheetPresentationController.swift | Swift | 10,739 | 0.95 | 0.059406 | 0.090196 | vue-tools | 133 | 2024-07-21T15:37:03.687239 | GPL-3.0 | false | 4c1df7090451bf6ae37a6043d04bedc8 |
//\n// CellFactoryProtocol.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-03-09.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\n/// Protocol for creating factories to make ``UITableViewCell``s of various kinds.\n/// Typically used in conjunction with a ``UITableViewDiffableDataSource.CellProvider``.\nprotocol CellFactoryProtocol {\n associatedtype ItemIdentifier\n\n var tableView: UITableView { get }\n\n func makeCell(for item: ItemIdentifier, indexPath: IndexPath) -> UITableViewCell\n func configureCell(_ cell: UITableViewCell, item: ItemIdentifier, indexPath: IndexPath)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Protocols\CellFactoryProtocol.swift | CellFactoryProtocol.swift | Swift | 629 | 0.95 | 0.1 | 0.5625 | vue-tools | 766 | 2023-09-29T08:29:10.191058 | BSD-3-Clause | false | e77e2cdc26f270cd28dac9a7bd0fe456 |
//\n// SettingsMigrationUIHandler.swift\n// MullvadVPN\n//\n// Created by pronebird on 24/11/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol SettingsMigrationUIHandler {\n func showMigrationError(_ error: Error, completionHandler: @escaping () -> Void)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Protocols\SettingsMigrationUIHandler.swift | SettingsMigrationUIHandler.swift | Swift | 305 | 0.95 | 0 | 0.636364 | python-kit | 604 | 2024-06-28T19:11:16.481898 | GPL-3.0 | false | e227b1ee845db8ede47748b986c04330 |
//\n// URLSessionProtocol.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-11-16.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol URLSessionProtocol {\n func data(for request: URLRequest) async throws -> (Data, URLResponse)\n}\n\nextension URLSession: URLSessionProtocol {}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\Protocols\URLSessionProtocol.swift | URLSessionProtocol.swift | Swift | 328 | 0.95 | 0.066667 | 0.583333 | awesome-app | 455 | 2024-01-15T17:22:16.507091 | Apache-2.0 | false | 5c60abf37b6cda98166b2dd819821b47 |
//\n// RelayCacheTracker.swift\n// MullvadVPN\n//\n// Created by pronebird on 05/06/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport UIKit\n\nprotocol RelayCacheTrackerProtocol: Sendable {\n func startPeriodicUpdates()\n func stopPeriodicUpdates()\n func updateRelays(completionHandler: ((sending Result<RelaysFetchResult, Error>) -> Void)?) -> Cancellable\n func getCachedRelays() throws -> CachedRelays\n func getNextUpdateDate() -> Date\n func addObserver(_ observer: RelayCacheTrackerObserver)\n func removeObserver(_ observer: RelayCacheTrackerObserver)\n func refreshCachedRelays() throws\n}\n\nfinal class RelayCacheTracker: RelayCacheTrackerProtocol, @unchecked Sendable {\n /// Relay update interval.\n static let relayUpdateInterval: Duration = .hours(1)\n\n /// Tracker log.\n nonisolated(unsafe) private let logger = Logger(label: "RelayCacheTracker")\n\n /// Relay cache.\n private let cache: RelayCacheProtocol\n\n private let backgroundTaskProvider: BackgroundTaskProviding\n\n /// Lock used for synchronization.\n private let relayCacheLock = NSLock()\n\n /// Internal operation queue.\n private let operationQueue = AsyncOperationQueue.makeSerial()\n\n /// A timer source used for periodic updates.\n private var timerSource: DispatchSourceTimer?\n\n /// A flag that indicates whether periodic updates are running.\n private var isPeriodicUpdatesEnabled = false\n\n /// API proxy.\n private let apiProxy: APIQuerying\n\n /// Observers.\n private let observerList = ObserverList<RelayCacheTrackerObserver>()\n\n /// Memory cache.\n private var cachedRelays: CachedRelays?\n\n init(relayCache: RelayCacheProtocol, backgroundTaskProvider: BackgroundTaskProviding, apiProxy: APIQuerying) {\n self.backgroundTaskProvider = backgroundTaskProvider\n self.apiProxy = apiProxy\n cache = relayCache\n\n do {\n cachedRelays = try cache.read().cachedRelays\n try hotfixRelaysThatDoNotHaveDaita()\n } catch {\n logger.error(\n error: error,\n message: "Failed to read the relay cache during initialization."\n )\n\n _ = updateRelays(completionHandler: nil)\n }\n }\n\n /// This method updates the cached relay to include daita information\n ///\n /// This is a hotfix meant to upgrade clients shipped with 2024.5 or before that did not have\n /// daita information in their representation of `ServerRelay`.\n /// If a version <= 2024.5 is installed less than an hour before a new upgrade,\n /// no servers will be shown in locations when filtering for daita relays.\n ///\n /// > Info: `relayCacheLock` does not need to be accessed here, this method should be ran from `init` only.\n private func hotfixRelaysThatDoNotHaveDaita() throws {\n guard let cachedRelays else { return }\n let daitaPropertyMissing = cachedRelays.relays.wireguard.relays.first { $0.daita ?? false } == nil\n // If the cached relays already have daita information, this fix is not necessary\n guard daitaPropertyMissing else { return }\n\n let preBundledRelays = try cache.readPrebundledRelays().relays\n let preBundledDaitaRelays = preBundledRelays.wireguard.relays.filter { $0.daita == true }\n var cachedRelaysWithFixedDaita = cachedRelays.relays.wireguard.relays\n\n // For each daita enabled relay in the prebundled relays\n // Find the corresponding relay in the cache by matching relay hostnames\n // Then update it to toggle daita\n for index in 0 ..< cachedRelaysWithFixedDaita.endIndex {\n let relay = cachedRelaysWithFixedDaita[index]\n preBundledDaitaRelays.forEach {\n if $0.hostname == relay.hostname {\n cachedRelaysWithFixedDaita[index] = relay.override(daita: true)\n }\n }\n }\n\n let wireguard = REST.ServerWireguardTunnels(\n ipv4Gateway:\n cachedRelays.relays.wireguard.ipv4Gateway,\n ipv6Gateway: cachedRelays.relays.wireguard.ipv6Gateway,\n portRanges: cachedRelays.relays.wireguard.portRanges,\n relays: cachedRelaysWithFixedDaita,\n shadowsocksPortRanges: cachedRelays.relays.wireguard.shadowsocksPortRanges\n )\n\n let updatedRelays = REST.ServerRelaysResponse(\n locations: cachedRelays.relays.locations,\n wireguard: wireguard,\n bridge: cachedRelays.relays.bridge\n )\n\n let updatedRawRelayData = try REST.Coding.makeJSONEncoder().encode(updatedRelays)\n let updatedCachedRelays = try StoredRelays(\n etag: cachedRelays.etag,\n rawData: updatedRawRelayData,\n updatedAt: cachedRelays.updatedAt\n )\n\n try cache.write(record: updatedCachedRelays)\n self.cachedRelays = CachedRelays(\n etag: cachedRelays.etag,\n relays: updatedRelays,\n updatedAt: cachedRelays.updatedAt\n )\n }\n\n func startPeriodicUpdates() {\n relayCacheLock.lock()\n defer { relayCacheLock.unlock() }\n\n guard !isPeriodicUpdatesEnabled else { return }\n\n logger.debug("Start periodic relay updates.")\n\n isPeriodicUpdatesEnabled = true\n\n let nextUpdate = _getNextUpdateDate()\n\n scheduleRepeatingTimer(startTime: .now() + nextUpdate.timeIntervalSinceNow)\n }\n\n func stopPeriodicUpdates() {\n relayCacheLock.lock()\n defer { relayCacheLock.unlock() }\n\n guard isPeriodicUpdatesEnabled else { return }\n\n logger.debug("Stop periodic relay updates.")\n\n isPeriodicUpdatesEnabled = false\n\n timerSource?.cancel()\n timerSource = nil\n }\n\n func updateRelays(completionHandler: ((sending Result<RelaysFetchResult, Error>) -> Void)? = nil)\n -> Cancellable {\n let operation = ResultBlockOperation<RelaysFetchResult> { finish in\n let cachedRelays = try? self.getCachedRelays()\n\n if self.getNextUpdateDate() > Date() {\n finish(.success(.throttled))\n return AnyCancellable()\n }\n\n return self.apiProxy.getRelays(etag: cachedRelays?.etag, retryStrategy: .noRetry) { result in\n finish(self.handleResponse(result: result))\n }\n }\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Update relays",\n cancelUponExpiration: true\n )\n )\n\n operation.completionQueue = .main\n operation.completionHandler = completionHandler\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n func getCachedRelays() throws -> CachedRelays {\n relayCacheLock.lock()\n defer { relayCacheLock.unlock() }\n\n if let cachedRelays {\n return cachedRelays\n } else {\n throw NoCachedRelaysError()\n }\n }\n\n func refreshCachedRelays() throws {\n let newCachedRelays = try cache.read().cachedRelays\n\n relayCacheLock.lock()\n cachedRelays = newCachedRelays\n relayCacheLock.unlock()\n\n DispatchQueue.main.async {\n self.observerList.notify { observer in\n observer.relayCacheTracker(self, didUpdateCachedRelays: newCachedRelays)\n }\n }\n }\n\n func getNextUpdateDate() -> Date {\n relayCacheLock.lock()\n defer { relayCacheLock.unlock() }\n\n return _getNextUpdateDate()\n }\n\n // MARK: - Observation\n\n func addObserver(_ observer: RelayCacheTrackerObserver) {\n observerList.append(observer)\n }\n\n func removeObserver(_ observer: RelayCacheTrackerObserver) {\n observerList.remove(observer)\n }\n\n // MARK: - Private\n\n private func _getNextUpdateDate() -> Date {\n let now = Date()\n\n guard let cachedRelays else {\n return now\n }\n\n let nextUpdate = cachedRelays.updatedAt.addingTimeInterval(Self.relayUpdateInterval.timeInterval)\n\n return max(nextUpdate, Date())\n }\n\n private func handleResponse(result: Result<REST.ServerRelaysCacheResponse, Error>)\n -> Result<RelaysFetchResult, Error> {\n result.tryMap { response -> RelaysFetchResult in\n switch response {\n case let .newContent(etag, rawData):\n try self.storeResponse(etag: etag, rawData: rawData)\n\n return .newContent\n\n case .notModified:\n return .sameContent\n }\n }.inspectError { error in\n guard !error.isOperationCancellationError else { return }\n\n logger.error(\n error: error,\n message: "Failed to update relays."\n )\n }\n }\n\n private func storeResponse(etag: String?, rawData: Data) throws {\n let newCachedData = try StoredRelays(\n etag: etag,\n rawData: rawData,\n updatedAt: Date()\n )\n\n try cache.write(record: newCachedData)\n try refreshCachedRelays()\n }\n\n private func scheduleRepeatingTimer(startTime: DispatchWallTime) {\n let timerSource = DispatchSource.makeTimerSource()\n timerSource.setEventHandler { [weak self] in\n _ = self?.updateRelays()\n }\n\n timerSource.schedule(\n wallDeadline: startTime,\n repeating: Self.relayUpdateInterval.timeInterval\n )\n timerSource.activate()\n\n self.timerSource = timerSource\n }\n}\n\n/// Type describing the result of an attempt to fetch the new relay list from server.\nenum RelaysFetchResult: CustomStringConvertible {\n /// Request to update relays was throttled.\n case throttled\n\n /// Refreshed relays but the same content was found on remote.\n case sameContent\n\n /// Refreshed relays with new content.\n case newContent\n\n var description: String {\n switch self {\n case .throttled:\n return "throttled"\n case .sameContent:\n return "same content"\n case .newContent:\n return "new content"\n }\n }\n}\n\nstruct NoCachedRelaysError: LocalizedError {\n var errorDescription: String? {\n "Relay cache is empty."\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\RelayCacheTracker\RelayCacheTracker.swift | RelayCacheTracker.swift | Swift | 10,443 | 0.95 | 0.069697 | 0.134615 | vue-tools | 915 | 2024-09-24T03:50:24.383984 | BSD-3-Clause | false | 89a5c68c35a5b7b02de01a4391142605 |
//\n// RelayCacheTrackerObserver.swift\n// RelayCacheTrackerObserver\n//\n// Created by pronebird on 09/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n\nprotocol RelayCacheTrackerObserver: AnyObject {\n func relayCacheTracker(\n _ tracker: RelayCacheTracker,\n didUpdateCachedRelays cachedRelays: CachedRelays\n )\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\RelayCacheTracker\RelayCacheTrackerObserver.swift | RelayCacheTrackerObserver.swift | Swift | 392 | 0.95 | 0 | 0.466667 | vue-tools | 777 | 2023-08-09T21:26:51.915020 | BSD-3-Clause | false | 025d130c120c4db0fb7029fc411d6df5 |
//\n// SimulatorTunnelInfo.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-09-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n#if targetEnvironment(simulator)\n\nimport Foundation\nimport NetworkExtension\n\nfinal class SimulatorTunnelProviderSession: SimulatorVPNConnection, VPNTunnelProviderSessionProtocol,\n @unchecked Sendable {\n func sendProviderMessage(_ messageData: Data, responseHandler: ((Data?) -> Void)?) throws {\n SimulatorTunnelProvider.shared.handleAppMessage(\n messageData,\n completionHandler: responseHandler\n )\n }\n}\n\n/// A mock struct for tunnel configuration and connection\nstruct SimulatorTunnelInfo {\n /// A unique identifier for the configuration\n var identifier = UUID().uuidString\n\n /// An associated VPN connection.\n /// Intentionally initialized with a `SimulatorTunnelProviderSession` subclass which\n /// implements the necessary protocol\n var connection: SimulatorVPNConnection = SimulatorTunnelProviderSession()\n\n /// Whether configuration is enabled\n var isEnabled = false\n\n /// Whether on-demand VPN is enabled\n var isOnDemandEnabled = false\n\n /// On-demand VPN rules\n var onDemandRules = [NEOnDemandRule]()\n\n /// Protocol configuration\n var protocolConfiguration: NEVPNProtocol? {\n didSet {\n connection.protocolConfiguration = protocolConfiguration ?? NEVPNProtocol()\n }\n }\n\n /// Tunnel description\n var localizedDescription: String?\n\n /// Designated initializer\n init() {}\n}\n\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\SimulatorTunnelProvider\SimulatorTunnelInfo.swift | SimulatorTunnelInfo.swift | Swift | 1,570 | 0.95 | 0.070175 | 0.444444 | react-lib | 263 | 2025-06-20T02:00:35.917256 | BSD-3-Clause | false | ce0ac35e31be55c60c7cd4c96df050ca |
//\n// SimulatorTunnelProvider.swift\n// MullvadVPN\n//\n// Created by pronebird on 05/02/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\n#if targetEnvironment(simulator)\n\nclass SimulatorTunnelProviderDelegate {\n var connection: SimulatorVPNConnection?\n\n var protocolConfiguration: NEVPNProtocol {\n connection?.protocolConfiguration ?? NEVPNProtocol()\n }\n\n var reasserting: Bool {\n get {\n connection?.reasserting ?? false\n }\n set {\n connection?.reasserting = newValue\n }\n }\n\n func startTunnel(options: [String: NSObject]?, completionHandler: @escaping @Sendable (Error?) -> Void) {\n completionHandler(nil)\n }\n\n func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping @Sendable () -> Void) {\n completionHandler()\n }\n\n func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {\n completionHandler?(nil)\n }\n}\n\nfinal class SimulatorTunnelProvider: Sendable {\n static let shared = SimulatorTunnelProvider()\n\n private let lock = NSLock()\n nonisolated(unsafe) private var _delegate: SimulatorTunnelProviderDelegate?\n\n var delegate: SimulatorTunnelProviderDelegate! {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return _delegate\n }\n set {\n lock.lock()\n _delegate = newValue\n lock.unlock()\n }\n }\n\n private init() {}\n\n func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)? = nil) {\n delegate.handleAppMessage(messageData, completionHandler: completionHandler)\n }\n}\n\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\SimulatorTunnelProvider\SimulatorTunnelProvider.swift | SimulatorTunnelProvider.swift | Swift | 1,741 | 0.95 | 0.042857 | 0.163636 | vue-tools | 180 | 2024-09-18T03:26:37.191951 | BSD-3-Clause | false | 49c524b71e2f326e685a26b58f0262ab |
//\n// SimulatorTunnelProviderHost.swift\n// MullvadVPN\n//\n// Created by pronebird on 10/02/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n#if targetEnvironment(simulator)\n\n@preconcurrency import Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport NetworkExtension\nimport PacketTunnelCore\n\nfinal class SimulatorTunnelProviderHost: SimulatorTunnelProviderDelegate, @unchecked Sendable {\n private var observedState: ObservedState = .disconnected\n private var selectedRelays: SelectedRelays?\n private let urlRequestProxy: URLRequestProxy\n private let apiRequestProxy: APIRequestProxy\n private let relaySelector: RelaySelectorProtocol\n\n private let providerLogger = Logger(label: "SimulatorTunnelProviderHost")\n private let dispatchQueue = DispatchQueue(label: "SimulatorTunnelProviderHostQueue")\n\n init(\n relaySelector: RelaySelectorProtocol,\n transportProvider: TransportProvider,\n apiTransportProvider: APITransportProvider\n ) {\n self.relaySelector = relaySelector\n self.urlRequestProxy = URLRequestProxy(\n dispatchQueue: dispatchQueue,\n transportProvider: transportProvider\n )\n self.apiRequestProxy = APIRequestProxy(\n dispatchQueue: dispatchQueue,\n transportProvider: apiTransportProvider\n )\n }\n\n override func startTunnel(\n options: [String: NSObject]?,\n completionHandler: @escaping @Sendable (Error?) -> Void\n ) {\n dispatchQueue.async { [weak self] in\n guard let self else {\n completionHandler(nil)\n return\n }\n\n var selectedRelays: SelectedRelays?\n\n do {\n let tunnelOptions = PacketTunnelOptions(rawOptions: options ?? [:])\n\n selectedRelays = try tunnelOptions.getSelectedRelays()\n } catch {\n providerLogger.error(\n error: error,\n message: """\n Failed to decode selected relay passed from the app. \\n Will continue by picking new relay.\n """\n )\n }\n\n do {\n setInternalStateConnected(with: try selectedRelays ?? pickRelays())\n completionHandler(nil)\n } catch let error where error is NoRelaysSatisfyingConstraintsError {\n observedState = .error(ObservedBlockedState(reason: .noRelaysSatisfyingConstraints))\n completionHandler(error)\n } catch {\n providerLogger.error(\n error: error,\n message: "Failed to pick relay."\n )\n completionHandler(error)\n }\n }\n }\n\n override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping @Sendable () -> Void) {\n dispatchQueue.async { [weak self] in\n self?.selectedRelays = nil\n self?.observedState = .disconnected\n\n completionHandler()\n }\n }\n\n override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {\n dispatchQueue.sync {\n do {\n let message = try TunnelProviderMessage(messageData: messageData)\n\n self.handleProviderMessage(message, completionHandler: completionHandler)\n } catch {\n self.providerLogger.error(\n error: error,\n message: "Failed to decode app message."\n )\n\n completionHandler?(nil)\n }\n }\n }\n\n private func handleProviderMessage(\n _ message: TunnelProviderMessage,\n completionHandler: ((Data?) -> Void)?\n ) {\n nonisolated(unsafe) let handler = completionHandler\n switch message {\n case .getTunnelStatus:\n var reply: Data?\n do {\n reply = try TunnelProviderReply(observedState).encode()\n } catch {\n self.providerLogger.error(\n error: error,\n message: "Failed to encode tunnel status."\n )\n }\n\n handler?(reply)\n\n case let .reconnectTunnel(nextRelay):\n reasserting = true\n\n switch nextRelay {\n case let .preSelected(selectedRelays):\n self.selectedRelays = selectedRelays\n case .random:\n if let nextRelays = try? pickRelays() {\n self.selectedRelays = nextRelays\n }\n case .current:\n break\n }\n\n setInternalStateConnected(with: selectedRelays)\n reasserting = false\n\n completionHandler?(nil)\n\n case let .sendURLRequest(proxyRequest):\n urlRequestProxy.sendRequest(proxyRequest) { response in\n var reply: Data?\n do {\n reply = try TunnelProviderReply(response).encode()\n } catch {\n self.providerLogger.error(\n error: error,\n message: "Failed to encode ProxyURLResponse."\n )\n }\n handler?(reply)\n }\n\n case let .sendAPIRequest(proxyRequest):\n apiRequestProxy.sendRequest(proxyRequest) { response in\n var reply: Data?\n do {\n reply = try TunnelProviderReply(response).encode()\n } catch {\n self.providerLogger.error(\n error: error,\n message: "Failed to encode ProxyURLResponse."\n )\n }\n handler?(reply)\n }\n\n case let .cancelURLRequest(listId):\n urlRequestProxy.cancelRequest(identifier: listId)\n\n completionHandler?(nil)\n\n case let .cancelAPIRequest(listId):\n apiRequestProxy.cancelRequest(identifier: listId)\n\n completionHandler?(nil)\n\n case .privateKeyRotation:\n completionHandler?(nil)\n }\n }\n\n private func pickRelays() throws -> SelectedRelays {\n let settings = try SettingsManager.readSettings()\n return try relaySelector.selectRelays(\n tunnelSettings: settings,\n connectionAttemptCount: 0\n )\n }\n\n private func setInternalStateConnected(with selectedRelays: SelectedRelays?) {\n guard let selectedRelays = selectedRelays else { return }\n\n do {\n let settings = try SettingsManager.readSettings()\n observedState = .connected(\n ObservedConnectionState(\n selectedRelays: selectedRelays,\n relayConstraints: settings.relayConstraints,\n networkReachability: .reachable,\n connectionAttemptCount: 0,\n transportLayer: .udp,\n remotePort: selectedRelays.entry?.endpoint.ipv4Relay.port ?? selectedRelays.exit.endpoint.ipv4Relay\n .port,\n isPostQuantum: settings.tunnelQuantumResistance.isEnabled,\n isDaitaEnabled: settings.daita.daitaState.isEnabled\n )\n )\n } catch {\n providerLogger.error(\n error: error,\n message: "Failed to read device settings."\n )\n }\n }\n}\n\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\SimulatorTunnelProvider\SimulatorTunnelProviderHost.swift | SimulatorTunnelProviderHost.swift | Swift | 7,582 | 0.95 | 0.100437 | 0.045685 | node-utils | 810 | 2024-07-16T09:36:04.750744 | Apache-2.0 | false | 0114f14ebd7fef82d409eed372db1add |
//\n// SimulatorTunnelProviderManager.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-09-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n#if targetEnvironment(simulator)\n\nimport Foundation\nimport NetworkExtension\n\nfinal class SimulatorTunnelProviderManager: NSObject, VPNTunnelProviderManagerProtocol {\n static let tunnelsLock = NSRecursiveLock()\n nonisolated(unsafe) fileprivate static var tunnels = [SimulatorTunnelInfo]()\n\n private let lock = NSLock()\n private var tunnelInfo: SimulatorTunnelInfo\n private var identifier: String {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.identifier\n }\n\n var isOnDemandEnabled: Bool {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.isOnDemandEnabled\n }\n set {\n lock.lock()\n tunnelInfo.isOnDemandEnabled = newValue\n lock.unlock()\n }\n }\n\n var onDemandRules: [NEOnDemandRule] {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.onDemandRules\n }\n set {\n lock.lock()\n tunnelInfo.onDemandRules = newValue\n lock.unlock()\n }\n }\n\n var isEnabled: Bool {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.isEnabled\n }\n set {\n lock.lock()\n tunnelInfo.isEnabled = newValue\n lock.unlock()\n }\n }\n\n var protocolConfiguration: NEVPNProtocol? {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.protocolConfiguration\n }\n set {\n lock.lock()\n tunnelInfo.protocolConfiguration = newValue\n lock.unlock()\n }\n }\n\n var localizedDescription: String? {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.localizedDescription\n }\n set {\n lock.lock()\n tunnelInfo.localizedDescription = newValue\n lock.unlock()\n }\n }\n\n var connection: SimulatorVPNConnection {\n lock.lock()\n defer { lock.unlock() }\n\n return tunnelInfo.connection\n }\n\n static func loadAllFromPreferences(completionHandler: (\n [SimulatorTunnelProviderManager]?,\n Error?\n ) -> Void) {\n Self.tunnelsLock.lock()\n let tunnelProviders = tunnels.map { tunnelInfo in\n SimulatorTunnelProviderManager(tunnelInfo: tunnelInfo)\n }\n Self.tunnelsLock.unlock()\n\n completionHandler(tunnelProviders, nil)\n }\n\n override required init() {\n tunnelInfo = SimulatorTunnelInfo()\n super.init()\n }\n\n private init(tunnelInfo: SimulatorTunnelInfo) {\n self.tunnelInfo = tunnelInfo\n super.init()\n }\n\n func loadFromPreferences(completionHandler: (Error?) -> Void) {\n var error: NEVPNError?\n\n Self.tunnelsLock.lock()\n\n if let savedTunnel = Self.tunnels.first(where: { $0.identifier == self.identifier }) {\n tunnelInfo = savedTunnel\n } else {\n error = NEVPNError(.configurationInvalid)\n }\n\n Self.tunnelsLock.unlock()\n\n completionHandler(error)\n }\n\n func saveToPreferences(completionHandler: ((Error?) -> Void)?) {\n Self.tunnelsLock.lock()\n\n if let index = Self.tunnels.firstIndex(where: { $0.identifier == self.identifier }) {\n Self.tunnels[index] = tunnelInfo\n } else {\n Self.tunnels.append(tunnelInfo)\n }\n\n Self.tunnelsLock.unlock()\n\n completionHandler?(nil)\n }\n\n func removeFromPreferences(completionHandler: ((Error?) -> Void)?) {\n var error: NEVPNError?\n\n Self.tunnelsLock.lock()\n\n if let index = Self.tunnels.firstIndex(where: { $0.identifier == self.identifier }) {\n Self.tunnels.remove(at: index)\n } else {\n error = NEVPNError(.configurationReadWriteFailed)\n }\n\n Self.tunnelsLock.unlock()\n\n completionHandler?(error)\n }\n\n override func isEqual(_ object: Any?) -> Bool {\n guard let other = object as? Self else { return false }\n return self.identifier == other.identifier\n }\n}\n\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\SimulatorTunnelProvider\SimulatorTunnelProviderManager.swift | SimulatorTunnelProviderManager.swift | Swift | 4,374 | 0.95 | 0.027933 | 0.06338 | awesome-app | 201 | 2025-06-18T21:28:08.617225 | MIT | false | 870d9c3e336971a08b8ef25b459033d2 |
//\n// SimulatorVPNConnection.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-09-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n#if targetEnvironment(simulator)\n\nimport Foundation\nimport MullvadREST\nimport NetworkExtension\n\nclass SimulatorVPNConnection: NSObject, VPNConnectionProtocol, @unchecked Sendable {\n // Protocol configuration is automatically synced by `SimulatorTunnelInfo`\n var protocolConfiguration = NEVPNProtocol()\n\n private let lock = NSRecursiveLock()\n private var _status: NEVPNStatus = .disconnected\n private var _reasserting = false\n private var _connectedDate: Date?\n\n private(set) var status: NEVPNStatus {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return _status\n }\n set {\n lock.lock()\n\n if _status != newValue {\n _status = newValue\n\n // Send notification while holding the lock. This should enable the receiver\n // to fetch the `SimulatorVPNConnection.status` before the concurrent code gets\n // opportunity to change it again.\n postStatusDidChangeNotification()\n }\n\n lock.unlock()\n }\n }\n\n var reasserting: Bool {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return _reasserting\n }\n set {\n lock.lock()\n\n if _reasserting != newValue {\n _reasserting = newValue\n\n if newValue {\n status = .reasserting\n } else {\n status = .connected\n }\n }\n\n lock.unlock()\n }\n }\n\n private(set) var connectedDate: Date? {\n get {\n lock.lock()\n defer { lock.unlock() }\n\n return _connectedDate\n }\n set {\n lock.lock()\n _connectedDate = newValue\n lock.unlock()\n }\n }\n\n func startVPNTunnel() throws {\n try startVPNTunnel(options: nil)\n }\n\n func startVPNTunnel(options: [String: NSObject]?) throws {\n SimulatorTunnelProvider.shared.delegate.connection = self\n\n status = .connecting\n\n SimulatorTunnelProvider.shared.delegate.startTunnel(options: options) { error in\n if error == nil {\n self.status = .connected\n self.connectedDate = Date()\n } else if error is NoRelaysSatisfyingConstraintsError {\n self.reasserting = true\n self.connectedDate = nil\n } else {\n self.status = .disconnected\n self.connectedDate = nil\n }\n }\n }\n\n func stopVPNTunnel() {\n status = .disconnecting\n\n SimulatorTunnelProvider.shared.delegate.stopTunnel(with: .userInitiated) {\n self.status = .disconnected\n self.connectedDate = nil\n }\n }\n\n private func postStatusDidChangeNotification() {\n NotificationCenter.default.post(name: .NEVPNStatusDidChange, object: self)\n }\n}\n\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\SimulatorTunnelProvider\SimulatorVPNConnection.swift | SimulatorVPNConnection.swift | Swift | 3,139 | 0.95 | 0.07377 | 0.132653 | awesome-app | 364 | 2023-09-05T02:00:41.703093 | GPL-3.0 | false | 0146d97778c95f0469f2ad47de92886c |
//\n// SendStoreReceiptOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/03/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport StoreKit\n\nclass SendStoreReceiptOperation: ResultOperation<REST.CreateApplePaymentResponse>, SKRequestDelegate,\n @unchecked Sendable {\n private let apiProxy: APIQuerying\n private let accountNumber: String\n\n private let forceRefresh: Bool\n private let receiptProperties: [String: Any]?\n private var refreshRequest: SKReceiptRefreshRequest?\n\n private var submitReceiptTask: Cancellable?\n\n private let logger = Logger(label: "SendStoreReceiptOperation")\n\n init(\n apiProxy: APIQuerying,\n accountNumber: String,\n forceRefresh: Bool,\n receiptProperties: [String: Any]?,\n completionHandler: @escaping CompletionHandler\n ) {\n self.apiProxy = apiProxy\n self.accountNumber = accountNumber\n self.forceRefresh = forceRefresh\n self.receiptProperties = receiptProperties\n\n super.init(\n dispatchQueue: .main,\n completionQueue: .main,\n completionHandler: completionHandler\n )\n }\n\n override func operationDidCancel() {\n refreshRequest?.cancel()\n refreshRequest = nil\n\n submitReceiptTask?.cancel()\n submitReceiptTask = nil\n }\n\n override func main() {\n // Pull receipt from AppStore if requested.\n guard !forceRefresh else {\n startRefreshRequest()\n return\n }\n\n // Read AppStore receipt from disk.\n do {\n let data = try readReceiptFromDisk()\n\n sendReceipt(data)\n } catch is StoreReceiptNotFound {\n // Pull receipt from AppStore if it's not cached locally.\n startRefreshRequest()\n } catch {\n logger.error(\n error: error,\n message: "Failed to read the AppStore receipt."\n )\n finish(result: .failure(StorePaymentManagerError.readReceipt(error)))\n }\n }\n\n // - MARK: SKRequestDelegate\n\n func requestDidFinish(_ request: SKRequest) {\n dispatchQueue.async {\n do {\n let data = try self.readReceiptFromDisk()\n\n self.sendReceipt(data)\n } catch {\n self.logger.error(\n error: error,\n message: "Failed to read the AppStore receipt after refresh."\n )\n self.finish(result: .failure(StorePaymentManagerError.readReceipt(error)))\n }\n }\n }\n\n func request(_ request: SKRequest, didFailWithError error: Error) {\n dispatchQueue.async {\n self.logger.error(\n error: error,\n message: "Failed to refresh the AppStore receipt."\n )\n self.finish(result: .failure(StorePaymentManagerError.readReceipt(error)))\n }\n }\n\n // MARK: - Private\n\n private func startRefreshRequest() {\n let refreshRequest = SKReceiptRefreshRequest(receiptProperties: receiptProperties)\n refreshRequest.delegate = self\n refreshRequest.start()\n\n self.refreshRequest = refreshRequest\n }\n\n private func readReceiptFromDisk() throws -> Data {\n guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL else {\n throw StoreReceiptNotFound()\n }\n\n do {\n return try Data(contentsOf: appStoreReceiptURL)\n } catch let error as CocoaError\n where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile {\n throw StoreReceiptNotFound()\n } catch {\n throw error\n }\n }\n\n private func sendReceipt(_ receiptData: Data) {\n submitReceiptTask = apiProxy.createApplePayment(\n accountNumber: accountNumber,\n receiptString: receiptData\n ).execute(retryStrategy: .noRetry) { result in\n switch result {\n case let .success(response):\n self.logger.info(\n """\n AppStore receipt was processed. \\n Time added: \(response.timeAdded), \\n New expiry: \(response.newExpiry.logFormatted)\n """\n )\n self.finish(result: .success(response))\n\n case let .failure(error):\n if error.isOperationCancellationError {\n self.logger.debug("Receipt submission cancelled.")\n self.finish(result: .failure(error))\n } else {\n self.logger.error(\n error: error,\n message: "Failed to send the AppStore receipt."\n )\n self.finish(result: .failure(StorePaymentManagerError.sendReceipt(error)))\n }\n }\n }\n }\n}\n\nstruct StoreReceiptNotFound: LocalizedError {\n var errorDescription: String? {\n "AppStore receipt file does not exist on disk."\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\SendStoreReceiptOperation.swift | SendStoreReceiptOperation.swift | Swift | 5,175 | 0.95 | 0.076923 | 0.082759 | awesome-app | 353 | 2025-02-23T09:23:51.299998 | BSD-3-Clause | false | fecb1157be4607c9e79dcf20257edc17 |
//\n// StorePaymentBlockObserver.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nfinal class StorePaymentBlockObserver: StorePaymentObserver {\n typealias BlockHandler = @Sendable (StorePaymentManager, StorePaymentEvent) -> Void\n\n private let blockHandler: BlockHandler\n\n init(_ blockHandler: @escaping BlockHandler) {\n self.blockHandler = blockHandler\n }\n\n func storePaymentManager(\n _ manager: StorePaymentManager,\n didReceiveEvent event: StorePaymentEvent\n ) {\n blockHandler(manager, event)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StorePaymentBlockObserver.swift | StorePaymentBlockObserver.swift | Swift | 645 | 0.95 | 0.038462 | 0.333333 | awesome-app | 49 | 2024-02-23T17:33:22.854673 | GPL-3.0 | false | 08918e71044a6f1a1ccab8a370646006 |
//\n// StorePaymentEvent.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\n@preconcurrency import StoreKit\n\n/// The payment event received by observers implementing ``StorePaymentObserver``.\nenum StorePaymentEvent: @unchecked Sendable {\n /// The payment is successfully completed.\n case finished(StorePaymentCompletion)\n\n /// Failure to complete the payment.\n case failure(StorePaymentFailure)\n\n /// An instance of `SKPayment` held in the associated value.\n var payment: SKPayment {\n switch self {\n case let .finished(completion):\n return completion.transaction.payment\n case let .failure(failure):\n return failure.payment\n }\n }\n}\n\n/// Successful payment metadata.\nstruct StorePaymentCompletion {\n /// Transaction object.\n let transaction: SKPaymentTransaction\n\n /// The account number credited.\n let accountNumber: String\n\n /// The server response received after uploading the AppStore receipt.\n let serverResponse: REST.CreateApplePaymentResponse\n}\n\n/// Failed payment metadata.\nstruct StorePaymentFailure: @unchecked Sendable {\n /// Transaction object, if available.\n /// May not be available due to account validation failure.\n let transaction: SKPaymentTransaction?\n\n /// The payment object associated with payment request.\n let payment: SKPayment\n\n /// The account number to credit.\n /// May not be available if the payment manager couldn't establish the association between the payment and account number.\n /// Typically in such case, the error would be set to ``StorePaymentManagerError/noAccountSet``.\n let accountNumber: String?\n\n /// The payment manager error.\n let error: StorePaymentManagerError\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StorePaymentEvent.swift | StorePaymentEvent.swift | Swift | 1,847 | 0.95 | 0.05 | 0.469388 | node-utils | 902 | 2024-05-07T20:34:18.166741 | BSD-3-Clause | false | 9fd19729640d49485bd73dde3a6e3c83 |
//\n// StorePaymentManager.swift\n// MullvadVPN\n//\n// Created by pronebird on 10/03/2020.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport MullvadREST\nimport MullvadTypes\nimport Operations\n@preconcurrency import StoreKit\nimport UIKit\n\n/// Manager responsible for handling AppStore payments and passing StoreKit receipts to the backend.\n///\n/// - Warning: only interact with this object on the main queue.\nfinal class StorePaymentManager: NSObject, SKPaymentTransactionObserver, @unchecked Sendable {\n private enum OperationCategory {\n static let sendStoreReceipt = "StorePaymentManager.sendStoreReceipt"\n static let productsRequest = "StorePaymentManager.productsRequest"\n }\n\n private let logger = Logger(label: "StorePaymentManager")\n\n private let operationQueue: OperationQueue = {\n let queue = AsyncOperationQueue()\n queue.name = "StorePaymentManagerQueue"\n return queue\n }()\n\n private let backgroundTaskProvider: BackgroundTaskProviding\n private let paymentQueue: SKPaymentQueue\n private let apiProxy: APIQuerying\n private let accountsProxy: RESTAccountHandling\n private var observerList = ObserverList<StorePaymentObserver>()\n private let transactionLog: StoreTransactionLog\n\n /// Payment manager's delegate.\n weak var delegate: StorePaymentManagerDelegate?\n\n /// A dictionary that maps each payment to account number.\n private var paymentToAccountToken = [SKPayment: String]()\n\n /// Returns true if the device is able to make payments.\n static var canMakePayments: Bool {\n SKPaymentQueue.canMakePayments()\n }\n\n /// Designated initializer\n ///\n /// - Parameters:\n /// - backgroundTaskProvider: the background task provider.\n /// - queue: the payment queue. Typically `SKPaymentQueue.default()`.\n /// - apiProxy: the object implement `APIQuerying`\n /// - accountsProxy: the object implementing `RESTAccountHandling`.\n /// - transactionLog: an instance of transaction log. Typically ``StoreTransactionLog/default``.\n init(\n backgroundTaskProvider: BackgroundTaskProviding,\n queue: SKPaymentQueue,\n apiProxy: APIQuerying,\n accountsProxy: RESTAccountHandling,\n transactionLog: StoreTransactionLog\n ) {\n self.backgroundTaskProvider = backgroundTaskProvider\n paymentQueue = queue\n self.apiProxy = apiProxy\n self.accountsProxy = accountsProxy\n self.transactionLog = transactionLog\n }\n\n /// Loads transaction log from disk and starts monitoring payment queue.\n func start() {\n // Load transaction log from file before starting the payment queue.\n logger.debug("Load transaction log.")\n transactionLog.read()\n\n logger.debug("Start payment queue monitoring")\n paymentQueue.add(self)\n }\n\n // MARK: - SKPaymentTransactionObserver\n\n func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {\n // Ensure that all calls happen on main queue because StoreKit does not guarantee on which queue the delegate\n // will be invoked.\n DispatchQueue.main.async {\n self.handleTransactions(transactions)\n }\n }\n\n // MARK: - Payment observation\n\n /// Add payment observer\n /// - Parameter observer: an observer object.\n func addPaymentObserver(_ observer: StorePaymentObserver) {\n observerList.append(observer)\n }\n\n /// Remove payment observer\n /// - Parameter observer: an observer object.\n func removePaymentObserver(_ observer: StorePaymentObserver) {\n observerList.remove(observer)\n }\n\n // MARK: - Products and payments\n\n /// Fetch products from AppStore using product identifiers.\n ///\n /// - Parameters:\n /// - productIdentifiers: a set of product identifiers.\n /// - completionHandler: completion handler. Invoked on main queue.\n /// - Returns: the request cancellation token\n func requestProducts(\n with productIdentifiers: Set<StoreSubscription>,\n completionHandler: @escaping @Sendable (Result<SKProductsResponse, Error>) -> Void\n ) -> Cancellable {\n let productIdentifiers = productIdentifiers.productIdentifiersSet\n let operation = ProductsRequestOperation(\n productIdentifiers: productIdentifiers,\n completionHandler: completionHandler\n )\n operation.addCondition(MutuallyExclusive(category: OperationCategory.productsRequest))\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n /// Add payment and associate it with the account number.\n ///\n /// Validates the user account with backend before adding the payment to the queue.\n ///\n /// - Parameters:\n /// - payment: an intance of `SKPayment`.\n /// - accountNumber: the account number to credit.\n func addPayment(_ payment: SKPayment, for accountNumber: String) {\n logger.debug("Validating account before the purchase.")\n\n // Validate account token before adding new payment to the queue.\n validateAccount(accountNumber: accountNumber) { error in\n if let error {\n self.logger.error("Failed to validate the account. Payment is ignored.")\n\n let event = StorePaymentEvent.failure(\n StorePaymentFailure(\n transaction: nil,\n payment: payment,\n accountNumber: accountNumber,\n error: error\n )\n )\n\n self.observerList.notify { observer in\n observer.storePaymentManager(self, didReceiveEvent: event)\n }\n } else {\n self.logger.debug("Add payment to the queue.")\n\n self.associateAccountNumber(accountNumber, and: payment)\n self.paymentQueue.add(payment)\n }\n }\n }\n\n /// Restore purchases by sending the AppStore receipt to backend.\n ///\n /// - Parameters:\n /// - accountNumber: the account number to credit.\n /// - completionHandler: completion handler invoked on the main queue.\n /// - Returns: the request cancellation token.\n func restorePurchases(\n for accountNumber: String,\n completionHandler: @escaping @Sendable (Result<REST.CreateApplePaymentResponse, Error>) -> Void\n ) -> Cancellable {\n logger.debug("Restore purchases.")\n\n return sendStoreReceipt(\n accountNumber: accountNumber,\n forceRefresh: true,\n completionHandler: completionHandler\n )\n }\n\n // MARK: - Private methods\n\n /// Associate account number with the payment object.\n ///\n /// - Parameters:\n /// - accountNumber: the account number that should be credited with the payment.\n /// - payment: the payment object.\n private func associateAccountNumber(_ accountNumber: String, and payment: SKPayment) {\n dispatchPrecondition(condition: .onQueue(.main))\n\n paymentToAccountToken[payment] = accountNumber\n }\n\n /// Remove association between the payment object and the account number.\n ///\n /// Since the association between account numbers and payments is not persisted, this method may consult the delegate to provide the account number to\n /// credit. This can happen for dangling transactions that remain in the payment queue between the application restarts. In the future this association should be\n /// solved by using `SKPaymentQueue.applicationUsername`.\n ///\n /// - Parameter payment: the payment object.\n /// - Returns: The account number on success, otherwise `nil`.\n private func deassociateAccountNumber(_ payment: SKPayment) -> String? {\n dispatchPrecondition(condition: .onQueue(.main))\n\n if let accountToken = paymentToAccountToken[payment] {\n paymentToAccountToken.removeValue(forKey: payment)\n return accountToken\n } else {\n return delegate?.storePaymentManager(self, didRequestAccountTokenFor: payment)\n }\n }\n\n /// Validate account number.\n ///\n /// - Parameters:\n /// - accountNumber: the account number\n /// - completionHandler: completion handler invoked on main queue. The completion block Receives `nil` upon success, otherwise an error.\n private func validateAccount(\n accountNumber: String,\n completionHandler: @escaping @Sendable (StorePaymentManagerError?) -> Void\n ) {\n let accountOperation = ResultBlockOperation<Account>(dispatchQueue: .main) { finish in\n self.accountsProxy.getAccountData(accountNumber: accountNumber, retryStrategy: .default, completion: finish)\n }\n\n accountOperation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Validate account number",\n cancelUponExpiration: false\n ))\n\n accountOperation.completionQueue = .main\n accountOperation.completionHandler = { result in\n completionHandler(result.error.map { StorePaymentManagerError.validateAccount($0) })\n }\n\n operationQueue.addOperation(accountOperation)\n }\n\n /// Send the AppStore receipt stored on device to the backend.\n ///\n /// - Parameters:\n /// - accountNumber: the account number to credit.\n /// - forceRefresh: indicates whether the receipt should be downloaded from AppStore even when it's present on device.\n /// - completionHandler: a completion handler invoked on main queue.\n /// - Returns: the request cancellation token.\n private func sendStoreReceipt(\n accountNumber: String,\n forceRefresh: Bool,\n completionHandler: @escaping @Sendable (Result<REST.CreateApplePaymentResponse, Error>) -> Void\n ) -> Cancellable {\n let operation = SendStoreReceiptOperation(\n apiProxy: apiProxy,\n accountNumber: accountNumber,\n forceRefresh: forceRefresh,\n receiptProperties: nil,\n completionHandler: completionHandler\n )\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Send AppStore receipt",\n cancelUponExpiration: true\n )\n )\n\n operation.addCondition(MutuallyExclusive(category: OperationCategory.sendStoreReceipt))\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n /// Handles an array of StoreKit transactions.\n /// - Parameter transactions: an array of transactions\n private func handleTransactions(_ transactions: [SKPaymentTransaction]) {\n transactions.forEach { transaction in\n handleTransaction(transaction)\n }\n }\n\n /// Handle single StoreKit transaction.\n /// - Parameter transaction: a transaction\n private func handleTransaction(_ transaction: SKPaymentTransaction) {\n switch transaction.transactionState {\n case .deferred:\n logger.info("Deferred \(transaction.payment.productIdentifier)")\n\n case .failed:\n let transactionError = transaction.error?.localizedDescription ?? "No error"\n logger.error("Failed to purchase \(transaction.payment.productIdentifier): \(transactionError)")\n\n didFailPurchase(transaction: transaction)\n\n case .purchased:\n logger.info("Purchased \(transaction.payment.productIdentifier)")\n\n didFinishOrRestorePurchase(transaction: transaction)\n\n case .purchasing:\n logger.info("Purchasing \(transaction.payment.productIdentifier)")\n\n case .restored:\n logger.info("Restored \(transaction.payment.productIdentifier)")\n\n didFinishOrRestorePurchase(transaction: transaction)\n\n @unknown default:\n logger.warning("Unknown transactionState = \(transaction.transactionState.rawValue)")\n }\n }\n\n /// Handle failed transaction by finishing it and notifying the observers.\n ///\n /// - Parameter transaction: the failed transaction.\n private func didFailPurchase(transaction: SKPaymentTransaction) {\n paymentQueue.finishTransaction(transaction)\n\n let paymentFailure = if let accountToken = deassociateAccountNumber(transaction.payment) {\n StorePaymentFailure(\n transaction: transaction,\n payment: transaction.payment,\n accountNumber: accountToken,\n error: .storePayment(transaction.error!)\n )\n } else {\n StorePaymentFailure(\n transaction: transaction,\n payment: transaction.payment,\n accountNumber: nil,\n error: .noAccountSet\n )\n }\n\n observerList.notify { observer in\n observer.storePaymentManager(self, didReceiveEvent: .failure(paymentFailure))\n }\n }\n\n /// Handle successful transaction that's in purchased or restored state.\n ///\n /// - Consults with transaction log before handling the transaction. Transactions that are already processed are removed from the payment queue,\n /// observers are not notified as they had already received the corresponding events.\n /// - Keeps transaction in the queue if association between transaction payment and account number cannot be established. Notifies observers with the error.\n /// - Sends the AppStore receipt to backend.\n ///\n /// - Parameter transaction: the transaction that's in purchased or restored state.\n private func didFinishOrRestorePurchase(transaction: SKPaymentTransaction) {\n // Obtain transaction identifier which must be set on transactions with purchased or restored state.\n guard let transactionIdentifier = transaction.transactionIdentifier else {\n logger.warning("Purchased or restored transaction does not contain a transaction identifier!")\n return\n }\n\n // Check if transaction is already processed.\n guard !transactionLog.contains(transactionIdentifier: transactionIdentifier) else {\n logger.debug("Found transaction that is already processed.")\n paymentQueue.finishTransaction(transaction)\n return\n }\n\n // Find the account number associated with the payment.\n guard let accountNumber = deassociateAccountNumber(transaction.payment) else {\n logger.debug("Cannot locate the account associated with the purchase. Keep transaction in the queue.")\n\n let event = StorePaymentEvent.failure(\n StorePaymentFailure(\n transaction: transaction,\n payment: transaction.payment,\n accountNumber: nil,\n error: .noAccountSet\n )\n )\n\n observerList.notify { observer in\n observer.storePaymentManager(self, didReceiveEvent: event)\n }\n return\n }\n\n // Send the AppStore receipt to the backend.\n _ = sendStoreReceipt(accountNumber: accountNumber, forceRefresh: false) { result in\n self.didSendStoreReceipt(\n accountNumber: accountNumber,\n transactionIdentifier: transactionIdentifier,\n transaction: transaction,\n result: result\n )\n }\n }\n\n /// Handles the result of uploading the AppStore receipt to the backend.\n ///\n /// If the server response is successful, this function adds the transaction identifier to the transaction log to make sure that the same transaction is not\n /// processed twice, then finishes the transaction.\n ///\n /// This is important because the call to `SKPaymentQueue.finishTransaction()` may fail, causing the same transaction to re-appear on the payment\n /// queue. Since the transaction was already processed, no action needs to be performed besides another attempt to finish it and hopefully remove it from\n /// the payment queue for good.\n ///\n /// If the server response indicates an error, then this function keeps the transaction in the payment queue in order to process it again later.\n ///\n /// Finally, the ``StorePaymentEvent`` is produced and dispatched to observers to notify them on the progress.\n ///\n /// - Parameters:\n /// - accountNumber: the account number to credit\n /// - transactionIdentifier: the transaction identifier\n /// - transaction: the transaction object\n /// - result: the result of uploading the AppStore receipt to the backend.\n private func didSendStoreReceipt(\n accountNumber: String,\n transactionIdentifier: String,\n transaction: SKPaymentTransaction,\n result: Result<REST.CreateApplePaymentResponse, Error>\n ) {\n var event: StorePaymentEvent?\n\n switch result {\n case let .success(response):\n // Save transaction identifier to transaction log to identify it later if it resurrects on the payment queue.\n transactionLog.add(transactionIdentifier: transactionIdentifier)\n\n // Finish transaction to remove it from the payment queue.\n paymentQueue.finishTransaction(transaction)\n\n event = StorePaymentEvent.finished(StorePaymentCompletion(\n transaction: transaction,\n accountNumber: accountNumber,\n serverResponse: response\n ))\n\n case let .failure(error as StorePaymentManagerError):\n logger.debug("Failed to upload the receipt. Keep transaction in the queue.")\n\n event = StorePaymentEvent.failure(StorePaymentFailure(\n transaction: transaction,\n payment: transaction.payment,\n accountNumber: accountNumber,\n error: error\n ))\n\n default:\n break\n }\n\n if let event {\n observerList.notify { observer in\n observer.storePaymentManager(self, didReceiveEvent: event)\n }\n }\n }\n}\n\n// swiftlint:disable:this file_length\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StorePaymentManager.swift | StorePaymentManager.swift | Swift | 18,264 | 0.95 | 0.03913 | 0.30179 | awesome-app | 137 | 2024-05-07T18:55:17.359490 | MIT | false | 5d0e0ab8263d530d96163c8191f0f8f9 |
//\n// StorePaymentManagerDelegate.swift\n// MullvadVPN\n//\n// Created by pronebird on 03/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport StoreKit\n\nprotocol StorePaymentManagerDelegate: AnyObject, Sendable {\n /// Return the account number associated with the payment.\n /// Usually called for unfinished transactions coming back after the app was restarted.\n func storePaymentManager(_ manager: StorePaymentManager, didRequestAccountTokenFor payment: SKPayment) -> String?\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StorePaymentManagerDelegate.swift | StorePaymentManagerDelegate.swift | Swift | 532 | 0.95 | 0.0625 | 0.642857 | python-kit | 720 | 2024-11-08T03:47:02.777893 | Apache-2.0 | false | c94874951c10f0ee8055304057ba4186 |
//\n// StorePaymentManagerError.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\n/// An error type emitted by `StorePaymentManager`.\nenum StorePaymentManagerError: LocalizedError, WrappingError {\n /// Failure to find the account token associated with the transaction.\n case noAccountSet\n\n /// Failure to validate the account token.\n case validateAccount(Error)\n\n /// Failure to handle payment transaction. Contains error returned by StoreKit.\n case storePayment(Error)\n\n /// Failure to read the AppStore receipt.\n case readReceipt(Error)\n\n /// Failure to send the AppStore receipt to backend.\n case sendReceipt(Error)\n\n var errorDescription: String? {\n switch self {\n case .noAccountSet:\n return "Account is not set."\n case .validateAccount:\n return "Account validation error."\n case .storePayment:\n return "Store payment error."\n case .readReceipt:\n return "Read recept error."\n case .sendReceipt:\n return "Send receipt error."\n }\n }\n\n var underlyingError: Error? {\n switch self {\n case .noAccountSet:\n return nil\n case let .sendReceipt(error):\n return error\n case let .validateAccount(error):\n return error\n case let .readReceipt(error):\n return error\n case let .storePayment(error):\n return error\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StorePaymentManagerError.swift | StorePaymentManagerError.swift | Swift | 1,594 | 0.95 | 0.033898 | 0.254902 | awesome-app | 784 | 2024-05-11T18:26:44.604416 | GPL-3.0 | false | ccf370e096520eeb283fde572baa6b5a |
//\n// StorePaymentObserver.swift\n// MullvadVPN\n//\n// Created by pronebird on 03/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\n\nprotocol StorePaymentObserver: AnyObject, Sendable {\n func storePaymentManager(\n _ manager: StorePaymentManager,\n didReceiveEvent event: StorePaymentEvent\n )\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StorePaymentObserver.swift | StorePaymentObserver.swift | Swift | 354 | 0.95 | 0 | 0.5 | python-kit | 156 | 2024-01-16T15:56:59.967176 | Apache-2.0 | false | 837e594cab30f303be3b26808562ccc1 |
//\n// StoreSubscription.swift\n// MullvadVPN\n//\n// Created by pronebird on 03/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport StoreKit\n\nenum StoreSubscription: String, CaseIterable {\n /// Thirty days non-renewable subscription\n case thirtyDays = "net.mullvad.MullvadVPN.subscription.30days"\n case ninetyDays = "net.mullvad.MullvadVPN.subscription.90days"\n\n var localizedTitle: String {\n switch self {\n case .thirtyDays:\n return NSLocalizedString(\n "STORE_SUBSCRIPTION_TITLE_ADD_30_DAYS",\n tableName: "StoreSubscriptions",\n value: "Add 30 days",\n comment: ""\n )\n case .ninetyDays:\n return NSLocalizedString(\n "STORE_SUBSCRIPTION_TITLE_ADD_90_DAYS",\n tableName: "StoreSubscriptions",\n value: "Add 90 days",\n comment: ""\n )\n }\n }\n}\n\nextension SKProduct {\n var customLocalizedTitle: String? {\n guard let localizedTitle = StoreSubscription(rawValue: productIdentifier)?.localizedTitle,\n let localizedPrice else {\n return nil\n }\n return "\(localizedTitle) (\(localizedPrice))"\n }\n}\n\nextension Set<StoreSubscription> {\n var productIdentifiersSet: Set<String> {\n Set<String>(map { $0.rawValue })\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StoreSubscription.swift | StoreSubscription.swift | Swift | 1,415 | 0.95 | 0.019608 | 0.173913 | node-utils | 906 | 2024-11-21T09:12:41.651708 | GPL-3.0 | false | cc769409c89fc6b87f0ca73ace7eae96 |
//\n// StoreTransactionLog.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\n\n/// Transaction log responsible for storing and querying processed transactions.\n///\n/// This class is thread safe.\nfinal class StoreTransactionLog: @unchecked Sendable {\n private let logger = Logger(label: "StoreTransactionLog")\n private var transactionIdentifiers: Set<String> = []\n private let stateLock = NSLock()\n\n /// The location of the transaction log file on disk.\n let fileURL: URL\n\n /// Default location for the transaction log.\n static var defaultFileURL: URL {\n let directories = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)\n let location = directories.first?.appendingPathComponent("transaction.log", isDirectory: false)\n // swiftlint:disable:next force_unwrapping\n return location!\n }\n\n /// Default transaction log.\n static let `default` = StoreTransactionLog(fileURL: defaultFileURL)\n\n /// Initialize the new transaction log.\n ///\n /// - Warning: Panics on attempt to initialize with a non-file URL.\n ///\n /// - Parameter fileURL: a file URL to the transaction log file within the local filesystem.\n init(fileURL: URL) {\n precondition(fileURL.isFileURL, "Only local filesystem URLs are accepted.")\n self.fileURL = fileURL\n }\n\n /// Check if transaction log contains the transaction identifier.\n ///\n /// - Parameter transactionIdentifier: a transaction identifier.\n /// - Returns: `true` if transaction log contains such transaction identifier, otherwise `false`.\n func contains(transactionIdentifier: String) -> Bool {\n stateLock.withLock {\n transactionIdentifiers.contains(transactionIdentifier)\n }\n }\n\n /// Add transaction identifier into transaction log.\n ///\n /// Automatically persists the transaction log for new transaction identifiers. Returns immediately If the transaction identifier is already present in the\n /// transaction log.\n ///\n /// - Parameter transactionIdentifier: a transaction identifier.\n func add(transactionIdentifier: String) {\n stateLock.withLock {\n guard !transactionIdentifiers.contains(transactionIdentifier) else { return }\n\n transactionIdentifiers.insert(transactionIdentifier)\n persist()\n }\n }\n\n /// Read transaction log from file.\n func read() {\n stateLock.withLock {\n do {\n let serializedString = try String(contentsOf: fileURL)\n transactionIdentifiers = deserialize(from: serializedString)\n } catch {\n switch error {\n case CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile:\n // Ignore errors pointing at missing transaction log file.\n break\n default:\n logger.error(error: error, message: "Failed to load transaction log from disk.")\n }\n }\n }\n }\n\n /// Persist the transaction identifiers on disk.\n /// Creates the cache directory if it doesn't exist yet.\n private func persist() {\n let serializedData = serialize()\n\n do {\n try persistInner(serializedString: serializedData)\n } catch CocoaError.fileNoSuchFile {\n createDirectoryAndPersist(serializedString: serializedData)\n } catch {\n logger.error(error: error, message: "Failed to persist transaction log.")\n }\n }\n\n /// Create the cache directory, then write the transaction log.\n /// - Parameter serializedString: serialized transaction log.\n private func createDirectoryAndPersist(serializedString: String) {\n do {\n try FileManager.default.createDirectory(\n at: fileURL.deletingLastPathComponent(),\n withIntermediateDirectories: true\n )\n } catch {\n logger.error(\n error: error,\n message: "Failed to create a directory for transaction log. Trying to persist once again."\n )\n }\n\n do {\n try persistInner(serializedString: serializedString)\n } catch {\n logger.error(error: error, message: "Failed to persist transaction log.")\n }\n }\n\n /// Serialize transaction log into a string.\n /// - Returns: string that contains a serialized transaction log.\n private func serialize() -> String {\n transactionIdentifiers.joined(separator: "\n")\n }\n\n /// Deserialize transaction log from a string.\n /// - Parameter serializedString: serialized string representation of a transaction log.\n /// - Returns: a set of transaction identifiers.\n private func deserialize(from serializedString: String) -> Set<String> {\n let transactionIdentifiers = serializedString.split { $0.isNewline }\n .map { String($0) }\n\n return Set(transactionIdentifiers)\n }\n\n /// Write a list of transaction identifiers on disk.\n ///\n /// Transaction identifiers are stored as one per line.\n /// Always ensures to exclude the transaction log file from backups after writing contents on disk.\n /// - Parameter serializedString: serialized transaction log\n private func persistInner(serializedString: String) throws {\n try serializedString.write(to: fileURL, atomically: true, encoding: .utf8)\n excludeFromBackups()\n }\n\n /// Exclude transaction log file from backups.\n private func excludeFromBackups() {\n do {\n var resourceValues = URLResourceValues()\n resourceValues.isExcludedFromBackup = true\n\n var mutableFileURL = fileURL\n try mutableFileURL.setResourceValues(resourceValues)\n } catch {\n logger.error(error: error, message: "Failed to exclude transaction log from backups.")\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\StorePaymentManager\StoreTransactionLog.swift | StoreTransactionLog.swift | Swift | 6,031 | 0.95 | 0.142857 | 0.326241 | vue-tools | 520 | 2024-09-13T14:22:40.738315 | MIT | false | 562c4ec1128b0b0cf39e3163e1195f35 |
//\n// PacketTunnelTransport.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadRustRuntime\nimport MullvadTypes\nimport Operations\nimport PacketTunnelCore\n\nstruct PacketTunnelTransport: RESTTransport {\n var name: String {\n "packet-tunnel"\n }\n\n let tunnel: any TunnelProtocol\n\n init(tunnel: any TunnelProtocol) {\n self.tunnel = tunnel\n }\n\n func sendRequest(\n _ request: URLRequest,\n completion: @escaping @Sendable (Data?, URLResponse?, Error?) -> Void\n ) -> Cancellable {\n let proxyRequest = ProxyURLRequest(\n id: UUID(),\n urlRequest: request\n )\n\n // If the URL provided to the proxy request was invalid, indicate failure via `.badURL` and return a no-op.\n guard let proxyRequest else {\n completion(nil, nil, URLError(.badURL))\n return AnyCancellable {}\n }\n\n return tunnel.sendRequest(proxyRequest) { result in\n switch result {\n case let .success(reply):\n completion(\n reply.data,\n reply.response?.originalResponse,\n reply.error?.originalError\n )\n\n case let .failure(error):\n let returnError = error.isOperationCancellationError ? URLError(.cancelled) : error\n\n completion(nil, nil, returnError)\n }\n }\n }\n}\n\nfinal class PacketTunnelAPITransport: APITransportProtocol {\n var name: String {\n "packet-tunnel-transport"\n }\n\n let tunnel: any TunnelProtocol\n\n init(tunnel: any TunnelProtocol) {\n self.tunnel = tunnel\n }\n\n func sendRequest(\n _ request: APIRequest,\n completion: @escaping @Sendable (ProxyAPIResponse) -> Void\n ) -> Cancellable {\n let proxyRequest = ProxyAPIRequest(\n id: UUID(),\n request: request\n )\n\n return tunnel.sendAPIRequest(proxyRequest) { result in\n switch result {\n case let .success(reply):\n completion(reply)\n\n case let .failure(error):\n let error = error.isOperationCancellationError ? URLError(.cancelled) : error\n completion(ProxyAPIResponse(data: nil, error: APIError(\n statusCode: 0,\n errorDescription: error.localizedDescription,\n serverResponseCode: nil\n )))\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TransportMonitor\PacketTunnelTransport.swift | PacketTunnelTransport.swift | Swift | 2,596 | 0.95 | 0.031579 | 0.1 | vue-tools | 326 | 2025-06-04T06:50:00.100428 | GPL-3.0 | false | 3d2acc067d5b1a08b31b0c981c566476 |
//\n// TransportMonitor.swift\n// MullvadVPN\n//\n// Created by Sajad Vishkai on 2022-10-07.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadTypes\n\nfinal class TransportMonitor: RESTTransportProvider {\n private let tunnelManager: TunnelManager\n private let tunnelStore: TunnelStore\n private let transportProvider: TransportProvider\n\n // MARK: -\n\n // MARK: Public API\n\n init(tunnelManager: TunnelManager, tunnelStore: TunnelStore, transportProvider: TransportProvider) {\n self.tunnelManager = tunnelManager\n self.tunnelStore = tunnelStore\n self.transportProvider = transportProvider\n }\n\n /// Selects a transport to use for sending an `URLRequest`\n ///\n /// This method returns the appropriate transport layer based on whether a tunnel is available, and whether it should be bypassed whenever a transport is\n /// requested.\n ///\n /// - Returns: A transport to use for sending an `URLRequest`\n func makeTransport() -> RESTTransport? {\n let tunnel = tunnelStore.getPersistentTunnels().first { tunnel in\n tunnel.status == .connecting || tunnel.status == .reasserting || tunnel.status == .connected\n }\n\n if let tunnel, shouldBypassVPN(tunnel: tunnel) {\n return PacketTunnelTransport(tunnel: tunnel)\n } else {\n return transportProvider.makeTransport()\n }\n }\n\n private func shouldBypassVPN(tunnel: any TunnelProtocol) -> Bool {\n switch tunnel.status {\n case .connected:\n if case .error = tunnelManager.tunnelStatus.state {\n return true\n }\n return tunnelManager.isConfigurationLoaded && tunnelManager.deviceState == .revoked\n\n case .connecting, .reasserting:\n return true\n\n default:\n return false\n }\n }\n}\n\nfinal class APITransportMonitor: APITransportProviderProtocol {\n private let tunnelManager: TunnelManager\n private let tunnelStore: TunnelStore\n private let requestFactory: MullvadApiRequestFactory\n\n init(tunnelManager: TunnelManager, tunnelStore: TunnelStore, requestFactory: MullvadApiRequestFactory) {\n self.tunnelManager = tunnelManager\n self.tunnelStore = tunnelStore\n self.requestFactory = requestFactory\n }\n\n func makeTransport() -> APITransportProtocol? {\n let tunnel = tunnelStore.getPersistentTunnels().first { tunnel in\n tunnel.status == .connecting || tunnel.status == .reasserting || tunnel.status == .connected\n }\n\n return if let tunnel, shouldBypassVPN(tunnel: tunnel) {\n PacketTunnelAPITransport(tunnel: tunnel)\n } else {\n APITransport(requestFactory: requestFactory)\n }\n }\n\n private func shouldBypassVPN(tunnel: any TunnelProtocol) -> Bool {\n switch tunnel.status {\n case .connected:\n if case .error = tunnelManager.tunnelStatus.state {\n true\n } else {\n tunnelManager.isConfigurationLoaded && tunnelManager.deviceState == .revoked\n }\n\n case .connecting, .reasserting:\n true\n\n default:\n false\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TransportMonitor\TransportMonitor.swift | TransportMonitor.swift | Swift | 3,282 | 0.95 | 0.097087 | 0.174419 | node-utils | 800 | 2024-09-15T18:01:26.294325 | MIT | false | 6da1babc05030b032ca4d7abf4bcf054 |
//\n// BackgroundTaskProvider.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-10-02.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\n#if canImport(UIKit)\n\nimport Foundation\nimport UIKit\n\n@available(iOSApplicationExtension, unavailable)\npublic protocol BackgroundTaskProviding: Sendable {\n var backgroundTimeRemaining: TimeInterval { get }\n nonisolated func beginBackgroundTask(\n withName taskName: String?,\n expirationHandler handler: (@MainActor @Sendable () -> Void)?\n ) -> UIBackgroundTaskIdentifier\n\n func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier)\n}\n\n@available(iOSApplicationExtension, unavailable)\npublic final class BackgroundTaskProvider: BackgroundTaskProviding {\n nonisolated(unsafe) public var backgroundTimeRemaining: TimeInterval\n nonisolated(unsafe) weak var application: UIApplication!\n\n public init(backgroundTimeRemaining: TimeInterval, application: UIApplication) {\n self.backgroundTimeRemaining = backgroundTimeRemaining\n self.application = application\n }\n\n nonisolated public func beginBackgroundTask(\n withName taskName: String?,\n expirationHandler handler: (@MainActor @Sendable () -> Void)? = nil\n ) -> UIBackgroundTaskIdentifier {\n application.beginBackgroundTask(withName: taskName, expirationHandler: handler)\n }\n\n public func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier) {\n application.endBackgroundTask(identifier)\n }\n}\n#endif\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\BackgroundTaskProvider.swift | BackgroundTaskProvider.swift | Swift | 1,509 | 0.95 | 0.043478 | 0.236842 | awesome-app | 921 | 2023-12-12T01:01:51.570811 | BSD-3-Clause | false | 3034ef3d3855effa72c008d3f534ffb0 |
//\n// LoadTunnelConfigurationOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 16/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\n\nclass LoadTunnelConfigurationOperation: ResultOperation<Void>, @unchecked Sendable {\n private let logger = Logger(label: "LoadTunnelConfigurationOperation")\n private let interactor: TunnelInteractor\n\n init(dispatchQueue: DispatchQueue, interactor: TunnelInteractor) {\n self.interactor = interactor\n\n super.init(dispatchQueue: dispatchQueue)\n }\n\n override func main() {\n let settingsResult = readSettings()\n let deviceStateResult = readDeviceState()\n\n let persistentTunnels = interactor.getPersistentTunnels()\n let tunnel = persistentTunnels.first\n let settings = settingsResult.flattenValue()\n let deviceState = deviceStateResult.flattenValue()\n\n interactor.setSettings(settings ?? LatestTunnelSettings(), persist: false)\n interactor.setDeviceState(deviceState ?? .loggedOut, persist: false)\n\n if let tunnel, deviceState == nil {\n logger.debug("Remove orphaned VPN configuration.")\n\n tunnel.removeFromPreferences { error in\n if let error {\n self.logger.error(\n error: error,\n message: "Failed to remove VPN configuration."\n )\n }\n self.finishOperation(tunnel: nil)\n }\n } else {\n finishOperation(tunnel: tunnel)\n }\n }\n\n private func finishOperation(tunnel: (any TunnelProtocol)?) {\n interactor.setTunnel(tunnel, shouldRefreshTunnelState: true)\n interactor.setConfigurationLoaded()\n\n finish(result: .success(()))\n }\n\n private func readSettings() -> Result<LatestTunnelSettings?, Error> {\n Result { try SettingsManager.readSettings() }\n .flatMapError { error in\n if let error = error as? ReadSettingsVersionError,\n let keychainError = error.underlyingError as? KeychainError, keychainError == .itemNotFound {\n logger.debug("Settings not found in keychain.")\n\n return .success(nil)\n } else {\n logger.error(\n error: error,\n message: "Cannot read settings."\n )\n\n return .failure(error)\n }\n }\n }\n\n private func readDeviceState() -> Result<DeviceState?, Error> {\n Result { try SettingsManager.readDeviceState() }\n .flatMapError { error in\n if let error = error as? KeychainError, error == .itemNotFound {\n logger.debug("Device state not found in keychain.")\n\n return .success(nil)\n } else {\n logger.error(\n error: error,\n message: "Cannot read device state."\n )\n\n return .failure(error)\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\LoadTunnelConfigurationOperation.swift | LoadTunnelConfigurationOperation.swift | Swift | 3,227 | 0.95 | 0.072165 | 0.0875 | awesome-app | 689 | 2023-12-13T09:31:09.530987 | BSD-3-Clause | false | e39a53455cf816bcb95261c870fd994e |
//\n// MapConnectionStatusOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadTypes\nimport NetworkExtension\nimport Operations\nimport PacketTunnelCore\n\nclass MapConnectionStatusOperation: AsyncOperation, @unchecked Sendable {\n private let interactor: TunnelInteractor\n private let connectionStatus: NEVPNStatus\n private var request: Cancellable?\n private var pathStatus: Network.NWPath.Status?\n\n private let logger = Logger(label: "TunnelManager.MapConnectionStatusOperation")\n\n required init(\n queue: DispatchQueue,\n interactor: TunnelInteractor,\n connectionStatus: NEVPNStatus,\n networkStatus: Network.NWPath.Status?\n ) {\n self.interactor = interactor\n self.connectionStatus = connectionStatus\n pathStatus = networkStatus\n\n super.init(dispatchQueue: queue)\n }\n\n // swiftlint:disable:next function_body_length\n override func main() {\n guard let tunnel = interactor.tunnel else {\n setTunnelDisconnectedStatus()\n\n finish()\n return\n }\n\n let tunnelState = interactor.tunnelStatus.state\n\n switch connectionStatus {\n case .connecting, .reasserting, .connected:\n fetchTunnelStatus(tunnel: tunnel) { observedState in\n switch observedState {\n case let .connected(connectionState):\n return connectionState.isNetworkReachable\n ? .connected(\n connectionState.selectedRelays,\n isPostQuantum: connectionState.isPostQuantum,\n isDaita: connectionState.isDaitaEnabled\n )\n : .waitingForConnectivity(.noConnection)\n case let .connecting(connectionState):\n return connectionState.isNetworkReachable\n ? .connecting(\n connectionState.selectedRelays,\n isPostQuantum: connectionState.isPostQuantum,\n isDaita: connectionState.isDaitaEnabled\n )\n : .waitingForConnectivity(.noConnection)\n case let .negotiatingEphemeralPeer(connectionState, privateKey):\n return connectionState.isNetworkReachable\n ? .negotiatingEphemeralPeer(\n connectionState.selectedRelays,\n privateKey,\n isPostQuantum: connectionState.isPostQuantum,\n isDaita: connectionState.isDaitaEnabled\n )\n : .waitingForConnectivity(.noConnection)\n case let .reconnecting(connectionState):\n return connectionState.isNetworkReachable\n ? .reconnecting(\n connectionState.selectedRelays,\n isPostQuantum: connectionState.isPostQuantum,\n isDaita: connectionState.isDaitaEnabled\n )\n : .waitingForConnectivity(.noConnection)\n case let .error(blockedState):\n return .error(blockedState.reason)\n case .initial, .disconnecting, .disconnected:\n return .none\n }\n }\n return\n\n case .disconnected:\n handleDisconnectedState(tunnelState)\n\n case .disconnecting:\n handleDisconnectingState(tunnelState)\n\n case .invalid:\n setTunnelDisconnectedStatus()\n\n @unknown default:\n logger.debug("Unknown NEVPNStatus: \(connectionStatus.rawValue)")\n }\n\n finish()\n }\n\n override func operationDidCancel() {\n request?.cancel()\n }\n\n private func handleDisconnectingState(_ tunnelState: TunnelState) {\n switch tunnelState {\n case .disconnecting:\n break\n default:\n interactor.updateTunnelStatus { tunnelStatus in\n // Avoid displaying waiting for connectivity banners if the tunnel in a blocked state when disconnecting\n if tunnelStatus.observedState.blockedState != nil {\n tunnelStatus.state = .disconnecting(.nothing)\n } else {\n let isNetworkReachable = tunnelStatus.observedState.connectionState?.isNetworkReachable ?? false\n tunnelStatus.state = isNetworkReachable\n ? .disconnecting(.nothing)\n : .waitingForConnectivity(.noNetwork)\n }\n }\n }\n }\n\n private func handleDisconnectedState(_ tunnelState: TunnelState) {\n switch tunnelState {\n case .pendingReconnect:\n logger.debug("Ignore disconnected state when pending reconnect.")\n\n case .disconnecting(.reconnect):\n logger.debug("Restart the tunnel on disconnect.")\n interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus = TunnelStatus()\n tunnelStatus.state = .pendingReconnect\n }\n interactor.startTunnel()\n\n default:\n setTunnelDisconnectedStatus()\n }\n }\n\n private func setTunnelDisconnectedStatus() {\n interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus = TunnelStatus()\n tunnelStatus.state = pathStatus == .unsatisfied\n ? .waitingForConnectivity(.noNetwork)\n : .disconnected\n }\n }\n\n private func fetchTunnelStatus(\n tunnel: any TunnelProtocol,\n mapToState: @escaping @Sendable (ObservedState) -> TunnelState?\n ) {\n request = tunnel.getTunnelStatus { [weak self] result in\n guard let self else { return }\n\n dispatchQueue.async {\n if case let .success(observedState) = result, !self.isCancelled {\n self.interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus.observedState = observedState\n\n if let newState = mapToState(observedState) {\n tunnelStatus.state = newState\n }\n }\n }\n\n self.finish()\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\MapConnectionStatusOperation.swift | MapConnectionStatusOperation.swift | Swift | 6,567 | 0.95 | 0.054945 | 0.056962 | node-utils | 312 | 2025-02-14T16:44:40.213723 | MIT | false | fa4d0262706cd5b641da11cba048d2b6 |
//\n// RedeemVoucherOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 29/03/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\n\nclass RedeemVoucherOperation: ResultOperation<REST.SubmitVoucherResponse>, @unchecked Sendable {\n private let logger = Logger(label: "RedeemVoucherOperation")\n private let interactor: TunnelInteractor\n\n private let voucherCode: String\n private let apiProxy: APIQuerying\n private var task: Cancellable?\n\n init(\n dispatchQueue: DispatchQueue,\n interactor: TunnelInteractor,\n voucherCode: String,\n apiProxy: APIQuerying\n ) {\n self.interactor = interactor\n self.voucherCode = voucherCode\n self.apiProxy = apiProxy\n\n super.init(dispatchQueue: dispatchQueue)\n }\n\n override func main() {\n guard case let .loggedIn(accountData, _) = interactor.deviceState else {\n finish(result: .failure(InvalidDeviceStateError()))\n return\n }\n task = apiProxy.submitVoucher(\n voucherCode: voucherCode,\n accountNumber: accountData.number,\n retryStrategy: .default\n ) { result in\n self.dispatchQueue.async {\n self.didReceiveVoucherResponse(result: result)\n }\n }\n }\n\n override func operationDidCancel() {\n task?.cancel()\n task = nil\n }\n\n private func didReceiveVoucherResponse(result: Result<REST.SubmitVoucherResponse, Error>) {\n let result = result.inspectError { error in\n guard !error.isOperationCancellationError else { return }\n\n self.logger.error(\n error: error,\n message: "Failed to redeem voucher."\n )\n }.tryMap { voucherResponse in\n switch interactor.deviceState {\n case .loggedIn(var storedAccountData, let storedDeviceData):\n storedAccountData.expiry = voucherResponse.newExpiry\n\n let newDeviceState = DeviceState.loggedIn(storedAccountData, storedDeviceData)\n\n interactor.setDeviceState(newDeviceState, persist: true)\n\n return voucherResponse\n\n default:\n throw InvalidDeviceStateError()\n }\n }\n\n finish(result: result)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\RedeemVoucherOperation.swift | RedeemVoucherOperation.swift | Swift | 2,436 | 0.95 | 0.02381 | 0.1 | vue-tools | 436 | 2024-10-29T17:58:25.328496 | BSD-3-Clause | false | 77d9904d8be9fd308ec381e8c095ed2e |
//\n// RotateKeyOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport WireGuardKitTypes\n\nclass RotateKeyOperation: ResultOperation<Void>, @unchecked Sendable {\n private let logger = Logger(label: "RotateKeyOperation")\n private let interactor: TunnelInteractor\n private let devicesProxy: DeviceHandling\n private var task: Cancellable?\n\n init(dispatchQueue: DispatchQueue, interactor: TunnelInteractor, devicesProxy: DeviceHandling) {\n self.interactor = interactor\n self.devicesProxy = devicesProxy\n\n super.init(dispatchQueue: dispatchQueue, completionQueue: nil, completionHandler: nil)\n }\n\n override func main() {\n // Extract login metadata.\n guard case let .loggedIn(accountData, deviceData) = interactor.deviceState else {\n finish(result: .failure(InvalidDeviceStateError()))\n return\n }\n\n // Create key rotation.\n nonisolated(unsafe) var keyRotation = WgKeyRotation(data: deviceData)\n\n // Check if key rotation can take place.\n guard keyRotation.shouldRotate else {\n logger.debug("Throttle private key rotation.")\n finish(result: .success(()))\n return\n }\n\n logger.debug("Private key is old enough, rotate right away.")\n\n // Mark the beginning of key rotation and receive the public key to push to backend.\n let publicKey = keyRotation.beginAttempt()\n\n // Persist mutated device data.\n interactor.setDeviceState(.loggedIn(accountData, keyRotation.data), persist: true)\n\n // Send REST request to rotate the device key.\n logger.debug("Replacing old key with new key on server...")\n\n task = devicesProxy.rotateDeviceKey(\n accountNumber: accountData.number,\n identifier: deviceData.identifier,\n publicKey: publicKey,\n retryStrategy: .default\n ) { [self] result in\n dispatchQueue.async { [self] in\n switch result {\n case let .success(device):\n handleSuccess(accountData: accountData, fetchedDevice: device, keyRotation: keyRotation)\n case let .failure(error):\n handleError(error)\n }\n }\n }\n }\n\n override func operationDidCancel() {\n task?.cancel()\n task = nil\n }\n\n private func handleSuccess(accountData: StoredAccountData, fetchedDevice: Device, keyRotation: WgKeyRotation) {\n logger.debug("Successfully rotated device key. Persisting device state...")\n\n var keyRotation = keyRotation\n\n // Mark key rotation completed.\n _ = keyRotation.setCompleted(with: fetchedDevice)\n\n // Persist changes.\n interactor.setDeviceState(.loggedIn(accountData, keyRotation.data), persist: true)\n\n // Notify the tunnel that key rotation took place and that it should reload VPN configuration.\n if let tunnel = interactor.tunnel {\n _ = tunnel.notifyKeyRotation { [weak self] _ in\n self?.finish(result: .success(()))\n }\n } else {\n finish(result: .success(()))\n }\n }\n\n private func handleError(_ error: Error) {\n if !error.isOperationCancellationError {\n logger.error(error: error, message: "Failed to rotate device key.")\n }\n\n interactor.handleRestError(error)\n finish(result: .failure(error))\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\RotateKeyOperation.swift | RotateKeyOperation.swift | Swift | 3,662 | 0.95 | 0.045872 | 0.179775 | awesome-app | 397 | 2024-05-11T23:37:13.132341 | GPL-3.0 | false | 23899ee31bff27a1246eeef960106366 |
//\n// SetAccountOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 16/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\n@preconcurrency import WireGuardKitTypes\n\nenum SetAccountAction {\n /// Set new account.\n case new\n\n /// Set existing account.\n case existing(String)\n\n /// Unset account.\n case unset\n\n /// Delete account.\n case delete(String)\n\n var taskName: String {\n switch self {\n case .new: "Set new account"\n case .existing: "Set existing account"\n case .unset: "Unset account"\n case .delete: "Delete account"\n }\n }\n}\n\nclass SetAccountOperation: ResultOperation<StoredAccountData?>, @unchecked Sendable {\n private let interactor: TunnelInteractor\n private let accountsProxy: RESTAccountHandling\n private let devicesProxy: DeviceHandling\n private let action: SetAccountAction\n private let accessTokenManager: RESTAccessTokenManagement\n\n private let logger = Logger(label: "SetAccountOperation")\n private var tasks: [Cancellable] = []\n\n init(\n dispatchQueue: DispatchQueue,\n interactor: TunnelInteractor,\n accountsProxy: RESTAccountHandling,\n devicesProxy: DeviceHandling,\n accessTokenManager: RESTAccessTokenManagement,\n action: SetAccountAction\n ) {\n self.interactor = interactor\n self.accountsProxy = accountsProxy\n self.devicesProxy = devicesProxy\n self.accessTokenManager = accessTokenManager\n self.action = action\n\n super.init(dispatchQueue: dispatchQueue)\n }\n\n // MARK: -\n\n override func main() {\n startLogoutFlow { [self] in\n self.accessTokenManager.invalidateAllTokens()\n switch action {\n case .new:\n startNewAccountFlow { [self] result in\n finish(result: result.map { .some($0) })\n }\n\n case let .existing(accountNumber):\n startExistingAccountFlow(accountNumber: accountNumber) { [self] result in\n finish(result: result.map { .some($0) })\n }\n\n case .unset:\n finish(result: .success(nil))\n\n case let .delete(accountNumber):\n startDeleteAccountFlow(accountNumber: accountNumber) { [self] result in\n finish(result: result.map { .none })\n }\n }\n }\n }\n\n override func operationDidCancel() {\n tasks.forEach { $0.cancel() }\n tasks.removeAll()\n }\n\n // MARK: - Private\n\n /**\n Begin logout flow by performing the following steps:\n\n 1. Delete currently logged in device from the API if device is logged in.\n 2. Transition device state to logged out state.\n 3. Remove system VPN configuration if exists.\n 4. Reset tunnel status to disconnected state.\n\n Does nothing if device is already logged out.\n */\n private func startLogoutFlow(completion: @escaping @Sendable () -> Void) {\n switch interactor.deviceState {\n case let .loggedIn(accountData, deviceData):\n deleteDevice(accountNumber: accountData.number, deviceIdentifier: deviceData.identifier) { [self] _ in\n unsetDeviceState(completion: completion)\n }\n\n case .revoked:\n unsetDeviceState(completion: completion)\n\n case .loggedOut:\n completion()\n }\n }\n\n /**\n Begin login flow with a new account and performing the following steps:\n\n 1. Create new account via API.\n 2. Call `continueLoginFlow()` passing the result of account creation request.\n */\n private func startNewAccountFlow(completion: @escaping @Sendable (Result<StoredAccountData, Error>) -> Void) {\n createAccount { [self] result in\n continueLoginFlow(result, completion: completion)\n }\n }\n\n /**\n Begin login flow with an existing account by performing the following steps:\n\n 1. Retrieve existing account from the API.\n 2. Call `continueLoginFlow()` passing the result of account retrieval request.\n */\n private func startExistingAccountFlow(\n accountNumber: String,\n completion: @escaping @Sendable (Result<StoredAccountData, Error>) -> Void\n ) {\n getAccount(accountNumber: accountNumber) { [self] result in\n continueLoginFlow(result, completion: completion)\n }\n }\n\n /**\n Begin delete flow of an existing account by performing the following steps:\n\n 1. Delete existing account with the API.\n 2. Reset tunnel settings to default and remove last used account.\n */\n private func startDeleteAccountFlow(\n accountNumber: String,\n completion: @escaping @Sendable (Result<Void, Error>) -> Void\n ) {\n deleteAccount(accountNumber: accountNumber) { [self] result in\n if result.isSuccess {\n interactor.removeLastUsedAccount()\n }\n\n completion(result)\n }\n }\n\n /**\n Continue login flow after receiving account data as a part of creating new or retrieving existing account from\n the API by performing the following steps:\n\n 1. Store last used account number.\n 2. Create new device with the API.\n 3. Persist settings.\n */\n private func continueLoginFlow(\n _ result: Result<StoredAccountData, Error>,\n completion: @escaping @Sendable (Result<StoredAccountData, Error>) -> Void\n ) {\n do {\n let accountData = try result.get()\n\n storeLastUsedAccount(accountNumber: accountData.number)\n\n createDevice(accountNumber: accountData.number) { [self] result in\n completion(result.map { newDevice in\n storeSettings(accountData: accountData, newDevice: newDevice)\n\n return accountData\n })\n }\n } catch {\n completion(.failure(error))\n }\n }\n\n /// Store last used account number in settings.\n /// Errors are ignored but logged.\n private func storeLastUsedAccount(accountNumber: String) {\n logger.debug("Store last used account.")\n\n do {\n try SettingsManager.setLastUsedAccount(accountNumber)\n } catch {\n logger.error(error: error, message: "Failed to store last used account number.")\n }\n }\n\n /// Store account data and newly created device in settings and transition device state to logged in state.\n private func storeSettings(accountData: StoredAccountData, newDevice: NewDevice) {\n logger.debug("Saving settings...")\n\n // Create stored device data.\n let restDevice = newDevice.device\n let storedDeviceData = StoredDeviceData(\n creationDate: restDevice.created,\n identifier: restDevice.id,\n name: restDevice.name,\n hijackDNS: restDevice.hijackDNS,\n ipv4Address: restDevice.ipv4Address,\n ipv6Address: restDevice.ipv6Address,\n wgKeyData: StoredWgKeyData(\n creationDate: Date(),\n privateKey: newDevice.privateKey\n )\n )\n\n // Transition device state to logged in.\n interactor.setDeviceState(.loggedIn(accountData, storedDeviceData), persist: true)\n }\n\n /// Create new account and produce `StoredAccountData` upon success.\n private func createAccount(completion: @escaping @Sendable (Result<StoredAccountData, Error>) -> Void) {\n logger.debug("Create new account...")\n\n let task = accountsProxy.createAccount(retryStrategy: .default) { [self] result in\n dispatchQueue.async { [self] in\n let result = result.inspectError { error in\n guard !error.isOperationCancellationError else { return }\n\n logger.error(error: error, message: "Failed to create new account.")\n }.map { newAccountData -> StoredAccountData in\n logger.debug("Created new account.")\n\n return StoredAccountData(\n identifier: newAccountData.id,\n number: newAccountData.number,\n expiry: newAccountData.expiry\n )\n }\n\n completion(result)\n }\n }\n\n tasks.append(task)\n }\n\n /// Get account data from the API and produce `StoredAccountData` upon success.\n private func getAccount(\n accountNumber: String,\n completion: @escaping @Sendable (Result<StoredAccountData, Error>) -> Void\n ) {\n logger.debug("Request account data...")\n\n let task = accountsProxy.getAccountData(\n accountNumber: accountNumber,\n retryStrategy: .default\n ) { [self] result in\n dispatchQueue.async { [self] in\n let result = result.inspectError { error in\n guard !error.isOperationCancellationError else { return }\n\n logger.error(error: error, message: "Failed to receive account data.")\n }.map { accountData -> StoredAccountData in\n logger.debug("Received account data.")\n\n return StoredAccountData(\n identifier: accountData.id,\n number: accountNumber,\n expiry: accountData.expiry\n )\n }\n\n completion(result)\n }\n }\n\n tasks.append(task)\n }\n\n /// Delete account.\n private func deleteAccount(accountNumber: String, completion: @escaping @Sendable (Result<Void, Error>) -> Void) {\n logger.debug("Delete account...")\n\n let task = accountsProxy.deleteAccount(\n accountNumber: accountNumber,\n retryStrategy: .default\n ) { [self] result in\n dispatchQueue.async { [self] in\n let result = result.inspectError { error in\n guard !error.isOperationCancellationError else { return }\n\n logger.error(error: error, message: "Failed to delete account.")\n }\n\n completion(result)\n }\n }\n\n tasks.append(task)\n }\n\n /// Delete device from API.\n private func deleteDevice(\n accountNumber: String,\n deviceIdentifier: String,\n completion: @escaping @Sendable (Error?) -> Void\n ) {\n logger.debug("Delete current device...")\n\n let task = devicesProxy.deleteDevice(\n accountNumber: accountNumber,\n identifier: deviceIdentifier,\n retryStrategy: .default\n ) { [self] result in\n dispatchQueue.async { [self] in\n switch result {\n case let .success(isDeleted):\n logger.debug(isDeleted ? "Deleted device." : "Device is already deleted.")\n\n case let .failure(error):\n if !error.isOperationCancellationError {\n logger.error(error: error, message: "Failed to delete device.")\n }\n }\n\n completion(result.error)\n }\n }\n\n tasks.append(task)\n }\n\n /**\n Transitions device state into logged out state by performing the following tasks:\n\n 1. Prepare tunnel manager for removal of VPN configuration. In response tunnel manager stops processing VPN status\n notifications coming from VPN configuration.\n 2. Reset device staate to logged out and persist it.\n 3. Remove VPN configuration and release an instance of `Tunnel` object.\n */\n private func unsetDeviceState(completion: @escaping @Sendable () -> Void) {\n // Tell the caller to unsubscribe from VPN status notifications.\n interactor.prepareForVPNConfigurationDeletion()\n\n // Reset tunnel and device state.\n interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus = TunnelStatus()\n tunnelStatus.state = .disconnected\n }\n interactor.setDeviceState(.loggedOut, persist: true)\n\n // Finish immediately if tunnel provider is not set.\n guard let tunnel = interactor.tunnel else {\n completion()\n return\n }\n\n // Remove VPN configuration.\n tunnel.removeFromPreferences { [self] error in\n dispatchQueue.async { [self] in\n // Ignore error but log it.\n if let error {\n logger.error(error: error, message: "Failed to remove VPN configuration.")\n }\n\n interactor.setTunnel(nil, shouldRefreshTunnelState: false)\n\n completion()\n }\n }\n }\n\n /// Create new private key and create new device via API.\n private func createDevice(\n accountNumber: String,\n completion: @escaping @Sendable (Result<NewDevice, Error>) -> Void\n ) {\n let privateKey = PrivateKey()\n let request = REST.CreateDeviceRequest(publicKey: privateKey.publicKey, hijackDNS: false)\n\n logger.debug("Create device...")\n\n let task = devicesProxy\n .createDevice(accountNumber: accountNumber, request: request, retryStrategy: .default) { [self] result in\n dispatchQueue.async { [self] in\n // Due to retry strategy, it's possible for server to register the new key without being\n // able to return the acknowledgment back to client.\n // In that case the subsequent retry attempt will error with `.publicKeyInUse`. Fetch the device\n // from API when that happens.\n if let error = result.error as? REST.Error, error.compareErrorCode(.publicKeyInUse) {\n self.findDevice(accountNumber: accountNumber, publicKey: privateKey.publicKey) { result in\n let result = result.flatMap { device in\n if let device {\n return .success(NewDevice(privateKey: privateKey, device: device))\n } else {\n return .failure(error)\n }\n }\n completion(result)\n }\n } else {\n completion(result.map { NewDevice(privateKey: privateKey, device: $0) })\n }\n }\n }\n\n tasks.append(task)\n }\n\n /// Find device by public key in the list of devices registered on server. The result passed to `completion` handler\n /// may contain `nil` if such device is not found for some reason.\n private func findDevice(\n accountNumber: String,\n publicKey: PublicKey,\n completion: @escaping @Sendable (Result<Device?, Error>) -> Void\n ) {\n let task = devicesProxy.getDevices(accountNumber: accountNumber, retryStrategy: .default) { [self] result in\n dispatchQueue.async { [self] in\n let result = result\n .flatMap { devices in\n .success(devices.first { device in\n device.pubkey == publicKey\n })\n }\n .inspectError { error in\n logger.error(error: error, message: "Failed to get devices.")\n }\n\n completion(result)\n }\n }\n\n tasks.append(task)\n }\n\n /// Struct that holds a private key that was used for creating a new device on the API along with the successful\n /// response from the API.\n private struct NewDevice {\n var privateKey: PrivateKey\n var device: Device\n }\n}\n\n// swiftlint:disable:this file_length\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\SetAccountOperation.swift | SetAccountOperation.swift | Swift | 16,011 | 0.95 | 0.05 | 0.127937 | python-kit | 114 | 2023-09-22T01:15:29.896163 | MIT | false | ec9da7f0b8d291e7a930a7f65d0cd05b |
//\n// StartTunnelOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport NetworkExtension\nimport Operations\nimport PacketTunnelCore\n\nclass StartTunnelOperation: ResultOperation<Void>, @unchecked Sendable {\n typealias EncodeErrorHandler = (Error) -> Void\n\n private let interactor: TunnelInteractor\n private let logger = Logger(label: "StartTunnelOperation")\n\n init(\n dispatchQueue: DispatchQueue,\n interactor: TunnelInteractor,\n completionHandler: @escaping CompletionHandler\n ) {\n self.interactor = interactor\n\n super.init(\n dispatchQueue: dispatchQueue,\n completionQueue: dispatchQueue,\n completionHandler: completionHandler\n )\n }\n\n override func main() {\n guard case .loggedIn = interactor.deviceState else {\n finish(result: .failure(InvalidDeviceStateError()))\n return\n }\n\n switch interactor.tunnelStatus.state {\n case .disconnecting(.nothing):\n interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus = TunnelStatus()\n tunnelStatus.state = .disconnecting(.reconnect)\n }\n\n finish(result: .success(()))\n\n case .disconnected, .pendingReconnect, .waitingForConnectivity:\n makeTunnelProviderAndStartTunnel { error in\n self.finish(result: error.map { .failure($0) } ?? .success(()))\n }\n\n default:\n finish(result: .success(()))\n }\n }\n\n private func makeTunnelProviderAndStartTunnel(completionHandler: @escaping @Sendable (Error?) -> Void) {\n makeTunnelProvider { result in\n self.dispatchQueue.async {\n do {\n try self.startTunnel(tunnel: result.get())\n completionHandler(nil)\n } catch {\n completionHandler(error)\n }\n }\n }\n }\n\n private func startTunnel(tunnel: any TunnelProtocol) throws {\n let selectedRelays = try? interactor.selectRelays()\n var tunnelOptions = PacketTunnelOptions()\n\n do {\n if let selectedRelays {\n try tunnelOptions.setSelectedRelays(selectedRelays)\n }\n } catch {\n logger.error(\n error: error,\n message: "Failed to encode the selector result."\n )\n }\n\n interactor.setTunnel(tunnel, shouldRefreshTunnelState: false)\n\n interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus = TunnelStatus()\n tunnelStatus.state = .connecting(\n selectedRelays,\n isPostQuantum: interactor.settings.tunnelQuantumResistance.isEnabled,\n isDaita: interactor.settings.daita.daitaState.isEnabled\n )\n }\n\n try tunnel.start(options: tunnelOptions.rawOptions())\n }\n\n private func makeTunnelProvider(\n completionHandler: @escaping @Sendable (Result<any TunnelProtocol, Error>)\n -> Void\n ) {\n let persistentTunnels = interactor.getPersistentTunnels()\n let tunnel = persistentTunnels.first ?? interactor.createNewTunnel()\n let configuration = TunnelConfiguration(\n includeAllNetworks: interactor.settings.includeAllNetworks,\n excludeLocalNetworks: interactor.settings.localNetworkSharing\n )\n\n tunnel.setConfiguration(configuration)\n tunnel.saveToPreferences { error in\n completionHandler(error.map { .failure($0) } ?? .success(tunnel))\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\StartTunnelOperation.swift | StartTunnelOperation.swift | Swift | 3,779 | 0.95 | 0.075 | 0.068627 | react-lib | 297 | 2023-12-01T11:57:03.027045 | BSD-3-Clause | false | 9b3629f85d16604c58c74844e7ab836a |
//\n// StopTunnelOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 15/12/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport Operations\n\nclass StopTunnelOperation: ResultOperation<Void>, @unchecked Sendable {\n private let interactor: TunnelInteractor\n var isOnDemandEnabled = false\n\n init(\n dispatchQueue: DispatchQueue,\n interactor: TunnelInteractor,\n completionHandler: @escaping CompletionHandler\n ) {\n self.interactor = interactor\n\n super.init(\n dispatchQueue: dispatchQueue,\n completionQueue: dispatchQueue,\n completionHandler: completionHandler\n )\n }\n\n override func main() {\n switch interactor.tunnelStatus.state {\n case .disconnecting(.reconnect):\n interactor.updateTunnelStatus { tunnelStatus in\n tunnelStatus.state = .disconnecting(.nothing)\n }\n\n finish(result: .success(()))\n\n case .connected, .connecting, .reconnecting, .waitingForConnectivity(.noConnection), .error,\n .negotiatingEphemeralPeer:\n doShutDownTunnel()\n\n case .disconnected, .disconnecting, .pendingReconnect, .waitingForConnectivity(.noNetwork):\n finish(result: .success(()))\n }\n }\n\n private func doShutDownTunnel() {\n guard let tunnel = interactor.tunnel else {\n finish(result: .failure(UnsetTunnelError()))\n return\n }\n\n tunnel.isOnDemandEnabled = isOnDemandEnabled\n\n tunnel.saveToPreferences { error in\n self.dispatchQueue.async {\n if let error {\n self.finish(result: .failure(error))\n } else {\n tunnel.stop()\n self.finish(result: .success(()))\n }\n }\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\StopTunnelOperation.swift | StopTunnelOperation.swift | Swift | 1,892 | 0.95 | 0.044776 | 0.125 | node-utils | 43 | 2023-08-15T07:53:26.457743 | GPL-3.0 | false | 1b6dc9f0d1f1b59f22ea2cc73968e178 |
//\n// Tunnel+Messaging.swift\n// MullvadVPN\n//\n// Created by pronebird on 16/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport Operations\nimport PacketTunnelCore\n\n/// Shared operation queue used for IPC requests.\nprivate let operationQueue = AsyncOperationQueue()\n\n/// Shared queue used by IPC operations.\nprivate let dispatchQueue = DispatchQueue(label: "Tunnel.dispatchQueue")\n\n/// Timeout for proxy requests.\nprivate let proxyRequestTimeout = REST.defaultAPINetworkTimeout + 2\n\nextension TunnelProtocol {\n /// Request packet tunnel process to reconnect the tunnel with the given relays.\n func reconnectTunnel(\n to nextRelays: NextRelays,\n completionHandler: @escaping @Sendable (Result<Void, Error>) -> Void\n ) -> Cancellable {\n let operation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .reconnectTunnel(nextRelays),\n decoderHandler: { _ in () },\n completionHandler: completionHandler\n )\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n /// Request status from packet tunnel process.\n func getTunnelStatus(\n completionHandler: @escaping @Sendable (Result<ObservedState, Error>) -> Void\n ) -> Cancellable {\n let decoderHandler: (Data?) throws -> ObservedState = { data in\n if let data {\n return try TunnelProviderReply<ObservedState>(messageData: data).value\n } else {\n throw EmptyTunnelProviderResponseError()\n }\n }\n\n let operation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .getTunnelStatus,\n decoderHandler: decoderHandler,\n completionHandler: completionHandler\n )\n\n operationQueue.addOperation(operation)\n return operation\n }\n\n /// Send HTTP request via packet tunnel process bypassing VPN.\n func sendRequest(\n _ proxyRequest: ProxyURLRequest,\n completionHandler: @escaping @Sendable (Result<ProxyURLResponse, Error>) -> Void\n ) -> Cancellable {\n let decoderHandler: (Data?) throws -> ProxyURLResponse = { data in\n if let data {\n return try TunnelProviderReply<ProxyURLResponse>(messageData: data).value\n } else {\n throw EmptyTunnelProviderResponseError()\n }\n }\n\n let operation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .sendURLRequest(proxyRequest),\n timeout: proxyRequestTimeout,\n decoderHandler: decoderHandler,\n completionHandler: completionHandler\n )\n\n operation.onCancel { [weak self] _ in\n guard let self else { return }\n\n let cancelOperation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .cancelURLRequest(proxyRequest.id),\n decoderHandler: decoderHandler,\n completionHandler: nil\n )\n\n operationQueue.addOperation(cancelOperation)\n }\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n /// Send API request via packet tunnel process bypassing VPN.\n func sendAPIRequest(\n _ proxyRequest: ProxyAPIRequest,\n completionHandler: @escaping @Sendable (Result<ProxyAPIResponse, Error>) -> Void\n ) -> Cancellable {\n let decoderHandler: (Data?) throws -> ProxyAPIResponse = { data in\n if let data {\n return try TunnelProviderReply<ProxyAPIResponse>(messageData: data).value\n } else {\n throw EmptyTunnelProviderResponseError()\n }\n }\n\n let operation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .sendAPIRequest(proxyRequest),\n timeout: proxyRequestTimeout,\n decoderHandler: decoderHandler,\n completionHandler: completionHandler\n )\n\n operation.onCancel { [weak self] _ in\n guard let self else { return }\n\n let cancelOperation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .cancelAPIRequest(proxyRequest.id),\n decoderHandler: decoderHandler,\n completionHandler: nil\n )\n\n operationQueue.addOperation(cancelOperation)\n }\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n /// Notify tunnel about private key rotation.\n func notifyKeyRotation(\n completionHandler: @escaping @Sendable (Result<Void, Error>) -> Void\n ) -> Cancellable {\n let operation = SendTunnelProviderMessageOperation(\n dispatchQueue: dispatchQueue,\n backgroundTaskProvider: backgroundTaskProvider,\n tunnel: self,\n message: .privateKeyRotation,\n decoderHandler: { _ in () },\n completionHandler: completionHandler\n )\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\Tunnel+Messaging.swift | Tunnel+Messaging.swift | Swift | 5,804 | 0.95 | 0.046512 | 0.103448 | react-lib | 550 | 2024-06-27T11:21:01.352317 | GPL-3.0 | false | 812d9791db6efe11f8065cd0af01f3a5 |
//\n// Tunnel.swift\n// MullvadVPN\n//\n// Created by pronebird on 25/02/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\nimport NetworkExtension\n\n// Switch to stabs on simulator\n#if targetEnvironment(simulator)\ntypealias TunnelProviderManagerType = SimulatorTunnelProviderManager\n#else\ntypealias TunnelProviderManagerType = NETunnelProviderManager\n#endif\n\nprotocol TunnelStatusObserver {\n func tunnel(_ tunnel: any TunnelProtocol, didReceiveStatus status: NEVPNStatus)\n}\n\nprotocol TunnelProtocol: AnyObject, Sendable {\n associatedtype TunnelManagerProtocol: VPNTunnelProviderManagerProtocol\n var status: NEVPNStatus { get }\n var isOnDemandEnabled: Bool { get set }\n var startDate: Date? { get }\n var backgroundTaskProvider: BackgroundTaskProviding { get }\n\n init(tunnelProvider: TunnelManagerProtocol, backgroundTaskProvider: BackgroundTaskProviding)\n\n func addObserver(_ observer: any TunnelStatusObserver)\n func removeObserver(_ observer: any TunnelStatusObserver)\n func addBlockObserver(\n queue: DispatchQueue?,\n handler: @escaping (any TunnelProtocol, NEVPNStatus) -> Void\n ) -> TunnelStatusBlockObserver\n\n func logFormat() -> String\n\n func saveToPreferences(_ completion: @escaping (Error?) -> Void)\n func removeFromPreferences(completion: @escaping (Error?) -> Void)\n\n func setConfiguration(_ configuration: TunnelConfiguration)\n func start(options: [String: NSObject]?) throws\n func stop()\n func sendProviderMessage(_ messageData: Data, responseHandler: ((Data?) -> Void)?) throws\n}\n\n/// Tunnel wrapper class.\nfinal class Tunnel: TunnelProtocol, Equatable, @unchecked Sendable {\n /// Unique identifier assigned to instance at the time of creation.\n let identifier = UUID()\n\n var backgroundTaskProvider: BackgroundTaskProviding\n\n #if DEBUG\n /// System VPN configuration identifier.\n /// This property performs a private call to obtain system configuration ID so it does not\n /// guarantee to return anything, also it may not return anything for newly created tunnels.\n var systemIdentifier: UUID? {\n let configurationKey = "configuration"\n let identifierKey = "identifier"\n\n guard tunnelProvider.responds(to: NSSelectorFromString(configurationKey)),\n let config = tunnelProvider.value(forKey: configurationKey) as? NSObject,\n config.responds(to: NSSelectorFromString(identifierKey)),\n let identifier = config.value(forKey: identifierKey) as? UUID\n else {\n return nil\n }\n\n return identifier\n }\n #endif\n\n /// Tunnel start date.\n ///\n /// It's set to `distantPast` when the VPN connection was established prior to being observed\n /// by the class.\n var startDate: Date? {\n lock.lock()\n defer { lock.unlock() }\n\n return _startDate\n }\n\n /// Tunnel connection status.\n var status: NEVPNStatus {\n tunnelProvider.connection.status\n }\n\n /// Whether on-demand VPN is enabled.\n var isOnDemandEnabled: Bool {\n get {\n tunnelProvider.isOnDemandEnabled\n }\n set {\n tunnelProvider.isOnDemandEnabled = newValue\n }\n }\n\n func logFormat() -> String {\n var s = identifier.uuidString\n #if DEBUG\n if let configurationIdentifier = systemIdentifier?.uuidString {\n s += " (system profile ID: \(configurationIdentifier))"\n }\n #endif\n return s\n }\n\n private let lock = NSLock()\n private var observerList = ObserverList<any TunnelStatusObserver>()\n\n private var _startDate: Date?\n internal let tunnelProvider: TunnelProviderManagerType\n\n init(tunnelProvider: TunnelProviderManagerType, backgroundTaskProvider: BackgroundTaskProviding) {\n self.tunnelProvider = tunnelProvider\n self.backgroundTaskProvider = backgroundTaskProvider\n\n NotificationCenter.default.addObserver(\n self, selector: #selector(handleVPNStatusChangeNotification(_:)),\n name: .NEVPNStatusDidChange,\n object: tunnelProvider.connection\n )\n\n handleVPNStatus(tunnelProvider.connection.status)\n }\n\n func start(options: [String: NSObject]?) throws {\n try tunnelProvider.connection.startVPNTunnel(options: options)\n }\n\n func stop() {\n tunnelProvider.connection.stopVPNTunnel()\n }\n\n func sendProviderMessage(_ messageData: Data, responseHandler: ((Data?) -> Void)?) throws {\n let session = tunnelProvider.connection as? VPNTunnelProviderSessionProtocol\n\n try session?.sendProviderMessage(messageData, responseHandler: responseHandler)\n }\n\n func setConfiguration(_ configuration: TunnelConfiguration) {\n configuration.apply(to: tunnelProvider)\n }\n\n func saveToPreferences(_ completion: @escaping (Error?) -> Void) {\n tunnelProvider.saveToPreferences { error in\n if let error {\n completion(error)\n } else {\n // Refresh connection status after saving the tunnel preferences.\n // Basically it's only necessary to do for new instances of\n // `NETunnelProviderManager`, but we do that for the existing ones too\n // for simplicity as it has no side effects.\n self.tunnelProvider.loadFromPreferences(completionHandler: completion)\n }\n }\n }\n\n func removeFromPreferences(completion: @escaping (Error?) -> Void) {\n tunnelProvider.removeFromPreferences(completionHandler: completion)\n }\n\n func addBlockObserver(\n queue: DispatchQueue? = nil,\n handler: @escaping (any TunnelProtocol, NEVPNStatus) -> Void\n ) -> TunnelStatusBlockObserver {\n let observer = TunnelStatusBlockObserver(tunnel: self, queue: queue, handler: handler)\n\n addObserver(observer)\n\n return observer\n }\n\n func addObserver(_ observer: any TunnelStatusObserver) {\n observerList.append(observer)\n }\n\n func removeObserver(_ observer: any TunnelStatusObserver) {\n observerList.remove(observer)\n }\n\n @objc private func handleVPNStatusChangeNotification(_ notification: Notification) {\n guard let connection = notification.object as? VPNConnectionProtocol else { return }\n\n let newStatus = connection.status\n\n handleVPNStatus(newStatus)\n\n observerList.notify { observer in\n observer.tunnel(self, didReceiveStatus: newStatus)\n }\n }\n\n private func handleVPNStatus(_ status: NEVPNStatus) {\n switch status {\n case .connecting:\n lock.lock()\n _startDate = Date()\n lock.unlock()\n\n case .connected, .reasserting:\n lock.lock()\n if _startDate == nil {\n _startDate = .distantPast\n }\n lock.unlock()\n\n case .disconnecting:\n break\n\n case .disconnected, .invalid:\n lock.lock()\n _startDate = nil\n lock.unlock()\n\n @unknown default:\n break\n }\n }\n\n static func == (lhs: Tunnel, rhs: Tunnel) -> Bool {\n lhs.tunnelProvider == rhs.tunnelProvider\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\Tunnel.swift | Tunnel.swift | Swift | 7,273 | 0.95 | 0.069565 | 0.163043 | awesome-app | 543 | 2024-03-03T09:11:03.970483 | MIT | false | 490d0b76a0cd43e5e362e7adbce16d02 |
//\n// TunnelBlockObserver.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nfinal class TunnelBlockObserver: TunnelObserver, @unchecked Sendable {\n typealias DidLoadConfigurationHandler = (TunnelManager) -> Void\n typealias DidUpdateTunnelStatusHandler = (TunnelManager, TunnelStatus) -> Void\n typealias DidUpdateDeviceStateHandler = (\n _ tunnelManager: TunnelManager,\n _ deviceState: DeviceState,\n _ previousDeviceState: DeviceState\n ) -> Void\n typealias DidUpdateTunnelSettingsHandler = (TunnelManager, LatestTunnelSettings) -> Void\n typealias DidFailWithErrorHandler = (TunnelManager, Error) -> Void\n\n private let didLoadConfiguration: DidLoadConfigurationHandler?\n private let didUpdateTunnelStatus: DidUpdateTunnelStatusHandler?\n private let didUpdateDeviceState: DidUpdateDeviceStateHandler?\n private let didUpdateTunnelSettings: DidUpdateTunnelSettingsHandler?\n private let didFailWithError: DidFailWithErrorHandler?\n\n init(\n didLoadConfiguration: DidLoadConfigurationHandler? = nil,\n didUpdateTunnelStatus: DidUpdateTunnelStatusHandler? = nil,\n didUpdateDeviceState: DidUpdateDeviceStateHandler? = nil,\n didUpdateTunnelSettings: DidUpdateTunnelSettingsHandler? = nil,\n didFailWithError: DidFailWithErrorHandler? = nil\n ) {\n self.didLoadConfiguration = didLoadConfiguration\n self.didUpdateTunnelStatus = didUpdateTunnelStatus\n self.didUpdateDeviceState = didUpdateDeviceState\n self.didUpdateTunnelSettings = didUpdateTunnelSettings\n self.didFailWithError = didFailWithError\n }\n\n func tunnelManagerDidLoadConfiguration(_ manager: TunnelManager) {\n didLoadConfiguration?(manager)\n }\n\n func tunnelManager(_ manager: TunnelManager, didUpdateTunnelStatus tunnelStatus: TunnelStatus) {\n didUpdateTunnelStatus?(manager, tunnelStatus)\n }\n\n func tunnelManager(\n _ manager: TunnelManager,\n didUpdateDeviceState deviceState: DeviceState,\n previousDeviceState: DeviceState\n ) {\n didUpdateDeviceState?(manager, deviceState, previousDeviceState)\n }\n\n func tunnelManager(_ manager: TunnelManager, didUpdateTunnelSettings tunnelSettings: LatestTunnelSettings) {\n didUpdateTunnelSettings?(manager, tunnelSettings)\n }\n\n func tunnelManager(_ manager: TunnelManager, didFailWithError error: Error) {\n didFailWithError?(manager, error)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelBlockObserver.swift | TunnelBlockObserver.swift | Swift | 2,568 | 0.95 | 0.015152 | 0.122807 | python-kit | 389 | 2024-01-16T13:34:48.241584 | GPL-3.0 | false | 269fe19370140c7b7d03e59ed0063147 |
//\n// TunnelConfiguration.swift\n// MullvadVPN\n//\n// Created by pronebird on 07/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\nstruct TunnelConfiguration {\n var isEnabled: Bool\n var localizedDescription: String\n var protocolConfiguration: NETunnelProviderProtocol\n var onDemandRules: [NEOnDemandRule]\n var isOnDemandEnabled: Bool\n\n init(includeAllNetworks: Bool, excludeLocalNetworks: Bool, isOnDemandEnabled: Bool = true) {\n let protocolConfig = NETunnelProviderProtocol()\n protocolConfig.providerBundleIdentifier = ApplicationTarget.packetTunnel.bundleIdentifier\n protocolConfig.serverAddress = ""\n #if DEBUG\n protocolConfig.includeAllNetworks = includeAllNetworks\n #endif\n protocolConfig.excludeLocalNetworks = excludeLocalNetworks\n\n let alwaysOnRule = NEOnDemandRuleConnect()\n alwaysOnRule.interfaceTypeMatch = .any\n\n isEnabled = true\n localizedDescription = "WireGuard"\n protocolConfiguration = protocolConfig\n onDemandRules = [alwaysOnRule]\n self.isOnDemandEnabled = isOnDemandEnabled\n }\n\n func apply(to manager: TunnelProviderManagerType) {\n manager.isEnabled = isEnabled\n manager.localizedDescription = localizedDescription\n manager.protocolConfiguration = protocolConfiguration\n manager.onDemandRules = onDemandRules\n manager.isOnDemandEnabled = isOnDemandEnabled\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelConfiguration.swift | TunnelConfiguration.swift | Swift | 1,508 | 0.95 | 0.022222 | 0.230769 | node-utils | 702 | 2024-09-06T02:09:41.212656 | MIT | false | 3ced0280dd1c78fc7e2474681b6a816b |
//\n// TunnelInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 05/07/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport PacketTunnelCore\n\nprotocol TunnelInteractor {\n // MARK: - Tunnel manipulation\n\n var tunnel: (any TunnelProtocol)? { get }\n var backgroundTaskProvider: BackgroundTaskProviding { get }\n\n func getPersistentTunnels() -> [any TunnelProtocol]\n func createNewTunnel() -> any TunnelProtocol\n func setTunnel(_ tunnel: (any TunnelProtocol)?, shouldRefreshTunnelState: Bool)\n\n // MARK: - Tunnel status\n\n var tunnelStatus: TunnelStatus { get }\n @discardableResult func updateTunnelStatus(_ block: @Sendable (inout TunnelStatus) -> Void) -> TunnelStatus\n\n // MARK: - Configuration\n\n var isConfigurationLoaded: Bool { get }\n var settings: LatestTunnelSettings { get }\n var deviceState: DeviceState { get }\n\n func setConfigurationLoaded()\n func setSettings(_ settings: LatestTunnelSettings, persist: Bool)\n func setDeviceState(_ deviceState: DeviceState, persist: Bool)\n func removeLastUsedAccount()\n func handleRestError(_ error: Error)\n\n func startTunnel()\n func prepareForVPNConfigurationDeletion()\n func selectRelays() throws -> SelectedRelays\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelInteractor.swift | TunnelInteractor.swift | Swift | 1,336 | 0.95 | 0 | 0.285714 | node-utils | 961 | 2023-08-04T16:57:51.527783 | BSD-3-Clause | false | f0320c3ddb6465bfd3a0775fcd691c77 |
//\n// TunnelManager.swift\n// MullvadVPN\n//\n// Created by pronebird on 25/09/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport NetworkExtension\nimport Operations\nimport PacketTunnelCore\nimport StoreKit\nimport UIKit\nimport WireGuardKitTypes\n\n/// Interval used for periodic polling of tunnel relay status when tunnel is establishing\n/// connection.\nprivate let establishingTunnelStatusPollInterval: Duration = .seconds(3)\n\n/// Interval used for periodic polling of tunnel connectivity status once the tunnel connection\n/// is established.\nprivate let establishedTunnelStatusPollInterval: Duration = .seconds(5)\n\n/// A class that provides a convenient interface for VPN tunnels configuration, manipulation and\n/// monitoring.\nfinal class TunnelManager: StorePaymentObserver, @unchecked Sendable {\n private enum OperationCategory: String, Sendable {\n case manageTunnel\n case deviceStateUpdate\n case settingsUpdate\n case tunnelStateUpdate\n\n var category: String {\n "TunnelManager.\(rawValue)"\n }\n }\n\n // MARK: - Internal variables\n\n let backgroundTaskProvider: BackgroundTaskProviding\n fileprivate let tunnelStore: any TunnelStoreProtocol\n private let relayCacheTracker: RelayCacheTrackerProtocol\n private let accountsProxy: RESTAccountHandling\n private let devicesProxy: DeviceHandling\n private let apiProxy: APIQuerying\n private let accessTokenManager: RESTAccessTokenManagement\n\n private let logger = Logger(label: "TunnelManager")\n private var nslock = NSRecursiveLock()\n private let operationQueue = AsyncOperationQueue()\n private let internalQueue = DispatchQueue(label: "TunnelManager.internalQueue")\n\n private var statusObserver: TunnelStatusBlockObserver?\n private var lastMapConnectionStatusOperation: Operation?\n private let observerList = ObserverList<TunnelObserver>()\n private var networkMonitor: NWPathMonitor?\n private let relaySelector: RelaySelectorProtocol\n\n private var privateKeyRotationTimer: DispatchSourceTimer?\n public private(set) var isRunningPeriodicPrivateKeyRotation = false\n public private(set) var nextKeyRotationDate: Date?\n\n private var tunnelStatusPollTimer: DispatchSourceTimer?\n private var isPolling = false\n\n private var _isConfigurationLoaded = false\n private var _deviceState: DeviceState = .loggedOut\n private var _tunnelSettings = LatestTunnelSettings()\n\n private var _tunnel: (any TunnelProtocol)?\n private var _tunnelStatus = TunnelStatus()\n\n /// Last processed device check.\n private var lastPacketTunnelKeyRotation: Date?\n\n private var observer: TunnelObserver?\n\n // MARK: - Initialization\n\n init(\n backgroundTaskProvider: BackgroundTaskProviding,\n tunnelStore: any TunnelStoreProtocol,\n relayCacheTracker: RelayCacheTrackerProtocol,\n accountsProxy: RESTAccountHandling,\n devicesProxy: DeviceHandling,\n apiProxy: APIQuerying,\n accessTokenManager: RESTAccessTokenManagement,\n relaySelector: RelaySelectorProtocol\n ) {\n self.backgroundTaskProvider = backgroundTaskProvider\n self.tunnelStore = tunnelStore\n self.relayCacheTracker = relayCacheTracker\n self.accountsProxy = accountsProxy\n self.devicesProxy = devicesProxy\n self.apiProxy = apiProxy\n self.operationQueue.name = "TunnelManager.operationQueue"\n self.operationQueue.underlyingQueue = internalQueue\n self.accessTokenManager = accessTokenManager\n self.relaySelector = relaySelector\n\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(applicationDidBecomeActive),\n name: UIApplication.didBecomeActiveNotification,\n object: nil\n )\n }\n\n // MARK: - Periodic private key rotation\n\n func startPeriodicPrivateKeyRotation() {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard !isRunningPeriodicPrivateKeyRotation, deviceState.isLoggedIn else { return }\n\n logger.debug("Start periodic private key rotation.")\n\n isRunningPeriodicPrivateKeyRotation = true\n updatePrivateKeyRotationTimer()\n }\n\n func stopPeriodicPrivateKeyRotation() {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard isRunningPeriodicPrivateKeyRotation else { return }\n\n logger.debug("Stop periodic private key rotation.")\n\n isRunningPeriodicPrivateKeyRotation = false\n updatePrivateKeyRotationTimer()\n }\n\n func startOrStopPeriodicPrivateKeyRotation() {\n if deviceState.isLoggedIn {\n startPeriodicPrivateKeyRotation()\n } else {\n stopPeriodicPrivateKeyRotation()\n }\n }\n\n func getNextKeyRotationDate() -> Date? {\n nslock.lock()\n defer { nslock.unlock() }\n\n return deviceState.deviceData.flatMap { WgKeyRotation(data: $0).nextRotationDate }\n }\n\n private func updatePrivateKeyRotationTimer() {\n nslock.lock()\n defer { nslock.unlock() }\n\n privateKeyRotationTimer?.cancel()\n privateKeyRotationTimer = nil\n nextKeyRotationDate = nil\n\n guard isRunningPeriodicPrivateKeyRotation,\n let scheduleDate = getNextKeyRotationDate() else { return }\n nextKeyRotationDate = scheduleDate\n\n let timer = DispatchSource.makeTimerSource(queue: .main)\n\n timer.setEventHandler { [weak self] in\n _ = self?.rotatePrivateKey { _ in\n // no-op\n }\n }\n\n timer.schedule(wallDeadline: .now() + scheduleDate.timeIntervalSinceNow)\n timer.activate()\n\n privateKeyRotationTimer = timer\n\n logger.debug("Schedule next private key rotation at \(scheduleDate.logFormatted).")\n }\n\n // MARK: - Public methods\n\n func loadConfiguration(completionHandler: @escaping @Sendable () -> Void) {\n let loadTunnelOperation = LoadTunnelConfigurationOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self)\n )\n loadTunnelOperation.completionQueue = .main\n loadTunnelOperation.completionHandler = { [weak self] completion in\n guard let self else { return }\n\n if case let .failure(error) = completion {\n self.logger.error(\n error: error,\n message: "Failed to load configuration."\n )\n }\n\n self.updatePrivateKeyRotationTimer()\n self.startNetworkMonitor()\n\n completionHandler()\n }\n\n loadTunnelOperation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Load tunnel configuration",\n cancelUponExpiration: false\n )\n )\n\n loadTunnelOperation.addCondition(\n MutuallyExclusive(category: OperationCategory.manageTunnel.category)\n )\n\n operationQueue.addOperation(loadTunnelOperation)\n }\n\n func startTunnel(completionHandler: ((Error?) -> Void)? = nil) {\n let operation = StartTunnelOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n completionHandler: { [weak self] result in\n guard let self else { return }\n if let error = result.error {\n self.logger.error(\n error: error,\n message: "Failed to start the tunnel."\n )\n\n let tunnelError = StartTunnelError(underlyingError: error)\n\n self.observerList.notify { observer in\n observer.tunnelManager(self, didFailWithError: tunnelError)\n }\n }\n\n completionHandler?(result.error)\n }\n )\n\n operation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Start tunnel",\n cancelUponExpiration: true\n ))\n operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))\n\n operationQueue.addOperation(operation)\n }\n\n func stopTunnel(isOnDemandEnabled: Bool = false, completionHandler: ((Error?) -> Void)? = nil) {\n let operation = StopTunnelOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self)\n ) { [weak self] result in\n guard let self else { return }\n\n if let error = result.error {\n self.logger.error(\n error: error,\n message: "Failed to stop the tunnel."\n )\n\n let tunnelError = StopTunnelError(underlyingError: error)\n\n self.observerList.notify { observer in\n observer.tunnelManager(self, didFailWithError: tunnelError)\n }\n }\n\n completionHandler?(result.error)\n }\n operation.isOnDemandEnabled = isOnDemandEnabled\n operation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Stop tunnel",\n cancelUponExpiration: true\n ))\n operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))\n\n operationQueue.addOperation(operation)\n }\n\n func reconnectTunnel(selectNewRelay: Bool, completionHandler: (@Sendable (Error?) -> Void)? = nil) {\n let operation = AsyncBlockOperation(dispatchQueue: internalQueue) { finish -> Cancellable in\n do {\n guard let tunnel = self.tunnel else {\n throw UnsetTunnelError()\n }\n\n return tunnel.reconnectTunnel(to: selectNewRelay ? .random : .current) { result in\n finish(result.error)\n }\n } catch {\n finish(error)\n\n return AnyCancellable()\n }\n }\n\n operation.completionBlock = {\n DispatchQueue.main.async {\n self.didReconnectTunnel(error: operation.error)\n\n completionHandler?(operation.error)\n }\n }\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Reconnect tunnel",\n cancelUponExpiration: true\n )\n )\n operation.addCondition(MutuallyExclusive(category: OperationCategory.manageTunnel.category))\n\n operationQueue.addOperation(operation)\n }\n\n func reapplyTunnelConfiguration() {\n guard let tunnel else { return }\n if self.tunnelStatus.state.isSecured {\n let observer = TunnelBlockObserver(\n didUpdateTunnelStatus: { _, status in\n if case .disconnected = status.state {\n if let observer = self.observer {\n self.removeObserver(observer)\n self.observer = nil\n }\n self.startTunnel()\n }\n }\n )\n addObserver(observer)\n self.observer = observer\n\n let configuration = TunnelConfiguration(\n includeAllNetworks: settings.includeAllNetworks,\n excludeLocalNetworks: settings.localNetworkSharing\n )\n\n tunnel.setConfiguration(configuration)\n tunnel.saveToPreferences { _ in\n self.stopTunnel(isOnDemandEnabled: true)\n }\n }\n }\n\n func setNewAccount() async throws -> StoredAccountData {\n try await setAccount(action: .new)!\n }\n\n func setExistingAccount(accountNumber: String) async throws -> StoredAccountData {\n try await setAccount(action: .existing(accountNumber))!\n }\n\n private func setAccount(\n action: SetAccountAction,\n completionHandler: @escaping @Sendable (Result<StoredAccountData?, Error>) -> Void\n ) {\n let operation = SetAccountOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n accountsProxy: accountsProxy,\n devicesProxy: devicesProxy,\n accessTokenManager: accessTokenManager,\n action: action\n )\n\n operation.completionQueue = .main\n operation.completionHandler = { [weak self] result in\n guard let self else { return }\n startOrStopPeriodicPrivateKeyRotation()\n\n completionHandler(result)\n }\n\n operation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: action.taskName,\n cancelUponExpiration: true\n ))\n\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.manageTunnel.category)\n )\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)\n )\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.settingsUpdate.category)\n )\n\n // Unsetting (ie. logging out) or deleting the account should cancel all other\n // currently ongoing activity.\n switch action {\n case .unset, .delete:\n operationQueue.cancelAllOperations()\n default:\n break\n }\n\n operationQueue.addOperation(operation)\n }\n\n private func setAccount(action: SetAccountAction) async throws -> StoredAccountData? {\n try await withCheckedThrowingContinuation { continuation in\n setAccount(action: action) { result in\n continuation.resume(with: result)\n }\n }\n }\n\n func unsetAccount() async {\n _ = try? await setAccount(action: .unset)\n }\n\n func updateAccountData(_ completionHandler: (@Sendable (Error?) -> Void)? = nil) {\n let operation = UpdateAccountDataOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n accountsProxy: accountsProxy\n )\n\n operation.completionQueue = .main\n operation.completionHandler = { completion in\n completionHandler?(completion.error)\n }\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Update account data",\n cancelUponExpiration: true\n )\n )\n\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)\n )\n\n operationQueue.addOperation(operation)\n }\n\n func redeemVoucher(\n _ voucherCode: String,\n completion: (@Sendable (Result<REST.SubmitVoucherResponse, Error>) -> Void)? = nil\n ) -> Cancellable {\n let operation = RedeemVoucherOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n voucherCode: voucherCode,\n apiProxy: apiProxy\n )\n\n operation.completionQueue = .main\n operation.completionHandler = completion\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Redeem voucher",\n cancelUponExpiration: true\n )\n )\n\n operation.addCondition(MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category))\n\n operationQueue.addOperation(operation)\n return operation\n }\n\n func deleteAccount(accountNumber: String) async throws {\n _ = try await setAccount(action: .delete(accountNumber))\n }\n\n func updateDeviceData(_ completionHandler: (@Sendable (Error?) -> Void)? = nil) {\n let operation = UpdateDeviceDataOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n devicesProxy: devicesProxy\n )\n\n operation.completionQueue = .main\n operation.completionHandler = { completion in\n completionHandler?(completion.error)\n }\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Update device data",\n cancelUponExpiration: true\n )\n )\n\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)\n )\n\n operationQueue.addOperation(operation)\n }\n\n func rotatePrivateKey(completionHandler: @MainActor @escaping @Sendable (Error?) -> Void) -> Cancellable {\n let operation = RotateKeyOperation(\n dispatchQueue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n devicesProxy: devicesProxy\n )\n\n operation.completionQueue = .main\n operation.completionHandler = { [weak self] result in\n guard let self else { return }\n MainActor.assumeIsolated {\n self.updatePrivateKeyRotationTimer()\n\n let error = result.error\n if let error {\n self.handleRestError(error)\n }\n\n completionHandler(error)\n }\n }\n\n operation.addObserver(\n BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Rotate private key",\n cancelUponExpiration: true\n )\n )\n\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)\n )\n\n operationQueue.addOperation(operation)\n\n return operation\n }\n\n func updateSettings(_ updates: [TunnelSettingsUpdate], completionHandler: (@Sendable () -> Void)? = nil) {\n let taskName = "Set " + updates.map(\.subjectName).joined(separator: ", ")\n scheduleSettingsUpdate(\n taskName: taskName,\n modificationBlock: { settings in\n for update in updates {\n update.apply(to: &settings)\n }\n },\n completionHandler: completionHandler\n )\n }\n\n func refreshRelayCacheTracker() throws {\n try relayCacheTracker.refreshCachedRelays()\n }\n\n func selectRelays(tunnelSettings: LatestTunnelSettings) throws -> SelectedRelays {\n let retryAttempts = tunnelStatus.observedState.connectionState?.connectionAttemptCount ?? 0\n\n return try relaySelector.selectRelays(\n tunnelSettings: tunnelSettings,\n connectionAttemptCount: retryAttempts\n )\n }\n\n // MARK: - Tunnel observeration\n\n /// Add tunnel observer.\n /// In order to cancel the observation, either call `removeObserver(_:)` or simply release\n /// the observer.\n func addObserver(_ observer: TunnelObserver) {\n observerList.append(observer)\n }\n\n /// Remove tunnel observer.\n func removeObserver(_ observer: TunnelObserver) {\n observerList.remove(observer)\n }\n\n // MARK: - StorePaymentObserver\n\n func storePaymentManager(\n _ manager: StorePaymentManager,\n didReceiveEvent event: StorePaymentEvent\n ) {\n guard case let .finished(paymentCompletion) = event else {\n return\n }\n\n scheduleDeviceStateUpdate(\n taskName: "Update account expiry after in-app purchase",\n modificationBlock: { deviceState in\n switch deviceState {\n case .loggedIn(var accountData, let deviceData):\n if accountData.number == paymentCompletion.accountNumber {\n accountData.expiry = paymentCompletion.serverResponse.newExpiry\n deviceState = .loggedIn(accountData, deviceData)\n }\n\n case .loggedOut, .revoked:\n break\n }\n },\n completionHandler: nil\n )\n }\n\n // MARK: - TunnelInteractor\n\n var isConfigurationLoaded: Bool {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _isConfigurationLoaded\n }\n\n fileprivate var tunnel: (any TunnelProtocol)? {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _tunnel\n }\n\n var tunnelStatus: TunnelStatus {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _tunnelStatus\n }\n\n var settings: LatestTunnelSettings {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _tunnelSettings\n }\n\n var deviceState: DeviceState {\n nslock.lock()\n defer { nslock.unlock() }\n\n return _deviceState\n }\n\n fileprivate func setConfigurationLoaded() {\n nslock.lock()\n defer { nslock.unlock() }\n\n guard !_isConfigurationLoaded else {\n return\n }\n\n _isConfigurationLoaded = true\n\n DispatchQueue.main.async {\n self.observerList.notify { observer in\n observer.tunnelManagerDidLoadConfiguration(self)\n }\n }\n }\n\n fileprivate func setTunnel(_ tunnel: (any TunnelProtocol)?, shouldRefreshTunnelState: Bool) {\n nslock.lock()\n defer { nslock.unlock() }\n\n if let tunnel {\n subscribeVPNStatusObserver(tunnel: tunnel)\n } else {\n unsubscribeVPNStatusObserver()\n }\n\n _tunnel = tunnel\n\n // Update the existing state\n if shouldRefreshTunnelState {\n logger.debug("Refresh tunnel status for new tunnel.")\n refreshTunnelStatus()\n }\n }\n\n fileprivate func setTunnelStatus(_ block: @Sendable (inout TunnelStatus) -> Void) -> TunnelStatus {\n nslock.lock()\n defer { nslock.unlock() }\n\n var newTunnelStatus = _tunnelStatus\n block(&newTunnelStatus)\n\n guard _tunnelStatus != newTunnelStatus else {\n return newTunnelStatus\n }\n\n logger.info("Status: \(newTunnelStatus).")\n\n _tunnelStatus = newTunnelStatus\n\n // Packet tunnel may have attempted or rotated the key.\n // In that case we have to reload device state from Keychain as it's likely was modified by packet tunnel.\n let newPacketTunnelKeyRotation = _tunnelStatus.observedState.connectionState?.lastKeyRotation\n if lastPacketTunnelKeyRotation != newPacketTunnelKeyRotation {\n lastPacketTunnelKeyRotation = newPacketTunnelKeyRotation\n refreshDeviceState()\n }\n switch _tunnelStatus.state {\n case .connecting, .reconnecting, .negotiatingEphemeralPeer:\n // Start polling tunnel status to keep the relay information up to date\n // while the tunnel process is trying to connect.\n startPollingTunnelStatus(interval: establishingTunnelStatusPollInterval)\n\n case .connected, .waitingForConnectivity(.noConnection):\n // Start polling tunnel status to keep connectivity status up to date.\n startPollingTunnelStatus(interval: establishedTunnelStatusPollInterval)\n\n case .pendingReconnect, .disconnecting, .disconnected, .waitingForConnectivity(.noNetwork):\n // Stop polling tunnel status once connection moved to final state.\n cancelPollingTunnelStatus()\n\n case let .error(blockedStateReason):\n switch blockedStateReason {\n case .deviceRevoked, .invalidAccount:\n handleBlockedState(reason: blockedStateReason)\n default:\n break\n }\n\n // Stop polling tunnel status once blocked state has been determined.\n cancelPollingTunnelStatus()\n }\n\n DispatchQueue.main.async {\n self.observerList.notify { observer in\n observer.tunnelManager(self, didUpdateTunnelStatus: self._tunnelStatus)\n }\n }\n\n return newTunnelStatus\n }\n\n fileprivate func setSettings(_ settings: LatestTunnelSettings, persist: Bool) {\n nslock.lock()\n defer { nslock.unlock() }\n\n let shouldCallDelegate = _tunnelSettings != settings && _isConfigurationLoaded\n\n _tunnelSettings = settings\n\n if persist {\n do {\n try SettingsManager.writeSettings(settings)\n } catch {\n logger.error(\n error: error,\n message: "Failed to write settings."\n )\n }\n }\n\n if shouldCallDelegate {\n DispatchQueue.main.async {\n self.observerList.notify { observer in\n observer.tunnelManager(self, didUpdateTunnelSettings: settings)\n }\n }\n }\n }\n\n fileprivate func setDeviceState(_ deviceState: DeviceState, persist: Bool) {\n nslock.lock()\n defer { nslock.unlock() }\n\n let shouldCallDelegate = _deviceState != deviceState && _isConfigurationLoaded\n let previousDeviceState = _deviceState\n\n _deviceState = deviceState\n\n if persist {\n do {\n try SettingsManager.writeDeviceState(deviceState)\n } catch {\n logger.error(\n error: error,\n message: "Failed to write device state."\n )\n }\n }\n\n if shouldCallDelegate {\n DispatchQueue.main.async {\n self.observerList.notify { observer in\n observer.tunnelManager(\n self,\n didUpdateDeviceState: deviceState,\n previousDeviceState: previousDeviceState\n )\n }\n }\n }\n }\n\n // MARK: - Private methods\n\n @objc private func applicationDidBecomeActive() {\n #if DEBUG\n logger.debug("Refresh device state and tunnel status due to application becoming active.")\n #endif\n refreshTunnelStatus()\n refreshDeviceState()\n }\n\n private func didUpdateNetworkPath(_ path: Network.NWPath) {\n updateTunnelStatus(tunnel?.status ?? .disconnected)\n }\n\n fileprivate func prepareForVPNConfigurationDeletion() {\n nslock.lock()\n defer { nslock.unlock() }\n\n // Unregister from receiving VPN connection status changes\n unsubscribeVPNStatusObserver()\n\n // Cancel last VPN status mapping operation\n lastMapConnectionStatusOperation?.cancel()\n lastMapConnectionStatusOperation = nil\n }\n\n private func didReconnectTunnel(error: Error?) {\n nslock.lock()\n defer { nslock.unlock() }\n\n if let error, !error.isOperationCancellationError {\n logger.error(error: error, message: "Failed to reconnect the tunnel.")\n }\n\n // Refresh tunnel status only when connecting,reasserting or error to pick up the next relay,\n // since both states may persist for a long period of time until the tunnel is fully\n // connected.\n switch tunnelStatus.state {\n case .connecting, .reconnecting, .error:\n logger.debug("Refresh tunnel status due to reconnect.")\n refreshTunnelStatus()\n\n default:\n break\n }\n }\n\n private func subscribeVPNStatusObserver(tunnel: any TunnelProtocol) {\n nslock.lock()\n defer { nslock.unlock() }\n\n unsubscribeVPNStatusObserver()\n\n statusObserver = tunnel\n .addBlockObserver(queue: internalQueue) { [weak self] tunnel, status in\n guard let self else { return }\n\n self.logger.debug("VPN connection status changed to \(status).")\n\n if [.disconnected, .invalid].contains(tunnel.status) {\n self.startNetworkMonitor()\n } else {\n self.cancelNetworkMonitor()\n }\n\n self.updateTunnelStatus(status)\n }\n }\n\n private func startNetworkMonitor() {\n cancelNetworkMonitor()\n\n networkMonitor = NWPathMonitor(prohibitedInterfaceTypes: [.other])\n networkMonitor?.pathUpdateHandler = { [weak self] path in\n self?.didUpdateNetworkPath(path)\n }\n\n networkMonitor?.start(queue: internalQueue)\n }\n\n private func cancelNetworkMonitor() {\n networkMonitor?.pathUpdateHandler = nil\n networkMonitor?.cancel()\n networkMonitor = nil\n }\n\n private func unsubscribeVPNStatusObserver() {\n nslock.lock()\n defer { nslock.unlock() }\n\n statusObserver?.invalidate()\n statusObserver = nil\n }\n\n private func refreshTunnelStatus() {\n nslock.lock()\n defer { nslock.unlock() }\n\n if let connectionStatus = _tunnel?.status {\n updateTunnelStatus(connectionStatus)\n }\n }\n\n /// Refresh device state from settings and update the in-memory value.\n /// Used to refresh device state when it's modified by packet tunnel during key rotation.\n private func refreshDeviceState() {\n let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {\n do {\n let newDeviceState = try SettingsManager.readDeviceState()\n\n self.setDeviceState(newDeviceState, persist: false)\n } catch {\n if let error = error as? KeychainError, error == .itemNotFound {\n return\n }\n\n self.logger.error(error: error, message: "Failed to refresh device state")\n }\n }\n\n operation.addCondition(MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category))\n operation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: "Refresh device state",\n cancelUponExpiration: true\n ))\n\n operationQueue.addOperation(operation)\n }\n\n /// Update `TunnelStatus` from `NEVPNStatus`.\n /// Collects the `PacketTunnelStatus` from the tunnel via IPC if needed before assigning\n /// the `tunnelStatus`.\n private func updateTunnelStatus(_ connectionStatus: NEVPNStatus) {\n nslock.lock()\n defer { nslock.unlock() }\n\n let operation = MapConnectionStatusOperation(\n queue: internalQueue,\n interactor: TunnelInteractorProxy(self),\n connectionStatus: connectionStatus,\n networkStatus: networkMonitor?.currentPath.status\n )\n\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.tunnelStateUpdate.category)\n )\n\n // Cancel last VPN status mapping operation\n lastMapConnectionStatusOperation?.cancel()\n lastMapConnectionStatusOperation = operation\n\n operationQueue.addOperation(operation)\n }\n\n private func scheduleSettingsUpdate(\n taskName: String,\n modificationBlock: @escaping @Sendable (inout LatestTunnelSettings) -> Void,\n completionHandler: (@Sendable () -> Void)?\n ) {\n let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {\n let currentSettings = self._tunnelSettings\n var updatedSettings = self._tunnelSettings\n let settingsStrategy = TunnelSettingsStrategy()\n\n modificationBlock(&updatedSettings)\n\n self.setSettings(updatedSettings, persist: true)\n let reconnectionStrategy = settingsStrategy.getReconnectionStrategy(\n oldSettings: currentSettings,\n newSettings: updatedSettings\n )\n switch reconnectionStrategy {\n case .currentRelayReconnect:\n self.reconnectTunnel(selectNewRelay: false)\n case .newRelayReconnect:\n self.reconnectTunnel(selectNewRelay: true)\n case .hardReconnect:\n self.reapplyTunnelConfiguration()\n }\n }\n\n operation.completionBlock = {\n DispatchQueue.main.async {\n completionHandler?()\n }\n }\n\n operation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: taskName,\n cancelUponExpiration: false\n ))\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.settingsUpdate.category)\n )\n\n operationQueue.addOperation(operation)\n }\n\n private func scheduleDeviceStateUpdate(\n taskName: String,\n reconnectTunnel: Bool = true,\n modificationBlock: @escaping @Sendable (inout DeviceState) -> Void,\n completionHandler: (@Sendable () -> Void)? = nil\n ) {\n let operation = AsyncBlockOperation(dispatchQueue: internalQueue) {\n var deviceState = self.deviceState\n\n modificationBlock(&deviceState)\n\n self.setDeviceState(deviceState, persist: true)\n\n if reconnectTunnel {\n self.reconnectTunnel(selectNewRelay: false, completionHandler: nil)\n }\n }\n\n operation.completionBlock = {\n DispatchQueue.main.async {\n completionHandler?()\n }\n }\n\n operation.addObserver(BackgroundObserver(\n backgroundTaskProvider: backgroundTaskProvider,\n name: taskName,\n cancelUponExpiration: false\n ))\n operation.addCondition(\n MutuallyExclusive(category: OperationCategory.deviceStateUpdate.category)\n )\n\n operationQueue.addOperation(operation)\n }\n\n // MARK: - Tunnel status polling\n\n private func startPollingTunnelStatus(interval: Duration) {\n guard !isPolling else { return }\n\n isPolling = true\n\n logger.debug("Start polling tunnel status every \(interval.logFormat()).")\n\n let timer = DispatchSource.makeTimerSource(queue: .main)\n timer.setEventHandler { [weak self] in\n self?.refreshTunnelStatus()\n }\n timer.schedule(wallDeadline: .now() + interval, repeating: interval.timeInterval)\n timer.activate()\n\n tunnelStatusPollTimer?.cancel()\n tunnelStatusPollTimer = timer\n }\n\n private func cancelPollingTunnelStatus() {\n guard isPolling else { return }\n\n logger.debug("Cancel tunnel status polling.")\n\n tunnelStatusPollTimer?.cancel()\n tunnelStatusPollTimer = nil\n isPolling = false\n }\n\n fileprivate func removeLastUsedAccount() {\n do {\n try SettingsManager.setLastUsedAccount(nil)\n } catch {\n logger.error(\n error: error,\n message: "Failed to delete account data."\n )\n }\n }\n\n func handleRestError(_ error: Error) {\n guard let restError = error as? REST.Error else { return }\n\n if restError.compareErrorCode(.deviceNotFound) {\n handleBlockedState(reason: .deviceRevoked)\n } else if restError.compareErrorCode(.invalidAccount) {\n handleBlockedState(reason: .invalidAccount)\n }\n }\n\n private func handleBlockedState(reason: BlockedStateReason) {\n switch reason {\n case .deviceRevoked:\n setDeviceState(.revoked, persist: true)\n case .invalidAccount:\n unsetTunnelConfiguration {\n self.setDeviceState(.revoked, persist: true)\n self.operationQueue.cancelAllOperations()\n self.removeLastUsedAccount()\n }\n default:\n break\n }\n }\n\n private func unsetTunnelConfiguration(completion: @escaping @Sendable () -> Void) {\n // Tell the caller to unsubscribe from VPN status notifications.\n prepareForVPNConfigurationDeletion()\n\n // Reset tunnel.\n _ = setTunnelStatus { tunnelStatus in\n tunnelStatus = TunnelStatus()\n tunnelStatus.state = .disconnected\n }\n\n // Finish immediately if tunnel provider is not set.\n guard let tunnel else {\n completion()\n return\n }\n\n // Remove VPN configuration.\n tunnel.removeFromPreferences { [self] error in\n internalQueue.async { [self] in\n // Ignore error but log it.\n if let error {\n logger.error(\n error: error,\n message: "Failed to remove VPN configuration."\n )\n }\n\n setTunnel(nil, shouldRefreshTunnelState: false)\n\n completion()\n }\n }\n }\n}\n\n#if DEBUG\n\n// MARK: - Simulations\n\nextension TunnelManager {\n enum AccountExpirySimulationOption {\n case closeToExpiry(days: Int)\n case expired\n case active\n\n fileprivate var date: Date? {\n let calendar = Calendar.current\n let now = Date()\n\n switch self {\n case .active:\n return calendar.date(byAdding: .year, value: 1, to: now)\n\n case let .closeToExpiry(days):\n return calendar.date(\n byAdding: DateComponents(day: days, second: 5),\n to: now\n )\n\n case .expired:\n return calendar.date(byAdding: .minute, value: -1, to: now)\n }\n }\n }\n\n /**\n\n This function simulates account state transitions. The change is not permanent and any call to\n `updateAccountData()` will overwrite it, but it's usually enough for quick testing.\n\n It can be invoked somewhere in `initTunnelManagerOperation` (`AppDelegate`) after tunnel manager is fully\n initialized. The following code snippet can be used to cycle through various states:\n\n ```\n func delay(seconds: UInt) async throws {\n try await Task.sleep(nanoseconds: UInt64(seconds) * 1_000_000_000)\n }\n\n Task {\n print("Wait 5 seconds")\n try await delay(seconds: 5)\n\n print("Simulate active account")\n self.tunnelManager.simulateAccountExpiration(option: .active)\n try await delay(seconds: 5)\n\n print("Simulate close to expiry")\n self.tunnelManager.simulateAccountExpiration(option: .closeToExpiry)\n try await delay(seconds: 10)\n\n print("Simulate expired account")\n self.tunnelManager.simulateAccountExpiration(option: .expired)\n try await delay(seconds: 5)\n\n print("Simulate active account")\n self.tunnelManager.simulateAccountExpiration(option: .active)\n }\n ```\n\n Another way to invoke this code is to pause debugger and run it directly:\n\n ```\n command alias swift expression -l Swift -O --\n\n swift import MullvadVPN\n swift (UIApplication.shared.delegate as? AppDelegate)?.tunnelManager.simulateAccountExpiration(option: .closeToExpiry)\n ```\n\n */\n func simulateAccountExpiration(option: AccountExpirySimulationOption) {\n scheduleDeviceStateUpdate(taskName: "Simulating account expiry", reconnectTunnel: false) { deviceState in\n guard case .loggedIn(var accountData, let deviceData) = deviceState, let date = option.date else { return }\n\n accountData.expiry = date\n\n deviceState = .loggedIn(accountData, deviceData)\n }\n }\n}\n\n#endif\n\nprivate struct TunnelInteractorProxy: TunnelInteractor {\n private let tunnelManager: TunnelManager\n\n init(_ tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n }\n\n var tunnel: (any TunnelProtocol)? {\n tunnelManager.tunnel\n }\n\n var backgroundTaskProvider: BackgroundTaskProviding {\n tunnelManager.backgroundTaskProvider\n }\n\n func getPersistentTunnels() -> [any TunnelProtocol] {\n tunnelManager.tunnelStore.getPersistentTunnels()\n }\n\n func createNewTunnel() -> any TunnelProtocol {\n tunnelManager.tunnelStore.createNewTunnel()\n }\n\n func setTunnel(_ tunnel: (any TunnelProtocol)?, shouldRefreshTunnelState: Bool) {\n tunnelManager.setTunnel(tunnel, shouldRefreshTunnelState: shouldRefreshTunnelState)\n }\n\n var tunnelStatus: TunnelStatus {\n tunnelManager.tunnelStatus\n }\n\n func updateTunnelStatus(_ block: @Sendable (inout TunnelStatus) -> Void) -> TunnelStatus {\n tunnelManager.setTunnelStatus(block)\n }\n\n var isConfigurationLoaded: Bool {\n tunnelManager.isConfigurationLoaded\n }\n\n var settings: LatestTunnelSettings {\n tunnelManager.settings\n }\n\n var deviceState: DeviceState {\n tunnelManager.deviceState\n }\n\n func setConfigurationLoaded() {\n tunnelManager.setConfigurationLoaded()\n }\n\n func setSettings(_ settings: LatestTunnelSettings, persist: Bool) {\n tunnelManager.setSettings(settings, persist: persist)\n }\n\n func setDeviceState(_ deviceState: DeviceState, persist: Bool) {\n tunnelManager.setDeviceState(deviceState, persist: persist)\n }\n\n func removeLastUsedAccount() {\n tunnelManager.removeLastUsedAccount()\n }\n\n func startTunnel() {\n tunnelManager.startTunnel()\n }\n\n func prepareForVPNConfigurationDeletion() {\n tunnelManager.prepareForVPNConfigurationDeletion()\n }\n\n func selectRelays() throws -> SelectedRelays {\n try tunnelManager.selectRelays(tunnelSettings: tunnelManager.settings)\n }\n\n func handleRestError(_ error: Error) {\n tunnelManager.handleRestError(error)\n }\n}\n\n// swiftlint:disable:this file_length\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelManager.swift | TunnelManager.swift | Swift | 41,794 | 0.95 | 0.052632 | 0.059273 | react-lib | 107 | 2025-02-23T19:14:30.844127 | MIT | false | 3585929433510c066bf8c8d343d237e8 |
//\n// TunnelManagerErrors.swift\n// MullvadVPN\n//\n// Created by pronebird on 07/09/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadTypes\n\nstruct UnsetTunnelError: LocalizedError {\n var errorDescription: String? {\n NSLocalizedString(\n "UNSET_TUNNEL_ERROR",\n tableName: "TunnelManager",\n value: "Tunnel is unset.",\n comment: ""\n )\n }\n}\n\nstruct InvalidDeviceStateError: LocalizedError {\n var errorDescription: String? {\n NSLocalizedString(\n "INVALID_DEVICE_STATE_ERROR",\n tableName: "TunnelManager",\n value: "Invalid device state.",\n comment: ""\n )\n }\n}\n\nstruct StartTunnelError: LocalizedError, WrappingError {\n private let _underlyingError: Error\n\n var errorDescription: String? {\n NSLocalizedString(\n "START_TUNNEL_ERROR",\n tableName: "TunnelManager",\n value: "Failed to start the tunnel.",\n comment: ""\n )\n }\n\n var underlyingError: Error? {\n _underlyingError\n }\n\n init(underlyingError: Error) {\n _underlyingError = underlyingError\n }\n}\n\nstruct StopTunnelError: LocalizedError, WrappingError {\n private let _underlyingError: Error\n\n var errorDescription: String? {\n NSLocalizedString(\n "STOP_TUNNEL_ERROR",\n tableName: "TunnelManager",\n value: "Failed to stop the tunnel.",\n comment: ""\n )\n }\n\n var underlyingError: Error? {\n _underlyingError\n }\n\n init(underlyingError: Error) {\n _underlyingError = underlyingError\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelManagerErrors.swift | TunnelManagerErrors.swift | Swift | 1,689 | 0.95 | 0 | 0.111111 | node-utils | 162 | 2024-02-26T15:41:58.964307 | MIT | false | 7c2caeb6091a4593293af32fd5bb0874 |
//\n// TunnelObserver.swift\n// MullvadVPN\n//\n// Created by pronebird on 19/08/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\n\nprotocol TunnelObserver: AnyObject, Sendable {\n func tunnelManagerDidLoadConfiguration(_ manager: TunnelManager)\n func tunnelManager(_ manager: TunnelManager, didUpdateTunnelStatus tunnelStatus: TunnelStatus)\n func tunnelManager(\n _ manager: TunnelManager,\n didUpdateDeviceState deviceState: DeviceState,\n previousDeviceState: DeviceState\n )\n func tunnelManager(_ manager: TunnelManager, didUpdateTunnelSettings tunnelSettings: LatestTunnelSettings)\n func tunnelManager(_ manager: TunnelManager, didFailWithError error: Error)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelObserver.swift | TunnelObserver.swift | Swift | 759 | 0.95 | 0 | 0.35 | node-utils | 722 | 2024-08-29T21:02:54.161172 | MIT | false | 8755ad22be674961d332574997b67c7e |
//\n// TunnelState+UI.swift\n// MullvadVPN\n//\n// Created by Andrew Bulhak on 2024-05-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension TunnelState {\n enum TunnelControlActionButton {\n case connect\n case disconnect\n case cancel\n }\n\n var textColorForSecureLabel: UIColor {\n switch self {\n case .connecting, .reconnecting, .waitingForConnectivity(.noConnection), .negotiatingEphemeralPeer:\n .white\n case .connected:\n .successColor\n case .disconnecting, .disconnected, .pendingReconnect, .waitingForConnectivity(.noNetwork), .error:\n .dangerColor\n }\n }\n\n var shouldEnableButtons: Bool {\n if case .waitingForConnectivity(.noNetwork) = self {\n return false\n }\n\n return true\n }\n\n var localizedTitleForSecureLabel: String {\n switch self {\n case let .connecting(_, isPostQuantum, _), let .reconnecting(_, isPostQuantum, _):\n if isPostQuantum {\n NSLocalizedString(\n "TUNNEL_STATE_PQ_CONNECTING",\n tableName: "Main",\n value: "Creating quantum secure connection",\n comment: ""\n )\n } else {\n NSLocalizedString(\n "TUNNEL_STATE_CONNECTING",\n tableName: "Main",\n value: "Creating secure connection",\n comment: ""\n )\n }\n\n case let .negotiatingEphemeralPeer(_, _, isPostQuantum, _):\n if isPostQuantum {\n NSLocalizedString(\n "TUNNEL_STATE_NEGOTIATING_KEY",\n tableName: "Main",\n value: "Creating quantum secure connection",\n comment: ""\n )\n } else {\n NSLocalizedString(\n "TUNNEL_STATE_CONNECTING",\n tableName: "Main",\n value: "Creating secure connection",\n comment: ""\n )\n }\n\n case let .connected(_, isPostQuantum, _):\n if isPostQuantum {\n NSLocalizedString(\n "TUNNEL_STATE_PQ_CONNECTED",\n tableName: "Main",\n value: "Quantum secure connection",\n comment: ""\n )\n } else {\n NSLocalizedString(\n "TUNNEL_STATE_CONNECTED",\n tableName: "Main",\n value: "Connected",\n comment: ""\n )\n }\n\n case .disconnecting(.nothing):\n NSLocalizedString(\n "TUNNEL_STATE_DISCONNECTING",\n tableName: "Main",\n value: "Disconnecting",\n comment: ""\n )\n\n case .disconnecting(.reconnect), .pendingReconnect:\n NSLocalizedString(\n "TUNNEL_STATE_PENDING_RECONNECT",\n tableName: "Main",\n value: "Reconnecting",\n comment: ""\n )\n\n case .disconnected:\n NSLocalizedString(\n "TUNNEL_STATE_DISCONNECTED",\n tableName: "Main",\n value: "Unsecured connection",\n comment: ""\n )\n\n case .waitingForConnectivity(.noConnection), .error:\n NSLocalizedString(\n "TUNNEL_STATE_WAITING_FOR_CONNECTIVITY",\n tableName: "Main",\n value: "Blocked connection",\n comment: ""\n )\n\n case .waitingForConnectivity(.noNetwork):\n NSLocalizedString(\n "TUNNEL_STATE_NO_NETWORK",\n tableName: "Main",\n value: "No network",\n comment: ""\n )\n }\n }\n\n var localizedTitleForSelectLocationButton: String {\n switch self {\n case .disconnecting(.reconnect), .pendingReconnect:\n NSLocalizedString(\n "SWITCH_LOCATION_BUTTON_TITLE",\n tableName: "Main",\n value: "Select location",\n comment: ""\n )\n\n case .disconnected, .disconnecting(.nothing):\n NSLocalizedString(\n "SELECT_LOCATION_BUTTON_TITLE",\n tableName: "Main",\n value: "Select location",\n comment: ""\n )\n\n case .connecting, .connected, .reconnecting, .waitingForConnectivity, .error:\n NSLocalizedString(\n "SWITCH_LOCATION_BUTTON_TITLE",\n tableName: "Main",\n value: "Switch location",\n comment: ""\n )\n\n case .negotiatingEphemeralPeer:\n NSLocalizedString(\n "SWITCH_LOCATION_BUTTON_TITLE",\n tableName: "Main",\n value: "Switch location",\n comment: ""\n )\n }\n }\n\n var localizedAccessibilityLabel: String {\n switch self {\n case let .connecting(_, isPostQuantum, _):\n secureConnectionLabel(isPostQuantum: isPostQuantum)\n\n case let .negotiatingEphemeralPeer(_, _, isPostQuantum, _):\n secureConnectionLabel(isPostQuantum: isPostQuantum)\n\n case let .connected(tunnelInfo, isPostQuantum, _):\n if isPostQuantum {\n String(\n format: NSLocalizedString(\n "TUNNEL_STATE_PQ_CONNECTED_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Quantum secure connection. Connected to %@, %@",\n comment: ""\n ),\n tunnelInfo.exit.location.city,\n tunnelInfo.exit.location.country\n )\n } else {\n String(\n format: NSLocalizedString(\n "TUNNEL_STATE_CONNECTED_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Secure connection. Connected to %@, %@",\n comment: ""\n ),\n tunnelInfo.exit.location.city,\n tunnelInfo.exit.location.country\n )\n }\n\n case .disconnected:\n NSLocalizedString(\n "TUNNEL_STATE_DISCONNECTED_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Unsecured connection",\n comment: ""\n )\n\n case let .reconnecting(tunnelInfo, _, _):\n String(\n format: NSLocalizedString(\n "TUNNEL_STATE_RECONNECTING_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Reconnecting to %@, %@",\n comment: ""\n ),\n tunnelInfo.exit.location.city,\n tunnelInfo.exit.location.country\n )\n\n case .waitingForConnectivity(.noConnection), .error:\n NSLocalizedString(\n "TUNNEL_STATE_WAITING_FOR_CONNECTIVITY_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Blocked connection",\n comment: ""\n )\n\n case .waitingForConnectivity(.noNetwork):\n NSLocalizedString(\n "TUNNEL_STATE_NO_NETWORK_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "No network",\n comment: ""\n )\n\n case .disconnecting(.nothing):\n NSLocalizedString(\n "TUNNEL_STATE_DISCONNECTING_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Disconnecting",\n comment: ""\n )\n\n case .disconnecting(.reconnect), .pendingReconnect:\n NSLocalizedString(\n "TUNNEL_STATE_PENDING_RECONNECT_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Reconnecting",\n comment: ""\n )\n }\n }\n\n var actionButton: TunnelControlActionButton {\n switch self {\n case .disconnected, .disconnecting(.nothing), .waitingForConnectivity(.noNetwork):\n .connect\n case .connecting, .pendingReconnect, .disconnecting(.reconnect), .waitingForConnectivity(.noConnection):\n .cancel\n case .negotiatingEphemeralPeer:\n .cancel\n case .connected, .reconnecting, .error:\n .disconnect\n }\n }\n\n var titleForCountryAndCity: String? {\n guard isSecured, let tunnelRelays = relays else {\n return nil\n }\n\n return "\(tunnelRelays.exit.location.country), \(tunnelRelays.exit.location.city)"\n }\n\n func titleForServer(daitaEnabled: Bool) -> String? {\n guard isSecured, let tunnelRelays = relays else {\n return nil\n }\n\n let exitName = tunnelRelays.exit.hostname\n let entryName = tunnelRelays.entry?.hostname\n let usingDaita = daitaEnabled == true\n\n return if let entryName {\n String(format: NSLocalizedString(\n "CONNECT_PANEL_TITLE",\n tableName: "Main",\n value: "%@ via %@\(usingDaita ? " using DAITA" : "")",\n comment: ""\n ), exitName, entryName)\n } else {\n String(format: NSLocalizedString(\n "CONNECT_PANEL_TITLE",\n tableName: "Main",\n value: "%@\(usingDaita ? " using DAITA" : "")",\n comment: ""\n ), exitName)\n }\n }\n\n func secureConnectionLabel(isPostQuantum: Bool) -> String {\n if isPostQuantum {\n NSLocalizedString(\n "TUNNEL_STATE_PQ_CONNECTING_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Creating quantum secure connection",\n comment: ""\n )\n } else {\n NSLocalizedString(\n "TUNNEL_STATE_CONNECTING_ACCESSIBILITY_LABEL",\n tableName: "Main",\n value: "Creating secure connection",\n comment: ""\n )\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelState+UI.swift | TunnelState+UI.swift | Swift | 10,341 | 0.95 | 0.037618 | 0.024476 | node-utils | 885 | 2023-07-22T01:08:21.163422 | MIT | false | 392e58813b3825729e3f6cf477f55549 |
//\n// TunnelState.swift\n// TunnelState\n//\n// Created by pronebird on 11/08/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\nimport PacketTunnelCore\n@preconcurrency import WireGuardKitTypes\n\n/// A struct describing the tunnel status.\nstruct TunnelStatus: Equatable, CustomStringConvertible, Sendable {\n /// Tunnel status returned by tunnel process.\n var observedState: ObservedState = .disconnected\n\n /// Tunnel state.\n var state: TunnelState = .disconnected\n\n var description: String {\n var s = "\(state), network "\n\n if let connectionState = observedState.connectionState {\n if connectionState.isNetworkReachable {\n s += "reachable"\n } else {\n s += "unreachable"\n }\n } else {\n s += "reachability unknown"\n }\n\n return s\n }\n}\n\n/// An enum that describes the tunnel state.\nenum TunnelState: Equatable, CustomStringConvertible, Sendable {\n enum WaitingForConnectionReason {\n /// Tunnel connection is down.\n case noConnection\n /// Network is down.\n case noNetwork\n }\n\n /// Pending reconnect after disconnect.\n case pendingReconnect\n\n /// Connecting the tunnel.\n case connecting(SelectedRelays?, isPostQuantum: Bool, isDaita: Bool)\n\n /// Negotiating an ephemeral peer either for post-quantum resistance or Daita\n case negotiatingEphemeralPeer(SelectedRelays, PrivateKey, isPostQuantum: Bool, isDaita: Bool)\n\n /// Connected the tunnel\n case connected(SelectedRelays, isPostQuantum: Bool, isDaita: Bool)\n\n /// Disconnecting the tunnel\n case disconnecting(ActionAfterDisconnect)\n\n /// Disconnected the tunnel\n case disconnected\n\n /// Reconnecting the tunnel.\n /// Transition to this state happens when:\n /// 1. Asking the running tunnel to reconnect to new relays via IPC.\n /// 2. Tunnel attempts to reconnect to new relays as the current relays appear to be\n /// dysfunctional.\n case reconnecting(SelectedRelays, isPostQuantum: Bool, isDaita: Bool)\n\n /// Waiting for connectivity to come back up.\n case waitingForConnectivity(WaitingForConnectionReason)\n\n /// Error state.\n case error(BlockedStateReason)\n\n var description: String {\n switch self {\n case .pendingReconnect:\n "pending reconnect after disconnect"\n case let .connecting(tunnelRelays, isPostQuantum, isDaita):\n if let tunnelRelays {\n """\n connecting \(isPostQuantum ? "(PQ) " : ""), \\n daita: \(isDaita), \\n to \(tunnelRelays.exit.hostname)\\n \(tunnelRelays.entry.flatMap { " via \($0.hostname)" } ?? "")\n """\n } else {\n "connecting\(isPostQuantum ? " (PQ)" : ""), fetching relay"\n }\n case let .connected(tunnelRelays, isPostQuantum, isDaita):\n """\n connected \(isPostQuantum ? "(PQ) " : ""), \\n daita: \(isDaita), \\n to \(tunnelRelays.exit.hostname)\\n \(tunnelRelays.entry.flatMap { " via \($0.hostname)" } ?? "")\n """\n case let .disconnecting(actionAfterDisconnect):\n "disconnecting and then \(actionAfterDisconnect)"\n case .disconnected:\n "disconnected"\n case let .reconnecting(tunnelRelays, isPostQuantum, isDaita):\n """\n reconnecting \(isPostQuantum ? "(PQ) " : ""), \\n daita: \(isDaita), \\n to \(tunnelRelays.exit.hostname)\\n \(tunnelRelays.entry.flatMap { " via \($0.hostname)" } ?? "")\n """\n case .waitingForConnectivity:\n "waiting for connectivity"\n case let .error(blockedStateReason):\n "error state: \(blockedStateReason)"\n case let .negotiatingEphemeralPeer(tunnelRelays, _, isPostQuantum, isDaita):\n """\n negotiating key with exit relay: \(tunnelRelays.exit.hostname)\\n \(tunnelRelays.entry.flatMap { " via \($0.hostname)" } ?? ""), \\n isPostQuantum: \(isPostQuantum), isDaita: \(isDaita)\n """\n }\n }\n\n var isSecured: Bool {\n switch self {\n case .reconnecting, .connecting, .connected, .waitingForConnectivity(.noConnection), .error(.accountExpired),\n .error(.deviceRevoked), .negotiatingEphemeralPeer:\n true\n case .pendingReconnect, .disconnecting, .disconnected, .waitingForConnectivity(.noNetwork), .error:\n false\n }\n }\n\n var relays: SelectedRelays? {\n switch self {\n case let .connected(relays, _, _),\n let .reconnecting(relays, _, _),\n let .negotiatingEphemeralPeer(relays, _, _, _):\n relays\n case let .connecting(relays, _, _):\n relays\n case .disconnecting, .disconnected, .waitingForConnectivity, .pendingReconnect, .error:\n nil\n }\n }\n\n // the two accessors below return a Bool?, to differentiate known\n // truth values from undefined/meaningless values, which the caller\n // may want to interpret differently\n var isPostQuantum: Bool? {\n switch self {\n case let .connecting(_, isPostQuantum: isPostQuantum, isDaita: _),\n let .connected(_, isPostQuantum: isPostQuantum, isDaita: _),\n let .reconnecting(_, isPostQuantum: isPostQuantum, isDaita: _):\n isPostQuantum\n default:\n nil\n }\n }\n\n var isDaita: Bool? {\n switch self {\n case let .connecting(_, isPostQuantum: _, isDaita: isDaita),\n let .connected(_, isPostQuantum: _, isDaita: isDaita),\n let .reconnecting(_, isPostQuantum: _, isDaita: isDaita):\n isDaita\n default:\n nil\n }\n }\n\n var isMultihop: Bool {\n relays?.entry != nil\n }\n}\n\n/// A enum that describes the action to perform after disconnect.\nenum ActionAfterDisconnect: CustomStringConvertible {\n /// Do nothing after disconnecting.\n case nothing\n\n /// Reconnect after disconnecting.\n case reconnect\n\n var description: String {\n switch self {\n case .nothing:\n "do nothing"\n case .reconnect:\n "reconnect"\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelState.swift | TunnelState.swift | Swift | 6,381 | 0.95 | 0.061538 | 0.188235 | react-lib | 160 | 2024-04-17T08:27:10.350700 | MIT | false | aa7ee342a4192733b668aa57496da43b |
//\n// TunnelStatusBlockObserver.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-10-03.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\nfinal class TunnelStatusBlockObserver: TunnelStatusObserver, @unchecked Sendable {\n typealias Handler = (any TunnelProtocol, NEVPNStatus) -> Void\n\n private weak var tunnel: (any TunnelProtocol)?\n private let queue: DispatchQueue?\n private let handler: Handler\n\n init(tunnel: any TunnelProtocol, queue: DispatchQueue?, handler: @escaping Handler) {\n self.tunnel = tunnel\n self.queue = queue\n self.handler = handler\n }\n\n func invalidate() {\n tunnel?.removeObserver(self)\n }\n\n func tunnel(_ tunnel: any TunnelProtocol, didReceiveStatus status: NEVPNStatus) {\n let block: @Sendable () -> Void = {\n self.handler(tunnel, status)\n }\n\n if let queue {\n queue.async(execute: block)\n } else {\n block()\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelStatusBlockObserver.swift | TunnelStatusBlockObserver.swift | Swift | 1,030 | 0.95 | 0.05 | 0.212121 | python-kit | 670 | 2025-04-03T14:19:25.777224 | Apache-2.0 | false | 0829642551a2a9dccd56a44cae5133b0 |
//\n// TunnelStore.swift\n// MullvadVPN\n//\n// Created by pronebird on 07/12/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadTypes\nimport NetworkExtension\nimport UIKit\n\nprotocol TunnelStoreProtocol: Sendable {\n associatedtype TunnelType: TunnelProtocol, Equatable\n func getPersistentTunnels() -> [TunnelType]\n func createNewTunnel() -> TunnelType\n}\n\n/// Wrapper around system VPN tunnels.\nfinal class TunnelStore: TunnelStoreProtocol, TunnelStatusObserver, @unchecked Sendable {\n typealias TunnelType = Tunnel\n private let logger = Logger(label: "TunnelStore")\n private let lock = NSLock()\n private let application: BackgroundTaskProviding\n\n /// Persistent tunnels registered with the system.\n private var persistentTunnels: [TunnelType] = []\n\n /// Newly created tunnels, stored as collection of weak boxes.\n private var newTunnels: [WeakBox<TunnelType>] = []\n\n init(application: BackgroundTaskProviding) {\n self.application = application\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(applicationDidBecomeActive(_:)),\n name: UIApplication.didBecomeActiveNotification,\n object: application\n )\n }\n\n func getPersistentTunnels() -> [TunnelType] {\n lock.lock()\n defer { lock.unlock() }\n\n return persistentTunnels\n }\n\n func loadPersistentTunnels(completion: @escaping (Error?) -> Void) {\n TunnelProviderManagerType.loadAllFromPreferences { managers, error in\n self.lock.lock()\n defer {\n self.lock.unlock()\n\n completion(error)\n }\n\n guard error == nil else { return }\n\n self.persistentTunnels.forEach { tunnel in\n tunnel.removeObserver(self)\n }\n\n self.persistentTunnels = managers?.map { manager in\n let tunnel = Tunnel(tunnelProvider: manager, backgroundTaskProvider: self.application)\n tunnel.addObserver(self)\n\n self.logger.debug(\n "Loaded persistent tunnel: \(tunnel.logFormat()) with status: \(tunnel.status)."\n )\n\n return tunnel\n } ?? []\n }\n }\n\n func createNewTunnel() -> TunnelType {\n lock.lock()\n defer { lock.unlock() }\n\n let tunnelProviderManager = TunnelProviderManagerType()\n let tunnel = TunnelType(tunnelProvider: tunnelProviderManager, backgroundTaskProvider: application)\n tunnel.addObserver(self)\n\n newTunnels = newTunnels.filter { $0.value != nil }\n newTunnels.append(WeakBox(tunnel))\n\n logger.debug("Create new tunnel: \(tunnel.logFormat()).")\n\n return tunnel\n }\n\n func tunnel(_ tunnel: any TunnelProtocol, didReceiveStatus status: NEVPNStatus) {\n lock.lock()\n defer { lock.unlock() }\n\n // swiftlint:disable:next force_cast\n handleTunnelStatus(tunnel: tunnel as! TunnelType, status: status)\n }\n\n private func handleTunnelStatus(tunnel: TunnelType, status: NEVPNStatus) {\n if status == .invalid,\n let index = persistentTunnels.firstIndex(of: tunnel) {\n persistentTunnels.remove(at: index)\n logger.debug("Persistent tunnel was removed: \(tunnel.logFormat()).")\n }\n\n if status != .invalid,\n let index = newTunnels.compactMap({ $0.value }).firstIndex(where: { $0 == tunnel }) {\n newTunnels.remove(at: index)\n persistentTunnels.append(tunnel)\n logger.debug("New tunnel became persistent: \(tunnel.logFormat()).")\n }\n }\n\n @objc private func applicationDidBecomeActive(_ notification: Notification) {\n refreshStatus()\n }\n\n private func refreshStatus() {\n lock.lock()\n defer { lock.unlock() }\n\n let allTunnels = persistentTunnels + newTunnels.compactMap { $0.value }\n\n for tunnel in allTunnels {\n handleTunnelStatus(tunnel: tunnel, status: tunnel.status)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\TunnelStore.swift | TunnelStore.swift | Swift | 4,119 | 0.95 | 0.030303 | 0.105769 | react-lib | 585 | 2023-11-12T04:14:51.570278 | MIT | false | 46c6d8bee0beaf5a3a870ae732c75df0 |
//\n// UpdateAccountDataOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 12/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\n\nclass UpdateAccountDataOperation: ResultOperation<Void>, @unchecked Sendable {\n private let logger = Logger(label: "UpdateAccountDataOperation")\n private let interactor: TunnelInteractor\n private let accountsProxy: RESTAccountHandling\n private var task: Cancellable?\n\n init(\n dispatchQueue: DispatchQueue,\n interactor: TunnelInteractor,\n accountsProxy: RESTAccountHandling\n ) {\n self.interactor = interactor\n self.accountsProxy = accountsProxy\n\n super.init(dispatchQueue: dispatchQueue)\n }\n\n override func main() {\n guard case let .loggedIn(accountData, _) = interactor.deviceState else {\n finish(result: .failure(InvalidDeviceStateError()))\n return\n }\n\n task = accountsProxy.getAccountData(\n accountNumber: accountData.number,\n retryStrategy: .default,\n completion: { result in\n self.dispatchQueue.async {\n self.didReceiveAccountData(result: result)\n }\n }\n )\n }\n\n override func operationDidCancel() {\n task?.cancel()\n task = nil\n }\n\n private func didReceiveAccountData(result: Result<Account, Error>) {\n let result = result.inspectError { error in\n guard !error.isOperationCancellationError else { return }\n\n self.logger.error(\n error: error,\n message: "Failed to fetch account expiry."\n )\n }.tryMap { accountData in\n switch interactor.deviceState {\n case .loggedIn(var storedAccountData, let storedDeviceData):\n storedAccountData.expiry = accountData.expiry\n\n let newDeviceState = DeviceState.loggedIn(storedAccountData, storedDeviceData)\n\n interactor.setDeviceState(newDeviceState, persist: true)\n\n default:\n throw InvalidDeviceStateError()\n }\n }\n\n finish(result: result)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\UpdateAccountDataOperation.swift | UpdateAccountDataOperation.swift | Swift | 2,295 | 0.95 | 0.025316 | 0.106061 | node-utils | 67 | 2023-11-21T00:02:21.307653 | GPL-3.0 | false | 72b7b72609d974719a75dfc8eaf51b17 |
//\n// UpdateDeviceDataOperation.swift\n// MullvadVPN\n//\n// Created by pronebird on 13/05/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport WireGuardKitTypes\n\nclass UpdateDeviceDataOperation: ResultOperation<StoredDeviceData>, @unchecked Sendable {\n private let interactor: TunnelInteractor\n private let devicesProxy: DeviceHandling\n\n private var task: Cancellable?\n\n init(\n dispatchQueue: DispatchQueue,\n interactor: TunnelInteractor,\n devicesProxy: DeviceHandling\n ) {\n self.interactor = interactor\n self.devicesProxy = devicesProxy\n\n super.init(dispatchQueue: dispatchQueue)\n }\n\n override func main() {\n guard case let .loggedIn(accountData, deviceData) = interactor.deviceState else {\n finish(result: .failure(InvalidDeviceStateError()))\n return\n }\n\n task = devicesProxy.getDevice(\n accountNumber: accountData.number,\n identifier: deviceData.identifier,\n retryStrategy: .default,\n completion: { [weak self] result in\n self?.dispatchQueue.async { [weak self] in\n self?.didReceiveDeviceResponse(result: result)\n }\n }\n )\n }\n\n override func operationDidCancel() {\n task?.cancel()\n task = nil\n }\n\n private func didReceiveDeviceResponse(result: Result<Device, Error>) {\n let result = result.tryMap { device -> StoredDeviceData in\n switch interactor.deviceState {\n case .loggedIn(let storedAccount, var storedDevice):\n storedDevice.update(from: device)\n let newDeviceState = DeviceState.loggedIn(storedAccount, storedDevice)\n interactor.setDeviceState(newDeviceState, persist: true)\n\n return storedDevice\n\n default:\n throw InvalidDeviceStateError()\n }\n }\n\n if let error = result.error {\n interactor.handleRestError(error)\n }\n\n finish(result: result)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\UpdateDeviceDataOperation.swift | UpdateDeviceDataOperation.swift | Swift | 2,210 | 0.95 | 0.038462 | 0.107692 | vue-tools | 834 | 2024-10-31T08:38:02.241850 | MIT | false | 9ca6a33b8132c87cbd5f8be4e4808fc3 |
//\n// VPNConnectionProtocol.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-09-08.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport NetworkExtension\n\nprotocol VPNTunnelProviderManagerProtocol: Equatable {\n associatedtype SelfType: VPNTunnelProviderManagerProtocol\n associatedtype ConnectionType: VPNConnectionProtocol\n\n var isEnabled: Bool { get set }\n var protocolConfiguration: NEVPNProtocol? { get set }\n var localizedDescription: String? { get set }\n var connection: ConnectionType { get }\n\n init()\n\n func loadFromPreferences(completionHandler: @escaping (Error?) -> Void)\n func saveToPreferences(completionHandler: ((Error?) -> Void)?)\n func removeFromPreferences(completionHandler: ((Error?) -> Void)?)\n\n static func loadAllFromPreferences(completionHandler: @escaping ([SelfType]?, Error?) -> Void)\n}\n\nprotocol VPNConnectionProtocol: NSObject {\n var status: NEVPNStatus { get }\n var connectedDate: Date? { get }\n\n func startVPNTunnel() throws\n func startVPNTunnel(options: [String: NSObject]?) throws\n func stopVPNTunnel()\n}\n\nprotocol VPNTunnelProviderSessionProtocol {\n func sendProviderMessage(_ messageData: Data, responseHandler: ((Data?) -> Void)?) throws\n}\n\nextension NEVPNConnection: VPNConnectionProtocol {}\nextension NETunnelProviderSession: VPNTunnelProviderSessionProtocol {}\nextension NETunnelProviderManager: VPNTunnelProviderManagerProtocol {}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\VPNConnectionProtocol.swift | VPNConnectionProtocol.swift | Swift | 1,467 | 0.95 | 0 | 0.2 | vue-tools | 935 | 2023-07-22T12:42:00.182863 | GPL-3.0 | false | bdefb7ccc3151190fa5b7932e28f4be6 |
//\n// WgKeyRotation.swift\n// MullvadVPN\n//\n// Created by pronebird on 24/05/2023.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadSettings\nimport MullvadTypes\n@preconcurrency import WireGuardKitTypes\n\n/**\n Implements manipulations related to marking the beginning and the completion of key rotation, private key creation and other tasks relevant to handling the state of\n key rotation.\n */\nstruct WgKeyRotation: Sendable {\n /// Private key rotation interval counted from the time when the key was successfully pushed\n /// to the backend.\n public static let rotationInterval: Duration = .days(30)\n\n /// Private key rotation retry interval counted from the time when the last rotation\n /// attempt took place.\n public static let retryInterval: Duration = .days(1)\n\n /// Cooldown interval used to prevent packet tunnel from forcefully pushing the key to our\n /// backend in the event of restart loop.\n public static let packetTunnelCooldownInterval: Duration = .seconds(15)\n\n /// Mutated device data value.\n private(set) var data: StoredDeviceData\n\n /// Initialize object with `StoredDeviceData` that the struct is going to manipulate.\n init(data: StoredDeviceData) {\n self.data = data\n }\n\n /**\n Begin key rotation attempt by marking last rotation attempt and creating next private key if needed.\n If the next private key was created during the preivous rotation attempt then continue using the same key.\n\n Returns the public key that should be pushed to the backend.\n */\n mutating func beginAttempt() -> PublicKey {\n // Mark the rotation attempt.\n data.wgKeyData.lastRotationAttemptDate = Date()\n\n // Fetch the next private key we're attempting to rotate to.\n if let nextPrivateKey = data.wgKeyData.nextPrivateKey {\n return nextPrivateKey.publicKey\n } else {\n // If not found then create a new one and store it.\n let newKey = PrivateKey()\n data.wgKeyData.nextPrivateKey = newKey\n return newKey.publicKey\n }\n }\n\n /**\n Successfuly finish key rotation by swapping the current key with the next one, marking key creation date and\n removing the date of last rotation attempt which indicates that the last rotation had succedeed and no new\n rotation attempts were made.\n\n Device related properties are refreshed from `Device` struct that the caller should have received from the API. This function does nothing if the next private\n key is unset.\n\n Returns `false` if next private key is unset. Otherwise `true`.\n */\n mutating func setCompleted(with updatedDevice: Device) -> Bool {\n guard let nextKey = data.wgKeyData.nextPrivateKey else { return false }\n\n // Update stored device data with properties from updated `Device` struct.\n data.update(from: updatedDevice)\n\n // Reset creation date so that next period key rotation could happen relative to this date.\n data.wgKeyData.creationDate = Date()\n\n // Swap old and new keys.\n data.wgKeyData.privateKey = nextKey\n data.wgKeyData.nextPrivateKey = nil\n\n // Unset the date of last rotation attempt to mark the end of key rotation sequence.\n data.wgKeyData.lastRotationAttemptDate = nil\n\n return true\n }\n\n /**\n Returns the date of next key rotation, as it normally occurs in the app process using the following rules:\n\n 1. Returns the date relative to key creation date + 14 days, if last rotation attempt was successful.\n 2. Returns the date relative to last rotation attempt date + 24 hours, if last rotation attempt was unsuccessful.\n\n If the date produced is in the past then `Date()` is returned instead.\n */\n var nextRotationDate: Date {\n let nextRotationDate = data.wgKeyData.lastRotationAttemptDate?\n .addingTimeInterval(Self.retryInterval.timeInterval)\n ?? data.wgKeyData.creationDate.addingTimeInterval(Self.rotationInterval.timeInterval)\n\n return max(nextRotationDate, Date())\n }\n\n /// Returns `true` if the app should rotate the private key.\n var shouldRotate: Bool {\n nextRotationDate <= Date()\n }\n\n /**\n Returns `true` if packet tunnel should perform key rotation.\n\n During the startup packet tunnel rotates the key immediately if it detected that the key stored on server does not\n match the key stored on device. In that case it passes `rotateImmediately = true`.\n\n To dampen the effect of packet tunnel entering into a restart cycle and going on a key rotation rampage,\n this function adds a 15 seconds cooldown interval to prevent it from pushing keys too often.\n\n After performing the initial key rotation on startup, packet tunnel will keep a 24 hour interval between the\n subsequent key rotation attempts.\n */\n func shouldRotateFromPacketTunnel(rotateImmediately: Bool) -> Bool {\n guard let lastRotationAttemptDate = data.wgKeyData.lastRotationAttemptDate else { return true }\n\n let now = Date()\n\n // Add cooldown interval when requested to rotate the key immediately.\n if rotateImmediately, lastRotationAttemptDate.distance(to: now) > Self.packetTunnelCooldownInterval {\n return true\n }\n\n let nextRotationAttempt = max(now, lastRotationAttemptDate.addingTimeInterval(Self.retryInterval.timeInterval))\n if nextRotationAttempt <= now {\n return true\n }\n\n return false\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\TunnelManager\WgKeyRotation.swift | WgKeyRotation.swift | Swift | 5,572 | 0.95 | 0.093525 | 0.311927 | python-kit | 351 | 2024-06-10T14:09:21.735903 | GPL-3.0 | false | 4e4c6361ba7dbe684333841fdbdce87c |
//\n// UIColor+Palette.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nextension UIColor {\n enum AccountTextField {\n enum NormalState {\n static let borderColor = secondaryColor\n static let textColor = primaryColor\n static let backgroundColor = UIColor.white\n }\n\n enum ErrorState {\n static let borderColor = dangerColor.withAlphaComponent(0.4)\n static let textColor = dangerColor\n static let backgroundColor = UIColor.white\n }\n\n enum AuthenticatingState {\n static let borderColor = secondaryColor\n static let textColor = primaryColor\n static let backgroundColor = UIColor.white.withAlphaComponent(0.4)\n }\n }\n\n enum TextField {\n static let placeholderTextColor = UIColor(red: 0.16, green: 0.30, blue: 0.45, alpha: 0.40)\n static let inactivePlaceholderTextColor = UIColor(white: 1.0, alpha: 0.4)\n static let textColor = UIColor(red: 0.16, green: 0.30, blue: 0.45, alpha: 1.0)\n static let inactiveTextColor = UIColor.white\n static let backgroundColor = UIColor.white\n static let inactiveBackgroundColor = UIColor(white: 1.0, alpha: 0.1)\n static let invalidInputTextColor = UIColor.dangerColor\n }\n\n enum SearchTextField {\n static let placeholderTextColor = TextField.placeholderTextColor\n static let inactivePlaceholderTextColor = TextField.inactivePlaceholderTextColor\n static let textColor = TextField.textColor\n static let inactiveTextColor = TextField.inactiveTextColor\n static let backgroundColor = TextField.backgroundColor\n static let inactiveBackgroundColor = TextField.inactiveBackgroundColor\n static let leftViewTintColor = UIColor.primaryColor\n static let inactiveLeftViewTintColor = UIColor.white\n }\n\n enum AppButton {\n static let normalTitleColor = UIColor.white\n static let highlightedTitleColor = UIColor.lightGray\n static let disabledTitleColor = UIColor.white.withAlphaComponent(0.2)\n }\n\n enum Switch {\n static let borderColor = UIColor(white: 1.0, alpha: 0.8)\n static let onThumbColor = successColor\n static let offThumbColor = dangerColor\n }\n\n // Relay availability indicator view\n enum RelayStatusIndicator {\n static let activeColor = successColor.withAlphaComponent(0.9)\n static let inactiveColor = dangerColor.withAlphaComponent(0.95)\n static let highlightColor = UIColor.white\n }\n\n enum MainSplitView {\n static let dividerColor = UIColor.black\n }\n\n // Navigation bars\n enum NavigationBar {\n static let buttonColor = UIColor(white: 1.0, alpha: 0.8)\n static let backButtonTitleColor = UIColor.white\n static let titleColor = UIColor.white\n static let promptColor = UIColor.white\n }\n\n // Heading displayed below the navigation bar.\n enum ContentHeading {\n static let textColor = UIColor(white: 1.0, alpha: 0.6)\n static let linkColor = UIColor.white\n }\n\n // Cells\n enum Cell {\n enum Background {\n static let indentationLevelZero = UIColor(red: 0.14, green: 0.25, blue: 0.38, alpha: 1.0)\n static let indentationLevelOne = UIColor(red: 0.12, green: 0.23, blue: 0.34, alpha: 1.0)\n static let indentationLevelTwo = UIColor(red: 0.11, green: 0.20, blue: 0.31, alpha: 1.0)\n static let indentationLevelThree = UIColor(red: 0.11, green: 0.19, blue: 0.29, alpha: 1.0)\n\n static let normal = indentationLevelZero\n static let disabled = normal.darkened(by: 0.1)!\n static let selected = successColor\n static let disabledSelected = selected.darkened(by: 0.3)!\n static let selectedAlt = normal.darkened(by: 0.1)!\n }\n\n static let titleTextColor = UIColor.white\n static let detailTextColor = UIColor(white: 1.0, alpha: 0.8)\n\n static let disclosureIndicatorColor = UIColor(white: 1.0, alpha: 0.8)\n static let textFieldTextColor = UIColor.white\n static let textFieldPlaceholderColor = UIColor(white: 1.0, alpha: 0.6)\n\n static let validationErrorBorderColor = UIColor.dangerColor\n }\n\n enum TableSection {\n static let headerTextColor = UIColor(white: 1.0, alpha: 0.8)\n static let footerTextColor = UIColor(white: 1.0, alpha: 0.6)\n }\n\n enum SettingsCellBackground {}\n\n enum HeaderBar {\n static let defaultBackgroundColor = primaryColor\n static let unsecuredBackgroundColor = dangerColor\n static let securedBackgroundColor = successColor\n static let dividerColor = secondaryColor\n static let brandNameColor = UIColor(white: 1.0, alpha: 0.8)\n static let buttonColor = UIColor(white: 1.0, alpha: 0.8)\n static let disabledButtonColor = UIColor(white: 1.0, alpha: 0.5)\n }\n\n enum InAppNotificationBanner {\n static let errorIndicatorColor = dangerColor\n static let successIndicatorColor = successColor\n static let warningIndicatorColor = warningColor\n\n static let titleColor = UIColor.white\n static let bodyColor = UIColor(white: 1.0, alpha: 0.6)\n static let actionButtonColor = UIColor(white: 1.0, alpha: 0.8)\n }\n\n enum SegmentedControl {\n static let backgroundColor = UIColor(red: 0.14, green: 0.25, blue: 0.38, alpha: 1.0)\n static let selectedColor = successColor\n }\n\n enum AlertController {\n static let tintColor = UIColor(red: 0.0, green: 0.59, blue: 1.0, alpha: 1)\n }\n\n // Common colors\n static let primaryColor = UIColor(red: 0.16, green: 0.30, blue: 0.45, alpha: 1.0)\n static let secondaryColor = UIColor(red: 0.10, green: 0.18, blue: 0.27, alpha: 1.0)\n static let dangerColor = UIColor(red: 0.89, green: 0.25, blue: 0.22, alpha: 1.0)\n static let warningColor = UIColor(red: 1.0, green: 0.84, blue: 0.14, alpha: 1.0)\n static let successColor = UIColor(red: 0.27, green: 0.68, blue: 0.30, alpha: 1.0)\n\n static let primaryTextColor = UIColor.white\n static let secondaryTextColor = UIColor(white: 1.0, alpha: 0.8)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\UI appearance\UIColor+Palette.swift | UIColor+Palette.swift | Swift | 6,266 | 0.95 | 0 | 0.089552 | python-kit | 841 | 2024-12-09T12:42:18.633302 | GPL-3.0 | false | 3120687fe4a64dfa4ea97670acb4d22d |
//\n// UIEdgeInsets+Extensions.swift\n// MullvadVPN\n//\n// Created by Marco Nikic on 2023-09-20.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport SwiftUI\nimport UIKit\n\nextension UIEdgeInsets {\n /// Returns directional edge insets mapping left edge to leading and right edge to trailing.\n var toDirectionalInsets: NSDirectionalEdgeInsets {\n NSDirectionalEdgeInsets(\n top: top,\n leading: left,\n bottom: bottom,\n trailing: right\n )\n }\n\n /// Returns edge insets.\n var toEdgeInsets: EdgeInsets {\n EdgeInsets(toDirectionalInsets)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\UI appearance\UIEdgeInsets+Extensions.swift | UIEdgeInsets+Extensions.swift | Swift | 633 | 0.95 | 0 | 0.375 | node-utils | 665 | 2025-01-16T13:04:28.119498 | Apache-2.0 | false | f4c9abc12f467dee98fc51474c871b2b |
//\n// UIMetrics.swift\n// MullvadVPN\n//\n// Created by pronebird on 10/03/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport SwiftUI\nimport UIKit\n\nenum UIMetrics {\n enum TableView {\n /// Height for separators between cells and/or sections.\n static let separatorHeight: CGFloat = 0.33\n /// Spacing used between distinct sections of views\n static let sectionSpacing: CGFloat = 24\n /// Common layout margins for row views presentation\n /// Similar to `SettingsCell.layoutMargins` however maintains equal horizontal spacing\n static let rowViewLayoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 24, bottom: 16, trailing: 24)\n /// Common cell indentation width\n static let cellIndentationWidth: CGFloat = 16\n }\n\n enum CustomAlert {\n /// Layout margins for container (main view) in `CustomAlertViewController`\n static let containerMargins = NSDirectionalEdgeInsets(\n top: 28,\n leading: 16,\n bottom: 16,\n trailing: 16\n )\n\n /// Spacing between view containers in `CustomAlertViewController`\n static let containerSpacing: CGFloat = 16\n\n /// Spacing between view containers in `CustomAlertViewController`\n static let interContainerSpacing: CGFloat = 4\n }\n\n enum DimmingView {\n static let opacity: CGFloat = 0.5\n static let cornerRadius: CGFloat = 8\n static let backgroundColor: UIColor = .black\n }\n\n enum FormSheetTransition {\n static let duration: Duration = .milliseconds(500)\n static let delay: Duration = .zero\n static let animationOptions: UIView.AnimationOptions = [.curveEaseInOut]\n }\n\n enum AccessMethodActionSheetTransition {\n static let duration: Duration = .milliseconds(250)\n static let animationOptions: UIView.AnimationOptions = [.curveEaseInOut]\n }\n\n enum SettingsRedeemVoucher {\n static let cornerRadius: CGFloat = 8\n static let preferredContentSize = CGSize(width: 280, height: 260)\n static let contentLayoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)\n static let successfulRedeemMargins = NSDirectionalEdgeInsets(top: 16, leading: 8, bottom: 16, trailing: 8)\n }\n\n enum AccountDeletion {\n static let preferredContentSize = CGSize(width: 480, height: 640)\n }\n\n enum Button {\n static let barButtonSize: CGFloat = 32\n static let accountInfoSize: CGFloat = 18\n static let minimumTappableAreaSize = CGSize(width: 44, height: 44)\n }\n\n enum SettingsCell {\n static let textFieldContentInsets = UIEdgeInsets(top: 8, left: 24, bottom: 8, right: 24)\n static let textFieldNonEditingContentInsetLeft: CGFloat = 40\n static let layoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 24, bottom: 16, trailing: 12)\n static let inputCellTextFieldLayoutMargins = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 8)\n static let selectableSettingsCellLeftViewSpacing: CGFloat = 12\n static let checkableSettingsCellLeftViewSpacing: CGFloat = 20\n\n /// Cell layout margins used in table views that use inset style.\n static let insetLayoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 24, bottom: 16, trailing: 24)\n\n static let apiAccessLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 24, bottom: 24, trailing: 24)\n static let apiAccessInsetLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)\n static let settingsValidationErrorLayoutMargins = NSDirectionalEdgeInsets(\n top: 8,\n leading: 16,\n bottom: 8,\n trailing: 16\n )\n static let apiAccessCellHeight: CGFloat = 44\n static let customListsCellHeight: CGFloat = 44\n static let apiAccessSwitchCellTrailingMargin: CGFloat = apiAccessInsetLayoutMargins.trailing - 4\n static let apiAccessPickerListContentInsetTop: CGFloat = 16\n static let verticalDividerHeight: CGFloat = 22\n static let detailsButtonSize: CGFloat = 60\n static let infoButtonLeadingMargin: CGFloat = 8\n }\n\n enum SettingsInfoView {\n static let layoutMargins = EdgeInsets(top: 0, leading: 24, bottom: 0, trailing: 24)\n }\n\n enum SettingsRowView {\n static let height: CGFloat = 44\n static let cornerRadius: CGFloat = 10\n static let layoutMargins = EdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)\n static let footerLayoutMargins = EdgeInsets(top: 5, leading: 16, bottom: 5, trailing: 16)\n }\n\n enum InAppBannerNotification {\n /// Layout margins for contents presented within the banner.\n static let layoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 24, bottom: 16, trailing: 24)\n\n /// Size of little round severity indicator.\n static let indicatorSize = CGSize(width: 12, height: 12)\n }\n\n enum DisconnectSplitButton {\n static let secondaryButton = CGSize(width: 42, height: 42)\n }\n\n enum FilterView {\n static let interChipViewSpacing: CGFloat = 8\n static let chipViewCornerRadius: CGFloat = 8\n static let chipViewLayoutMargins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)\n static let chipViewLabelSpacing: CGFloat = 7\n }\n\n enum ConnectionPanelView {\n static let inRowHeight: CGFloat = 22\n static let outRowHeight: CGFloat = 44\n }\n\n enum MainButton {\n static let cornerRadius: CGFloat = 4\n }\n\n enum FeatureIndicators {\n static let chipViewHorisontalPadding: CGFloat = 8\n static let chipViewTrailingMargin: CGFloat = 6\n }\n}\n\nextension UIMetrics {\n /// Spacing used in stack views of buttons\n static let interButtonSpacing: CGFloat = 16\n\n /// Text field margins\n static let textFieldMargins = UIEdgeInsets(top: 12, left: 14, bottom: 12, right: 14)\n\n /// Text view margins\n static let textViewMargins = UIEdgeInsets(top: 14, left: 14, bottom: 14, right: 14)\n\n /// Corner radius used for controls such as buttons and text fields\n static let controlCornerRadius: CGFloat = 4\n\n /// Maximum width of the split view content container on iPad\n static let maximumSplitViewContentContainerWidth: CGFloat = 810 * 0.7\n\n /// Minimum sidebar width in points\n static let minimumSplitViewSidebarWidth: CGFloat = 300\n\n /// Maximum sidebar width in percentage points (0...1)\n static let maximumSplitViewSidebarWidthFraction: CGFloat = 0.3\n\n /// Spacing between buttons in header bar.\n static let headerBarButtonSpacing: CGFloat = 20\n\n /// Size of a square logo image in header bar.\n static let headerBarLogoSize: CGFloat = 44\n\n /// Height of brand name. Width is automatically produced based on aspect ratio.\n static let headerBarBrandNameHeight: CGFloat = 18\n\n /// Various paddings used throughout the app to visually separate elements in StackViews\n static let padding4: CGFloat = 4\n static let padding8: CGFloat = 8\n static let padding10: CGFloat = 10\n static let padding16: CGFloat = 16\n static let padding24: CGFloat = 24\n static let padding32: CGFloat = 32\n static let padding40: CGFloat = 40\n static let padding48: CGFloat = 48\n\n /// Preferred content size for controllers presented using formsheet modal presentation style.\n static let preferredFormSheetContentSize = CGSize(width: 480, height: 640)\n\n /// Common layout margins for content presentation\n static let contentLayoutMargins = contentInsets.toDirectionalInsets\n\n /// Common content margins for content presentation\n static let contentInsets = UIEdgeInsets(top: 24, left: 24, bottom: 24, right: 24)\n\n /// Common layout margins for location cell presentation\n static let locationCellLayoutMargins = NSDirectionalEdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 12)\n\n /// Layout margins used by content heading displayed below the large navigation title.\n static let contentHeadingLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 24, bottom: 24, trailing: 24)\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\UI appearance\UIMetrics.swift | UIMetrics.swift | Swift | 8,174 | 0.95 | 0.044118 | 0.206061 | python-kit | 593 | 2024-09-13T14:06:56.989058 | GPL-3.0 | false | 61dc44786100c9b719923e5b2f11d568 |
//\n// AccountContentView.swift\n// MullvadVPN\n//\n// Created by pronebird on 08/07/2021.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass AccountContentView: UIView {\n let purchaseButton: InAppPurchaseButton = {\n let button = InAppPurchaseButton()\n button.setAccessibilityIdentifier(.purchaseButton)\n button.setTitle(NSLocalizedString(\n "ADD_TIME_BUTTON_TITLE",\n tableName: "Account",\n value: "Add time",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let storeKit2PurchaseButton: AppButton = {\n let button = AppButton(style: .success)\n button.setTitle(NSLocalizedString(\n "BUY_SUBSCRIPTION_STOREKIT_2",\n tableName: "Account",\n value: "Make a purchase with StoreKit2",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let storeKit2RefundButton: AppButton = {\n let button = AppButton(style: .success)\n button.setTitle(NSLocalizedString(\n "BUY_SUBSCRIPTION_STOREKIT_2",\n tableName: "Account",\n value: "Refund last purchase with StoreKit2",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let redeemVoucherButton: AppButton = {\n let button = AppButton(style: .success)\n button.setAccessibilityIdentifier(.redeemVoucherButton)\n button.setTitle(NSLocalizedString(\n "REDEEM_VOUCHER_BUTTON_TITLE",\n tableName: "Account",\n value: "Redeem voucher",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let logoutButton: AppButton = {\n let button = AppButton(style: .danger)\n button.setAccessibilityIdentifier(.logoutButton)\n button.setTitle(NSLocalizedString(\n "LOGOUT_BUTTON_TITLE",\n tableName: "Account",\n value: "Log out",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let deleteButton: AppButton = {\n let button = AppButton(style: .danger)\n button.setAccessibilityIdentifier(.deleteButton)\n button.setTitle(NSLocalizedString(\n "DELETE_BUTTON_TITLE",\n tableName: "Account",\n value: "Delete account",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n let accountDeviceRow: AccountDeviceRow = {\n AccountDeviceRow()\n }()\n\n let accountTokenRowView: AccountNumberRow = {\n AccountNumberRow()\n }()\n\n let accountExpiryRowView: AccountExpiryRow = {\n AccountExpiryRow()\n }()\n\n let restorePurchasesView: RestorePurchasesView = {\n RestorePurchasesView()\n }()\n\n lazy var contentStackView: UIStackView = {\n let stackView =\n UIStackView(arrangedSubviews: [\n accountDeviceRow,\n accountTokenRowView,\n accountExpiryRowView,\n restorePurchasesView,\n ])\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.padding24\n stackView.setCustomSpacing(UIMetrics.padding8, after: accountExpiryRowView)\n return stackView\n }()\n\n lazy var buttonStackView: UIStackView = {\n var arrangedSubviews = [UIView]()\n #if DEBUG\n arrangedSubviews.append(redeemVoucherButton)\n arrangedSubviews.append(storeKit2PurchaseButton)\n arrangedSubviews.append(storeKit2RefundButton)\n #endif\n arrangedSubviews.append(contentsOf: [\n purchaseButton,\n logoutButton,\n deleteButton,\n ])\n arrangedSubviews.forEach { $0.isExclusiveTouch = true }\n let stackView = UIStackView(arrangedSubviews: arrangedSubviews)\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.padding16\n return stackView\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n setAccessibilityIdentifier(.accountView)\n\n addConstrainedSubviews([contentStackView, buttonStackView]) {\n contentStackView.pinEdgesToSuperviewMargins(.all().excluding(.bottom))\n buttonStackView.topAnchor.constraint(\n greaterThanOrEqualTo: contentStackView.bottomAnchor,\n constant: UIMetrics.TableView.sectionSpacing\n )\n buttonStackView.pinEdgesToSuperviewMargins(.all().excluding(.top))\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\AccountContentView.swift | AccountContentView.swift | Swift | 4,637 | 0.95 | 0.053333 | 0.067669 | react-lib | 704 | 2025-04-29T18:01:59.134294 | BSD-3-Clause | false | 23130e327c73fff8090cb2205f99f1c2 |
//\n// AccountDeviceRow.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-28.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass AccountDeviceRow: UIView {\n var deviceName: String? {\n didSet {\n deviceLabel.text = deviceName?.capitalized ?? ""\n accessibilityValue = deviceName\n setAccessibilityIdentifier(.accountPageDeviceNameLabel)\n }\n }\n\n var infoButtonAction: (() -> Void)?\n\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.text = NSLocalizedString(\n "DEVICE_NAME",\n tableName: "Account",\n value: "Device name",\n comment: ""\n )\n label.font = UIFont.systemFont(ofSize: 14)\n label.textColor = UIColor(white: 1.0, alpha: 0.6)\n return label\n }()\n\n private let deviceLabel: UILabel = {\n let label = UILabel()\n label.font = UIFont.systemFont(ofSize: 17)\n label.textColor = .white\n return label\n }()\n\n private let infoButton: UIButton = {\n let button = IncreasedHitButton(type: .system)\n button.isExclusiveTouch = true\n button.setAccessibilityIdentifier(.infoButton)\n button.tintColor = .white\n button.setBackgroundImage(UIImage.Buttons.info, for: .normal)\n button.heightAnchor.constraint(equalToConstant: UIMetrics.Button.accountInfoSize).isActive = true\n button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true\n return button\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n let contentContainerView = UIStackView(arrangedSubviews: [titleLabel, deviceLabel])\n contentContainerView.axis = .vertical\n contentContainerView.alignment = .leading\n contentContainerView.spacing = 8\n\n addConstrainedSubviews([contentContainerView, infoButton]) {\n contentContainerView.pinEdgesToSuperview()\n infoButton.leadingAnchor.constraint(equalToSystemSpacingAfter: deviceLabel.trailingAnchor, multiplier: 1)\n infoButton.centerYAnchor.constraint(equalTo: deviceLabel.centerYAnchor)\n }\n\n isAccessibilityElement = true\n accessibilityLabel = titleLabel.text\n\n infoButton.addTarget(\n self,\n action: #selector(didTapInfoButton),\n for: .touchUpInside\n )\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setButtons(enabled: Bool) {\n infoButton.isEnabled = enabled\n }\n\n @objc private func didTapInfoButton() {\n infoButtonAction?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\AccountDeviceRow.swift | AccountDeviceRow.swift | Swift | 2,699 | 0.95 | 0.034091 | 0.094595 | vue-tools | 612 | 2024-11-25T19:24:51.162638 | GPL-3.0 | false | f72e81e24d56a173bc981afac3c59aad |
//\n// AccountExpiryRow.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-28.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass AccountExpiryRow: UIView {\n var value: Date? {\n didSet {\n let expiry = value\n\n if let expiry, expiry <= Date() {\n let localizedString = NSLocalizedString(\n "ACCOUNT_OUT_OF_TIME_LABEL",\n tableName: "Account",\n value: "OUT OF TIME",\n comment: ""\n )\n\n valueLabel.text = localizedString\n accessibilityValue = localizedString\n\n valueLabel.textColor = .dangerColor\n } else {\n let formattedDate = expiry.map { date in\n DateFormatter.localizedString(\n from: date,\n dateStyle: .medium,\n timeStyle: .short\n )\n }\n\n valueLabel.text = formattedDate ?? ""\n accessibilityValue = formattedDate\n\n valueLabel.textColor = .white\n }\n }\n }\n\n private let textLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.translatesAutoresizingMaskIntoConstraints = false\n textLabel.text = NSLocalizedString(\n "ACCOUNT_EXPIRY_LABEL",\n tableName: "Account",\n value: "Paid until",\n comment: ""\n )\n textLabel.font = UIFont.systemFont(ofSize: 14)\n textLabel.textColor = UIColor(white: 1.0, alpha: 0.6)\n return textLabel\n }()\n\n private let valueLabel: UILabel = {\n let valueLabel = UILabel()\n valueLabel.translatesAutoresizingMaskIntoConstraints = false\n valueLabel.font = UIFont.systemFont(ofSize: 17)\n valueLabel.textColor = .white\n valueLabel.setAccessibilityIdentifier(.accountPagePaidUntilLabel)\n return valueLabel\n }()\n\n let activityIndicator: SpinnerActivityIndicatorView = {\n let activityIndicator = SpinnerActivityIndicatorView(style: .small)\n activityIndicator.translatesAutoresizingMaskIntoConstraints = false\n activityIndicator.tintColor = .white\n activityIndicator.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n activityIndicator.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n return activityIndicator\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n addConstrainedSubviews([textLabel, activityIndicator, valueLabel]) {\n textLabel.pinEdgesToSuperview(.all().excluding([.trailing, .bottom]))\n textLabel.trailingAnchor.constraint(\n greaterThanOrEqualTo: activityIndicator.leadingAnchor,\n constant: -UIMetrics.padding8\n )\n\n activityIndicator.topAnchor.constraint(equalTo: textLabel.topAnchor)\n activityIndicator.bottomAnchor.constraint(equalTo: textLabel.bottomAnchor)\n activityIndicator.trailingAnchor.constraint(equalTo: trailingAnchor)\n\n valueLabel.pinEdgesToSuperview(.all().excluding(.top))\n valueLabel.topAnchor.constraint(equalTo: textLabel.bottomAnchor, constant: UIMetrics.padding8)\n }\n isAccessibilityElement = true\n accessibilityLabel = textLabel.text\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\AccountExpiryRow.swift | AccountExpiryRow.swift | Swift | 3,541 | 0.95 | 0.039216 | 0.08046 | node-utils | 724 | 2023-09-21T14:55:57.492110 | MIT | false | 5c096d99caca66d629910d81954abd87 |
//\n// AccountInteractor.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport StoreKit\n\nfinal class AccountInteractor: Sendable {\n let tunnelManager: TunnelManager\n let accountsProxy: RESTAccountHandling\n let apiProxy: APIQuerying\n\n nonisolated(unsafe) var didReceiveDeviceState: (@Sendable (DeviceState) -> Void)?\n\n nonisolated(unsafe) private var tunnelObserver: TunnelObserver?\n\n init(\n tunnelManager: TunnelManager,\n accountsProxy: RESTAccountHandling,\n apiProxy: APIQuerying\n ) {\n self.tunnelManager = tunnelManager\n self.accountsProxy = accountsProxy\n self.apiProxy = apiProxy\n\n let tunnelObserver =\n TunnelBlockObserver(didUpdateDeviceState: { [weak self] _, deviceState, _ in\n self?.didReceiveDeviceState?(deviceState)\n })\n\n tunnelManager.addObserver(tunnelObserver)\n\n self.tunnelObserver = tunnelObserver\n }\n\n var deviceState: DeviceState {\n tunnelManager.deviceState\n }\n\n func logout() async {\n await tunnelManager.unsetAccount()\n }\n\n func sendStoreKitReceipt(_ transaction: VerificationResult<Transaction>, for accountNumber: String) async throws {\n _ = try await apiProxy.createApplePayment(\n accountNumber: accountNumber,\n receiptString: transaction.jwsRepresentation.data(using: .utf8)!\n ).execute()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\AccountInteractor.swift | AccountInteractor.swift | Swift | 1,590 | 0.95 | 0.051724 | 0.148936 | vue-tools | 245 | 2023-11-29T06:40:36.647243 | BSD-3-Clause | false | 37fdd2c6ec05cf7059d3258f845a368d |
//\n// AccountNumberRow.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-08-28.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport UIKit\n\nclass AccountNumberRow: UIView {\n var accountNumber: String? {\n didSet {\n updateView()\n }\n }\n\n var isObscured = true {\n didSet {\n updateView()\n }\n }\n\n var copyAccountNumber: (() -> Void)?\n\n private let titleLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.text = NSLocalizedString(\n "ACCOUNT_TOKEN_LABEL",\n tableName: "Account",\n value: "Account number",\n comment: ""\n )\n textLabel.font = UIFont.systemFont(ofSize: 14)\n textLabel.textColor = UIColor(white: 1.0, alpha: 0.6)\n return textLabel\n }()\n\n private let accountNumberLabel: UILabel = {\n let textLabel = UILabel()\n textLabel.font = UIFont.monospacedSystemFont(ofSize: 17, weight: .regular)\n textLabel.textColor = .white\n return textLabel\n }()\n\n private let showHideButton: UIButton = {\n let button = UIButton(type: .system)\n button.tintColor = .white\n button.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n return button\n }()\n\n private let copyButton: UIButton = {\n let button = UIButton(type: .system)\n button.tintColor = .white\n button.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n return button\n }()\n\n private var revertCopyImageWorkItem: DispatchWorkItem?\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n addConstrainedSubviews([titleLabel, accountNumberLabel, showHideButton, copyButton]) {\n titleLabel.pinEdgesToSuperview(.all().excluding([.trailing, .bottom]))\n titleLabel.trailingAnchor.constraint(greaterThanOrEqualTo: trailingAnchor)\n\n accountNumberLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: UIMetrics.padding8)\n accountNumberLabel.leadingAnchor.constraint(equalTo: leadingAnchor)\n accountNumberLabel.trailingAnchor.constraint(equalTo: showHideButton.leadingAnchor)\n accountNumberLabel.bottomAnchor.constraint(equalTo: bottomAnchor)\n\n showHideButton.heightAnchor.constraint(equalTo: accountNumberLabel.heightAnchor)\n showHideButton.centerYAnchor.constraint(equalTo: accountNumberLabel.centerYAnchor)\n showHideButton.leadingAnchor.constraint(equalTo: accountNumberLabel.trailingAnchor)\n\n copyButton.heightAnchor.constraint(equalTo: accountNumberLabel.heightAnchor)\n copyButton.centerYAnchor.constraint(equalTo: accountNumberLabel.centerYAnchor)\n copyButton.leadingAnchor.constraint(\n equalTo: showHideButton.trailingAnchor,\n constant: UIMetrics.padding24\n )\n copyButton.trailingAnchor.constraint(equalTo: trailingAnchor)\n }\n\n showHideButton.addTarget(\n self,\n action: #selector(didTapShowHideAccount),\n for: .touchUpInside\n )\n\n copyButton.addTarget(\n self,\n action: #selector(didTapCopyAccountNumber),\n for: .touchUpInside\n )\n\n isAccessibilityElement = true\n accessibilityLabel = titleLabel.text\n\n showCheckmark(false)\n updateView()\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setButtons(enabled: Bool) {\n showHideButton.isEnabled = enabled\n copyButton.isEnabled = enabled\n }\n\n // MARK: - Private\n\n private func updateView() {\n accountNumberLabel.text = displayAccountNumber ?? ""\n showHideButton.setImage(showHideImage, for: .normal)\n\n accessibilityAttributedValue = _accessibilityAttributedValue\n accessibilityCustomActions = _accessibilityCustomActions\n }\n\n private var displayAccountNumber: String? {\n guard let accountNumber else {\n return nil\n }\n\n let formattedString = accountNumber.formattedAccountNumber\n\n if isObscured {\n return String(formattedString.map { ch in\n ch == " " ? ch : "•"\n })\n } else {\n return formattedString\n }\n }\n\n private var showHideImage: UIImage? {\n if isObscured {\n return UIImage.Buttons.show\n } else {\n return UIImage.Buttons.hide\n }\n }\n\n private var _accessibilityAttributedValue: NSAttributedString? {\n guard let accountNumber else {\n return nil\n }\n\n if isObscured {\n return NSAttributedString(\n string: NSLocalizedString(\n "ACCOUNT_ACCESSIBILITY_OBSCURED",\n tableName: "Account",\n value: "Obscured",\n comment: ""\n )\n )\n } else {\n return NSAttributedString(\n string: accountNumber,\n attributes: [.accessibilitySpeechSpellOut: true]\n )\n }\n }\n\n private var _accessibilityCustomActions: [UIAccessibilityCustomAction]? {\n guard accountNumber != nil else { return nil }\n\n return [\n UIAccessibilityCustomAction(\n name: showHideAccessibilityActionName,\n target: self,\n selector: #selector(didTapShowHideAccount)\n ),\n UIAccessibilityCustomAction(\n name: NSLocalizedString(\n "ACCOUNT_ACCESSIBILITY_COPY_TO_PASTEBOARD",\n tableName: "Account",\n value: "Copy to pasteboard",\n comment: ""\n ),\n target: self,\n selector: #selector(didTapCopyAccountNumber)\n ),\n ]\n }\n\n private var showHideAccessibilityActionName: String {\n if isObscured {\n return NSLocalizedString(\n "ACCOUNT_ACCESSIBILITY_SHOW_ACCOUNT_NUMBER",\n tableName: "Account",\n value: "Show account number",\n comment: ""\n )\n } else {\n return NSLocalizedString(\n "ACCOUNT_ACCESSIBILITY_HIDE_ACCOUNT_NUMBER",\n tableName: "Account",\n value: "Hide account number",\n comment: ""\n )\n }\n }\n\n private func showCheckmark(_ showCheckmark: Bool) {\n if showCheckmark {\n let tickIcon = UIImage.tick\n\n copyButton.setImage(tickIcon, for: .normal)\n copyButton.tintColor = .successColor\n } else {\n let copyIcon = UIImage.Buttons.copy\n\n copyButton.setImage(copyIcon, for: .normal)\n copyButton.tintColor = .white\n }\n }\n\n // MARK: - Actions\n\n @objc private func didTapShowHideAccount() {\n isObscured.toggle()\n updateView()\n\n UIAccessibility.post(notification: .layoutChanged, argument: nil)\n }\n\n @objc private func didTapCopyAccountNumber() {\n let delayedWorkItem = DispatchWorkItem { [weak self] in\n self?.showCheckmark(false)\n }\n\n revertCopyImageWorkItem?.cancel()\n revertCopyImageWorkItem = delayedWorkItem\n\n showCheckmark(true)\n copyAccountNumber?()\n\n DispatchQueue.main.asyncAfter(\n deadline: .now() + .seconds(2),\n execute: delayedWorkItem\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\AccountNumberRow.swift | AccountNumberRow.swift | Swift | 7,603 | 0.95 | 0.051793 | 0.043062 | react-lib | 390 | 2024-05-02T13:10:21.555428 | MIT | false | 3b9755ba39c08e41cf0f426db714c805 |
//\n// AccountViewController.swift\n// MullvadVPN\n//\n// Created by pronebird on 20/03/2019.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadLogging\nimport MullvadREST\nimport MullvadSettings\nimport MullvadTypes\nimport Operations\nimport StoreKit\nimport UIKit\n\nenum AccountViewControllerAction: Sendable {\n case deviceInfo\n case finish\n case logOut\n case navigateToVoucher\n case navigateToDeleteAccount\n case restorePurchasesInfo\n case showPurchaseOptions\n case showFailedToLoadProducts\n case showRestorePurchases\n}\n\nclass AccountViewController: UIViewController, @unchecked Sendable {\n typealias ActionHandler = (AccountViewControllerAction) -> Void\n\n private let interactor: AccountInteractor\n private let errorPresenter: PaymentAlertPresenter\n\n private let contentView: AccountContentView = {\n let contentView = AccountContentView()\n contentView.translatesAutoresizingMaskIntoConstraints = false\n return contentView\n }()\n\n private var isFetchingProducts = false\n private var paymentState: PaymentState = .none\n private let storeKit2TestProduct = StoreSubscription.thirtyDays.rawValue\n\n var actionHandler: ActionHandler?\n\n init(interactor: AccountInteractor, errorPresenter: PaymentAlertPresenter) {\n self.interactor = interactor\n self.errorPresenter = errorPresenter\n\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n // MARK: - View lifecycle\n\n override var preferredStatusBarStyle: UIStatusBarStyle {\n .lightContent\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n view.backgroundColor = .secondaryColor\n\n navigationItem.title = NSLocalizedString(\n "NAVIGATION_TITLE",\n tableName: "Account",\n value: "Account",\n comment: ""\n )\n\n navigationItem.rightBarButtonItem = UIBarButtonItem(\n barButtonSystemItem: .done,\n target: self,\n action: #selector(handleDismiss)\n )\n\n contentView.accountTokenRowView.copyAccountNumber = { [weak self] in\n self?.copyAccountToken()\n }\n\n contentView.accountDeviceRow.infoButtonAction = { [weak self] in\n self?.actionHandler?(.deviceInfo)\n }\n\n contentView.restorePurchasesView.restoreButtonAction = { [weak self] in\n self?.restorePurchases()\n }\n\n contentView.restorePurchasesView.infoButtonAction = { [weak self] in\n self?.actionHandler?(.restorePurchasesInfo)\n }\n\n interactor.didReceiveDeviceState = { [weak self] deviceState in\n Task { @MainActor in\n self?.updateView(from: deviceState)\n }\n }\n\n configUI()\n addActions()\n updateView(from: interactor.deviceState)\n applyViewState(animated: false)\n }\n\n // MARK: - Private\n\n private func configUI() {\n let scrollView = UIScrollView()\n\n view.addConstrainedSubviews([scrollView]) {\n scrollView.pinEdgesToSuperview()\n }\n\n scrollView.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview(.all().excluding(.bottom))\n contentView.bottomAnchor.constraint(greaterThanOrEqualTo: scrollView.safeAreaLayoutGuide.bottomAnchor)\n contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor)\n }\n }\n\n private func addActions() {\n contentView.redeemVoucherButton.addTarget(\n self,\n action: #selector(redeemVoucher),\n for: .touchUpInside\n )\n\n contentView.purchaseButton.addTarget(\n self,\n action: #selector(requestStoreProducts),\n for: .touchUpInside\n )\n\n contentView.logoutButton.addTarget(self, action: #selector(logOut), for: .touchUpInside)\n contentView.deleteButton.addTarget(self, action: #selector(deleteAccount), for: .touchUpInside)\n contentView.storeKit2PurchaseButton.addTarget(\n self, action: #selector(handleStoreKit2Purchase),\n for: .touchUpInside\n )\n contentView.storeKit2RefundButton.addTarget(\n self, action: #selector(handleStoreKit2Refund),\n for: .touchUpInside\n )\n }\n\n @MainActor\n private func setPaymentState(_ newState: PaymentState, animated: Bool) {\n paymentState = newState\n\n applyViewState(animated: animated)\n }\n\n private func setIsFetchingProducts(_ isFetchingProducts: Bool, animated: Bool = false) {\n self.isFetchingProducts = isFetchingProducts\n\n applyViewState(animated: animated)\n }\n\n private func updateView(from deviceState: DeviceState?) {\n guard case let .loggedIn(accountData, deviceData) = deviceState else {\n return\n }\n\n contentView.accountDeviceRow.deviceName = deviceData.name\n contentView.accountTokenRowView.accountNumber = accountData.number\n contentView.accountExpiryRowView.value = accountData.expiry\n }\n\n private func applyViewState(animated: Bool) {\n let isInteractionEnabled = paymentState.allowsViewInteraction\n let purchaseButton = contentView.purchaseButton\n\n purchaseButton.isEnabled = !isFetchingProducts && isInteractionEnabled\n contentView.accountDeviceRow.setButtons(enabled: isInteractionEnabled)\n contentView.accountTokenRowView.setButtons(enabled: isInteractionEnabled)\n contentView.restorePurchasesView.setButtons(enabled: isInteractionEnabled)\n contentView.logoutButton.isEnabled = isInteractionEnabled\n contentView.redeemVoucherButton.isEnabled = isInteractionEnabled\n contentView.deleteButton.isEnabled = isInteractionEnabled\n contentView.storeKit2PurchaseButton.isEnabled = isInteractionEnabled\n contentView.storeKit2RefundButton.isEnabled = isInteractionEnabled\n navigationItem.rightBarButtonItem?.isEnabled = isInteractionEnabled\n\n view.isUserInteractionEnabled = isInteractionEnabled\n isModalInPresentation = !isInteractionEnabled\n\n navigationItem.setHidesBackButton(!isInteractionEnabled, animated: animated)\n }\n\n private func copyAccountToken() {\n guard let accountData = interactor.deviceState.accountData else {\n return\n }\n\n UIPasteboard.general.string = accountData.number\n }\n\n // MARK: - Actions\n\n @objc private func logOut() {\n actionHandler?(.logOut)\n }\n\n @objc private func handleDismiss() {\n actionHandler?(.finish)\n }\n\n @objc private func redeemVoucher() {\n actionHandler?(.navigateToVoucher)\n }\n\n @objc private func deleteAccount() {\n actionHandler?(.navigateToDeleteAccount)\n }\n\n @objc private func requestStoreProducts() {\n actionHandler?(.showPurchaseOptions)\n }\n\n @objc private func restorePurchases() {\n actionHandler?(.showRestorePurchases)\n }\n\n @objc private func handleStoreKit2Purchase() {\n guard let accountData = interactor.deviceState.accountData else {\n return\n }\n\n setPaymentState(.makingStoreKit2Purchase, animated: true)\n\n Task {\n do {\n let product = try await Product.products(for: [storeKit2TestProduct]).first!\n let result = try await product.purchase()\n\n switch result {\n case let .success(verification):\n let transaction = try checkVerified(verification)\n await sendReceiptToAPI(accountNumber: accountData.identifier, receipt: verification)\n await transaction.finish()\n case .userCancelled:\n print("User cancelled the purchase")\n case .pending:\n print("Purchase is pending")\n @unknown default:\n print("Unknown purchase result")\n }\n } catch {\n print("Error: \(error)")\n errorPresenter.showAlertForStoreKitError(error, context: .purchase)\n }\n\n setPaymentState(.none, animated: true)\n }\n }\n\n @objc private func handleStoreKit2Refund() {\n setPaymentState(.makingStoreKit2Refund, animated: true)\n\n Task {\n guard\n let latestTransactionResult = await Transaction.latest(for: storeKit2TestProduct),\n let windowScene = view.window?.windowScene\n else { return }\n\n do {\n switch latestTransactionResult {\n case let .verified(transaction):\n let refundStatus = try await transaction.beginRefundRequest(in: windowScene)\n\n switch refundStatus {\n case .success:\n print("Refund was successful")\n errorPresenter.showAlertForRefund()\n case .userCancelled:\n print("User cancelled the refund")\n @unknown default:\n print("Unknown refund result")\n }\n case .unverified:\n print("Transaction is unverified")\n }\n } catch {\n print("Error: \(error)")\n errorPresenter.showAlertForStoreKitError(error, context: .purchase)\n }\n\n setPaymentState(.none, animated: true)\n }\n }\n\n private func checkVerified<T>(_ result: VerificationResult<T>) throws -> T {\n switch result {\n case .unverified:\n throw StoreKit2Error.verificationFailed\n case let .verified(safe):\n return safe\n }\n }\n\n private func sendReceiptToAPI(accountNumber: String, receipt: VerificationResult<Transaction>) async {\n do {\n try await interactor.sendStoreKitReceipt(receipt, for: accountNumber)\n print("Receipt sent successfully")\n } catch {\n print("Error sending receipt: \(error)")\n errorPresenter.showAlertForStoreKitError(error, context: .purchase)\n }\n }\n}\n\nprivate enum StoreKit2Error: Error {\n case verificationFailed\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\AccountViewController.swift | AccountViewController.swift | Swift | 10,326 | 0.95 | 0.069182 | 0.03876 | node-utils | 144 | 2024-11-04T06:42:41.266006 | BSD-3-Clause | false | c7facbe440994a383a74a3c478f59053 |
//\n// PaymentErrorPresenter.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2023-05-30.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport Routing\n\n@MainActor\nstruct PaymentAlertPresenter {\n let alertContext: any Presenting\n\n func showAlertForRefund(completion: (@MainActor @Sendable () -> Void)? = nil) {\n let presentation = AlertPresentation(\n id: "payment-refund-alert",\n title: NSLocalizedString(\n "PAYMENT_REFUND_ALERT_TITLE",\n tableName: "Payment",\n value: "Refund successful",\n comment: ""\n ),\n message: NSLocalizedString(\n "PAYMENT_REFUND_ALERT_MESSAGE",\n tableName: "Payment",\n value: "Your purchase was successfully refunded.",\n comment: ""\n ),\n buttons: [\n AlertAction(\n title: okButtonTextForKey("PAYMENT_REFUND_ALERT_OK_ACTION"),\n style: .default,\n handler: {\n completion?()\n }\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: alertContext)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n func showAlertForError(\n _ error: StorePaymentManagerError,\n context: REST.CreateApplePaymentResponse.Context,\n completion: (@MainActor @Sendable () -> Void)? = nil\n ) {\n let presentation = AlertPresentation(\n id: "payment-error-alert",\n title: context.errorTitle,\n message: error.displayErrorDescription,\n buttons: [\n AlertAction(\n title: okButtonTextForKey("PAYMENT_ERROR_ALERT_OK_ACTION"),\n style: .default,\n handler: {\n completion?()\n }\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: alertContext)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n func showAlertForStoreKitError(\n _ error: any Error,\n context: REST.CreateApplePaymentResponse.Context,\n completion: (() -> Void)? = nil\n ) {\n let presentation = AlertPresentation(\n id: "payment-error-alert",\n title: context.errorTitle,\n message: "\(error)",\n buttons: [\n AlertAction(\n title: okButtonTextForKey("PAYMENT_ERROR_ALERT_OK_ACTION"),\n style: .default,\n handler: {\n completion?()\n }\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: alertContext)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n func showAlertForResponse(\n _ response: REST.CreateApplePaymentResponse,\n context: REST.CreateApplePaymentResponse.Context,\n completion: (@MainActor @Sendable () -> Void)? = nil\n ) {\n guard case .noTimeAdded = response else {\n completion?()\n return\n }\n\n let presentation = AlertPresentation(\n id: "payment-response-alert",\n title: response.alertTitle(context: context),\n message: response.alertMessage(context: context),\n buttons: [\n AlertAction(\n title: okButtonTextForKey("PAYMENT_RESPONSE_ALERT_OK_ACTION"),\n style: .default,\n handler: {\n completion?()\n }\n ),\n ]\n )\n\n let presenter = AlertPresenter(context: alertContext)\n presenter.showAlert(presentation: presentation, animated: true)\n }\n\n private func okButtonTextForKey(_ key: String) -> String {\n NSLocalizedString(\n key,\n tableName: "Payment",\n value: "Got it!",\n comment: ""\n )\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\PaymentAlertPresenter.swift | PaymentAlertPresenter.swift | Swift | 4,113 | 0.95 | 0 | 0.058824 | vue-tools | 41 | 2023-10-29T03:36:54.867429 | GPL-3.0 | false | 79f93427b370c93eb79f965081305ab2 |
//\n// PaymentState.swift\n// MullvadVPN\n//\n// Created by pronebird on 26/10/2022.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport StoreKit\n\nenum PaymentState: Equatable {\n case none\n case makingPayment(SKPayment)\n case makingStoreKit2Purchase\n case makingStoreKit2Refund\n case restoringPurchases\n\n var allowsViewInteraction: Bool {\n switch self {\n case .none:\n return true\n case .restoringPurchases, .makingPayment, .makingStoreKit2Purchase, .makingStoreKit2Refund:\n return false\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\PaymentState.swift | PaymentState.swift | Swift | 601 | 0.95 | 0.037037 | 0.291667 | react-lib | 313 | 2023-11-21T02:31:58.676722 | BSD-3-Clause | false | 0c7208f6c0a4c65f2ed4ab263d375713 |
//\n// RestorePurchasesView.swift\n// MullvadVPN\n//\n// Created by Jon Petersson on 2024-08-15.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport UIKit\n\nclass RestorePurchasesView: UIView {\n var restoreButtonAction: (() -> Void)?\n var infoButtonAction: (() -> Void)?\n\n private lazy var contentView: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [\n restoreButton,\n infoButton,\n UIView(), // Pushes the other views to the left.\n ])\n stackView.spacing = UIMetrics.padding8\n return stackView\n }()\n\n private lazy var restoreButton: UILabel = {\n let label = UILabel()\n label.setAccessibilityIdentifier(.restorePurchasesButton)\n label.attributedText = makeAttributedString()\n label.isUserInteractionEnabled = true\n label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapRestoreButton)))\n return label\n }()\n\n private lazy var infoButton: UIButton = {\n let button = IncreasedHitButton(type: .custom)\n button.isExclusiveTouch = true\n button.setBackgroundImage(UIImage.Buttons.info, for: .normal)\n button.tintColor = .white\n button.addTarget(self, action: #selector(didTapInfoButton), for: .touchUpInside)\n button.heightAnchor.constraint(equalToConstant: UIMetrics.Button.accountInfoSize).isActive = true\n button.widthAnchor.constraint(equalTo: button.heightAnchor, multiplier: 1).isActive = true\n return button\n }()\n\n override init(frame: CGRect) {\n super.init(frame: frame)\n\n addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview()\n }\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n func setButtons(enabled: Bool) {\n restoreButton.isUserInteractionEnabled = enabled\n restoreButton.alpha = enabled ? 1 : 0.5\n infoButton.isEnabled = enabled\n }\n\n private func makeAttributedString() -> NSAttributedString {\n let text = NSLocalizedString(\n "RESTORE_PURCHASES_BUTTON_TITLE",\n tableName: "Account",\n value: "Restore purchases",\n comment: ""\n )\n\n return NSAttributedString(string: text, attributes: [\n .font: UIFont.systemFont(ofSize: 13, weight: .semibold),\n .foregroundColor: UIColor.white,\n .underlineStyle: NSUnderlineStyle.single.rawValue,\n ])\n }\n\n @objc private func didTapRestoreButton() {\n restoreButtonAction?()\n }\n\n @objc private func didTapInfoButton() {\n infoButtonAction?()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\Account\RestorePurchasesView.swift | RestorePurchasesView.swift | Swift | 2,711 | 0.95 | 0.035294 | 0.097222 | react-lib | 978 | 2024-10-04T00:35:32.017616 | BSD-3-Clause | false | 193178d4b12562e671b8ea60cf8ef8ac |
//\n// AccountDeletionContentView.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadREST\nimport UIKit\n\nprotocol AccountDeletionContentViewDelegate: AnyObject {\n func didTapDeleteButton(contentView: AccountDeletionContentView, button: AppButton)\n func didTapCancelButton(contentView: AccountDeletionContentView, button: AppButton)\n}\n\nclass AccountDeletionContentView: UIView {\n enum State {\n case initial\n case loading\n case failure(Error)\n }\n\n private let scrollView: UIScrollView = {\n let scrollView = UIScrollView()\n return scrollView\n }()\n\n private let contentHolderView: UIView = {\n let contentHolderView = UIView()\n return contentHolderView\n }()\n\n private let titleLabel: UILabel = {\n let label = UILabel()\n label.translatesAutoresizingMaskIntoConstraints = false\n label.font = .preferredFont(forTextStyle: .title2, weight: .bold)\n label.numberOfLines = .zero\n label.lineBreakMode = .byWordWrapping\n label.textColor = .white\n label.text = NSLocalizedString(\n "ACCOUNT_DELETION_PAGE_TITLE",\n tableName: "Account",\n value: "Account deletion",\n comment: ""\n )\n return label\n }()\n\n private let messageLabel: UILabel = {\n let label = UILabel()\n label.translatesAutoresizingMaskIntoConstraints = false\n label.font = .preferredFont(forTextStyle: .body, weight: .bold)\n label.numberOfLines = .zero\n label.lineBreakMode = .byWordWrapping\n label.textColor = .white\n return label\n }()\n\n private let tipLabel: UILabel = {\n let label = UILabel()\n label.translatesAutoresizingMaskIntoConstraints = false\n label.font = .preferredFont(forTextStyle: .footnote, weight: .bold)\n label.numberOfLines = .zero\n label.lineBreakMode = .byWordWrapping\n label.textColor = .white\n label.text = NSLocalizedString(\n "TIP_TEXT",\n tableName: "Account",\n value: """\n This logs out all devices using this account and all \\n VPN access will be denied even if there is time left on the account. \\n Enter the last 4 digits of the account number and hit "Delete account" \\n if you really want to delete the account:\n """,\n comment: ""\n )\n return label\n }()\n\n private lazy var accountTextField: AccountTextField = {\n let groupingStyle = AccountTextField.GroupingStyle.lastPart\n let textField = AccountTextField(groupingStyle: groupingStyle)\n textField.setAccessibilityIdentifier(.deleteAccountTextField)\n textField.font = .preferredFont(forTextStyle: .body, weight: .bold)\n textField.placeholder = Array(repeating: "X", count: 4).joined()\n textField.placeholderTextColor = .lightGray\n textField.textContentType = .username\n textField.autocorrectionType = .no\n textField.smartDashesType = .no\n textField.smartInsertDeleteType = .no\n textField.smartQuotesType = .no\n textField.spellCheckingType = .no\n textField.keyboardType = .numberPad\n textField.returnKeyType = .done\n textField.enablesReturnKeyAutomatically = false\n textField.backgroundColor = .white\n textField.borderStyle = .line\n return textField\n }()\n\n private let deleteButton: AppButton = {\n let button = AppButton(style: .danger)\n button.setAccessibilityIdentifier(.deleteButton)\n button.setTitle(NSLocalizedString(\n "DELETE_ACCOUNT_BUTTON_TITLE",\n tableName: "Account",\n value: "Delete Account",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private let cancelButton: AppButton = {\n let button = AppButton(style: .default)\n button.setAccessibilityIdentifier(.cancelButton)\n button.setTitle(NSLocalizedString(\n "CANCEL_BUTTON_TITLE",\n tableName: "Account",\n value: "Cancel",\n comment: ""\n ), for: .normal)\n return button\n }()\n\n private lazy var textsStack: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [\n titleLabel,\n messageLabel,\n tipLabel,\n accountTextField,\n statusStack,\n ])\n stackView.setCustomSpacing(UIMetrics.padding8, after: titleLabel)\n stackView.setCustomSpacing(UIMetrics.padding16, after: messageLabel)\n stackView.setCustomSpacing(UIMetrics.padding8, after: tipLabel)\n stackView.setCustomSpacing(UIMetrics.padding4, after: accountTextField)\n stackView.setContentHuggingPriority(.defaultLow, for: .vertical)\n stackView.axis = .vertical\n return stackView\n }()\n\n private lazy var buttonsStack: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [deleteButton, cancelButton])\n stackView.axis = .vertical\n stackView.spacing = UIMetrics.padding16\n stackView.setContentCompressionResistancePriority(.required, for: .vertical)\n return stackView\n }()\n\n private let activityIndicator: SpinnerActivityIndicatorView = {\n let activityIndicator = SpinnerActivityIndicatorView(style: .medium)\n activityIndicator.translatesAutoresizingMaskIntoConstraints = false\n activityIndicator.tintColor = .white\n activityIndicator.setContentHuggingPriority(.defaultHigh, for: .horizontal)\n activityIndicator.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal)\n return activityIndicator\n }()\n\n private let statusLabel: UILabel = {\n let label = UILabel()\n label.font = .preferredFont(forTextStyle: .body)\n label.numberOfLines = 2\n label.lineBreakMode = .byWordWrapping\n label.textColor = .red\n label.setContentHuggingPriority(.defaultLow, for: .horizontal)\n label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)\n label.lineBreakStrategy = []\n return label\n }()\n\n private lazy var statusStack: UIStackView = {\n let stackView = UIStackView(arrangedSubviews: [activityIndicator, statusLabel])\n stackView.axis = .horizontal\n stackView.spacing = UIMetrics.padding8\n return stackView\n }()\n\n private var keyboardResponder: AutomaticKeyboardResponder?\n private var bottomsOfButtonsConstraint: NSLayoutConstraint?\n\n var state: State = .initial {\n didSet {\n updateUI()\n }\n }\n\n var isEditing: Bool {\n get {\n accountTextField.isEditing\n }\n set {\n guard accountTextField.isFirstResponder != newValue else { return }\n if newValue {\n accountTextField.becomeFirstResponder()\n } else {\n accountTextField.resignFirstResponder()\n }\n }\n }\n\n var viewModel: AccountDeletionViewModel? {\n didSet {\n updateData()\n }\n }\n\n var lastPartOfAccountNumber: String {\n accountTextField.parsedToken\n }\n\n private var text: String {\n switch state {\n case let .failure(error):\n return error.localizedDescription\n case .loading:\n return NSLocalizedString(\n "DELETE_ACCOUNT_STATUS_WAITING",\n tableName: "Account",\n value: "Deleting account...",\n comment: ""\n )\n default: return ""\n }\n }\n\n private var isDeleteButtonEnabled: Bool {\n switch state {\n case .initial, .failure:\n return true\n case .loading:\n return false\n }\n }\n\n private var textColor: UIColor {\n switch state {\n case .failure:\n return .dangerColor\n default:\n return .white\n }\n }\n\n private var isLoading: Bool {\n switch state {\n case .loading:\n return true\n default:\n return false\n }\n }\n\n private var isInputValid: Bool {\n guard let input = accountTextField.text,\n let accountNumber = viewModel?.accountNumber,\n !accountNumber.isEmpty\n else {\n return false\n }\n\n let inputLengthIsValid = input.count == 4\n let inputMatchesAccountNumber = accountNumber.suffix(4) == input\n\n return inputLengthIsValid && inputMatchesAccountNumber\n }\n\n weak var delegate: AccountDeletionContentViewDelegate?\n\n override init(frame: CGRect) {\n super.init(frame: .zero)\n commonInit()\n }\n\n required init?(coder: NSCoder) {\n super.init(coder: coder)\n commonInit()\n }\n\n private func commonInit() {\n setupAppearance()\n configureUI()\n addActions()\n updateUI()\n addKeyboardResponder()\n addObservers()\n }\n\n private func configureUI() {\n addConstrainedSubviews([scrollView]) {\n scrollView.pinEdgesToSuperviewMargins()\n }\n\n scrollView.addConstrainedSubviews([contentHolderView]) {\n contentHolderView.pinEdgesToSuperview()\n contentHolderView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: 1.0)\n contentHolderView.heightAnchor.constraint(greaterThanOrEqualTo: scrollView.heightAnchor, multiplier: 1.0)\n }\n contentHolderView.addConstrainedSubviews([textsStack, buttonsStack]) {\n textsStack.pinEdgesToSuperview(.all().excluding(.bottom))\n buttonsStack.pinEdgesToSuperview(PinnableEdges([.leading(.zero), .trailing(.zero)]))\n textsStack.bottomAnchor.constraint(\n lessThanOrEqualTo: buttonsStack.topAnchor,\n constant: -UIMetrics.padding16\n )\n }\n bottomsOfButtonsConstraint = buttonsStack.pinEdgesToSuperview(PinnableEdges([.bottom(.zero)])).first\n bottomsOfButtonsConstraint?.isActive = true\n }\n\n private func addActions() {\n [deleteButton, cancelButton].forEach { $0.addTarget(\n self,\n action: #selector(didPress(button:)),\n for: .touchUpInside\n ) }\n }\n\n private func updateData() {\n viewModel.flatMap { viewModel in\n let text = NSLocalizedString(\n "BODY_LABEL_TEXT",\n tableName: "Account",\n value: """\n Are you sure you want to delete account **\(viewModel.accountNumber)**?\n """,\n comment: ""\n )\n messageLabel.attributedText = NSAttributedString(\n markdownString: text,\n options: MarkdownStylingOptions(\n font: .preferredFont(forTextStyle: .body)\n )\n )\n }\n }\n\n private func updateUI() {\n if isLoading {\n activityIndicator.startAnimating()\n } else {\n activityIndicator.stopAnimating()\n }\n deleteButton.isEnabled = isDeleteButtonEnabled && isInputValid\n statusLabel.text = text\n statusLabel.textColor = textColor\n }\n\n private func setupAppearance() {\n setAccessibilityIdentifier(.deleteAccountView)\n translatesAutoresizingMaskIntoConstraints = false\n backgroundColor = .secondaryColor\n directionalLayoutMargins = UIMetrics.contentLayoutMargins\n }\n\n private func addKeyboardResponder() {\n keyboardResponder = AutomaticKeyboardResponder(\n targetView: self,\n handler: { [weak self] _, offset in\n guard let self else { return }\n self.bottomsOfButtonsConstraint?.constant = isEditing ? -offset : 0\n self.layoutIfNeeded()\n self.scrollView.flashScrollIndicators()\n }\n )\n }\n\n private func addObservers() {\n NotificationCenter.default.addObserver(\n self,\n selector: #selector(textDidChange),\n name: UITextField.textDidChangeNotification,\n object: accountTextField\n )\n }\n\n @objc private func didPress(button: AppButton) {\n switch button.accessibilityIdentifier {\n case AccessibilityIdentifier.deleteButton.asString:\n delegate?.didTapDeleteButton(contentView: self, button: button)\n case AccessibilityIdentifier.cancelButton.asString:\n delegate?.didTapCancelButton(contentView: self, button: button)\n default: return\n }\n }\n\n @objc private func textDidChange() {\n updateUI()\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\AccountDeletion\AccountDeletionContentView.swift | AccountDeletionContentView.swift | Swift | 12,765 | 0.95 | 0.048718 | 0.020115 | python-kit | 592 | 2025-05-24T18:43:09.061343 | BSD-3-Clause | false | 485c5c2f54bc811aa15216eac8e33a3c |
//\n// AccountDeletionInteractor.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport Foundation\nimport MullvadREST\nimport MullvadTypes\n\nenum AccountDeletionError: LocalizedError {\n case invalidInput\n\n var errorDescription: String? {\n switch self {\n case .invalidInput:\n return NSLocalizedString(\n "INVALID_ACCOUNT_NUMBER",\n tableName: "Account",\n value: "Last four digits of the account number are incorrect",\n comment: ""\n )\n }\n }\n}\n\nfinal class AccountDeletionInteractor: Sendable {\n private let tunnelManager: TunnelManager\n var viewModel: AccountDeletionViewModel {\n AccountDeletionViewModel(\n accountNumber: tunnelManager.deviceState.accountData?.number.formattedAccountNumber ?? ""\n )\n }\n\n init(tunnelManager: TunnelManager) {\n self.tunnelManager = tunnelManager\n }\n\n func validate(input: String) -> Result<String, Error> {\n if let accountNumber = tunnelManager.deviceState.accountData?.number,\n let fourLastDigits = accountNumber.split(every: 4).last,\n fourLastDigits == input {\n return .success(accountNumber)\n } else {\n return .failure(AccountDeletionError.invalidInput)\n }\n }\n\n func delete(accountNumber: String) async throws {\n try await tunnelManager.deleteAccount(accountNumber: accountNumber)\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\AccountDeletion\AccountDeletionInteractor.swift | AccountDeletionInteractor.swift | Swift | 1,532 | 0.95 | 0.074074 | 0.148936 | vue-tools | 524 | 2024-01-14T15:07:55.698423 | Apache-2.0 | false | 1499c3aadfcfe7d9be3f642b0e7f0b55 |
//\n// AccountDeletionViewController.swift\n// MullvadVPN\n//\n// Created by Mojgan on 2023-07-13.\n// Copyright © 2025 Mullvad VPN AB. All rights reserved.\n//\n\nimport MullvadTypes\nimport UIKit\n\nprotocol AccountDeletionViewControllerDelegate: AnyObject {\n func deleteAccountDidSucceed(controller: AccountDeletionViewController)\n func deleteAccountDidCancel(controller: AccountDeletionViewController)\n}\n\n@MainActor\nclass AccountDeletionViewController: UIViewController {\n private lazy var contentView: AccountDeletionContentView = {\n let view = AccountDeletionContentView()\n view.delegate = self\n return view\n }()\n\n weak var delegate: AccountDeletionViewControllerDelegate?\n let interactor: AccountDeletionInteractor\n\n init(interactor: AccountDeletionInteractor) {\n self.interactor = interactor\n super.init(nibName: nil, bundle: nil)\n }\n\n required init?(coder: NSCoder) {\n fatalError("init(coder:) has not been implemented")\n }\n\n override func viewDidLoad() {\n super.viewDidLoad()\n configureUI()\n contentView.viewModel = interactor.viewModel\n }\n\n override func viewDidAppear(_ animated: Bool) {\n super.viewDidAppear(animated)\n contentView.isEditing = true\n }\n\n override func viewWillDisappear(_ animated: Bool) {\n super.viewWillDisappear(animated)\n contentView.isEditing = false\n }\n\n override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {\n contentView.isEditing = false\n super.viewWillTransition(to: size, with: coordinator)\n }\n\n private func configureUI() {\n view.addConstrainedSubviews([contentView]) {\n contentView.pinEdgesToSuperview(.all())\n }\n }\n\n private func submit(accountNumber: String) {\n contentView.state = .loading\n Task { [weak self] in\n guard let self else { return }\n do {\n try await interactor.delete(accountNumber: accountNumber)\n self.contentView.state = .initial\n self.delegate?.deleteAccountDidSucceed(controller: self)\n } catch {\n self.contentView.state = .failure(error)\n }\n }\n }\n}\n\nextension AccountDeletionViewController: @preconcurrency AccountDeletionContentViewDelegate {\n func didTapCancelButton(contentView: AccountDeletionContentView, button: AppButton) {\n contentView.isEditing = false\n delegate?.deleteAccountDidCancel(controller: self)\n }\n\n func didTapDeleteButton(contentView: AccountDeletionContentView, button: AppButton) {\n switch interactor.validate(input: contentView.lastPartOfAccountNumber) {\n case let .success(accountNumber):\n contentView.isEditing = false\n submit(accountNumber: accountNumber)\n case let .failure(error):\n contentView.state = .failure(error)\n }\n }\n}\n | dataset_sample\swift\mullvad_mullvadvpn-app\ios\MullvadVPN\View controllers\AccountDeletion\AccountDeletionViewController.swift | AccountDeletionViewController.swift | Swift | 2,973 | 0.95 | 0.042553 | 0.0875 | python-kit | 865 | 2024-07-04T01:26:54.093145 | MIT | false | bd9380a401fc2175ee67e1aa3e6dd3d7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.