Implemented UpdateConfiguration intent

Signed-off-by: Alessio Nossa <alessio.nossa@gmail.com>
This commit is contained in:
Alessio Nossa
2022-02-01 10:16:38 +01:00
parent ceabb4ea34
commit fe3f2d089b
6 changed files with 358 additions and 1 deletions
@@ -33,6 +33,7 @@
<key>IntentsSupported</key>
<array>
<string>GetPeersIntent</string>
<string>UpdateConfigurationIntent</string>
</array>
</dict>
<key>NSExtensionPointIdentifier</key>
@@ -11,7 +11,7 @@ class IntentHandler: INExtension {
}
override func handler(for intent: INIntent) -> Any {
guard intent is GetPeersIntent else {
guard intent is GetPeersIntent || intent is UpdateConfigurationIntent else {
fatalError("Unhandled intent type: \(intent)")
}
@@ -118,3 +118,55 @@ extension IntentHandling: GetPeersIntentHandling {
}
}
extension IntentHandling: UpdateConfigurationIntentHandling {
@available(iOSApplicationExtension 14.0, *)
func provideTunnelOptionsCollection(for intent: UpdateConfigurationIntent, with completion: @escaping (INObjectCollection<NSString>?, Error?) -> Void) {
self.allTunnelNames { tunnelsNames in
let tunnelsNamesObjects = (tunnelsNames ?? []).map { NSString(string: $0) }
let objectCollection = INObjectCollection(items: tunnelsNamesObjects)
completion(objectCollection, nil)
}
}
func handle(intent: UpdateConfigurationIntent, completion: @escaping (UpdateConfigurationIntentResponse) -> Void) {
// Due to an Apple bug (https://developer.apple.com/forums/thread/96020) we can't update VPN
// configuration from extensions at the moment, so we should handle the action in the app.
// We check that the configuration update data is valid and then launch the main app.
guard let tunnelName = intent.tunnel,
let configurationString = intent.configuration else {
wg_log(.error, message: "Failed to get informations to update the configuration")
completion(UpdateConfigurationIntentResponse(code: .failure, userActivity: nil))
return
}
var configurations: [String: [String: String]]
let configurationsData = Data(configurationString.utf8)
do {
// Make sure this JSON is in the format we expect
if let decodedJson = try JSONSerialization.jsonObject(with: configurationsData, options: []) as? [String: [String: String]] {
configurations = decodedJson
} else {
throw IntentError.failedDecode
}
} catch _ {
wg_log(.error, message: "Failed to decode configuration data in JSON format for \(tunnelName)")
completion(UpdateConfigurationIntentResponse(code: .wrongConfiguration, userActivity: nil))
return
}
var activity: NSUserActivity?
if let bundleIdentifier = Bundle.main.bundleIdentifier {
activity = NSUserActivity(activityType: "\(bundleIdentifier).activity.update-tunnel-config")
activity?.userInfo = ["TunnelName": tunnelName,
"Configuration": configurations]
}
completion(UpdateConfigurationIntentResponse(code: .continueInApp, userActivity: activity))
}
}