Marino Faggiana 6 lat temu
rodzic
commit
78c065b336

+ 101 - 0
Libraries external/Firebase/Firebase.h

@@ -0,0 +1,101 @@
+#import <FirebaseCore/FirebaseCore.h>
+
+#if !defined(__has_include)
+  #error "Firebase.h won't import anything if your compiler doesn't support __has_include. Please \
+          import the headers individually."
+#else
+  #if __has_include(<FirebaseAnalytics/FirebaseAnalytics.h>)
+    #import <FirebaseAnalytics/FirebaseAnalytics.h>
+  #else
+    #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
+      #warning "FirebaseAnalytics.framework is not included in your target. Please add \
+`Firebase/Core` to your Podfile or add FirebaseAnalytics.framework to your project to ensure \
+Firebase services work as intended."
+    #endif // #ifndef FIREBASE_ANALYTICS_SUPPRESS_WARNING
+  #endif
+
+  #if __has_include(<FirebaseAuth/FirebaseAuth.h>)
+    #import <FirebaseAuth/FirebaseAuth.h>
+  #endif
+
+  #if __has_include(<FirebaseCrash/FirebaseCrash.h>)
+    #import <FirebaseCrash/FirebaseCrash.h>
+  #endif
+
+  #if __has_include(<FirebaseDatabase/FirebaseDatabase.h>)
+    #import <FirebaseDatabase/FirebaseDatabase.h>
+  #endif
+
+  #if __has_include(<FirebaseDynamicLinks/FirebaseDynamicLinks.h>)
+    #import <FirebaseDynamicLinks/FirebaseDynamicLinks.h>
+  #endif
+
+  #if __has_include(<FirebaseFirestore/FirebaseFirestore.h>)
+    #import <FirebaseFirestore/FirebaseFirestore.h>
+  #endif
+
+  #if __has_include(<FirebaseFunctions/FirebaseFunctions.h>)
+    #import <FirebaseFunctions/FirebaseFunctions.h>
+  #endif
+
+  #if __has_include(<FirebaseInstanceID/FirebaseInstanceID.h>)
+    #import <FirebaseInstanceID/FirebaseInstanceID.h>
+  #endif
+
+  #if __has_include(<FirebaseInvites/FirebaseInvites.h>)
+    #import <FirebaseInvites/FirebaseInvites.h>
+  #endif
+
+  #if __has_include(<FirebaseMessaging/FirebaseMessaging.h>)
+    #import <FirebaseMessaging/FirebaseMessaging.h>
+  #endif
+
+  #if __has_include(<FirebaseMLModelInterpreter/FirebaseMLModelInterpreter.h>)
+    #import <FirebaseMLModelInterpreter/FirebaseMLModelInterpreter.h>
+  #endif
+
+  #if __has_include(<FirebaseMLVision/FirebaseMLVision.h>)
+    #import <FirebaseMLVision/FirebaseMLVision.h>
+  #endif
+
+  #if __has_include(<FirebaseMLVisionBarcodeModel/FirebaseMLVisionBarcodeModel.h>)
+    #import <FirebaseMLVisionBarcodeModel/FirebaseMLVisionBarcodeModel.h>
+  #endif
+
+  #if __has_include(<FirebaseMLVisionFaceModel/FirebaseMLVisionFaceModel.h>)
+    #import <FirebaseMLVisionFaceModel/FirebaseMLVisionFaceModel.h>
+  #endif
+
+  #if __has_include(<FirebaseMLVisionLabelModel/FirebaseMLVisionLabelModel.h>)
+    #import <FirebaseMLVisionLabelModel/FirebaseMLVisionLabelModel.h>
+  #endif
+
+  #if __has_include(<FirebaseMLVisionTextModel/FirebaseMLVisionTextModel.h>)
+    #import <FirebaseMLVisionTextModel/FirebaseMLVisionTextModel.h>
+  #endif
+
+  #if __has_include(<FirebasePerformance/FirebasePerformance.h>)
+    #import <FirebasePerformance/FirebasePerformance.h>
+  #endif
+
+  #if __has_include(<FirebaseRemoteConfig/FirebaseRemoteConfig.h>)
+    #import <FirebaseRemoteConfig/FirebaseRemoteConfig.h>
+  #endif
+
+  #if __has_include(<FirebaseStorage/FirebaseStorage.h>)
+    #import <FirebaseStorage/FirebaseStorage.h>
+  #endif
+
+  #if __has_include(<GoogleMobileAds/GoogleMobileAds.h>)
+    #import <GoogleMobileAds/GoogleMobileAds.h>
+  #endif
+
+  #if __has_include(<Fabric/Fabric.h>)
+    #import <Fabric/Fabric.h>
+  #endif
+
+  #if __has_include(<Crashlytics/Crashlytics.h>)
+    #import <Crashlytics/Crashlytics.h>
+  #endif
+
+#endif  // defined(__has_include)

+ 182 - 18
Nextcloud.xcodeproj/project.pbxproj

@@ -108,6 +108,10 @@
 		F72D0FFF210B6638009C96B7 /* FirebaseNanoPB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F72D0FF6210B6638009C96B7 /* FirebaseNanoPB.framework */; };
 		F72D1000210B6638009C96B7 /* FirebaseInstanceID.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F72D0FF7210B6638009C96B7 /* FirebaseInstanceID.framework */; };
 		F72D1001210B6638009C96B7 /* FirebaseCoreDiagnostics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F72D0FF8210B6638009C96B7 /* FirebaseCoreDiagnostics.framework */; };
+		F72D1003210B67CE009C96B7 /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = F72D1002210B67CE009C96B7 /* GoogleService-Info.plist */; };
+		F72D1007210B6882009C96B7 /* NCPushNotification.m in Sources */ = {isa = PBXBuildFile; fileRef = F72D1005210B6882009C96B7 /* NCPushNotification.m */; };
+		F72D100F210B6B17009C96B7 /* NotificationService.swift in Sources */ = {isa = PBXBuildFile; fileRef = F72D100E210B6B17009C96B7 /* NotificationService.swift */; };
+		F72D1013210B6B17009C96B7 /* Notification Service Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = F72D100C210B6B16009C96B7 /* Notification Service Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
 		F732B3371E8045A1002B7D75 /* SwiftWebVC.strings in Resources */ = {isa = PBXBuildFile; fileRef = F732B3351E8045A1002B7D75 /* SwiftWebVC.strings */; };
 		F732BA061D76CE1500E9878B /* CCNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F732BA041D76CE1500E9878B /* CCNetworking.m */; };
 		F732BA0B1D76DBA500E9878B /* CCNetworking.m in Sources */ = {isa = PBXBuildFile; fileRef = F732BA041D76CE1500E9878B /* CCNetworking.m */; };
@@ -556,6 +560,13 @@
 			remoteGlobalIDString = F71459B41D12E3B700CAFEEC;
 			remoteInfo = "Share Ext Nextcloud";
 		};
+		F72D1011210B6B17009C96B7 /* PBXContainerItemProxy */ = {
+			isa = PBXContainerItemProxy;
+			containerPortal = F7F67BA01A24D27800EE80DA /* Project object */;
+			proxyType = 1;
+			remoteGlobalIDString = F72D100B210B6B16009C96B7;
+			remoteInfo = "Notification Service Extension";
+		};
 		F771E3E920E2392E00AFB62D /* PBXContainerItemProxy */ = {
 			isa = PBXContainerItemProxy;
 			containerPortal = F7F67BA01A24D27800EE80DA /* Project object */;
@@ -586,6 +597,7 @@
 			files = (
 				F771E3EB20E2392E00AFB62D /* File Provider Extension.appex in Embed App Extensions */,
 				F749E4E91DC1FB38009BA2FD /* Share.appex in Embed App Extensions */,
+				F72D1013210B6B17009C96B7 /* Notification Service Extension.appex in Embed App Extensions */,
 			);
 			name = "Embed App Extensions";
 			runOnlyForDeploymentPostprocessing = 0;
@@ -733,6 +745,12 @@
 		F72D0FF6210B6638009C96B7 /* FirebaseNanoPB.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = FirebaseNanoPB.framework; sourceTree = "<group>"; };
 		F72D0FF7210B6638009C96B7 /* FirebaseInstanceID.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = FirebaseInstanceID.framework; sourceTree = "<group>"; };
 		F72D0FF8210B6638009C96B7 /* FirebaseCoreDiagnostics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = FirebaseCoreDiagnostics.framework; sourceTree = "<group>"; };
+		F72D1002210B67CE009C96B7 /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = SOURCE_ROOT; };
+		F72D1004210B6835009C96B7 /* Firebase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Firebase.h; sourceTree = "<group>"; };
+		F72D1005210B6882009C96B7 /* NCPushNotification.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NCPushNotification.m; sourceTree = "<group>"; };
+		F72D1006210B6882009C96B7 /* NCPushNotification.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NCPushNotification.h; sourceTree = "<group>"; };
+		F72D100C210B6B16009C96B7 /* Notification Service Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "Notification Service Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; };
+		F72D100E210B6B17009C96B7 /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = "<group>"; };
 		F73049B81CB567F000C7C320 /* NSString+TruncateToWidth.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+TruncateToWidth.h"; sourceTree = "<group>"; };
 		F73049B91CB567F000C7C320 /* NSString+TruncateToWidth.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+TruncateToWidth.m"; sourceTree = "<group>"; };
 		F7320931201B812F008A0888 /* ko */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ko; path = ko.lproj/CTAssetsPicker.strings; sourceTree = "<group>"; };
