An open-source cross-platform alternative to AirDrop
Ios Local Network Permission (#368)
Gabriel Limaba5d50c54562
diff --git a/assets/i18n/strings.i18n.json b/assets/i18n/strings.i18n.jsonindex b6689ffe..d9852961 100644--- a/assets/i18n/strings.i18n.json+++ b/assets/i18n/strings.i18n.json@@ -341,6 +341,11 @@"single": "Sends files to one recipient. Selection will be cleared after finished file transfer.","multiple": "Sends files to multiple recipients. Selection will not be cleared.","link": "Recipients who do not have LocalSend installed can download the selected files by opening the link in their browser."+ },+ "localNetworkUnauthorized": {+ "title": "Local Network discovery unauthorized",+ "description": "Localsend can't find other devices without this permission, so make sure it's enabled!",+ "gotoSettings": "Go to Settings"}},"tray": {diff --git a/ios/Podfile.lock b/ios/Podfile.lockindex fe9c0c5a..26f525f3 100644--- a/ios/Podfile.lock+++ b/ios/Podfile.lock@@ -73,6 +73,8 @@ PODS:- Flutter- FlutterMacOS- SwiftyGif (5.4.4)+ - system_settings (0.0.1):+ - Flutter- url_launcher_ios (0.0.1):- Flutter- video_player_avfoundation (0.0.1):@@ -96,6 +98,7 @@ DEPENDENCIES:- share_handler_ios (from `.symlinks/plugins/share_handler_ios/ios`)- share_handler_ios_models (from `.symlinks/plugins/share_handler_ios/ios/Models`)- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/ios`)+ - system_settings (from `.symlinks/plugins/system_settings/ios`)- url_launcher_ios (from `.symlinks/plugins/url_launcher_ios/ios`)- video_player_avfoundation (from `.symlinks/plugins/video_player_avfoundation/ios`)- wakelock (from `.symlinks/plugins/wakelock/ios`)@@ -139,6 +142,8 @@ EXTERNAL SOURCES::path: ".symlinks/plugins/share_handler_ios/ios/Models"shared_preferences_foundation::path: ".symlinks/plugins/shared_preferences_foundation/ios"+ system_settings:+ :path: ".symlinks/plugins/system_settings/ios"url_launcher_ios::path: ".symlinks/plugins/url_launcher_ios/ios"video_player_avfoundation:@@ -167,6 +172,7 @@ SPEC CHECKSUMS:share_handler_ios_models: fc638c9b4330dc7f082586c92aee9dfa0b87b871shared_preferences_foundation: 986fc17f3d3251412d18b0265f9c64113a8c2472SwiftyGif: 93a1cc87bf3a51916001cf8f3d63835fb64c819f+ system_settings: 8f5cdbfa72c677fc8d665b863bcc20d393d87e9durl_launcher_ios: 08a3dfac5fb39e8759aeb0abbd5d9480f30fc8b4video_player_avfoundation: 81e49bb3d9fb63dccf9fa0f6d877dc3ddbeac126wakelock: d0fc7c864128eac40eba1617cb5264d9c940b46fdiff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxprojindex 1c9689d7..8b77a111 100644--- a/ios/Runner.xcodeproj/project.pbxproj+++ b/ios/Runner.xcodeproj/project.pbxproj@@ -14,6 +14,7 @@3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };7DA3203436DA0EAD484C6129 /* Pods_ShareExtension.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 052009B9C8E63670A6F30787 /* Pods_ShareExtension.framework */; };+ 841A12B929EC22BD00B99343 /* LocalNetworkAuthorization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 841A12B829EC22BD00B99343 /* LocalNetworkAuthorization.swift */; };97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };@@ -72,6 +73,7 @@74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };+ 841A12B829EC22BD00B99343 /* LocalNetworkAuthorization.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalNetworkAuthorization.swift; sourceTree = "<group>"; };9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };@@ -172,6 +174,7 @@1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,74858FAE1ED2DC5600515810 /* AppDelegate.swift */,74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,+ 841A12B829EC22BD00B99343 /* LocalNetworkAuthorization.swift */,);path = Runner;sourceTree = "<group>";@@ -399,6 +402,7 @@files = (74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,+ 841A12B929EC22BD00B99343 /* LocalNetworkAuthorization.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;};diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swiftindex 70693e4a..c04fb4f2 100644--- a/ios/Runner/AppDelegate.swift+++ b/ios/Runner/AppDelegate.swift@@ -7,6 +7,27 @@ import Flutter_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {+ let controller : FlutterViewController = window?.rootViewController as! FlutterViewController+ let channel = FlutterMethodChannel(name:"localsend.localsend_app/iosCall", binaryMessenger: controller.binaryMessenger)++ channel.setMethodCallHandler {+ (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in+ if call.method == "triggerLocalNetworkDialog" {+ if #available(iOS 14, *) {+ Task {+ let localNetworkAuthorization = LocalNetworkAuthorization()+ let granted = await localNetworkAuthorization.requestAuthorization()+ result(granted)+ }+ } else {+ // Fallback for older iOS versions+ result(true)+ }+ } else {+ result(FlutterMethodNotImplemented)+ }+ }+GeneratedPluginRegistrant.register(with: self)return super.application(application, didFinishLaunchingWithOptions: launchOptions)}diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plistindex e38c4332..f6a7f7f8 100644--- a/ios/Runner/Info.plist+++ b/ios/Runner/Info.plist@@ -88,6 +88,14 @@<string>The app requires the local IP to communicate.</string><key>NSLocationWhenInUseUsageDescription</key><string>The app requires the local IP to communicate.</string>+ <key>NSLocalNetworkUsageDescription</key>+ <string>The app uses the local network to find and connect to nearby devices.</string>+ <key>NSBonjourServices</key>+ <array>+ <string>_http._tcp</string>+ <string>_bonjour._tcp</string>+ <string>_lnp._tcp.</string>+ </array><!-- share_handler --><key>CFBundleURLTypes</key>diff --git a/ios/Runner/LocalNetworkAuthorization.swift b/ios/Runner/LocalNetworkAuthorization.swiftnew file mode 100644index 00000000..97659437--- /dev/null+++ b/ios/Runner/LocalNetworkAuthorization.swift@@ -0,0 +1,67 @@+import Foundation+import Network++@available(iOS 14.0, *)+public class LocalNetworkAuthorization: NSObject {+ private var browser: NWBrowser?+ private var netService: NetService?+ private var completion: ((Bool) -> Void)?++ public func requestAuthorization() async -> Bool {+ return await withCheckedContinuation { continuation in+ requestAuthorization() { result in+ continuation.resume(returning: result)+ }+ }+ }++ private func requestAuthorization(completion: @escaping (Bool) -> Void) {+ self.completion = completion++ // Create parameters, and allow browsing over peer-to-peer link.+ let parameters = NWParameters()+ parameters.includePeerToPeer = true++ // Browse for a custom service type.+ let browser = NWBrowser(for: .bonjour(type: "_bonjour._tcp", domain: nil), using: parameters)+ self.browser = browser+ browser.stateUpdateHandler = { newState in+ switch newState {+ case .failed(let error):+ print(error.localizedDescription)+ case .ready, .cancelled:+ break+ case let .waiting(error):+ print("Local network permission has been denied: \(error)")+ self.reset()+ self.completion?(false)+ default:+ break+ }+ }++ self.netService = NetService(domain: "local.", type:"_lnp._tcp.", name: "LocalNetworkPrivacy", port: 1100)+ netService?.schedule(in: .main, forMode: .common)+ self.netService?.delegate = self++ self.browser?.start(queue: .main)+ self.netService?.publish()+ }+++ private func reset() {+ self.browser?.cancel()+ self.browser = nil+ self.netService?.stop()+ self.netService = nil+ }+}++@available(iOS 14.0, *)+extension LocalNetworkAuthorization : NetServiceDelegate {+ public func netServiceDidPublish(_ sender: NetService) {+ self.reset()+ print("Local network permission has been granted")+ completion?(true)+ }+}\ No newline at end of filediff --git a/lib/pages/tabs/send_tab.dart b/lib/pages/tabs/send_tab.dartindex 487b8c73..d9d2c670 100644--- a/lib/pages/tabs/send_tab.dart+++ b/lib/pages/tabs/send_tab.dart@@ -1,5 +1,6 @@import 'package:collection/collection.dart';import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:flutter_riverpod/flutter_riverpod.dart';import 'package:localsend_app/gen/strings.g.dart';import 'package:localsend_app/model/device.dart';@@ -24,6 +25,7 @@ import 'package:localsend_app/widget/big_button.dart';import 'package:localsend_app/widget/custom_icon_button.dart';import 'package:localsend_app/widget/dialogs/add_file_dialog.dart';import 'package:localsend_app/widget/dialogs/address_input_dialog.dart';+import 'package:localsend_app/widget/dialogs/ios_network_permission_dialog.dart';import 'package:localsend_app/widget/dialogs/no_files_dialog.dart';import 'package:localsend_app/widget/dialogs/send_mode_help_dialog.dart';import 'package:localsend_app/widget/file_thumbnail.dart';@@ -44,6 +46,8 @@ class SendTab extends ConsumerStatefulWidget {}class _SendTabState extends ConsumerState<SendTab> {+ static const iosCall = MethodChannel('localsend.localsend_app/iosCall');+@overridevoid initState() {super.initState();@@ -52,7 +56,22 @@ class _SendTabState extends ConsumerState<SendTab> {WidgetsBinding.instance.addPostFrameCallback((_) async {final devices = ref.read(nearbyDevicesProvider.select((state) => state.devices));if (devices.isEmpty) {- await ref.read(scanProvider).startSmartScan();+ await ref.read(scanProvider).startSmartScan().whenComplete(() async {+ if (devices.isEmpty) {+ // After the first complete scan, if devices aren't found on IOS a Network trigger is called+ if(checkPlatform([TargetPlatform.iOS])) {+ try {+ final bool granted = await iosCall.invokeMethod('triggerLocalNetworkDialog');+ if (!granted) {+ print("Local Network Permission denied");+ if(context.mounted) await context.pushBottomSheet(() => const IosLocalNetworkDialog());+ }+ } on PlatformException catch (e) {+ print(e);+ }+ }+ }+ });}});}diff --git a/lib/widget/dialogs/ios_network_permission_dialog.dart b/lib/widget/dialogs/ios_network_permission_dialog.dartnew file mode 100644index 00000000..83181b91--- /dev/null+++ b/lib/widget/dialogs/ios_network_permission_dialog.dart@@ -0,0 +1,31 @@+import 'package:flutter/material.dart';+import 'package:localsend_app/gen/strings.g.dart';+import 'package:localsend_app/widget/dialogs/custom_bottom_sheet.dart';+import 'package:routerino/routerino.dart';+import 'package:system_settings/system_settings.dart';++class IosLocalNetworkDialog extends StatelessWidget {+ const IosLocalNetworkDialog({Key? key}) : super(key: key);++ @override+ Widget build(BuildContext context) {+ return CustomBottomSheet(+ title: t.dialogs.localNetworkUnauthorized.title,+ description: t.dialogs.localNetworkUnauthorized.description,+ child: Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,+ children: [+ TextButton(+ onPressed: () => context.pop(),+ child: Text(t.general.close),+ ),+ ElevatedButton.icon(+ onPressed: () async => SystemSettings.app(),+ icon: const Icon(Icons.settings),+ label: Text(t.dialogs.localNetworkUnauthorized.gotoSettings),+ ),+ ],+ ),+ );+ }+}diff --git a/pubspec.lock b/pubspec.lockindex aa405ddd..e77a9f88 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -1294,6 +1294,14 @@ packages:url: "https://pub.dev"source: hostedversion: "1.2.0"+ system_settings:+ dependency: "direct main"+ description:+ name: system_settings+ sha256: "666693f8dace789bcf1200a88f6132b6906026643a5ee93ff140d3a547e5faf1"+ url: "https://pub.dev"+ source: hosted+ version: "2.1.0"term_glyph:dependency: transitivedescription:diff --git a/pubspec.yaml b/pubspec.yamlindex 2c0a19db..66d5b7ad 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -44,6 +44,7 @@ dependencies:shelf_router: 1.1.3slang: 3.16.1slang_flutter: 3.16.0+ system_settings: ^2.1.0tray_manager:# https://github.com/leanflutter/tray_manager/issues/30# The Linux tray manager is disabled for now