@@ -1642,6 +1660,13 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
+		F72D1009210B6B16009C96B7 /* Frameworks */ = {
+			isa = PBXFrameworksBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F771E3CD20E2392D00AFB62D /* Frameworks */ = {
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
@@ -1959,6 +1984,7 @@
 		F72D0FED210B6638009C96B7 /* Firebase */ = {
 			isa = PBXGroup;
 			children = (
+				F72D1004210B6835009C96B7 /* Firebase.h */,
 				F72D0FEE210B6638009C96B7 /* Messaging */,
 				F72D0FF1210B6638009C96B7 /* Analytics */,
 			);
@@ -1988,6 +2014,14 @@
 			path = Analytics;
 			sourceTree = "<group>";
 		};
+		F72D100D210B6B17009C96B7 /* Notification Service Extension */ = {
+			isa = PBXGroup;
+			children = (
+				F72D100E210B6B17009C96B7 /* NotificationService.swift */,
+			);
+			path = "Notification Service Extension";
+			sourceTree = "<group>";
+		};
 		F73B4EAC1F470D9100BBEE4B /* src */ = {
 			isa = PBXGroup;
 			children = (
@@ -2712,6 +2746,7 @@
 				F7C742D31E7BD36600D9C973 /* Supporting Files */,
 				F710E80C1EF95C9C00DC2427 /* Intro */,
 				F700222B1EC479840080073F /* Custom.xcassets */,
+				F72D1002210B67CE009C96B7 /* GoogleService-Info.plist */,
 				F73CB5771ED46807005F2A5A /* NCBridgeSwift.h */,
 				F76B3CCD1EAE01BD00921AC9 /* NCBrand.swift */,
 				F76F23331ED4603700C40023 /* LaunchScreen.xib */,
@@ -3062,9 +3097,11 @@
 				F7F67BAB1A24D27800EE80DA /* Supporting Files */,
 				F7C0F46D1C8880540059EC54 /* Share */,
 				F771E3D120E2392D00AFB62D /* File Provider Extension */,
+				F72D100D210B6B17009C96B7 /* Notification Service Extension */,
 				F7FC7D651DC1F98700BB2C6A /* Products */,
 				F7FC7D541DC1F93700BB2C6A /* Frameworks */,
 				F771E3D020E2392D00AFB62D /* File Provider Extension.appex */,
+				F72D100C210B6B16009C96B7 /* Notification Service Extension.appex */,
 			);
 			sourceTree = "<group>";
 		};
@@ -3181,6 +3218,8 @@
 				F7F801001D98205A007537BC /* CCCertificate.h */,
 				F7F801011D98205A007537BC /* CCCertificate.m */,
 				F7F878AD1FB9E3B900599E4F /* NCEndToEndMetadata.swift */,
+				F72D1006210B6882009C96B7 /* NCPushNotification.h */,
+				F72D1005210B6882009C96B7 /* NCPushNotification.m */,
 				F70CAE381F8CF31A008125FD /* NCEndToEndEncryption.h */,
 				F70CAE391F8CF31A008125FD /* NCEndToEndEncryption.m */,
 			);
@@ -3207,6 +3246,23 @@
 			productReference = F7CE8AFB1DC1F8D8009CAE48 /* Share.appex */;
 			productType = "com.apple.product-type.app-extension";
 		};
+		F72D100B210B6B16009C96B7 /* Notification Service Extension */ = {
+			isa = PBXNativeTarget;
+			buildConfigurationList = F72D1014210B6B17009C96B7 /* Build configuration list for PBXNativeTarget "Notification Service Extension" */;
+			buildPhases = (
+				F72D1008210B6B16009C96B7 /* Sources */,
+				F72D1009210B6B16009C96B7 /* Frameworks */,
+				F72D100A210B6B16009C96B7 /* Resources */,
+			);
+			buildRules = (
+			);
+			dependencies = (
+			);
+			name = "Notification Service Extension";
+			productName = "Notification Service Extension";
+			productReference = F72D100C210B6B16009C96B7 /* Notification Service Extension.appex */;
+			productType = "com.apple.product-type.app-extension";
+		};
 		F771E3CF20E2392D00AFB62D /* File Provider Extension */ = {
 			isa = PBXNativeTarget;
 			buildConfigurationList = F771E3EF20E2392E00AFB62D /* Build configuration list for PBXNativeTarget "File Provider Extension" */;
@@ -3242,6 +3298,7 @@
 			dependencies = (
 				F7145A321D12E65F00CAFEEC /* PBXTargetDependency */,
 				F771E3EA20E2392E00AFB62D /* PBXTargetDependency */,
+				F72D1012210B6B17009C96B7 /* PBXTargetDependency */,
 			);
 			name = Nextcloud;
 			productName = "Crypto Cloud";
@@ -3270,6 +3327,16 @@
 							};
 						};
 					};
+					F72D100B210B6B16009C96B7 = {
+						CreatedOnToolsVersion = 9.4.1;
+						DevelopmentTeam = 6JLRKY9ZV7;
+						ProvisioningStyle = Automatic;
+						SystemCapabilities = {
+							com.apple.ApplicationGroups.iOS = {
+								enabled = 1;
+							};
+						};
+					};
 					F771E3CF20E2392D00AFB62D = {
 						CreatedOnToolsVersion = 9.4.1;
 						DevelopmentTeam = 6JLRKY9ZV7;
@@ -3344,6 +3411,7 @@
 				F77B0DEB1D118A16002130FE /* Nextcloud */,
 				F71459B41D12E3B700CAFEEC /* Share */,
 				F771E3CF20E2392D00AFB62D /* File Provider Extension */,
+				F72D100B210B6B16009C96B7 /* Notification Service Extension */,
 			);
 		};
 /* End PBXProject section */
@@ -3364,6 +3432,13 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
+		F72D100A210B6B16009C96B7 /* Resources */ = {
+			isa = PBXResourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F771E3CE20E2392D00AFB62D /* Resources */ = {
 			isa = PBXResourcesBuildPhase;
 			buildActionMask = 2147483647;
@@ -3455,6 +3530,7 @@
 				F77B0F671D118A16002130FE /* InfoPlist.strings in Resources */,
 				F7C525A21E3B6DA800FFE02C /* CCNotification.storyboard in Resources */,
 				F7F54CEB1E5B14C700E19C62 /* ImageSelectedOn.png in Resources */,
+				F72D1003210B67CE009C96B7 /* GoogleService-Info.plist in Resources */,
 				F762CB951EACB84400B38484 /* icon-error.png in Resources */,
 				F7F54CF01E5B14C700E19C62 /* ImageSelectedSmallOff@3x.png in Resources */,
 				F73B4EF01F470D9100BBEE4B /* CMakeLists.txt in Resources */,
@@ -3604,6 +3680,14 @@
 			);
 			runOnlyForDeploymentPostprocessing = 0;
 		};
+		F72D1008210B6B16009C96B7 /* Sources */ = {
+			isa = PBXSourcesBuildPhase;
+			buildActionMask = 2147483647;
+			files = (
+				F72D100F210B6B17009C96B7 /* NotificationService.swift in Sources */,
+			);
+			runOnlyForDeploymentPostprocessing = 0;
+		};
 		F771E3CC20E2392D00AFB62D /* Sources */ = {
 			isa = PBXSourcesBuildPhase;
 			buildActionMask = 2147483647;
@@ -3754,6 +3838,7 @@
 				F7CA1ED120E7E3FE002CC65E /* PKCircleProgressView.m in Sources */,
 				F75AE3C71E9D12900088BB09 /* SwiftyAvatar.swift in Sources */,
 				F762CAFC1EACB66200B38484 /* XLFormImageCell.m in Sources */,
+				F72D1007210B6882009C96B7 /* NCPushNotification.m in Sources */,
 				F70022D11EC4C9100080073F /* OCUserProfile.m in Sources */,
 				F73B4EF61F470D9100BBEE4B /* LangArabicModel.cpp in Sources */,
 				F7CA1ED420E7E3FE002CC65E /* PKPendingView.m in Sources */,
@@ -3953,6 +4038,11 @@
 			target = F71459B41D12E3B700CAFEEC /* Share */;
 			targetProxy = F7145A311D12E65F00CAFEEC /* PBXContainerItemProxy */;
 		};
+		F72D1012210B6B17009C96B7 /* PBXTargetDependency */ = {
+			isa = PBXTargetDependency;
+			target = F72D100B210B6B16009C96B7 /* Notification Service Extension */;
+			targetProxy = F72D1011210B6B17009C96B7 /* PBXContainerItemProxy */;
+		};
 		F771E3EA20E2392E00AFB62D /* PBXTargetDependency */ = {
 			isa = PBXTargetDependency;
 			target = F771E3CF20E2392D00AFB62D /* File Provider Extension */;
@@ -4323,10 +4413,7 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 9.0;
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
 				LIBRARY_SEARCH_PATHS = "\"Libraries external\"/**";
-				OTHER_LDFLAGS = (
-					"-Obj-C",
-					"-all_load",
-				);
+				OTHER_LDFLAGS = "-ObjC";
 				PRODUCT_BUNDLE_IDENTIFIER = it.twsweb.Nextcloud.Share;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
@@ -4369,10 +4456,7 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 9.0;
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
 				LIBRARY_SEARCH_PATHS = "\"Libraries external\"/**";
-				OTHER_LDFLAGS = (
-					"-Obj-C",
-					"-all_load",
-				);
+				OTHER_LDFLAGS = "-ObjC";
 				PRODUCT_BUNDLE_IDENTIFIER = it.twsweb.Nextcloud.Share;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
@@ -4384,6 +4468,81 @@
 			};
 			name = Release;
 		};
+		F72D1015210B6B17009C96B7 /* Debug */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+				CLANG_ENABLE_OBJC_WEAK = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+				CODE_SIGN_ENTITLEMENTS = "$(SRCROOT)/iOSClient/Brand/Notification_Service_Extension.entitlements";
+				CODE_SIGN_IDENTITY = "iPhone Developer";
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				CODE_SIGN_STYLE = Automatic;
+				DEBUG_INFORMATION_FORMAT = dwarf;
+				DEVELOPMENT_TEAM = 6JLRKY9ZV7;
+				GCC_C_LANGUAGE_STANDARD = gnu11;
+				GCC_PREFIX_HEADER = iOSClient/CryptoCloud.pch;
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					"$(inherited)",
+					EXTENSION,
+					EXTENSION_NOTIFICATION_SERVICE,
+					NC,
+				);
+				INFOPLIST_FILE = "$(SRCROOT)/iOSClient/Brand/Notification_Service_Extension.plist";
+				IPHONEOS_DEPLOYMENT_TARGET = 10.0;
+				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
+				OTHER_LDFLAGS = "-ObjC";
+				PRODUCT_BUNDLE_IDENTIFIER = "it.twsweb.Nextcloud.Notification-Service-Extension";
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SKIP_INSTALL = YES;
+				SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
+				SWIFT_OPTIMIZATION_LEVEL = "-Onone";
+				SWIFT_VERSION = 4.0;
+				TARGETED_DEVICE_FAMILY = "1,2";
+			};
+			name = Debug;
+		};
+		F72D1016210B6B17009C96B7 /* Release */ = {
+			isa = XCBuildConfiguration;
+			buildSettings = {
+				CLANG_ANALYZER_NONNULL = YES;
+				CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
+				CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
+				CLANG_ENABLE_OBJC_WEAK = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
+				CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
+				CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
+				CODE_SIGN_ENTITLEMENTS = "$(SRCROOT)/iOSClient/Brand/Notification_Service_Extension.entitlements";
+				CODE_SIGN_IDENTITY = "iPhone Developer";
+				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
+				CODE_SIGN_STYLE = Automatic;
+				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
+				DEVELOPMENT_TEAM = 6JLRKY9ZV7;
+				GCC_C_LANGUAGE_STANDARD = gnu11;
+				GCC_PREFIX_HEADER = iOSClient/CryptoCloud.pch;
+				GCC_PREPROCESSOR_DEFINITIONS = (
+					EXTENSION,
+					EXTENSION_NOTIFICATION_SERVICE,
+					NC,
+				);
+				INFOPLIST_FILE = "$(SRCROOT)/iOSClient/Brand/Notification_Service_Extension.plist";
+				IPHONEOS_DEPLOYMENT_TARGET = 10.0;
+				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
+				OTHER_LDFLAGS = "-ObjC";
+				PRODUCT_BUNDLE_IDENTIFIER = "it.twsweb.Nextcloud.Notification-Service-Extension";
+				PRODUCT_NAME = "$(TARGET_NAME)";
+				SKIP_INSTALL = YES;
+				SWIFT_VERSION = 4.0;
+				TARGETED_DEVICE_FAMILY = "1,2";
+			};
+			name = Release;
+		};
 		F771E3F020E2392E00AFB62D /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
@@ -4420,6 +4579,7 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 11.0;
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
 				LIBRARY_SEARCH_PATHS = "\"Libraries external\"/**";
+				OTHER_LDFLAGS = "-ObjC";
 				PRODUCT_BUNDLE_IDENTIFIER = "it.twsweb.Nextcloud.File-Provider-Extension";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
@@ -4466,6 +4626,7 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 11.0;
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
 				LIBRARY_SEARCH_PATHS = "\"Libraries external\"/**";
+				OTHER_LDFLAGS = "-ObjC";
 				PRODUCT_BUNDLE_IDENTIFIER = "it.twsweb.Nextcloud.File-Provider-Extension";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				SKIP_INSTALL = YES;
@@ -4484,7 +4645,7 @@
 				CLANG_ENABLE_MODULES = YES;
 				CLANG_WARN_STRICT_PROTOTYPES = NO;
 				CODE_SIGN_ENTITLEMENTS = iOSClient/Brand/iOSClient.entitlements;
-				CODE_SIGN_IDENTITY = "Apple Development IOS Push Services: it.twsweb.Nextcloud";
+				CODE_SIGN_IDENTITY = "iPhone Developer";
 				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
 				CURRENT_PROJECT_VERSION = "";
 				DEVELOPMENT_TEAM = 6JLRKY9ZV7;
@@ -4506,10 +4667,7 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 9.0;
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
 				LIBRARY_SEARCH_PATHS = "\"Libraries external/openssl\"";
-				OTHER_LDFLAGS = (
-					"-Obj-C",
-					"-all_load",
-				);
+				OTHER_LDFLAGS = "-ObjC";
 				OTHER_SWIFT_FLAGS = "-DDEBUG";
 				PRODUCT_BUNDLE_IDENTIFIER = "it.twsweb.$(PRODUCT_NAME:rfc1034identifier)";
 				PRODUCT_NAME = "$(TARGET_NAME)";
@@ -4534,7 +4692,7 @@
 				CLANG_ENABLE_MODULES = YES;
 				CLANG_WARN_STRICT_PROTOTYPES = NO;
 				CODE_SIGN_ENTITLEMENTS = iOSClient/Brand/iOSClient.entitlements;
-				CODE_SIGN_IDENTITY = "Apple Development IOS Push Services: it.twsweb.Nextcloud";
+				CODE_SIGN_IDENTITY = "iPhone Developer";
 				"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
 				COPY_PHASE_STRIP = NO;
 				CURRENT_PROJECT_VERSION = "";
@@ -4557,10 +4715,7 @@
 				IPHONEOS_DEPLOYMENT_TARGET = 9.0;
 				LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
 				LIBRARY_SEARCH_PATHS = "\"Libraries external/openssl\"";
-				OTHER_LDFLAGS = (
-					"-Obj-C",
-					"-all_load",
-				);
+				OTHER_LDFLAGS = "-ObjC";
 				PRODUCT_BUNDLE_IDENTIFIER = "it.twsweb.$(PRODUCT_NAME:rfc1034identifier)";
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				PROVISIONING_PROFILE = "";
@@ -4698,6 +4853,15 @@
 			defaultConfigurationIsVisible = 0;
 			defaultConfigurationName = Release;
 		};
+		F72D1014210B6B17009C96B7 /* Build configuration list for PBXNativeTarget "Notification Service Extension" */ = {
+			isa = XCConfigurationList;
+			buildConfigurations = (
+				F72D1015210B6B17009C96B7 /* Debug */,
+				F72D1016210B6B17009C96B7 /* Release */,
+			);
+			defaultConfigurationIsVisible = 0;
+			defaultConfigurationName = Release;
+		};
 		F771E3EF20E2392E00AFB62D /* Build configuration list for PBXNativeTarget "File Provider Extension" */ = {
 			isa = XCConfigurationList;
 			buildConfigurations = (

+ 36 - 0
Notification Service Extension/NotificationService.swift

@@ -0,0 +1,36 @@
+//
+//  NotificationService.swift
+//  Notification Service Extension
+//
+//  Created by Marino Faggiana on 27/07/18.
+//  Copyright © 2018 TWS. All rights reserved.
+//
+
+import UserNotifications
+
+class NotificationService: UNNotificationServiceExtension {
+
+    var contentHandler: ((UNNotificationContent) -> Void)?
+    var bestAttemptContent: UNMutableNotificationContent?
+
+    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
+        self.contentHandler = contentHandler
+        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
+        
+        if let bestAttemptContent = bestAttemptContent {
+            // Modify the notification content here...
+            bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
+            
+            contentHandler(bestAttemptContent)
+        }
+    }
+    
+    override func serviceExtensionTimeWillExpire() {
+        // Called just before the extension will be terminated by the system.
+        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
+        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
+            contentHandler(bestAttemptContent)
+        }
+    }
+
+}

+ 63 - 181
iOSClient/AppDelegate.m

@@ -36,15 +36,11 @@
 #import "JDStatusBarNotification.h"
 #import "NCBridgeSwift.h"
 #import "NCAutoUpload.h"
+#import "Firebase.h"
+#import "NCPushNotification.h"
 
-/* Remove comment for activate Firebase and push notification */
-//#import "Firebase.h"
-//@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
+@interface AppDelegate () <UNUserNotificationCenterDelegate, FIRMessagingDelegate>
 
-@interface AppDelegate () <UNUserNotificationCenterDelegate>
-{
-    
-}
 @end
 
 @implementation AppDelegate
@@ -63,43 +59,6 @@
 
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
-    // Brand
-    if ([NCBrandOptions sharedInstance].use_firebase) {
-    
-        /* Remove comment for activate Firebase and push notification */
-        
-        /*
-        //In order for this to work, proper GoogleService-Info.plist must be included
-        @try {
-            [FIRApp configure];
-        } @catch (NSException *exception) {
-            NSLog(@"[LOG] Something went wrong while configuring Firebase");
-        }
-    
-        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
-        
-            UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
-            UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
-        
-            [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
-        
-        } else {
-        
-            // iOS 10 or later
-            #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
-            // For iOS 10 display notification (sent via APNS)
-            [UNUserNotificationCenter currentNotificationCenter].delegate = self;
-            UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
-            [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
-            }];
-        
-            // For iOS 10 data message (sent via FCM)
-            [FIRMessaging messaging].remoteMessageDelegate = self;
-            #endif
-        }
-         */
-    }
-
     NSString *path;
     NSURL *dirGroup = [CCUtility getDirectoryGroup];
     
@@ -188,7 +147,36 @@
     // Initialization List
     self.listProgressMetadata = [[NSMutableDictionary alloc] init];
     self.listMainVC = [[NSMutableDictionary alloc] init];
-            
+    
+    // Firebase - Push Notification
+    @try {
+        [FIRApp configure];
+    } @catch (NSException *exception) {
+        NSLog(@"[LOG] Something went wrong while configuring Firebase");
+    }
+    
+    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
+        
+        UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
+        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];
+        
+        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
+        
+    } else {
+        
+        // iOS 10 or later
+#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
+        // For iOS 10 display notification (sent via APNS)
+        [UNUserNotificationCenter currentNotificationCenter].delegate = self;
+        UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
+        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError * _Nullable error) {
+        }];
+#endif
+    }
+    
+    [application registerForRemoteNotifications];
+    [FIRMessaging messaging].delegate = self;
+    
     // setting Reachable in back
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
 
@@ -388,9 +376,6 @@
                 });
             }
         }
-        
-        
-        
     }
 }
 
@@ -414,160 +399,57 @@
 #pragma mark ===== Push Notification =====
 #pragma --------------------------------------------------------------------------------------------
 
-- (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
-{
-    NSLog(@"[LOG] Error Subscribing Nextcloud Server %@", message);
-}
-
-- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
-{
-    [application registerForRemoteNotifications];
-}
-
-/* Remove comment for activate Firebase and push notification */
-
-/*
-- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
+- (void)subscribingNextcloudServerPushNotification
 {
     // test
     if (self.activeAccount.length == 0)
         return;
     
-    // FIREBASE registered token
-    
-    [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
-    NSString *pushToken = [[FIRInstanceID instanceID] token];
-    // NSString *pushToken = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
+    OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:self.activeUser withUserID:self.activeUserID withPassword:self.activePassword withUrl:self.activeUrl];
     
+    [[NCPushNotification sharedInstance] generatePushNotificationsKeyPair];
+
+    NSString *pushToken = [CCUtility getPushNotificationToken];
     NSString *pushTokenHash = [[NCEndToEndEncryption sharedManager] createSHA512:pushToken];
-    NSDictionary *devicePushKey = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"DevicePushKey-Info" ofType:@"plist"]];
-    
-#ifdef DEBUG
-    NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyDevelopment"];
-#else
-    NSString *devicePublicKey = [devicePushKey objectForKey:@"devicePublicKeyProduction"];
-#endif
-    
-    if ([devicePublicKey length] > 0 && [pushTokenHash length] > 0) {
-        
-        NSLog(@"[LOG] Firebase InstanceID push token: %@", pushToken);
-        
-        CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
-    
-        NSDictionary *options = [[NSDictionary alloc] initWithObjectsAndKeys:pushToken, @"pushToken", pushTokenHash, @"pushTokenHash", devicePublicKey, @"devicePublicKey", nil];
-        
-        metadataNet.action = actionSubscribingNextcloudServer;
-        metadataNet.options = options;
-        [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
-    }    
-}
-*/
+    NSString *devicePublicKey = [[NSString alloc] initWithData:[NCPushNotification sharedInstance].ncPNPublicKey encoding:NSUTF8StringEncoding];
 
-- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
-{
-    NSLog(@"[LOG] Error register remote notification %@", error);
+    [ocNetworking subscribingPushNotificationServer:self.activeUrl pushToken:pushToken Hash:pushTokenHash devicePublicKey:devicePublicKey success:^{
+        NSLog(@"[LOG] Subscribed to Push Notification server successfully.");
+    } failure:^(NSString *message, NSInteger errorCode) {
+        NSLog(@"[LOG] Error while subscribing to Push Notification server.");
+    }];
 }
 
-- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
-    
-    UIApplicationState state = [application applicationState];
-    
-    if (state == UIApplicationStateInactive || state == UIApplicationStateBackground) {
-        
-        NSLog(@"[LOG] Receive Notification on Inactive or Background state");
-        
-    } else {
-        
-        NSLog(@"[LOG] Receive Notification on Active state");
-    }
-    
-    // If you are receiving a notification message while your app is in the background,
-    // this callback will not be fired till the user taps on the notification launching the application.
-    // TODO: Handle data of notification
-    
-    // Print message ID.
-    //if (userInfo[kGCMMessageIDKey]) {
-    //    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
-    //}
-    
-    // Print full message.
-    NSLog(@"[LOG] %@", userInfo);
-
+-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
+{
+    //Called when a notification is delivered to a foreground app.
+    completionHandler(UNNotificationPresentationOptionAlert);
 }
 
-- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
+-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler
 {
-    UIApplicationState state = [application applicationState];
-    
-    // Print message ID.
-    //if (userInfo[kGCMMessageIDKey]) {
-    //    NSLog(@"Message ID: %@", userInfo[kGCMMessageIDKey]);
-    //}
-    
-    // Print full message.
-    NSLog(@"[LOG] %@", userInfo);
-
+    //Called to let your app know which action was selected by the user for a given notification.
+    NSString *message = [response.notification.request.content.userInfo objectForKey:@"subject"];
     
-    if (state == UIApplicationStateBackground || (state == UIApplicationStateInactive)) {
-        
-    } else if (state == UIApplicationStateInactive) {
-        
-        // user tapped notification
-        completionHandler(UIBackgroundFetchResultNewData);
-        
-    } else {
-        
-        // app is active
-        completionHandler(UIBackgroundFetchResultNoData);
+    if (message && [NCPushNotification sharedInstance].ncPNPrivateKey) {
+        NSString *decryptedMessage = [[NCPushNotification sharedInstance] decryptPushNotification:message withDevicePrivateKey:[NCPushNotification sharedInstance].ncPNPrivateKey];
+        if (decryptedMessage) {
+           
+        }
     }
+    completionHandler();
 }
 
-/* Remove comment for activate Firebase and push notification */
-
 #pragma FIREBASE
-/*
-- (void)tokenRefreshNotification:(NSNotification *)notification {
-    
-    // Note that this callback will be fired everytime a new token is generated, including the first
-    // time. So if you need to retrieve the token as soon as it is available this is where that
-    // should be done.
-    
-    NSString *refreshedToken = [[FIRInstanceID instanceID] token];
-    NSLog(@"[LOG] InstanceID token: %@", refreshedToken);
-    
-    // Connect to FCM since connection may have failed when attempted before having a token.
-    [self connectToFcm];
-    
-    // TODO: If necessary send token to application server.
-}
 
-- (void)connectToFcm {
-    
-    // Won't connect since there is no token
-    if (![[FIRInstanceID instanceID] token]) {
-        return;
-    }
-    
-    // Disconnect previous FCM connection if it exists.
-    [[FIRMessaging messaging] disconnect];
+- (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken
+{
+    NSLog(@"FCM registration token: %@", fcmToken);
+    [CCUtility setPushNotificationToken:fcmToken];
     
-    [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
-        if (error != nil) {
-            NSLog(@"[LOG] Unable to connect to FCM. %@", error);
-        } else {
-            NSLog(@"[LOG] Connected to FCM.");
-        }
-    }];
-}
-
-#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
-// Receive data message on iOS 10 devices while app is in the foreground.
-- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
-    // Print full message
-    NSLog(@"[LOG] %@", remoteMessage.appData);
+    //
+    [self subscribingNextcloudServerPushNotification];
 }
-#endif
-*/
 
 #pragma --------------------------------------------------------------------------------------------
 #pragma mark ===== Quick Actions - ShotcutItem =====

+ 0 - 1
iOSClient/Brand/NCBrand.swift

@@ -91,7 +91,6 @@ class NCBrandColor: NSObject {
     
     // Options
     @objc public let use_login_web_personalized:        Bool = false                                              // Don't touch me !!
-    @objc public let use_firebase:                      Bool = false
     @objc public let use_default_auto_upload:           Bool = false
     @objc public let use_themingColor:                  Bool = true
     @objc public let use_themingBackground:             Bool = true

+ 7 - 0
iOSClient/Brand/NCBridgeSwift.h

@@ -47,3 +47,10 @@
     #import "File_Provider_Extension-Swift.h"
 
 #endif
+
+// Nextcloud Notification Service Extension
+#if defined(EXTENSION_NOTIFICATION_SERVICE)
+
+    #import "Notification_Service_Extension-Swift.h"
+
+#endif

+ 10 - 0
iOSClient/Brand/Notification_Service_Extension.entitlements

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>com.apple.security.application-groups</key>
+	<array>
+		<string>group.it.twsweb.Crypto-Cloud</string>
+	</array>
+</dict>
+</plist>

+ 31 - 0
iOSClient/Brand/Notification_Service_Extension.plist

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+	<key>CFBundleDevelopmentRegion</key>
+	<string>$(DEVELOPMENT_LANGUAGE)</string>
+	<key>CFBundleDisplayName</key>
+	<string>Nextcloud</string>
+	<key>CFBundleExecutable</key>
+	<string>$(EXECUTABLE_NAME)</string>
+	<key>CFBundleIdentifier</key>
+	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+	<key>CFBundleInfoDictionaryVersion</key>
+	<string>6.0</string>
+	<key>CFBundleName</key>
+	<string>$(PRODUCT_NAME)</string>
+	<key>CFBundlePackageType</key>
+	<string>XPC!</string>
+	<key>CFBundleShortVersionString</key>
+	<string>2.22.0</string>
+	<key>CFBundleVersion</key>
+	<string>18</string>
+	<key>NSExtension</key>
+	<dict>
+		<key>NSExtensionPointIdentifier</key>
+		<string>com.apple.usernotifications.service</string>
+		<key>NSExtensionPrincipalClass</key>
+		<string>$(PRODUCT_MODULE_NAME).NotificationService</string>
+	</dict>
+</dict>
+</plist>

+ 0 - 1
iOSClient/CCGlobal.h

@@ -228,7 +228,6 @@
 #define actionSetNotificationServer                     @"setNotificationServer"
 #define actionShare                                     @"share"
 #define actionShareWith                                 @"shareWith"
-#define actionSubscribingNextcloudServer                @"subscribingNextcloudServer"
 #define actionUnShare                                   @"unShare"
 #define actionUpdateShare                               @"updateShare"
 

+ 48 - 12
iOSClient/Library/OCCommunicationLib/OCCommunication.m

@@ -723,7 +723,7 @@
     }];
 }
 
-#pragma mark - OC API Calls
+#pragma mark - OC/NC API Calls
 
 - (NSString *) getCurrentServerVersion {
     return self.currentServerVersion;
@@ -828,6 +828,8 @@
     }];
 }
 
+#pragma mark - Share
+
 - (void) readSharedByServer: (NSString *) path
             onCommunication:(OCCommunication *)sharedOCCommunication
              successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfShared, NSString *redirectedServer)) successRequest
@@ -1280,6 +1282,8 @@
     }];
 }
 
+#pragma mark - Capabilities
+
 - (void) getCapabilitiesOfServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest{
     
     serverPath = [serverPath encodeString:NSUTF8StringEncoding];
@@ -1487,6 +1491,8 @@
     }];
 }
 
+#pragma mark - Thumbnail
+
 - (NSURLSessionTask *) getRemoteThumbnailByServer:(NSString*)serverPath ofFilePath:(NSString *)filePath withWidth:(NSInteger)fileWidth andHeight:(NSInteger)fileHeight onCommunication:(OCCommunication *)sharedOCComunication
                      successRequest:(void(^)(NSHTTPURLResponse *response, NSData *thumbnail, NSString *redirectedServer)) successRequest
                      failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
@@ -1514,6 +1520,8 @@
     return operation;
 }
 
+#pragma mark - Notification
+
 - (void)getNotificationServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfNotifications, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
     
     serverPath = [serverPath encodeString:NSUTF8StringEncoding];
@@ -1663,6 +1671,8 @@
     }];
 }
 
+#pragma mark - Push Notification
+
 - (void)subscribingNextcloudServerPush:(NSString *)serverPath pushTokenHash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey proxyServerPath:(NSString *)proxyServerPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer)) successRequest failureRequest:(void (^)(NSHTTPURLResponse *, NSError *, NSString *))failureRequest {
     
     serverPath = [serverPath encodeString:NSUTF8StringEncoding];
@@ -1671,21 +1681,41 @@
     OCWebDAVClient *request = [OCWebDAVClient new];
     request = [self getRequestWithCredentials:request];
     
-    [request subscribingNextcloudServerPush:serverPath authorizationToken:_password pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath:proxyServerPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
+    [request subscribingNextcloudServerPush:serverPath pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath:proxyServerPath onCommunication:sharedOCComunication success:^(NSHTTPURLResponse *response, id responseObject) {
         
-        NSData *responseData = (NSData*) responseObject;
+        NSData *responseData = (NSData*)responseObject;
         
-        //Parse
         NSError *error;
         NSDictionary *jsongParsed = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
-        NSLog(@"[LOG] Subscribing at the Nextcloud server : %@",jsongParsed);
-        
-        NSString *publicKey = [jsongParsed objectForKey:@"publicKey"];
-        NSString *deviceIdentifier = [jsongParsed objectForKey:@"deviceIdentifier"];
-        NSString *signature = [jsongParsed objectForKey:@"signature"];
-        
-        successRequest(response, publicKey, deviceIdentifier, signature, request.redirectedServer);
         
+        if (jsongParsed && jsongParsed.allKeys > 0) {
+            
+            NSDictionary *ocs = [jsongParsed valueForKey:@"ocs"];
+            NSDictionary *meta = [ocs valueForKey:@"meta"];
+            NSDictionary *datas = [ocs valueForKey:@"data"];
+            
+            NSInteger statusCode = [[meta valueForKey:@"statuscode"] integerValue];
+            
+            if (statusCode == kOCPushNotificationAPISuccessful || statusCode == kOCPushNotificationAPINeedSendProxy) {
+                
+                NSString *publicKey = [datas objectForKey:@"publicKey"];
+                NSString *deviceIdentifier = [datas objectForKey:@"deviceIdentifier"];
+                NSString *signature = [datas objectForKey:@"signature"];
+                
+                successRequest(response, publicKey, deviceIdentifier, signature, request.redirectedServer);
+                
+            } else {
+                
+                NSString *message = (NSString *)[meta objectForKey:@"message"];
+                if ([message isKindOfClass:[NSNull class]]) {
+                    message = NSLocalizedStringFromTable(@"_server_response_error_", @"Error", nil);
+                }
+                failureRequest(response, [UtilsFramework getErrorWithCode:statusCode andCustomMessageFromTheServer:message], request.redirectedServer);
+            }
+        } else {
+            failureRequest(response, [UtilsFramework getErrorWithCode:k_CCErrorWebdavResponseError andCustomMessageFromTheServer:NSLocalizedStringFromTable(@"_server_response_error_", @"Error", nil)], request.redirectedServer);
+        }
+
     } failure:^(NSHTTPURLResponse *response, NSData *responseData, NSError *error) {
                 
         failureRequest(response, error, request.redirectedServer);
@@ -1713,6 +1743,8 @@
     }];
 }
 
+#pragma mark - Activity
+
 - (void) getActivityServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfActivity, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
 
     serverPath = [serverPath encodeString:NSUTF8StringEncoding];
@@ -1795,6 +1827,8 @@
     }];
 }
 
+#pragma mark - External Sites
+
 - (void) getExternalSitesServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSArray *listOfExternalSites, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
     serverPath = [serverPath encodeString:NSUTF8StringEncoding];
     serverPath = [serverPath stringByAppendingString:k_url_acces_external_sites_api];
@@ -1866,6 +1900,8 @@
     }];
 }
 
+#pragma mark - User Profile
+
 - (void) getUserProfileServer:(NSString*)serverPath onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, OCUserProfile *userProfile, NSString *redirectedServer)) successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
     
     serverPath = [serverPath stringByAppendingString:k_url_acces_remote_userprofile_api];
@@ -2137,7 +2173,7 @@
     }];
 }
 
-- (void)signEndToEndPublicKey:(NSString*)serverPath publicKey:(NSString *)publicKey onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSString *publicKey,NSString *redirectedServer))successRequest  failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
+- (void)signEndToEndPublicKey:(NSString*)serverPath publicKey:(NSString *)publicKey onCommunication:(OCCommunication *)sharedOCComunication successRequest:(void(^)(NSHTTPURLResponse *response, NSString *publicKey,NSString *redirectedServer))successRequest failureRequest:(void(^)(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer)) failureRequest {
     
     serverPath = [serverPath stringByAppendingString:k_url_client_side_encryption];
     serverPath = [serverPath stringByAppendingString:@"/public-key"];

+ 3 - 0
iOSClient/Library/OCCommunicationLib/OCErrorMsg.h

@@ -42,6 +42,9 @@
 
 #define kOCUserProfileAPISuccessful 200
 
+#define kOCPushNotificationAPISuccessful 200
+#define kOCPushNotificationAPINeedSendProxy 201
+
 typedef enum {
     OCServerErrorForbiddenCharacters = 101,
 } OCServerErrorEnum;

+ 1 - 1
iOSClient/Library/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.h

@@ -552,7 +552,7 @@ extern NSString * _Nullable OCWebDAVModificationDateKey;
  *
  */
 
-- (void)subscribingNextcloudServerPush:(NSString * _Nonnull)serverPath authorizationToken:(NSString * _Nonnull)authorizationToken pushTokenHash:(NSString * _Nonnull)pushTokenHash devicePublicKey:(NSString * _Nonnull)devicePublicKey proxyServerPath:(NSString * _Nonnull)proxyServerPath onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id  _Nullable responseObject, NSError * _Nonnull))failure;
+- (void)subscribingNextcloudServerPush:(NSString * _Nonnull)serverPath pushTokenHash:(NSString * _Nonnull)pushTokenHash devicePublicKey:(NSString * _Nonnull)devicePublicKey proxyServerPath:(NSString * _Nonnull)proxyServerPath onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id  _Nullable responseObject, NSError * _Nonnull))failure;
 
 
 - (void)subscribingPushProxy:(NSString * _Nonnull)serverPath authorizationToken:(NSString * _Nonnull)authorizationToken pushToken:(NSString * _Nonnull)pushToken deviceIdentifier:(NSString * _Nonnull)deviceIdentifier deviceIdentifierSignature:(NSString * _Nonnull)deviceIdentifierSignature userPublicKey:(NSString * _Nonnull)userPublicKey onCommunication:(OCCommunication * _Nonnull)sharedOCCommunication success:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id _Nonnull))success failure:(void(^ _Nonnull)(NSHTTPURLResponse * _Nonnull, id  _Nullable responseObject, NSError * _Nonnull))failure;

+ 12 - 20
iOSClient/Library/OCCommunicationLib/OCWebDavClient/OCWebDAVClient.m

@@ -819,23 +819,19 @@ NSString const *OCWebDAVModificationDateKey	= @"modificationdate";
     [operation resume];
 }
 
-- (void)subscribingNextcloudServerPush:(NSString *)serverPath authorizationToken:(NSString *)authorizationToken pushTokenHash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey proxyServerPath:(NSString *)proxyServerPath onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id  _Nullable responseObject, NSError *))failure {
+- (void)subscribingNextcloudServerPush:(NSString *)serverPath pushTokenHash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey proxyServerPath:(NSString *)proxyServerPath onCommunication:(OCCommunication *)sharedOCCommunication success:(void(^)(NSHTTPURLResponse *, id))success failure:(void(^)(NSHTTPURLResponse *, id  _Nullable responseObject, NSError *))failure {
     
     NSParameterAssert(success);
     
     _requestMethod = @"POST";
     
-    NSString *pushTokenHashParam = [NSString stringWithFormat:@"?pushTokenHash=%@",pushTokenHash];
-    NSString *devicePublicKeyParam = [NSString stringWithFormat:@"&devicePublicKey=%@",devicePublicKey];
-    NSString *proxyServerPathParam = [NSString stringWithFormat:@"&proxyServer=%@",proxyServerPath];
-    
-    serverPath = [serverPath stringByAppendingString:pushTokenHashParam];
-    serverPath = [serverPath stringByAppendingString:devicePublicKeyParam];
-    serverPath = [serverPath stringByAppendingString:proxyServerPathParam];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"?format=json"]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&pushTokenHash=%@",pushTokenHash]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&devicePublicKey=%@",devicePublicKey]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&proxyServer=%@",proxyServerPath]];
 
     NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil timeout:k_timeout_webdav];
-    [request setValue:[NSString stringWithFormat:@"token %@", authorizationToken] forHTTPHeaderField:@"Authorization"];
-    
+
     OCHTTPRequestOperation *operation = [self mr_operationWithRequest:request onCommunication:sharedOCCommunication success:success failure:failure];
     [self setRedirectionBlockOnDatataskWithOCCommunication:sharedOCCommunication andSessionManager:sharedOCCommunication.networkSessionManager];
     [operation resume];
@@ -846,16 +842,12 @@ NSString const *OCWebDAVModificationDateKey	= @"modificationdate";
     NSParameterAssert(success);
     
     _requestMethod = @"POST";
-    
-    pushToken = [NSString stringWithFormat:@"?pushToken=%@",pushToken];
-    deviceIdentifier = [NSString stringWithFormat:@"&deviceIdentifier=%@",deviceIdentifier];
-    deviceIdentifierSignature = [NSString stringWithFormat:@"&deviceIdentifierSignature=%@",deviceIdentifierSignature];
-    userPublicKey = [NSString stringWithFormat:@"&userPublicKey=%@",userPublicKey];
-    
-    serverPath = [serverPath stringByAppendingString:pushToken];
-    serverPath = [serverPath stringByAppendingString:deviceIdentifier];
-    serverPath = [serverPath stringByAppendingString:deviceIdentifierSignature];
-    serverPath = [serverPath stringByAppendingString:userPublicKey];
+        
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"?format=json"]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&pushToken=%@",pushToken]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&deviceIdentifier=%@",deviceIdentifier]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&deviceIdentifierSignature=%@",deviceIdentifierSignature]];
+    serverPath = [serverPath stringByAppendingString:[NSString stringWithFormat:@"&userPublicKey=%@",userPublicKey]];
     
     NSMutableURLRequest *request = [self sharedRequestWithMethod:_requestMethod path:serverPath parameters:nil timeout:k_timeout_webdav];
     

+ 2 - 3
iOSClient/Networking/OCNetworking.h

@@ -54,6 +54,8 @@
 - (void)settingFavorite:(NSString *)fileName favorite:(BOOL)favorite completion:(void (^)(NSString *message, NSInteger errorCode))completion;
 - (void)listingFavorites:(NSString *)serverUrl account:(NSString *)account success:(void(^)(NSArray *metadatas))success failure:(void (^)(NSString *message, NSInteger errorCode))failure;
 
+- (void)subscribingPushNotificationServer:(NSString *)urlServer pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure;
+
 @end
 
 @protocol OCNetworkingDelegate <NSObject>
@@ -103,9 +105,6 @@
 - (void)settingFavoriteSuccessFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode;
 - (void)listingFavoritesSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode;
 
-// Subscribing Nextcloud Server
-- (void)subscribingNextcloudServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode;
-
 // End-to-End Encryption
 - (void)getEndToEndPublicKeysSuccess:(CCMetadataNet *)metadataNet;
 - (void)getEndToEndPublicKeysFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode;

+ 27 - 41
iOSClient/Networking/OCNetworking.m

@@ -1601,84 +1601,70 @@
     }];
 }
 
-- (void)subscribingNextcloudServer
+#pragma --------------------------------------------------------------------------------------------
+#pragma mark ===== Push Notification =====
+#pragma --------------------------------------------------------------------------------------------
+
+- (void)subscribingPushNotificationServer:(NSString *)urlServer pushToken:(NSString *)pushToken Hash:(NSString *)pushTokenHash devicePublicKey:(NSString *)devicePublicKey success:(void (^)(void))success failure:(void (^)(NSString *message, NSInteger errorCode))failure
 {
     OCCommunication *communication = [CCNetworking sharedNetworking].sharedOCCommunication;
     
-    communication.kindOfCredential = credentialNotSet;
+    [communication setCredentialsWithUser:_activeUser andUserID:_activeUserID andPassword:_activePassword];
     [communication setUserAgent:[CCUtility getUserAgent]];
     
-    NSDictionary *parameter = _metadataNet.optionAny;
-    
-    NSString *pushToken = [parameter objectForKey:@"pushToken"];
-    NSString *pushTokenHash = [parameter objectForKey:@"pushTokenHash"];
-    NSString *devicePublicKey = [parameter objectForKey:@"devicePublicKey"];
-    
-    // encode URL
-    devicePublicKey = [devicePublicKey stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
-    
-    [communication subscribingNextcloudServerPush:_activeUrl pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
+    devicePublicKey = [CCUtility URLEncodeStringFromString:devicePublicKey];
+
+    [communication subscribingNextcloudServerPush:urlServer pushTokenHash:pushTokenHash devicePublicKey:devicePublicKey proxyServerPath: [NCBrandOptions sharedInstance].pushNotificationServer onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *publicKey, NSString *deviceIdentifier, NSString *signature, NSString *redirectedServer) {
         
-        // encode URL
-        deviceIdentifier = [deviceIdentifier stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
-        signature = [signature stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
-        publicKey = [publicKey stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
+        deviceIdentifier = [CCUtility URLEncodeStringFromString:deviceIdentifier];
+        signature = [CCUtility URLEncodeStringFromString:signature];
+        publicKey = [CCUtility URLEncodeStringFromString:publicKey];
         
         [communication subscribingPushProxy:[NCBrandOptions sharedInstance].pushNotificationServer pushToken:pushToken deviceIdentifier:deviceIdentifier deviceIdentifierSignature:signature userPublicKey:publicKey onCommunication:communication successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) {
             
             // Activity
             [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServer fileID:@"" action:k_activityDebugActionPushProxy selector:@"" note:@"Service registered." type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:_activeUrl];
             
-            [self complete];
+            success();
             
         } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
            
+            NSString *message;
+
             NSInteger errorCode = response.statusCode;
             if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
                 errorCode = error.code;
             
             // Error
-            if ([self.delegate respondsToSelector:@selector(subscribingNextcloudServerFailure:message:errorCode:)]) {
-                
-                if (errorCode == 503)
-                    [self.delegate subscribingNextcloudServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
-                else
-                    [self.delegate subscribingNextcloudServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
-            }
+            if (errorCode == 503)
+                message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
+            else
+                message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
             
-            // Request trusted certificated
-            if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
-                [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
-
             // Activity
             [[NCManageDatabase sharedInstance] addActivityClient:[NCBrandOptions sharedInstance].pushNotificationServer fileID:@"" action:k_activityDebugActionPushProxy selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
             
-            [self complete];
+            failure(message, errorCode);
         }];
         
     } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) {
         
+        NSString *message;
+
         NSInteger errorCode = response.statusCode;
         if (errorCode == 0 || (errorCode >= 200 && errorCode < 300))
             errorCode = error.code;
     
         // Error
-        if ([self.delegate respondsToSelector:@selector(subscribingNextcloudServerFailure:message:errorCode:)]) {
-            
-            if (errorCode == 503)
-                [self.delegate subscribingNextcloudServerFailure:_metadataNet message:NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil) errorCode:errorCode];
-            else
-                [self.delegate subscribingNextcloudServerFailure:_metadataNet message:[error.userInfo valueForKey:@"NSLocalizedDescription"] errorCode:errorCode];
-        }
+        if (errorCode == 503)
+            message = NSLocalizedStringFromTable(@"_server_error_retry_", @"Error", nil);
+        else
+            message = [error.userInfo valueForKey:@"NSLocalizedDescription"];
 
-        // Request trusted certificated
-        if ([error code] == NSURLErrorServerCertificateUntrusted && self.delegate)
-            [[CCCertificate sharedManager] presentViewControllerCertificateWithTitle:[error localizedDescription] viewController:(UIViewController *)self.delegate delegate:self];
-        
         // Activity
         [[NCManageDatabase sharedInstance] addActivityClient:_activeUrl fileID:@"" action:k_activityDebugActionServerPush selector:@"" note:[error.userInfo valueForKey:@"NSLocalizedDescription"] type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:_activeUrl];
         
-        [self complete];
+        failure(message, errorCode);
     }];
 }
 

+ 3 - 0
iOSClient/Security/NCEndToEndEncryption.h

@@ -23,6 +23,8 @@
 
 #import <Foundation/Foundation.h>
 
+#import <openssl/ssl.h>
+
 @class tableMetadata;
 
 @interface NCEndToEndEncryption : NSObject
@@ -42,6 +44,7 @@
 - (BOOL)encryptFileName:(NSString *)fileName fileNameIdentifier:(NSString *)fileNameIdentifier directory:(NSString *)directory key:(NSString **)key initializationVector:(NSString **)initializationVector authenticationTag:(NSString **)authenticationTag;
 - (BOOL)decryptFileName:(NSString *)fileName fileNameView:(NSString *)fileNameView fileID:(NSString *)fileID key:(NSString *)key initializationVector:(NSString *)initializationVector authenticationTag:(NSString *)authenticationTag;
 
+- (EVP_PKEY *)generateRSAKey:(NSError **)error;
 - (NSData *)generateKey:(int)length;
 - (NSString *)createSHA512:(NSString *)string;
 

+ 0 - 1
iOSClient/Security/NCEndToEndEncryption.m

@@ -34,7 +34,6 @@
 #import <openssl/pem.h>
 #import <openssl/rsa.h>
 #import <openssl/pkcs12.h>
-#import <openssl/ssl.h>
 #import <openssl/err.h>
 #import <openssl/bn.h>
 #import <openssl/md5.h>

+ 37 - 0
iOSClient/Security/NCPushNotification.h

@@ -0,0 +1,37 @@
+//
+//  NCPushNotification.h
+//  Nextcloud
+//
+//  Created by Marino Faggiana on 25/07/18.
+//  Copyright © 2018 TWS. All rights reserved.
+//
+//  Author Marino Faggiana <m.faggiana@twsweb.it>
+//
+//  This program is free software: you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation, either version 3 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+//  This code derived from : Nextcloud Talk - NCSettingsController Created by Ivan Sein on 26.06.17. Copyright © 2017 struktur AG. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface NCPushNotification : NSObject
+
+@property (nonatomic, copy) NSData *ncPNPublicKey;
+@property (nonatomic, copy) NSData *ncPNPrivateKey;
+
++ (NCPushNotification *)sharedInstance;
+- (BOOL)generatePushNotificationsKeyPair;
+- (NSString *)decryptPushNotification:(NSString *)message withDevicePrivateKey:(NSData *)privateKey;
+
+@end

+ 139 - 0
iOSClient/Security/NCPushNotification.m

@@ -0,0 +1,139 @@
+//
+//  NCPushNotification.m
+//  Nextcloud
+//
+//  Created by Marino Faggiana on 25/07/18.
+//  Copyright © 2018 TWS. All rights reserved.
+//
+//  Author Marino Faggiana <m.faggiana@twsweb.it>
+//
+//  This program is free software: you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation, either version 3 of the License, or
+//  (at your option) any later version.
+//
+//  This program is distributed in the hope that it will be useful,
+//  but WITHOUT ANY WARRANTY; without even the implied warranty of
+//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+//  GNU General Public License for more details.
+//
+//  You should have received a copy of the GNU General Public License
+//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+//
+
+#import "NCPushNotification.h"
+
+#import <openssl/rsa.h>
+#import <openssl/pem.h>
+#import <openssl/bio.h>
+#import <openssl/bn.h>
+#import <openssl/sha.h>
+#import <openssl/err.h>
+#import <openssl/ssl.h>
+#import <CommonCrypto/CommonDigest.h>
+
+#import "NCEndToEndEncryption.h"
+#import "CCUtility.h"
+
+@implementation NCPushNotification
+
++ (NCPushNotification *)sharedInstance
+{
+    static dispatch_once_t once;
+    static NCPushNotification *sharedInstance;
+    dispatch_once(&once, ^{
+        sharedInstance = [[self alloc] init];
+    });
+    return sharedInstance;
+}
+
+- (id)init
+{
+    self = [super init];
+    if (self) {
+       
+        self.ncPNPublicKey = [CCUtility getPushNotificationPublicKey];
+        self.ncPNPrivateKey = [CCUtility getPushNotificationPrivateKey];
+    }
+    return self;
+}
+
+- (BOOL)generatePushNotificationsKeyPair
+{
+    EVP_PKEY *pkey;
+    NSError *keyError;
+    pkey = [[NCEndToEndEncryption sharedManager] generateRSAKey:&keyError];
+    if (keyError) {
+        return NO;
+    }
+    
+    // Extract publicKey, privateKey
+    int len;
+    char *keyBytes;
+    
+    // PublicKey
+    BIO *publicKeyBIO = BIO_new(BIO_s_mem());
+    PEM_write_bio_PUBKEY(publicKeyBIO, pkey);
+    
+    len = BIO_pending(publicKeyBIO);
+    keyBytes  = malloc(len);
+    
+    BIO_read(publicKeyBIO, keyBytes, len);
+    _ncPNPublicKey = [NSData dataWithBytes:keyBytes length:len];
+    [CCUtility setPushNotificationPublicKey:_ncPNPublicKey];
+    NSLog(@"Push Notifications Key Pair generated: \n%@", [[NSString alloc] initWithData:_ncPNPublicKey encoding:NSUTF8StringEncoding]);
+    
+    // PrivateKey
+    BIO *privateKeyBIO = BIO_new(BIO_s_mem());
+    PEM_write_bio_PKCS8PrivateKey(privateKeyBIO, pkey, NULL, NULL, 0, NULL, NULL);
+    
+    len = BIO_pending(privateKeyBIO);
+    keyBytes = malloc(len);
+    
+    BIO_read(privateKeyBIO, keyBytes, len);
+    _ncPNPrivateKey = [NSData dataWithBytes:keyBytes length:len];
+    [CCUtility setPushNotificationPrivateKey:_ncPNPrivateKey];
+    
+    EVP_PKEY_free(pkey);
+    
+    return YES;
+}
+
+- (NSString *)decryptPushNotification:(NSString *)message withDevicePrivateKey:(NSData *)privateKey
+{
+    NSString *privateKeyString = [[NSString alloc] initWithData:privateKey encoding:NSUTF8StringEncoding];
+    NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:message options:0];
+    char *privKey = (char *)[privateKeyString UTF8String];
+    
+    // Get Device Private Key from PEM
+    BIO *bio = BIO_new(BIO_s_mem());
+    BIO_write(bio, privKey, (int)strlen(privKey));
+    
+    EVP_PKEY* pkey = 0;
+    PEM_read_bio_PrivateKey(bio, &pkey, 0, 0);
+    
+    RSA* rsa = EVP_PKEY_get1_RSA(pkey);
+    
+    // Decrypt the message
+    unsigned char *decrypted = (unsigned char *) malloc(4096);
+    
+    int decrypted_length = RSA_private_decrypt((int)[decodedData length], [decodedData bytes], decrypted, rsa, RSA_PKCS1_PADDING);
+    if(decrypted_length == -1) {
+        char buffer[500];
+        ERR_error_string(ERR_get_error(), buffer);
+        NSLog(@"%@",[NSString stringWithUTF8String:buffer]);
+        return nil;
+    }
+    
+    NSString *decryptString = [[NSString alloc] initWithBytes:decrypted length:decrypted_length encoding:NSUTF8StringEncoding];
+    
+    if (decrypted)
+        free(decrypted);
+    free(bio);
+    free(rsa);
+    
+    return decryptString;
+}
+
+
+@end

+ 7 - 0
iOSClient/Utility/CCUtility.h

@@ -151,6 +151,13 @@
 + (BOOL)getDisableFilesApp;
 + (void)setDisableFilesApp:(BOOL)disable;
 
++ (void)setPushNotificationPublicKey:(NSData *)data;
++ (NSData *)getPushNotificationPublicKey;
++ (void)setPushNotificationPrivateKey:(NSData *)data;
++ (NSData *)getPushNotificationPrivateKey;
++ (void)setPushNotificationToken:(NSString *)token;
++ (NSString *)getPushNotificationToken;
+
 // ===== Varius =====
 
 + (NSString *)getUserAgent;

+ 30 - 0
iOSClient/Utility/CCUtility.m

@@ -548,6 +548,36 @@
     [UICKeyChainStore setString:sDisable forKey:@"disablefilesapp" service:k_serviceShareKeyChain];
 }
 
++ (void)setPushNotificationPublicKey:(NSData *)data
+{
+    [UICKeyChainStore setData:data forKey:@"ncPNPublicKey" service:k_serviceShareKeyChain];
+}
+
++ (NSData *)getPushNotificationPublicKey
+{
+    return [UICKeyChainStore dataForKey:@"ncPNPublicKey" service:k_serviceShareKeyChain];
+}
+
++ (void)setPushNotificationPrivateKey:(NSData *)data
+{
+    [UICKeyChainStore setData:data forKey:@"ncPNPrivateKey" service:k_serviceShareKeyChain];
+}
+
++ (NSData *)getPushNotificationPrivateKey
+{
+    return [UICKeyChainStore dataForKey:@"ncPNPrivateKey" service:k_serviceShareKeyChain];
+}
+
++ (void)setPushNotificationToken:(NSString *)token
+{
+    [UICKeyChainStore setString:token forKey:@"ncPushToken" service:k_serviceShareKeyChain];
+}
+
++ (NSString *)getPushNotificationToken
+{
+    return [UICKeyChainStore stringForKey:@"ncPushToken" service:k_serviceShareKeyChain];
+}
+
 #pragma --------------------------------------------------------------------------------------------
 #pragma mark ===== Varius =====
 #pragma --------------------------------------------------------------------------------------------