diff --git a/.pubnub.yml b/.pubnub.yml index 5c6f1a18..518013c6 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,9 +1,32 @@ --- name: swift scm: github.com/pubnub/swift -version: "8.1.0" +version: "8.2.0" schema: 1 changelog: + - date: 2024-12-04 + version: 8.2.0 + changes: + - type: feature + text: "Add support for the Membership `type` field." + - type: feature + text: "Deprecate methods containing `uuid` parameter, introduce new versions." + - type: feature + text: "Deprecate methods containing `include` parameter of `Bool` type, introduce new versions." + - type: feature + text: "Deprecate `remove(channel:custom:completion:)`, introduce new version ." + - type: feature + text: "Replace `PubNubUUIDMetadata` with `PubNubUserMetadata`." + - type: feature + text: "Replace `PubNubUUIDMetadataBase` with `PubNubUserMetadataBase`." + - type: feature + text: "Add an alias for backward compatibility with the customer code using `PubNubUUIDMetadata`." + - type: feature + text: "Add an alias for backward compatibility with the customer code using `PubNubUUIDMetadataBase`." + - type: feature + text: "Replace `PubNubUUIDMetadataChangeset` with `PubNubUserMetadataChangeset`." + - type: feature + text: "Add an alias for backward compatibility with the customer code using `PubNubUUIDMetadataChangeset`." - date: 2024-11-18 version: 8.1.0 changes: @@ -596,7 +619,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: PubNub - location: https://github.com/pubnub/swift/archive/refs/tags/8.1.0.zip + location: https://github.com/pubnub/swift/archive/refs/tags/8.2.0.zip supported-platforms: supported-operating-systems: macOS: diff --git a/Gemfile b/Gemfile index 4ef40fcf..d5985c5f 100644 --- a/Gemfile +++ b/Gemfile @@ -2,4 +2,4 @@ source "https://rubygems.org" gem "cocoapods" gem "fastlane" -gem 'rexml', '3.3.8' +gem 'rexml', '3.3.9' diff --git a/Gemfile.lock b/Gemfile.lock index 7cf3445a..5b686feb 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -252,7 +252,7 @@ GEM trailblazer-option (>= 0.1.1, < 0.2.0) uber (< 0.2.0) retriable (3.1.2) - rexml (3.3.8) + rexml (3.3.9) rouge (2.0.7) ruby-macho (2.5.1) ruby2_keywords (0.0.5) @@ -311,7 +311,7 @@ PLATFORMS DEPENDENCIES cocoapods fastlane - rexml (= 3.3.8) + rexml (= 3.3.9) BUNDLED WITH 2.5.22 diff --git a/PubNub.xcodeproj/project.pbxproj b/PubNub.xcodeproj/project.pbxproj index bee3ba8c..56c85fb8 100644 --- a/PubNub.xcodeproj/project.pbxproj +++ b/PubNub.xcodeproj/project.pbxproj @@ -280,15 +280,15 @@ 35CDFEBA22E77E2B00F3B9F2 /* URLSessionConfiguration+PubNubTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CDFEB922E77E2B00F3B9F2 /* URLSessionConfiguration+PubNubTests.swift */; }; 35CDFEBC22E789B200F3B9F2 /* ConstantsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CDFEBB22E789B200F3B9F2 /* ConstantsTests.swift */; }; 35CDFEC022E7B48000F3B9F2 /* ImportTestResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CDFEBF22E7B48000F3B9F2 /* ImportTestResource.swift */; }; - 35CF548C248971BF0099FE81 /* ObjectsUUIDRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF548B248971BF0099FE81 /* ObjectsUUIDRouter.swift */; }; + 35CF548C248971BF0099FE81 /* ObjectsUserRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF548B248971BF0099FE81 /* ObjectsUserRouter.swift */; }; 35CF548E248971CD0099FE81 /* ObjectsChannelRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF548D248971CD0099FE81 /* ObjectsChannelRouter.swift */; }; 35CF5490248971DD0099FE81 /* ObjectsMembershipsRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF548F248971DD0099FE81 /* ObjectsMembershipsRouter.swift */; }; - 35CF54922489912F0099FE81 /* PubNubUUIDMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF54912489912F0099FE81 /* PubNubUUIDMetadata.swift */; }; + 35CF54922489912F0099FE81 /* PubNubUserMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF54912489912F0099FE81 /* PubNubUserMetadata.swift */; }; 35CF54942489918E0099FE81 /* PubNubChannelMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF54932489918E0099FE81 /* PubNubChannelMetadata.swift */; }; 35CF54962489B3760099FE81 /* PubNubMembershipMetadata.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF54952489B3760099FE81 /* PubNubMembershipMetadata.swift */; }; 35CF549C248ABE8B0099FE81 /* PubNubObjectMetadataPatcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF549B248ABE8B0099FE81 /* PubNubObjectMetadataPatcher.swift */; }; 35CF549D248D73500099FE81 /* SubscribeObjectPayload.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35AC162C2485E3C600A66030 /* SubscribeObjectPayload.swift */; }; - 35CF549E248D913A0099FE81 /* ObjectsUUIDRouterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35DA9AB42335491F00867989 /* ObjectsUUIDRouterTests.swift */; }; + 35CF549E248D913A0099FE81 /* ObjectsUserRouterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35DA9AB42335491F00867989 /* ObjectsUserRouterTests.swift */; }; 35CF54A0248D96320099FE81 /* SubscribeRouterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 359287BC23173D490046F7A2 /* SubscribeRouterTests.swift */; }; 35CF54A1248DA6430099FE81 /* ObjectsChannelRouterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3562DBC22345066F006DFFBC /* ObjectsChannelRouterTests.swift */; }; 35CF54A3248DA8650099FE81 /* ObjectsMembershipsRouterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35CF54A2248DA8650099FE81 /* ObjectsMembershipsRouterTests.swift */; }; @@ -517,8 +517,8 @@ A56445F22907D9FD0085B310 /* PubNubObjectsChannelMetadataContractTestSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = A56445F12907D9FD0085B310 /* PubNubObjectsChannelMetadataContractTestSteps.swift */; }; A56445F32907D9FD0085B310 /* PubNubObjectsChannelMetadataContractTestSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = A56445F12907D9FD0085B310 /* PubNubObjectsChannelMetadataContractTestSteps.swift */; }; A5A574D429C309750065D333 /* leave_success.json in Resources */ = {isa = PBXBuildFile; fileRef = A5A574D329C309750065D333 /* leave_success.json */; }; - A5F19EE329126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F19EE229126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift */; }; - A5F19EE429126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F19EE229126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift */; }; + A5F19EE329126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F19EE229126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift */; }; + A5F19EE429126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5F19EE229126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift */; }; D2635DFB22FCCF080097CF64 /* message_counts_success.json in Resources */ = {isa = PBXBuildFile; fileRef = D2635DFA22FCCF080097CF64 /* message_counts_success.json */; }; OBJ_31 /* PubNub.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_11 /* PubNub.swift */; }; OBJ_49 /* PubNubTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = OBJ_15 /* PubNubTests.swift */; }; @@ -909,10 +909,10 @@ 35CDFEB922E77E2B00F3B9F2 /* URLSessionConfiguration+PubNubTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URLSessionConfiguration+PubNubTests.swift"; sourceTree = ""; }; 35CDFEBB22E789B200F3B9F2 /* ConstantsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConstantsTests.swift; sourceTree = ""; }; 35CDFEBF22E7B48000F3B9F2 /* ImportTestResource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportTestResource.swift; sourceTree = ""; }; - 35CF548B248971BF0099FE81 /* ObjectsUUIDRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectsUUIDRouter.swift; sourceTree = ""; }; + 35CF548B248971BF0099FE81 /* ObjectsUserRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectsUserRouter.swift; sourceTree = ""; }; 35CF548D248971CD0099FE81 /* ObjectsChannelRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectsChannelRouter.swift; sourceTree = ""; }; 35CF548F248971DD0099FE81 /* ObjectsMembershipsRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectsMembershipsRouter.swift; sourceTree = ""; }; - 35CF54912489912F0099FE81 /* PubNubUUIDMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PubNubUUIDMetadata.swift; sourceTree = ""; }; + 35CF54912489912F0099FE81 /* PubNubUserMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PubNubUserMetadata.swift; sourceTree = ""; }; 35CF54932489918E0099FE81 /* PubNubChannelMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PubNubChannelMetadata.swift; sourceTree = ""; }; 35CF54952489B3760099FE81 /* PubNubMembershipMetadata.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PubNubMembershipMetadata.swift; sourceTree = ""; }; 35CF5499248AA5220099FE81 /* subscribe_uuidSet_nullUpdate.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = subscribe_uuidSet_nullUpdate.json; sourceTree = ""; }; @@ -934,7 +934,7 @@ 35DA9AAC2331674000867989 /* .swiftformat */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = .swiftformat; sourceTree = ""; }; 35DA9AB02334479800867989 /* objects_uuid_all_success.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; name = objects_uuid_all_success.json; path = Tests/PubNubTests/Mocking/Responses/Objects/objects_uuid_all_success.json; sourceTree = SOURCE_ROOT; }; 35DA9AB2233447F200867989 /* objects_uuid_fetch_success.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = objects_uuid_fetch_success.json; sourceTree = ""; }; - 35DA9AB42335491F00867989 /* ObjectsUUIDRouterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectsUUIDRouterTests.swift; sourceTree = ""; }; + 35DA9AB42335491F00867989 /* ObjectsUserRouterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ObjectsUserRouterTests.swift; sourceTree = ""; }; 35DB0C4A2874768C001E1F76 /* FlatJSONCodable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlatJSONCodable.swift; sourceTree = ""; }; 35DB0C4C287476BF001E1F76 /* OptionalChange.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OptionalChange.swift; sourceTree = ""; }; 35E381FC23149BA900A17549 /* AutomaticRetryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AutomaticRetryTests.swift; sourceTree = ""; }; @@ -1127,7 +1127,7 @@ A56445EE2906AFF40085B310 /* PubNubObjectsTestHelpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PubNubObjectsTestHelpers.swift; sourceTree = ""; }; A56445F12907D9FD0085B310 /* PubNubObjectsChannelMetadataContractTestSteps.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PubNubObjectsChannelMetadataContractTestSteps.swift; sourceTree = ""; }; A5A574D329C309750065D333 /* leave_success.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = leave_success.json; sourceTree = ""; }; - A5F19EE229126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PubNubObjectsUUIDMetadataContractTestSteps.swift; sourceTree = ""; }; + A5F19EE229126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PubNubObjectsUserMetadataContractTestSteps.swift; sourceTree = ""; }; D2635DFA22FCCF080097CF64 /* message_counts_success.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = message_counts_success.json; sourceTree = ""; }; E812941F9706B958CD448B54 /* Pods_PubNubContractTestsBeta.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_PubNubContractTestsBeta.framework; sourceTree = BUILT_PRODUCTS_DIR; }; FB0696E0E433339FBC48D1D3 /* Pods-PubNubContractTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PubNubContractTests.debug.xcconfig"; path = "Target Support Files/Pods-PubNubContractTests/Pods-PubNubContractTests.debug.xcconfig"; sourceTree = ""; }; @@ -1306,7 +1306,7 @@ 35293A792368F9680049A71F /* MessageActionsRouter.swift */, 35CF548D248971CD0099FE81 /* ObjectsChannelRouter.swift */, 35CF548F248971DD0099FE81 /* ObjectsMembershipsRouter.swift */, - 35CF548B248971BF0099FE81 /* ObjectsUUIDRouter.swift */, + 35CF548B248971BF0099FE81 /* ObjectsUserRouter.swift */, 35A6C77C22FB159F00E97CC5 /* PresenceRouter.swift */, 35A6C7A722FBCC8B00E97CC5 /* PushRouter.swift */, 3534D4E322C57659008E89FA /* PublishRouter.swift */, @@ -1716,7 +1716,7 @@ 359287B3231720C20046F7A2 /* PublishRouterTests.swift */, 359287BC23173D490046F7A2 /* SubscribeRouterTests.swift */, 3557CDFF237F6380004BBACC /* TimeRouterTests.swift */, - 35DA9AB42335491F00867989 /* ObjectsUUIDRouterTests.swift */, + 35DA9AB42335491F00867989 /* ObjectsUserRouterTests.swift */, 3562DBC22345066F006DFFBC /* ObjectsChannelRouterTests.swift */, 35CF54A2248DA8650099FE81 /* ObjectsMembershipsRouterTests.swift */, ); @@ -1807,7 +1807,7 @@ 35AC162E2486C9A400A66030 /* PubNubMessageAction.swift */, 35AC16322487179400A66030 /* PubNubPage.swift */, 35E71C3B2490678D0032A991 /* PubNubPresence.swift */, - 35CF54912489912F0099FE81 /* PubNubUUIDMetadata.swift */, + 35CF54912489912F0099FE81 /* PubNubUserMetadata.swift */, 35CF54932489918E0099FE81 /* PubNubChannelMetadata.swift */, 35CF54952489B3760099FE81 /* PubNubMembershipMetadata.swift */, 35CF549B248ABE8B0099FE81 /* PubNubObjectMetadataPatcher.swift */, @@ -2542,7 +2542,7 @@ isa = PBXGroup; children = ( A56445F12907D9FD0085B310 /* PubNubObjectsChannelMetadataContractTestSteps.swift */, - A5F19EE229126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift */, + A5F19EE229126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift */, A5115F27291D54F500F6ADA1 /* PubNubObjectsMembershipsContractTestSteps.swift */, A5115F2429195AF400F6ADA1 /* PubNubObjectsMembersContractTestSteps.swift */, A5115F2A291D5C2700F6ADA1 /* PubNubObjectsContractTests.swift */, @@ -3490,7 +3490,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 0; files = ( - A5F19EE329126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift in Sources */, + A5F19EE329126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift in Sources */, 79407BDC271D4CFA0032076C /* PubNubSubscribeContractTestSteps.swift in Sources */, 3D38A0242B35B00D006928E7 /* PubNubEventEngineTestsHelpers.swift in Sources */, 3D38A01D2B35AFBE006928E7 /* PubNubSubscribeEngineContractTestsSteps.swift in Sources */, @@ -3518,7 +3518,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 0; files = ( - A5F19EE429126D8200F185A9 /* PubNubObjectsUUIDMetadataContractTestSteps.swift in Sources */, + A5F19EE429126D8200F185A9 /* PubNubObjectsUserMetadataContractTestSteps.swift in Sources */, 79407BDD271D4CFA0032076C /* PubNubSubscribeContractTestSteps.swift in Sources */, 3D38A0252B35B00D006928E7 /* PubNubEventEngineTestsHelpers.swift in Sources */, 3D38A01E2B35AFBE006928E7 /* PubNubSubscribeEngineContractTestsSteps.swift in Sources */, @@ -3604,7 +3604,7 @@ 3DBFF2BB2C203EDC00142985 /* KMPUploadable.swift in Sources */, 35A66A8022F861BA00AC67A9 /* AutomaticRetry.swift in Sources */, 357D1C1B22CB04C4003625BA /* Bool+PubNub.swift in Sources */, - 35CF548C248971BF0099FE81 /* ObjectsUUIDRouter.swift in Sources */, + 35CF548C248971BF0099FE81 /* ObjectsUserRouter.swift in Sources */, 3585033222CD138300A11D9A /* Set+PubNub.swift in Sources */, 358C641C238C5232009CE354 /* FCMAndroidPayload.swift in Sources */, 35FAC1E72357C2AE0096E418 /* PubNubError.swift in Sources */, @@ -3615,7 +3615,7 @@ 357CA28E251D3D0C00BC40D3 /* HTTPFileTask.swift in Sources */, 3534D4E622C67CCA008E89FA /* HTTPRouter.swift in Sources */, 35CF5490248971DD0099FE81 /* ObjectsMembershipsRouter.swift in Sources */, - 35CF54922489912F0099FE81 /* PubNubUUIDMetadata.swift in Sources */, + 35CF54922489912F0099FE81 /* PubNubUserMetadata.swift in Sources */, 35B6FBAF22F226F4005EE490 /* NSNumber+PubNub.swift in Sources */, 3D38A02E2B35B087006928E7 /* LegacySubscriptionSessionStrategy.swift in Sources */, 3DA24A352C2AA9F5005B959B /* KMPPubNub+Publish.swift in Sources */, @@ -3784,7 +3784,7 @@ 3D38A0102B35AF6B006928E7 /* SubscribeEffectsTests.swift in Sources */, 3D38A0142B35AF6B006928E7 /* PresenceTransitionTests.swift in Sources */, OBJ_49 /* PubNubTests.swift in Sources */, - 35CF549E248D913A0099FE81 /* ObjectsUUIDRouterTests.swift in Sources */, + 35CF549E248D913A0099FE81 /* ObjectsUserRouterTests.swift in Sources */, 3DB925642B7A2BF5001B7E90 /* SubscriptionSetTests.swift in Sources */, 35458BA3230CB3570085B502 /* SubscribeSessionFactoryTests.swift in Sources */, 3580A5A222F13C6500B12E5E /* SessionStreamAwait.swift in Sources */, @@ -3995,7 +3995,7 @@ "@loader_path/Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++17"; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -4046,7 +4046,7 @@ "@loader_path/Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++17"; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; @@ -4154,7 +4154,7 @@ "@loader_path/Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++17"; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -4207,7 +4207,7 @@ "@loader_path/Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++17"; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; @@ -4328,7 +4328,7 @@ "@loader_path/Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++17"; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -4380,7 +4380,7 @@ "@loader_path/Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu11 gnu++17"; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; @@ -4860,7 +4860,7 @@ "$(TOOLCHAIN_DIR)/usr/lib/swift/macosx", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++14"; OTHER_CFLAGS = "$(inherited)"; OTHER_LDFLAGS = "$(inherited)"; @@ -4903,7 +4903,7 @@ "$(TOOLCHAIN_DIR)/usr/lib/swift/macosx", ); MACOSX_DEPLOYMENT_TARGET = 10.15; - MARKETING_VERSION = 8.1.0; + MARKETING_VERSION = 8.2.0; MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu17 gnu++14"; OTHER_CFLAGS = "$(inherited)"; OTHER_LDFLAGS = "$(inherited)"; diff --git a/PubNubMembership/Sources/Membership+PubNub.swift b/PubNubMembership/Sources/Membership+PubNub.swift index 31aece05..6e732334 100644 --- a/PubNubMembership/Sources/Membership+PubNub.swift +++ b/PubNubMembership/Sources/Membership+PubNub.swift @@ -350,7 +350,7 @@ public extension PubNubMembershipInterface { customFields: nil, totalCount: false, changes: .init( - set: users.map { .init(metadataId: $0.user.id, status: $0.status, custom: $0.custom?.flatJSON) }, + set: users.map { .init(metadataId: $0.user.id, status: $0.status, type: nil, custom: $0.custom?.flatJSON) }, delete: [] ), filter: nil, @@ -387,7 +387,7 @@ public extension PubNubMembershipInterface { customFields: nil, totalCount: false, changes: .init( - set: spaces.map { .init(metadataId: $0.space.id, status: $0.status, custom: $0.custom?.flatJSON) }, + set: spaces.map { .init(metadataId: $0.space.id, status: $0.status, type: nil, custom: $0.custom?.flatJSON) }, delete: [] ), filter: nil, @@ -451,7 +451,7 @@ public extension PubNubMembershipInterface { totalCount: false, changes: .init( set: [], - delete: userIds.map { .init(metadataId: $0, status: nil, custom: nil) } + delete: userIds.map { .init(metadataId: $0, status: nil, type: nil, custom: nil) } ), filter: nil, sort: [], @@ -488,7 +488,7 @@ public extension PubNubMembershipInterface { totalCount: false, changes: .init( set: [], - delete: spaceIds.map { .init(metadataId: $0, status: nil, custom: nil) } + delete: spaceIds.map { .init(metadataId: $0, status: nil, type: nil, custom: nil) } ), filter: nil, sort: [], diff --git a/PubNubSpace/Sources/Space+PubNub.swift b/PubNubSpace/Sources/Space+PubNub.swift index 13669b12..12b83d17 100644 --- a/PubNubSpace/Sources/Space+PubNub.swift +++ b/PubNubSpace/Sources/Space+PubNub.swift @@ -197,7 +197,7 @@ public extension PubNubSpaceInterface { ) { let router = ObjectsChannelRouter( .all( - customFields: includeCustom, + include: PubNub.ChannelIncludeFields(custom: includeCustom).includeFields, totalCount: includeTotalCount, filter: filter, sort: sort.map { $0.routerParameter }, @@ -229,7 +229,7 @@ public extension PubNubSpaceInterface { completion: @escaping (Result) -> Void ) { let router = ObjectsChannelRouter( - .fetch(metadataId: spaceId, customFields: includeCustom), + .fetch(metadataId: spaceId, include: PubNub.ChannelIncludeFields(custom: includeCustom).includeFields), configuration: requestConfig.customConfiguration ?? configuration ) @@ -265,7 +265,7 @@ public extension PubNubSpaceInterface { channelDescription: description, custom: custom?.flatJSON ), - customFields: includeCustom + include: PubNub.ChannelIncludeFields(custom: includeCustom).includeFields ), configuration: requestConfig.customConfiguration ?? configuration ) diff --git a/PubNubSwift.podspec b/PubNubSwift.podspec index d32f5f39..05388197 100644 --- a/PubNubSwift.podspec +++ b/PubNubSwift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'PubNubSwift' - s.version = '8.1.0' + s.version = '8.2.0' s.homepage = 'https://github.com/pubnub/swift' s.documentation_url = 'https://www.pubnub.com/docs/swift-native/pubnub-swift-sdk' s.authors = { 'PubNub, Inc.' => 'support@pubnub.com' } diff --git a/PubNubUser/Sources/PubNubUser.swift b/PubNubUser/Sources/PubNubUser.swift index 7054f7a3..b3914230 100644 --- a/PubNubUser/Sources/PubNubUser.swift +++ b/PubNubUser/Sources/PubNubUser.swift @@ -139,8 +139,8 @@ extension PubNubUser: Codable { // MARK: Object v2 Migration -public extension PubNubUUIDMetadata { - /// Converts Object V2 UUID Metadata to a Space entity +public extension PubNubUserMetadata { + /// Converts Object V2 User Metadata to a User entity /// /// - returns: The `PubNubUser` built from the Object V2 data func convert() -> PubNubUser { diff --git a/PubNubUser/Sources/User+PubNub.swift b/PubNubUser/Sources/User+PubNub.swift index bb6da9ba..2d40b826 100644 --- a/PubNubUser/Sources/User+PubNub.swift +++ b/PubNubUser/Sources/User+PubNub.swift @@ -203,9 +203,9 @@ public extension PubNubUserInterface { requestConfig: PubNub.RequestConfiguration = .init(), completion: @escaping ((Result<(users: [PubNubUser], next: PubNubHashedPage?), Error>) -> Void) ) { - let router = ObjectsUUIDRouter( + let router = ObjectsUserRouter( .all( - customFields: includeCustom, + include: PubNub.UserIncludeFields(custom: includeCustom).includeFields, totalCount: includeTotalCount, filter: filter, sort: sort.map { $0.routerParameter }, @@ -226,7 +226,7 @@ public extension PubNubUserInterface { completion(result.map { ( users: $0.payload.data, next: PubNub.Page(next: $0.payload.next, prev: $0.payload.prev, totalCount: $0.payload.totalCount) - ) }) + )}) } } @@ -236,10 +236,10 @@ public extension PubNubUserInterface { requestConfig: PubNub.RequestConfiguration = .init(), completion: @escaping (Result) -> Void ) { - let router = ObjectsUUIDRouter( + let router = ObjectsUserRouter( .fetch( metadataId: userId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid), - customFields: includeCustom + include: PubNub.UserIncludeFields(custom: includeCustom).includeFields ), configuration: requestConfig.customConfiguration ?? configuration ) @@ -268,9 +268,9 @@ public extension PubNubUserInterface { requestConfig: PubNub.RequestConfiguration = .init(), completion: ((Result) -> Void)? ) { - let router = ObjectsUUIDRouter( + let router = ObjectsUserRouter( .set( - metadata: PubNubUUIDMetadataBase( + metadata: PubNubUserMetadataBase( metadataId: userId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid), name: name, type: type, @@ -280,7 +280,7 @@ public extension PubNubUserInterface { email: email, custom: custom?.flatJSON ), - customFields: includeCustom + include: PubNub.UserIncludeFields(custom: includeCustom).includeFields ), configuration: requestConfig.customConfiguration ?? configuration ) @@ -329,7 +329,7 @@ public extension PubNubUserInterface { requestConfig: PubNub.RequestConfiguration = .init(), completion: ((Result) -> Void)? ) { - let router = ObjectsUUIDRouter( + let router = ObjectsUserRouter( .remove(metadataId: userId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid)), configuration: requestConfig.customConfiguration ?? configuration ) diff --git a/PubNubUser/Tests/Test+PubNubUser.swift b/PubNubUser/Tests/Test+PubNubUser.swift index 340ee4cc..544c9815 100644 --- a/PubNubUser/Tests/Test+PubNubUser.swift +++ b/PubNubUser/Tests/Test+PubNubUser.swift @@ -103,7 +103,7 @@ class PubNubUserModelTests: XCTestCase { } func testPubNubUser_Convert_UUIDMetadata() { - let userMetadata = PubNubUUIDMetadataBase( + let userMetadata = PubNubUserMetadataBase( metadataId: testUser.id, name: testUser.name, type: testUser.type, @@ -120,7 +120,7 @@ class PubNubUserModelTests: XCTestCase { } func testPubNubUser_Convert_UUIDMetadata_nilProfileUrl() { - let userMetadata = PubNubUUIDMetadataBase( + let userMetadata = PubNubUserMetadataBase( metadataId: testUser.id, name: testUser.name, type: testUser.type, @@ -140,7 +140,7 @@ class PubNubUserModelTests: XCTestCase { } func testPubNubUser_Convert_UUIDMetadata_nilCustom() { - let userMetadata = PubNubUUIDMetadataBase( + let userMetadata = PubNubUserMetadataBase( metadataId: testUser.id, name: testUser.name, type: testUser.type, diff --git a/PubNubUser/Tests/Test+PubNubUserInterface.swift b/PubNubUser/Tests/Test+PubNubUserInterface.swift index c6161327..288d3138 100644 --- a/PubNubUser/Tests/Test+PubNubUserInterface.swift +++ b/PubNubUser/Tests/Test+PubNubUserInterface.swift @@ -101,7 +101,7 @@ class PubNubUserInterfaceTests: XCTestCase { func testUser_FetchUsers() { let expectation = XCTestExpectation(description: "Fetch Users API") - let testRouterEndpoint = ObjectsUUIDRouter.Endpoint.all( + let testRouterEndpoint = ObjectsUserRouter.Endpoint.all( customFields: true, totalCount: true, filter: nil, @@ -113,7 +113,7 @@ class PubNubUserInterfaceTests: XCTestCase { // Validate Inputs mockSession.validateRouter = { router in - XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUUIDRouter)?.endpoint) + XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUserRouter)?.endpoint) } // Provide Output @@ -141,14 +141,14 @@ class PubNubUserInterfaceTests: XCTestCase { func testUser_FetchUser_ConfigUserId() { let expectation = XCTestExpectation(description: "Fetch User API") - let testRouterEndpoint = ObjectsUUIDRouter.Endpoint.fetch( + let testRouterEndpoint = ObjectsUserRouter.Endpoint.fetch( metadataId: pubnub.configuration.userId, customFields: true ) // Validate Inputs mockSession.validateRouter = { router in - XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUUIDRouter)?.endpoint) + XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUserRouter)?.endpoint) } // Provide Output @@ -173,8 +173,8 @@ class PubNubUserInterfaceTests: XCTestCase { func testUser_CreateUser() { let expectation = XCTestExpectation(description: "Fetch User API") - let testRouterEndpoint = ObjectsUUIDRouter.Endpoint.set( - metadata: PubNubUUIDMetadataBase( + let testRouterEndpoint = ObjectsUserRouter.Endpoint.set( + metadata: PubNubUserMetadataBase( metadataId: pubnub.configuration.userId, name: testUser.name, type: testUser.type, @@ -191,7 +191,7 @@ class PubNubUserInterfaceTests: XCTestCase { // Validate Inputs mockSession.validateRouter = { router in - XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUUIDRouter)?.endpoint) + XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUserRouter)?.endpoint) } // Provide Output @@ -227,8 +227,8 @@ class PubNubUserInterfaceTests: XCTestCase { func testUser_UpdateUser() { let expectation = XCTestExpectation(description: "Fetch User API") - let testRouterEndpoint = ObjectsUUIDRouter.Endpoint.set( - metadata: PubNubUUIDMetadataBase( + let testRouterEndpoint = ObjectsUserRouter.Endpoint.set( + metadata: PubNubUserMetadataBase( metadataId: pubnub.configuration.userId, name: testUser.name, type: testUser.type, @@ -245,7 +245,7 @@ class PubNubUserInterfaceTests: XCTestCase { // Validate Inputs mockSession.validateRouter = { router in - XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUUIDRouter)?.endpoint) + XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUserRouter)?.endpoint) } // Provide Output @@ -281,13 +281,13 @@ class PubNubUserInterfaceTests: XCTestCase { func testUser_RemoveUser() { let expectation = XCTestExpectation(description: "Fetch User API") - let testRouterEndpoint = ObjectsUUIDRouter.Endpoint.remove( + let testRouterEndpoint = ObjectsUserRouter.Endpoint.remove( metadataId: pubnub.configuration.uuid ) // Validate Inputs mockSession.validateRouter = { router in - XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUUIDRouter)?.endpoint) + XCTAssertEqual(testRouterEndpoint, (router as? ObjectsUserRouter)?.endpoint) } // Provide Output diff --git a/Sources/PubNub/APIs/Objects+PubNub.swift b/Sources/PubNub/APIs/Objects+PubNub.swift index 78a3cf02..599f3235 100644 --- a/Sources/PubNub/APIs/Objects+PubNub.swift +++ b/Sources/PubNub/APIs/Objects+PubNub.swift @@ -14,8 +14,10 @@ public extension PubNub { enum MembershipSortProperty: Hashable { /// Sort based on the nested object (UUID or Channel) belonging to the Membership case object(ObjectSortProperty) - + /// Sort on the status property of the Membership case status + /// Sort on the type property of the Membership + case type /// Sort on the last updated property of the Membership case updated @@ -25,6 +27,8 @@ public extension PubNub { return "\(objectType).\(property)" case .status: return "status" + case .type: + return "type" case .updated: return "updated" } @@ -46,6 +50,11 @@ public extension PubNub { /// The direction of the sort public let ascending: Bool + /// Creates a new `MembershipSortField` instance + /// + /// - Parameters: + /// - property: The property to sort by + /// - ascending: The direction of the sort public init(property: MembershipSortProperty, ascending: Bool = true) { self.property = property self.ascending = ascending @@ -58,6 +67,8 @@ public extension PubNub { public var customFields: Bool /// The `PubNubChannelMetadata` instance of the Membership public var channelFields: Bool + /// The `type` field of the `Membership` object + public var typeField: Bool /// The `status` field of the `Membership` object public var statusField: Bool /// The `type` field of the `PubNubChannelMetadata` instance in Membership @@ -70,10 +81,12 @@ public extension PubNub { public var totalCount: Bool /// Default init + /// /// - Parameters: /// - customFields: The `custom` dictionary for the Object /// - channelFields: The `PubNubChannelMetadata` instance of the Membership /// - statusField: The `status` field of the Membership + /// - typeField: The `type` field of the Membership /// - channelCustomFields: The `custom` dictionary of the `PubNubChannelMetadata` for the Membership object /// - channelTypeField: The `type` field of the `PubNubChannelMetadata` for the Membership object /// - channelStatusField: The `status` field of the `PubNubChannelMetadata` for the Membership object @@ -81,7 +94,8 @@ public extension PubNub { public init( customFields: Bool = true, channelFields: Bool = false, - statusField: Bool = false, + statusField: Bool = true, + typeField: Bool = true, channelCustomFields: Bool = false, channelTypeField: Bool = false, channelStatusField: Bool = false, @@ -90,18 +104,20 @@ public extension PubNub { self.customFields = customFields self.channelFields = channelFields self.statusField = statusField + self.typeField = typeField self.channelCustomFields = channelCustomFields self.channelTypeField = channelTypeField self.channelStatusField = channelStatusField self.totalCount = totalCount } - var customIncludes: [ObjectsMembershipsRouter.Include]? { + var includeFields: [ObjectsMembershipsRouter.Include]? { var includes = [ObjectsMembershipsRouter.Include]() if customFields { includes.append(.custom) } if channelFields { includes.append(.channel) } if statusField { includes.append(.status) } + if typeField { includes.append(.type) } if channelCustomFields { includes.append(.channelCustom) } if channelTypeField { includes.append(.channelType) } if channelStatusField { includes.append(.channelStatus) } @@ -113,32 +129,37 @@ public extension PubNub { struct MemberInclude: Hashable { /// The `custom` dictionary for the Object public var customFields: Bool - /// The `PubNubUUIDMetadata` instance of the Membership + /// The `PubNubUserMetadata` instance of the Membership public var uuidFields: Bool /// The `status` field of the `Membership` object public var statusField: Bool - /// The `type` field of the `PubNubUUIDMetadata` instance in Membership + /// The `type` field of the `Membership` object + public var typeField: Bool + /// The `type` field of the `PubNubUserMetadata` instance in Membership public var uuidTypeField: Bool - /// The `status` field of the `PubNubUUIDMetadata` instance in Membership + /// The `status` field of the `PubNubUserMetadata` instance in Membership public var uuidStatusField: Bool - /// The `custom` dictionary of the `PubNubUUIDMetadata` for the Membership object + /// The `custom` dictionary of the `PubNubUserMetadata` for the Membership object public var uuidCustomFields: Bool /// The `totalCount` of how many Objects are available public var totalCount: Bool /// Default init + /// /// - Parameters: /// - customFields: The `custom` dictionary for the Object - /// - uuidFields: The `PubNubUUIDMetadata` instance of the Membership + /// - uuidFields: The `PubNubUserMetadata` instance of the Membership /// - statusField: The `status` field of the Membership - /// - uuidCustomFields: The `custom` dictionary of the `PubNubUUIDMetadata` for the Membership object - /// - uuidTypeField: The `type` field of the `PubNubUUIDMetadata` for the Membership object - /// - uuidStatusField: The `status` field of the `PubNubUUIDMetadata` for the Membership object + /// - typeField: The `type` field of the Membership + /// - uuidCustomFields: The `custom` dictionary of the `PubNubUserMetadata` for the Membership object + /// - uuidTypeField: The `type` field of the `PubNubUserMetadata` for the Membership object + /// - uuidStatusField: The `status` field of the `PubNubUserMetadata` for the Membership object /// - totalCount: The `totalCount` of how many Objects are available public init( customFields: Bool = true, uuidFields: Bool = false, - statusField: Bool = false, + statusField: Bool = true, + typeField: Bool = true, uuidCustomFields: Bool = false, uuidTypeField: Bool = false, uuidStatusField: Bool = false, @@ -147,18 +168,20 @@ public extension PubNub { self.customFields = customFields self.uuidFields = uuidFields self.statusField = statusField + self.typeField = typeField self.uuidCustomFields = uuidCustomFields self.uuidTypeField = uuidTypeField self.uuidStatusField = uuidStatusField self.totalCount = totalCount } - var customIncludes: [ObjectsMembershipsRouter.Include]? { + var includeFields: [ObjectsMembershipsRouter.Include]? { var includes = [ObjectsMembershipsRouter.Include]() if customFields { includes.append(.custom) } if uuidFields { includes.append(.uuid) } if statusField { includes.append(.status) } + if typeField { includes.append(.type) } if uuidCustomFields { includes.append(.uuidCustom) } if uuidTypeField { includes.append(.uuidType) } if uuidStatusField { includes.append(.uuidStatus) } @@ -167,24 +190,122 @@ public extension PubNub { } } - /// Fields that include additional data inside the response + // swiftlint:disable:next line_length + @available(*, deprecated, message: "Will be replaced with PubNub.UserIncludeFields and PubNub.ChannelIncludeFields for the User and Channel methods, respectively") + /// Fields that include additional data inside the response for Channel or User metadata struct IncludeFields: Hashable { /// The `custom` dictionary for the Object public var customFields: Bool + /// The `type` field for the Object + public var typeField: Bool + /// The `status` field for the Object + public var statusField: Bool + /// The `totalCount` of how many Objects are available + public var totalCount: Bool + + /// Default init + /// + /// - Parameters: + /// - custom: Whether to include `custom` data in the response + /// - type: Whether to include `type` in the response + /// - status: Whether to include `status` field in the response + /// - totalCount: Whether to include `totalCount` in the response + public init( + custom: Bool = true, + type: Bool = true, + status: Bool = true, + totalCount: Bool = true + ) { + self.customFields = custom + self.typeField = type + self.statusField = status + self.totalCount = totalCount + } + } + + /// Fields that include additional data inside the response for User metadata + struct UserIncludeFields: Hashable { + /// The `custom` dictionary for the Object + public var custom: Bool + /// The `type` field for the Object + public var type: Bool + /// The `status` field for the Object + public var status: Bool + /// The `totalCount` of how many Objects are available + public var totalCount: Bool + + /// Default init + /// + /// - Parameters: + /// - custom: Whether to include `custom` data in the response + /// - status: Whether to include `status` field in the response + /// - type: Whether to include `type` in the response + /// - totalCount: Whether to include `totalCount` in the response + public init( + custom: Bool = true, + type: Bool = true, + status: Bool = true, + totalCount: Bool = true + ) { + self.custom = custom + self.type = type + self.status = status + self.totalCount = totalCount + } + + public var includeFields: [ObjectsUserRouter.Include]? { + var includes = [ObjectsUserRouter.Include]() + + if custom { includes.append(.custom) } + if status { includes.append(.status) } + if type { includes.append(.type) } + + return includes.isEmpty ? nil : includes + } + } + + /// Fields that include additional data inside the response for Channel metadata + struct ChannelIncludeFields: Hashable { + /// The `custom` dictionary for the Object + public var custom: Bool + /// The `type` field for the Object + public var type: Bool + /// The `status` field for the Object + public var status: Bool /// The `totalCount` of how many Objects are available public var totalCount: Bool /// Default init + /// /// - Parameters: /// - custom: Whether to include `custom` data in the response + /// - status: Whether to include `status` field in the response + /// - type: Whether to include `type` in the response /// - totalCount: Whether to include `totalCount` in the response - public init(custom: Bool = true, totalCount: Bool = true) { - customFields = custom + public init( + custom: Bool = true, + type: Bool = true, + status: Bool = true, + totalCount: Bool = true + ) { + self.custom = custom + self.type = type + self.status = status self.totalCount = totalCount } + + public var includeFields: [ObjectsChannelRouter.Include]? { + var includes = [ObjectsChannelRouter.Include]() + + if custom { includes.append(.custom) } + if status { includes.append(.status) } + if type { includes.append(.type) } + + return includes.isEmpty ? nil : includes + } } - /// The sort properties for UUID and Channel metadata objects + /// The sort properties for User and Channel metadata objects enum ObjectSortProperty: String, Hashable { /// Sort on the unique identifier property case id @@ -228,12 +349,13 @@ extension Array where Element == PubNub.MembershipSortField { } } -// MARK: - UUID Metadat Objects +// MARK: - User Metadata Objects public extension PubNub { - /// Gets metadata for all UUIDs + /// Gets metadata for all Users. + /// + /// Returns a paginated list of User Metadata objects, optionally including the custom data object for each. /// - /// Returns a paginated list of UUID Metadata objects, optionally including the custom data object for each. /// - Parameters: /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). @@ -242,8 +364,9 @@ public extension PubNub { /// - page: The paging hash strings used for pagination /// - custom: Custom configuration overrides for this request /// - completion: The async `Result` of the method call - /// - **Success**: A `Tuple` containing an `Array` of `PubNubUUIDMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Success**: A `Tuple` containing an `Array` of `PubNubUserMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "allUserMetadata(include:filter:sort:limit:page:custom:completion:)") func allUUIDMetadata( include: IncludeFields = IncludeFields(), filter: String? = nil, @@ -251,107 +374,245 @@ public extension PubNub { limit: Int? = 100, page: PubNubHashedPage? = Page(), custom requestConfig: RequestConfiguration = RequestConfiguration(), - completion: ((Result<(uuids: [PubNubUUIDMetadata], next: PubNubHashedPage?), Error>) -> Void)? + completion: ((Result<(uuids: [PubNubUserMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + allUserMetadata( + include: UserIncludeFields( + custom: include.customFields, + type: include.typeField, + status: include.statusField, + totalCount: include.totalCount + ), + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig + ) { + switch $0 { + case let .success((users, next)): + completion?(.success((uuids: users, next: next))) + case let .failure(error): + completion?(.failure(error)) + } + } + } + + /// Gets metadata for all Users. + /// + /// Returns a paginated list of User Metadata objects, optionally including the custom data object for each. + /// + /// - Parameters: + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubUserMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func allUserMetadata( + include: UserIncludeFields = UserIncludeFields(), + filter: String? = nil, + sort: [ObjectSortField] = [], + limit: Int? = 100, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(users: [PubNubUserMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { - let router = ObjectsUUIDRouter( - .all(customFields: include.customFields, totalCount: include.totalCount, - filter: filter, sort: sort.urlValue, - limit: limit, start: page?.start, end: page?.end), + let router = ObjectsUserRouter( + .all( + include: include.includeFields, + totalCount: include.totalCount, + filter: filter, + sort: sort.urlValue, + limit: limit, + start: page?.start, + end: page?.end + ), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubUUIDsMetadataResponseDecoder(), - custom: requestConfig) { result in - completion?(result.map { ( - uuids: $0.payload.data, - next: try? PubNubHashedPageBase(from: $0.payload) - ) }) + route( + router, + responseDecoder: PubNubUsersMetadataResponseDecoder(), + custom: requestConfig + ) { result in + completion?( + result.map { ( + users: $0.payload.data, + next: try? PubNubHashedPageBase(from: $0.payload) + ) + }) } } - /// Get Metadata for a UUID + /// Get Metadata for a User. + /// + /// Returns metadata for the specified User, optionally including the custom data object for each. /// - /// Returns metadata for the specified UUID, optionally including the custom data object for each. /// - Parameters: - /// - uuid: Unique UUID Metadata identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - uuid: Unique User Metadata identifier. If not supplied, then it will use the request configuration and then the default configuration /// - include: Include respective additional fields in the response. /// - custom: Custom configuration overrides for this request /// - completion: The async `Result` of the method call - /// - **Success**: The `PubNubUUIDMetadata` object belonging to the identifier + /// - **Success**: The `PubNubUserMetadata` object belonging to the identifier /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "fetchUserMetadata(_:include:custom:completion:)") func fetch( - uuid metadata: String?, + uuid metadataId: String?, include customFields: Bool = true, custom requestConfig: RequestConfiguration = RequestConfiguration(), - completion: ((Result) -> Void)? + completion: ((Result) -> Void)? + ) { + fetchUserMetadata( + metadataId, + include: UserIncludeFields(custom: customFields), + custom: requestConfig, + completion: completion + ) + } + + /// Get Metadata for a User. + /// + /// Returns metadata for the specified User, optionally including the custom data object for each. + /// + /// - Parameters: + /// - metadataId: Unique User Metadata identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - include: Include respective additional fields in the response. + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: The `PubNubUserMetadata` object belonging to the identifier + /// - **Failure**: An `Error` describing the failure + func fetchUserMetadata( + _ metadataId: String?, + include: UserIncludeFields = UserIncludeFields(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result) -> Void)? ) { - let router = ObjectsUUIDRouter( - .fetch(metadataId: metadata ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid), - customFields: customFields), + let router = ObjectsUserRouter( + .fetch( + metadataId: metadataId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid), + include: include.includeFields + ), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubUUIDMetadataResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubUserMetadataResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { $0.payload.data }) } } - /// Set UUID Metadata + /// Set User Metadata. /// - /// Set metadata for a UUID in the database, optionally including the custom data object for each. + /// Set metadata for a User in the database, optionally including the custom data object for each. /// - Parameters: - /// - uuid: The `PubNubUUIDMetadata` to set + /// - uuid: The `PubNubUserMetadata` to set /// - include: Include respective additional fields in the response. /// - custom: Custom configuration overrides for this request /// - completion: The async `Result` of the method call - /// - **Success**: The `PubNubUUIDMetadata` containing the set changes + /// - **Success**: The `PubNubUserMetadata` containing the set changes /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "setUserMetadata(_:include:custom:completion:)") func set( - uuid metadata: PubNubUUIDMetadata, + uuid metadata: PubNubUserMetadata, include customFields: Bool = true, custom requestConfig: RequestConfiguration = RequestConfiguration(), - completion: ((Result) -> Void)? + completion: ((Result) -> Void)? + ) { + setUserMetadata( + metadata, + include: UserIncludeFields(custom: customFields), + custom: requestConfig, + completion: completion + ) + } + + /// Set User Metadata. + /// + /// Set metadata for a User in the database, optionally including the custom data object for each. + /// - Parameters: + /// - user: The `PubNubUserMetadata` to set + /// - include: Include respective additional fields in the response. + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: The `PubNubUserMetadata` containing the set changes + /// - **Failure**: An `Error` describing the failure + func setUserMetadata( + _ metadata: PubNubUserMetadata, + include: UserIncludeFields = UserIncludeFields(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result) -> Void)? ) { - let router = ObjectsUUIDRouter( - .set(metadata: metadata, customFields: customFields), + let router = ObjectsUserRouter( + .set( + metadata: metadata, + include: include.includeFields + ), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubUUIDMetadataResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubUserMetadataResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { $0.payload.data }) } } - /// Remove UUID Metadata + /// Remove metadata for a specified User. /// - /// Remove metadata for a specified UUID. /// - Parameters: - /// - uuid: Unique UUID Metadata identifier to remove. If not supplied, then it will use the request configuration and then the default configuration + /// - uuid: Unique User Metadata identifier to remove. If not supplied, then it will use the request configuration and then the default configuration /// - custom: Custom configuration overrides for this request /// - completion: The async `Result` of the method call - /// - **Success**: The UUID identifier of the removed object + /// - **Success**: The User identifier of the removed object /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "removeUserMetadata(_:custom:completion:)") func remove( uuid metadataId: String?, custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result) -> Void)? + ) { + removeUserMetadata( + metadataId, + custom: requestConfig, + completion: completion + ) + } + + /// Remove metadata for a specified User. + /// + /// - Parameters: + /// - metadataId: Unique User Metadata identifier to remove. If not supplied, then it will use the request configuration and then the default configuration + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: The identifier of the removed object + /// - **Failure**: An `Error` describing the failure + func removeUserMetadata( + _ metadataId: String?, + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result) -> Void)? ) { // Capture the response or current configuration uuid let metadataId = metadataId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid) - let router = ObjectsUUIDRouter( + let router = ObjectsUserRouter( .remove(metadataId: metadataId), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: GenericServiceResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: GenericServiceResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { _ in metadataId }) } } @@ -360,7 +621,7 @@ public extension PubNub { // MARK: - Channel Metadata Objects public extension PubNub { - /// Get Metadata for All Channels + /// Get Metadata for All Channels. /// /// Returns a paginated list of metadata objects for channels, optionally including custom data objects. /// - Parameters: @@ -382,26 +643,41 @@ public extension PubNub { custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(channels: [PubNubChannelMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { + let channelIncludeFields = ChannelIncludeFields( + custom: include.customFields, + type: include.typeField, + status: include.statusField, + totalCount: include.totalCount + ) let router = ObjectsChannelRouter( - .all(customFields: include.customFields, totalCount: include.totalCount, - filter: filter, sort: sort.map { "\($0.property.rawValue)\($0.ascending ? "" : ":desc")" }, - limit: limit, start: page?.start, end: page?.end), + .all( + include: channelIncludeFields.includeFields, + totalCount: include.totalCount, + filter: filter, + sort: sort.map { "\($0.property.rawValue)\($0.ascending ? "" : ":desc")" }, + limit: limit, + start: page?.start, + end: page?.end + ), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubChannelsMetadataResponseDecoder(), - custom: requestConfig) { result in - completion?(result.map { ( - channels: $0.payload.data, - next: try? PubNubHashedPageBase(from: $0.payload) - ) }) + route( + router, + responseDecoder: PubNubChannelsMetadataResponseDecoder(), + custom: requestConfig + ) { result in + completion?( + result.map { ( + channels: $0.payload.data, + next: try? PubNubHashedPageBase(from: $0.payload) + )} + ) } } - /// Get Metadata for a Channel - /// /// Returns metadata for the specified channel including the channel's custom data. + /// /// - Parameters: /// - channel: Unique Channel Metadata identifier /// - include: Include respective additional fields in the response. @@ -409,27 +685,55 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: The `PubNubChannelMetadata` object belonging to the identifier /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "fetchChannelMetadata(_:include:custom:completion:)") func fetch( channel metadataId: String, include customFields: Bool = true, custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result) -> Void)? + ) { + fetchChannelMetadata( + metadataId, + include: ChannelIncludeFields(custom: customFields), + custom: requestConfig, + completion: completion + ) + } + + /// Returns metadata for the specified channel including the channel's custom data. + /// + /// - Parameters: + /// - metadataId: Unique Channel Metadata identifier + /// - include: Include respective additional fields in the response. + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: The `PubNubChannelMetadata` object belonging to the identifier + /// - **Failure**: An `Error` describing the failure + func fetchChannelMetadata( + _ metadataId: String, + include: ChannelIncludeFields = ChannelIncludeFields(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result) -> Void)? ) { let router = ObjectsChannelRouter( - .fetch(metadataId: metadataId, customFields: customFields), + .fetch( + metadataId: metadataId, + include: include.includeFields + ), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubChannelMetadataResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubChannelMetadataResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { $0.payload.data }) } } - /// Set Channel Metadata - /// /// Set metadata for a channel in the database. + /// /// - Parameters: /// - channel: The `PubNubChannelMetadata` to set /// - include: Include respective additional fields in the response. @@ -437,46 +741,94 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: The `PubNubChannelMetadata` containing the set changes /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "setChannelMetadata(_:include:custom:completion:)") func set( channel metadata: PubNubChannelMetadata, include customFields: Bool = true, custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result) -> Void)? + ) { + setChannelMetadata( + metadata, + include: ChannelIncludeFields(custom: customFields), + custom: requestConfig, + completion: completion + ) + } + + /// Set metadata for a channel in the database. + /// + /// - Parameters: + /// - metadata: The `PubNubChannelMetadata` to set + /// - include: Include respective additional fields in the response. + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: The `PubNubChannelMetadata` containing the set changes + /// - **Failure**: An `Error` describing the failure + func setChannelMetadata( + _ metadata: PubNubChannelMetadata, + include: ChannelIncludeFields = ChannelIncludeFields(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result) -> Void)? ) { let router = ObjectsChannelRouter( - .set(metadata: metadata, customFields: customFields), + .set(metadata: metadata, include: include.includeFields), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubChannelMetadataResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubChannelMetadataResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { $0.payload.data }) } } - /// Remove Channel Metadata + /// Remove metadata for a specified channel. /// - /// Remove metadata for a specified channel /// - Parameters: /// - channel: Unique Channel Metadata identifier to remove. /// - custom: Custom configuration overrides for this request /// - completion: The async `Result` of the method call /// - **Success**: The Channel identifier of the removed object /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "removeChannelMetadata(_:custom:completion:)") func remove( channel metadataId: String, custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result) -> Void)? + ) { + removeChannelMetadata( + metadataId, + custom: requestConfig, + completion: completion + ) + } + + /// Remove metadata for a specified channel. + /// + /// - Parameters: + /// - metadataId: Unique Channel Metadata identifier to remove. + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: The Channel identifier of the removed object + /// - **Failure**: An `Error` describing the failure + func removeChannelMetadata( + _ metadataId: String, + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result) -> Void)? ) { let router = ObjectsChannelRouter( .remove(metadataId: metadataId), configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: GenericServiceResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: GenericServiceResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { _ in metadataId }) } } @@ -485,11 +837,12 @@ public extension PubNub { // MARK: - Memberships public extension PubNub { - /// Get Channel Memberships + /// Get Channel Memberships. /// /// The method returns a list of channel memberships for a user. It does not return a user's subscriptions. + /// /// - Parameters: - /// - uuid: Unique UUID identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - uuid: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). /// - sort: List of properties to sort response objects @@ -499,6 +852,7 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "fetchMemberships(userId:include:filter:sort:limit:page:custom:completion:)") func fetchMemberships( uuid: String?, include: MembershipInclude = MembershipInclude(), @@ -509,12 +863,49 @@ public extension PubNub { custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { - let metadataId = uuid ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid) + fetchMemberships( + userId: uuid, + include: include, + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig, + completion: completion + ) + } + + /// Get Channel Memberships. + /// + /// The method returns a list of channel memberships for a user. It does not return a user's subscriptions. + /// + /// - Parameters: + /// - userId: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func fetchMemberships( + userId: String?, + include: MembershipInclude = MembershipInclude(), + filter: String? = nil, + sort: [MembershipSortField] = [], + limit: Int? = 100, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + let metadataId = userId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid) let router = ObjectsMembershipsRouter( .fetchMemberships( uuidMetadataId: metadataId, - customFields: include.customIncludes, + customFields: include.includeFields, totalCount: include.totalCount, filter: filter, sort: sort.membershipURLValue, limit: limit, start: page?.start, end: page?.end @@ -522,23 +913,24 @@ public extension PubNub { configuration: requestConfig.customConfiguration ?? configuration ) - route(router, - responseDecoder: PubNubMembershipsResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubMembershipsResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { response in ( - memberships: response.payload.data.compactMap { - PubNubMembershipMetadataBase(from: $0, other: metadataId) - }, + memberships: response.payload.data.compactMap { PubNubMembershipMetadataBase(from: $0, other: metadataId) }, next: try? PubNubHashedPageBase(from: response.payload) ) }) } } - /// Get Channel Members + /// Get Channel Members. /// /// The method returns a list of members in a channel. The list will include user metadata for members that have additional metadata stored in the database. + /// /// - Parameters: /// - channel: Unique Channel identifier. /// - include: Include respective additional fields in the response. @@ -561,30 +953,31 @@ public extension PubNub { completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { let router = ObjectsMembershipsRouter(.fetchMembers( - channelMetadataId: metadataId, customFields: include.customIncludes, + channelMetadataId: metadataId, customFields: include.includeFields, totalCount: include.totalCount, filter: filter, sort: sort.memberURLValue, limit: limit, start: page?.start, end: page?.end ), configuration: requestConfig.customConfiguration ?? configuration) - route(router, - responseDecoder: PubNubMembershipsResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubMembershipsResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { response in ( - memberships: response.payload.data.compactMap { - PubNubMembershipMetadataBase(from: $0, other: metadataId) - }, + memberships: response.payload.data.compactMap { PubNubMembershipMetadataBase(from: $0, other: metadataId) }, next: try? PubNubHashedPageBase(from: response.payload) ) }) } } - /// Set Channel memberships for a UUID. + /// Set Channel memberships for a User. + /// /// - Parameters: - /// - uuid: Unique UUID identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - uuid: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration /// - channels: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). @@ -595,6 +988,7 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "setMemberships(userId:channels:include:filter:sort:limit:page:custom:completion:)") func setMemberships( uuid metadataId: String?, channels memberships: [PubNubMembershipMetadata], @@ -605,17 +999,56 @@ public extension PubNub { page: PubNubHashedPage? = Page(), custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + setMemberships( + userId: metadataId, + channels: memberships, + include: include, + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig, + completion: completion + ) + } + + /// Set Channel memberships for a User ID. + /// + /// - Parameters: + /// - userId: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - channels: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func setMemberships( + userId metadataId: String?, + channels memberships: [PubNubMembershipMetadata], + include: MembershipInclude = MembershipInclude(), + filter: String? = nil, + sort: [MembershipSortField] = [], + limit: Int? = 100, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { manageMemberships( - uuid: metadataId, setting: memberships, removing: [], + userId: metadataId, setting: memberships, removing: [], include: include, filter: filter, sort: sort, limit: limit, page: page, custom: requestConfig, completion: completion ) } - /// Remove Channel memberships for a UUID. + /// Remove Channel memberships for a User. + /// /// - Parameters: - /// - uuid: Unique UUID identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - uuid: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration /// - channels: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). @@ -626,6 +1059,7 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "removeMemberships(userId:channels:include:filter:sort:limit:page:custom:completion:)") func removeMemberships( uuid metadataId: String?, channels memberships: [PubNubMembershipMetadata], @@ -636,17 +1070,56 @@ public extension PubNub { page: PubNubHashedPage? = Page(), custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + removeMemberships( + userId: metadataId, + channels: memberships, + include: include, + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig, + completion: completion + ) + } + + /// Remove Channel memberships for a User ID. + /// + /// - Parameters: + /// - userId: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - channels: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func removeMemberships( + userId metadataId: String?, + channels memberships: [PubNubMembershipMetadata], + include: MembershipInclude = MembershipInclude(), + filter: String? = nil, + sort: [MembershipSortField] = [], + limit: Int? = nil, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { manageMemberships( - uuid: metadataId, setting: [], removing: memberships, + userId: metadataId, setting: [], removing: memberships, include: include, filter: filter, sort: sort, limit: limit, page: page, custom: requestConfig, completion: completion ) } - /// Modify the Channel membership list for a UUID + /// Modify the Channel membership list for a User. + /// /// - Parameters: - /// - uuid: Unique UUID identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - uuid: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration /// - setting: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided /// - removing: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided /// - include: Include respective additional fields in the response. @@ -658,6 +1131,8 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "manageMemberships(userId:setting:removing:include:filter:sort:limit:page:custom:completion:)") + // swiftlint:disable:previous line_length func manageMemberships( uuid: String?, setting channelMembershipSets: [PubNubMembershipMetadata], @@ -670,40 +1145,82 @@ public extension PubNub { custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { - let metadataId = uuid ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid) + manageMemberships( + userId: uuid, + setting: channelMembershipSets, + removing: channelMembershipDeletes, + include: include, + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig, + completion: completion + ) + } + + /// Modify the Channel membership list for a User. + /// + /// - Parameters: + /// - userId: Unique User identifier. If not supplied, then it will use the request configuration and then the default configuration + /// - setting: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided + /// - removing: Array of `PubNubMembershipMetadata` with the `PubNubChannelMetadata` or `channelMetadataId` provided + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func manageMemberships( + userId: String?, + setting channelMembershipSets: [PubNubMembershipMetadata], + removing channelMembershipDeletes: [PubNubMembershipMetadata], + include: MembershipInclude = MembershipInclude(), + filter: String? = nil, + sort: [MembershipSortField] = [], + limit: Int? = 100, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + let metadataId = userId ?? (requestConfig.customConfiguration?.uuid ?? configuration.uuid) let router = ObjectsMembershipsRouter(.setMemberships( - uuidMetadataId: metadataId, customFields: include.customIncludes, totalCount: include.totalCount, + uuidMetadataId: metadataId, customFields: include.includeFields, totalCount: include.totalCount, changes: .init( set: channelMembershipSets.map { - .init(metadataId: $0.channelMetadataId, status: $0.status, custom: $0.custom) + .init(metadataId: $0.channelMetadataId, status: $0.status, type: $0.type, custom: $0.custom) }, delete: channelMembershipDeletes.map { - .init(metadataId: $0.channelMetadataId, status: $0.status, custom: $0.custom) + .init(metadataId: $0.channelMetadataId, status: $0.status, type: $0.type, custom: $0.custom) } ), filter: filter, sort: sort.membershipURLValue, limit: limit, start: page?.start, end: page?.end ), configuration: requestConfig.customConfiguration ?? configuration) - route(router, - responseDecoder: PubNubMembershipsResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubMembershipsResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { response in ( - memberships: response.payload.data.compactMap { - PubNubMembershipMetadataBase(from: $0, other: metadataId) - }, + memberships: response.payload.data.compactMap { PubNubMembershipMetadataBase(from: $0, other: metadataId) }, next: try? PubNubHashedPageBase(from: response.payload) ) }) } } - /// Get the specified user's space memberships. + /// Set the specified user's space memberships. + /// /// - Parameters: /// - channel: Unique Channel identifier. - /// - uuids: Array of `PubNubMembershipMetadata` with the `PubNubUUIDMetadata` or `uuidMetadataId` provided + /// - uuids: Array of `PubNubMembershipMetadata` with the `PubNubUserMetadata` or `userMetadataId` provided /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). /// - sort: List of properties to sort response objects @@ -713,6 +1230,7 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "setMembers(channels:users:include:filter:sort:limit:page:custom:completion:)") func setMembers( channel metadataId: String, uuids members: [PubNubMembershipMetadata], @@ -723,6 +1241,44 @@ public extension PubNub { page: PubNubHashedPage? = Page(), custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + setMembers( + channel: metadataId, + users: members, + include: include, + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig, + completion: completion + ) + } + + /// Set the specified user's space memberships. + /// + /// - Parameters: + /// - channel: Unique Channel identifier. + /// - users: Array of `PubNubMembershipMetadata` with the `PubNubUserMetadata` or `userMetadataId` provided + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func setMembers( + channel metadataId: String, + users members: [PubNubMembershipMetadata], + include: MemberInclude = MemberInclude(), + filter: String? = nil, + sort: [MembershipSortField] = [], + limit: Int? = 100, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { manageMembers( channel: metadataId, setting: members, removing: [], @@ -731,10 +1287,11 @@ public extension PubNub { ) } - /// Remove UUID members from a Channel. + /// Remove User members from a Channel. + /// /// - Parameters: /// - channel: Unique Channel identifier. - /// - uuids: Array of `PubNubMembershipMetadata` with the `PubNubUUIDMetadata` or `uuidMetadataId` provided + /// - uuids: Array of `PubNubMembershipMetadata` with the `PubNubUserMetadata` or `userMetadataId` provided /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). /// - sort: List of properties to sort response objects @@ -744,6 +1301,7 @@ public extension PubNub { /// - completion: The async `Result` of the method call /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) /// - **Failure**: An `Error` describing the failure + @available(*, deprecated, renamed: "removeMembers(channel:users:include:filter:sort:limit:page:custom:completion:)") func removeMembers( channel metadataId: String, uuids members: [PubNubMembershipMetadata], @@ -754,6 +1312,44 @@ public extension PubNub { page: PubNubHashedPage? = Page(), custom requestConfig: RequestConfiguration = RequestConfiguration(), completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? + ) { + removeMembers( + channel: metadataId, + users: members, + include: include, + filter: filter, + sort: sort, + limit: limit, + page: page, + custom: requestConfig, + completion: completion + ) + } + + /// Remove User members from a Channel. + /// + /// - Parameters: + /// - channel: Unique Channel identifier. + /// - users: Array of `PubNubMembershipMetadata` with the `PubNubUserMetadata` or `uuidMetadataId` provided + /// - include: Include respective additional fields in the response. + /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). + /// - sort: List of properties to sort response objects + /// - limit: The number of objects to retrieve at a time + /// - page: The paging hash strings used for pagination + /// - custom: Custom configuration overrides for this request + /// - completion: The async `Result` of the method call + /// - **Success**: A `Tuple` containing an `Array` of `PubNubMembershipMetadata`, and the next pagination `PubNubHashedPage` (if one exists) + /// - **Failure**: An `Error` describing the failure + func removeMembers( + channel metadataId: String, + users members: [PubNubMembershipMetadata], + include: MemberInclude = MemberInclude(), + filter: String? = nil, + sort: [MembershipSortField] = [], + limit: Int? = 100, + page: PubNubHashedPage? = Page(), + custom requestConfig: RequestConfiguration = RequestConfiguration(), + completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { manageMembers( channel: metadataId, setting: [], removing: members, @@ -762,11 +1358,12 @@ public extension PubNub { ) } - /// Modify the UUID member list for a Channel + /// Modify the User member list for a Channel. + /// /// - Parameters: /// - channel: Unique Channel identifier. - /// - setting: Array of `PubNubMembershipMetadata` with the `PubNubUUIDMetadata` or `uuidMetadataId` provided - /// - removing: Array of `PubNubMembershipMetadata` with the `PubNubUUIDMetadata` or `uuidMetadataId` provided + /// - setting: Array of `PubNubMembershipMetadata` with the `PubNubUserMetadata` or `userMetadataId` provided + /// - removing: Array of `PubNubMembershipMetadata` with the `PubNubUserMetadata` or `userMetadataId` provided /// - include: Include respective additional fields in the response. /// - filter: Expression used to filter the results. Only objects whose properties satisfy the given expression are returned. The filter language is defined [here](https://www.pubnub.com/docs/swift/stream-filtering-tutorial#filtering-language-definition). /// - sort: List of properties to sort response objects @@ -778,8 +1375,8 @@ public extension PubNub { /// - **Failure**: An `Error` describing the failure func manageMembers( channel metadataId: String, - setting uuidMembershipSets: [PubNubMembershipMetadata], - removing uuidMembershipDeletes: [PubNubMembershipMetadata], + setting userMembershipSets: [PubNubMembershipMetadata], + removing userMembershipDeletes: [PubNubMembershipMetadata], include: MemberInclude = MemberInclude(), filter: String? = nil, sort: [MembershipSortField] = [], @@ -789,23 +1386,27 @@ public extension PubNub { completion: ((Result<(memberships: [PubNubMembershipMetadata], next: PubNubHashedPage?), Error>) -> Void)? ) { let router = ObjectsMembershipsRouter(.setMembers( - channelMetadataId: metadataId, customFields: include.customIncludes, totalCount: include.totalCount, + channelMetadataId: metadataId, customFields: include.includeFields, totalCount: include.totalCount, changes: .init( - set: uuidMembershipSets.map { .init(metadataId: $0.uuidMetadataId, status: $0.status, custom: $0.custom) }, - delete: uuidMembershipDeletes.map { .init(metadataId: $0.uuidMetadataId, status: $0.status, custom: $0.custom) } + set: userMembershipSets.map { + .init(metadataId: $0.userMetadataId, status: $0.status, type: $0.type, custom: $0.custom) + }, + delete: userMembershipDeletes.map { + .init(metadataId: $0.userMetadataId, status: $0.status, type: $0.type, custom: $0.custom) + } ), filter: filter, sort: sort.memberURLValue, limit: limit, start: page?.start, end: page?.end ), configuration: requestConfig.customConfiguration ?? configuration) - route(router, - responseDecoder: PubNubMembershipsResponseDecoder(), - custom: requestConfig) { result in + route( + router, + responseDecoder: PubNubMembershipsResponseDecoder(), + custom: requestConfig + ) { result in completion?(result.map { response in ( - memberships: response.payload.data.compactMap { - PubNubMembershipMetadataBase(from: $0, other: metadataId) - }, + memberships: response.payload.data.compactMap { PubNubMembershipMetadataBase(from: $0, other: metadataId) }, next: try? PubNubHashedPageBase(from: response.payload) ) }) diff --git a/Sources/PubNub/Events/New/PubNubEvent.swift b/Sources/PubNub/Events/New/PubNubEvent.swift index 484e3939..228d49cd 100644 --- a/Sources/PubNub/Events/New/PubNubEvent.swift +++ b/Sources/PubNub/Events/New/PubNubEvent.swift @@ -36,9 +36,9 @@ public enum PubNubMessageActionEvent { /// Possible subevents for AppContext public enum PubNubAppContextEvent { - /// The `PubNubUUIDMetadataChangeset` of the set Membership - case userMetadataSet(PubNubUUIDMetadataChangeset) - /// The unique identifer of the UUID that was removed + /// The `PubNubUserMetadataChangeset` of the set Membership + case userMetadataSet(PubNubUserMetadataChangeset) + /// The unique identifer of the User that was removed case userMetadataRemoved(metadataId: String) /// The changeset for the Channel object that changed case channelMetadataSet(PubNubChannelMetadataChangeset) diff --git a/Sources/PubNub/Events/Old/Subscription/SubscriptionStream.swift b/Sources/PubNub/Events/Old/Subscription/SubscriptionStream.swift index 34bc88f7..5ec4d298 100644 --- a/Sources/PubNub/Events/Old/Subscription/SubscriptionStream.swift +++ b/Sources/PubNub/Events/Old/Subscription/SubscriptionStream.swift @@ -88,7 +88,7 @@ public enum PubNubCoreEvent { /// A presence change has been received case presenceChanged(PubNubPresenceChange) /// A User object has been updated - case uuidMetadataSet(PubNubUUIDMetadataChangeset) + case uuidMetadataSet(PubNubUserMetadataChangeset) /// A User object has been deleted case uuidMetadataRemoved(metadataId: String) /// A Space object has been updated @@ -135,7 +135,7 @@ public final class CoreListener: BaseSubscriptionListener { /// All the changes that can be received for Metadata objects public enum ObjectMetadataChangeEvents { /// The changeset for the UUID object that changed - case setUUID(PubNubUUIDMetadataChangeset) + case setUUID(PubNubUserMetadataChangeset) /// The unique identifer of the UUID that was removed case removedUUID(metadataId: String) /// The changeset for the Channel object that changed diff --git a/Sources/PubNub/Helpers/Constants.swift b/Sources/PubNub/Helpers/Constants.swift index 1f60a8f6..e7cfb76a 100644 --- a/Sources/PubNub/Helpers/Constants.swift +++ b/Sources/PubNub/Helpers/Constants.swift @@ -57,7 +57,7 @@ public enum Constant { static let pubnubSwiftSDKName: String = "PubNubSwift" - static let pubnubSwiftSDKVersion: String = "8.1.0" + static let pubnubSwiftSDKVersion: String = "8.2.0" static let appBundleId: String = { if let info = Bundle.main.infoDictionary, diff --git a/Sources/PubNub/KMP/KMPPubNub+AppContext.swift b/Sources/PubNub/KMP/KMPPubNub+AppContext.swift index 32d5f761..f48f3da5 100644 --- a/Sources/PubNub/KMP/KMPPubNub+AppContext.swift +++ b/Sources/PubNub/KMP/KMPPubNub+AppContext.swift @@ -57,9 +57,6 @@ extension KMPPubNub { } } - // swiftlint:disable todo - // TODO: Swift SDK allows to sort by the status field, it's not present in KMP - private func mapToMembershipSortFields(from array: [String]) -> [PubNub.MembershipSortField] { array.compactMap { switch $0 { @@ -69,15 +66,21 @@ extension KMPPubNub { return PubNub.MembershipSortField(property: .object(.name)) case "channel.updated", "uuid.updated": return PubNub.MembershipSortField(property: .object(.updated)) + case "channel.type", "uuid.type": + return PubNub.MembershipSortField(property: .object(.type)) + case "channel.status", "uuid.status": + return PubNub.MembershipSortField(property: .object(.status)) case "updated": return PubNub.MembershipSortField(property: .updated) + case "status": + return PubNub.MembershipSortField(property: .status) + case "type": + return PubNub.MembershipSortField(property: .type) default: return nil } } } - - // swiftlint:enable todo } @objc @@ -113,12 +116,12 @@ public extension KMPPubNub { } func getChannelMetadata( - channel: String, + metadataId: String, includeCustom: Bool, onSuccess: @escaping ((KMPChannelMetadata) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.fetch(channel: channel, include: includeCustom) { + pubnub.fetchChannelMetadata(metadataId, include: PubNub.ChannelIncludeFields(custom: includeCustom)) { switch $0 { case .success(let metadata): onSuccess(KMPChannelMetadata(metadata: metadata)) @@ -129,7 +132,7 @@ public extension KMPPubNub { } func setChannelMetadata( - channel: String, + metadataId: String, name: String?, description: String?, custom: KMPAnyJSON?, @@ -139,17 +142,15 @@ public extension KMPPubNub { onSuccess: @escaping ((KMPChannelMetadata) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.set( - channel: PubNubChannelMetadataBase( - metadataId: channel, - name: name, - type: type, - status: status, - channelDescription: description, - custom: convertDictionaryToScalars(custom?.asMap()) - ), - include: includeCustom - ) { + let channelMetadata = PubNubChannelMetadataBase( + metadataId: metadataId, + name: name, + type: type, + status: status, + channelDescription: description, + custom: convertDictionaryToScalars(custom?.asMap()) + ) + pubnub.setChannelMetadata(channelMetadata, include: PubNub.ChannelIncludeFields(custom: includeCustom)) { switch $0 { case .success(let metadata): onSuccess(KMPChannelMetadata(metadata: metadata)) @@ -160,11 +161,11 @@ public extension KMPPubNub { } func removeChannelMetadata( - channel: String, + metadataId: String, onSuccess: @escaping ((String) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.remove(channel: channel) { + pubnub.removeChannelMetadata(metadataId) { switch $0 { case .success(let channel): onSuccess(channel) @@ -174,18 +175,18 @@ public extension KMPPubNub { } } - func getAllUUIDMetadata( + func getAllUserMetadata( limit: NSNumber?, page: KMPHashedPage?, filter: String?, sort: [KMPObjectSortProperty], includeCount: Bool, includeCustom: Bool, - onSuccess: @escaping (([KMPUUIDMetadata], NSNumber?, KMPHashedPage) -> Void), + onSuccess: @escaping (([KMPUserMetadata], NSNumber?, KMPHashedPage) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.allUUIDMetadata( - include: PubNub.IncludeFields(custom: includeCustom, totalCount: includeCount), + pubnub.allUserMetadata( + include: PubNub.UserIncludeFields(custom: includeCustom, totalCount: includeCount), filter: filter, sort: objectSortProperties(from: sort), limit: limit?.intValue, @@ -194,7 +195,7 @@ public extension KMPPubNub { switch $0 { case .success(let res): onSuccess( - res.uuids.map { KMPUUIDMetadata(metadata: $0) }, + res.users.map { KMPUserMetadata(metadata: $0) }, res.next?.totalCount?.asNumber, KMPHashedPage(page: res.next) ) @@ -204,24 +205,24 @@ public extension KMPPubNub { } } - func getUUIDMetadata( - uuid: String?, + func getUserMetadata( + metadataId: String?, includeCustom: Bool, - onSuccess: @escaping ((KMPUUIDMetadata) -> Void), + onSuccess: @escaping ((KMPUserMetadata) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.fetch(uuid: uuid, include: includeCustom) { + pubnub.fetchUserMetadata(metadataId, include: PubNub.UserIncludeFields(custom: includeCustom)) { switch $0 { case .success(let metadata): - onSuccess(KMPUUIDMetadata(metadata: metadata)) + onSuccess(KMPUserMetadata(metadata: metadata)) case .failure(let error): onFailure(KMPError(underlying: error)) } } } - func setUUIDMetadata( - uuid: String?, + func setUserMetadata( + metadataId: String?, name: String?, externalId: String?, profileUrl: String?, @@ -230,37 +231,38 @@ public extension KMPPubNub { includeCustom: Bool, type: String?, status: String?, - onSuccess: @escaping ((KMPUUIDMetadata) -> Void), + onSuccess: @escaping ((KMPUserMetadata) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.set( - uuid: PubNubUUIDMetadataBase( - metadataId: uuid ?? pubnub.configuration.userId, - name: name, - type: type, - status: status, - externalId: externalId, - profileURL: profileUrl, - email: email, - custom: convertDictionaryToScalars(custom?.asMap()) - ), - include: includeCustom + let userMetadata = PubNubUserMetadataBase( + metadataId: metadataId ?? pubnub.configuration.userId, + name: name, + type: type, + status: status, + externalId: externalId, + profileURL: profileUrl, + email: email, + custom: convertDictionaryToScalars(custom?.asMap()) + ) + pubnub.setUserMetadata( + userMetadata, + include: PubNub.UserIncludeFields(custom: includeCustom) ) { switch $0 { case .success(let metadata): - onSuccess(KMPUUIDMetadata(metadata: metadata)) + onSuccess(KMPUserMetadata(metadata: metadata)) case .failure(let error): onFailure(KMPError(underlying: error)) } } } - func removeUUIDMetadata( - uuid: String?, + func removeUserMetadata( + metadataId: String?, onSuccess: @escaping ((String) -> Void), onFailure: @escaping ((Error) -> Void) ) { - pubnub.remove(uuid: uuid) { + pubnub.removeUserMetadata(metadataId) { switch $0 { case .success(let result): onSuccess(result) @@ -271,7 +273,7 @@ public extension KMPPubNub { } func getMemberships( - uuid: String?, + userId: String?, limit: NSNumber?, page: KMPHashedPage?, filter: String?, @@ -285,7 +287,7 @@ public extension KMPPubNub { onFailure: @escaping ((Error) -> Void) ) { pubnub.fetchMemberships( - uuid: uuid, + userId: userId, include: .init( customFields: includeCustom, channelFields: includeChannelFields, @@ -313,7 +315,7 @@ public extension KMPPubNub { func setMemberships( channels: [KMPChannelMetadata], - uuid: String?, + userId: String?, limit: NSNumber?, page: KMPHashedPage?, filter: String?, @@ -327,10 +329,10 @@ public extension KMPPubNub { onFailure: @escaping ((Error) -> Void) ) { pubnub.setMemberships( - uuid: uuid, + userId: userId, channels: channels.map { PubNubMembershipMetadataBase( - uuidMetadataId: uuid ?? pubnub.configuration.userId, + userMetadataId: userId ?? pubnub.configuration.userId, channelMetadataId: $0.id, status: $0.status, custom: convertDictionaryToScalars($0.custom) @@ -363,7 +365,7 @@ public extension KMPPubNub { func removeMemberships( channels: [String], - uuid: String?, + userId: String?, limit: NSNumber?, page: KMPHashedPage?, filter: String?, @@ -377,10 +379,10 @@ public extension KMPPubNub { onFailure: @escaping ((Error) -> Void) ) { pubnub.removeMemberships( - uuid: uuid, + userId: userId, channels: channels.map { PubNubMembershipMetadataBase( - uuidMetadataId: uuid ?? pubnub.configuration.userId, + userMetadataId: userId ?? pubnub.configuration.userId, channelMetadataId: $0 ) }, @@ -417,9 +419,9 @@ public extension KMPPubNub { sort: [String], includeCount: Bool, includeCustom: Bool, - includeUUIDFields: Bool, - includeUUIDCustomFields: Bool, - includeUUIDType: Bool, + includeUserFields: Bool, + includeUserCustomFields: Bool, + includeUserType: Bool, onSuccess: @escaping (([KMPMembershipMetadata], NSNumber?, KMPHashedPage?) -> Void), onFailure: @escaping ((Error) -> Void) ) { @@ -427,9 +429,9 @@ public extension KMPPubNub { channel: channel, include: .init( customFields: includeCustom, - uuidFields: includeUUIDFields, - uuidCustomFields: includeUUIDCustomFields, - uuidTypeField: includeUUIDType, + uuidFields: includeUserFields, + uuidCustomFields: includeUserCustomFields, + uuidTypeField: includeUserType, totalCount: includeCount ), filter: filter, @@ -452,24 +454,24 @@ public extension KMPPubNub { func setChannelMembers( channel: String, - uuids: [KMPUUIDMetadata], + users: [KMPUserMetadata], limit: NSNumber?, page: KMPHashedPage?, filter: String?, sort: [String], includeCount: Bool, includeCustom: Bool, - includeUUIDFields: Bool, - includeUUIDCustomFields: Bool, - includeUUIDType: Bool, + includeUser: Bool, + includeUserCustom: Bool, + includeUserType: Bool, onSuccess: @escaping (([KMPMembershipMetadata], NSNumber?, KMPHashedPage?) -> Void), onFailure: @escaping ((Error) -> Void) ) { pubnub.setMembers( channel: channel, - uuids: uuids.map { + users: users.map { PubNubMembershipMetadataBase( - uuidMetadataId: $0.id, + userMetadataId: $0.id, channelMetadataId: channel, status: $0.status, custom: convertDictionaryToScalars($0.custom) @@ -477,9 +479,9 @@ public extension KMPPubNub { }, include: .init( customFields: includeCustom, - uuidFields: includeUUIDFields, - uuidCustomFields: includeUUIDCustomFields, - uuidTypeField: includeUUIDType, + uuidFields: includeUser, + uuidCustomFields: includeUserCustom, + uuidTypeField: includeUserType, totalCount: includeCount ), filter: filter, @@ -502,32 +504,32 @@ public extension KMPPubNub { func removeChannelMembers( channel: String, - uuids: [String], + users: [String], limit: NSNumber?, page: KMPHashedPage?, filter: String?, sort: [String], includeCount: Bool, includeCustom: Bool, - includeUUIDFields: Bool, - includeUUIDCustomFields: Bool, - includeUUIDType: Bool, + includeUser: Bool, + includeUserCustom: Bool, + includeUserType: Bool, onSuccess: @escaping (([KMPMembershipMetadata], NSNumber?, KMPHashedPage?) -> Void), onFailure: @escaping ((Error) -> Void) ) { pubnub.removeMembers( channel: channel, - uuids: uuids.map { + users: users.map { PubNubMembershipMetadataBase( - uuidMetadataId: $0, + userMetadataId: $0, channelMetadataId: channel ) }, include: .init( customFields: includeCustom, - uuidFields: includeUUIDFields, - uuidCustomFields: includeUUIDCustomFields, - uuidTypeField: includeUUIDType, + uuidFields: includeUser, + uuidCustomFields: includeUserCustom, + uuidTypeField: includeUserType, totalCount: includeCount ), filter: filter, diff --git a/Sources/PubNub/KMP/KMPPubNub+History.swift b/Sources/PubNub/KMP/KMPPubNub+History.swift index 3e471fe7..59c5058d 100644 --- a/Sources/PubNub/KMP/KMPPubNub+History.swift +++ b/Sources/PubNub/KMP/KMPPubNub+History.swift @@ -25,6 +25,7 @@ public extension KMPPubNub { includeMeta: Bool, includeMessageActions: Bool, includeMessageType: Bool, + includeCustomMessageType: Bool, page: KMPBoundedPage?, onSuccess: @escaping ((KMPFetchMessagesResult)) -> Void, onFailure: @escaping ((Error) -> Void) @@ -35,6 +36,7 @@ public extension KMPPubNub { includeMeta: includeMeta, includeUUID: includeUUID, includeMessageType: includeMessageType, + includeCustomMessageType: includeCustomMessageType, page: PubNubBoundedPageBase( start: page?.start?.uint64Value, end: page?.end?.uint64Value, diff --git a/Sources/PubNub/KMP/Wrappers/KMPAppContextEventResult.swift b/Sources/PubNub/KMP/Wrappers/KMPAppContextEventResult.swift index e92cc4cf..0b68b4e4 100644 --- a/Sources/PubNub/KMP/Wrappers/KMPAppContextEventResult.swift +++ b/Sources/PubNub/KMP/Wrappers/KMPAppContextEventResult.swift @@ -63,9 +63,9 @@ public class KMPAppContextEventResult: NSObject { @objc public class KMPSetUUIDMetadataResult: KMPAppContextEventResult { - @objc public let metadata: KMPUUIDMetadata + @objc public let metadata: KMPUserMetadata - init(metadata: KMPUUIDMetadata) { + init(metadata: KMPUserMetadata) { self.metadata = metadata super.init() } @@ -139,7 +139,7 @@ extension KMPAppContextEventResult { static func from(event: PubNubAppContextEvent) -> KMPAppContextEventResult { switch event { case .userMetadataSet(let changeset): - return KMPSetUUIDMetadataResult(metadata: KMPUUIDMetadata(changeset: changeset)) + return KMPSetUUIDMetadataResult(metadata: KMPUserMetadata(changeset: changeset)) case .userMetadataRemoved(let metadataId): return KMPRemoveUUIDMetadataResult(uuid: metadataId) case .channelMetadataSet(let changeset): @@ -149,7 +149,7 @@ extension KMPAppContextEventResult { case .membershipMetadataSet(let metadata): return KMPSetMembershipResult(metadata: KMPMembershipMetadata(from: metadata)) case .membershipMetadataRemoved(let metadata): - return KMPRemoveMembershipResult(channelId: metadata.channelMetadataId, uuid: metadata.uuidMetadataId) + return KMPRemoveMembershipResult(channelId: metadata.channelMetadataId, uuid: metadata.userMetadataId) } } } @@ -228,10 +228,10 @@ public class KMPChannelMetadata: NSObject { } } -// MARK: - KMPUUIDMetadata +// MARK: - KMPUserMetadata @objc -public class KMPUUIDMetadata: NSObject { +public class KMPUserMetadata: NSObject { @objc public var id: String @objc public var name: String? @objc public var externalId: String? @@ -263,7 +263,7 @@ public class KMPUUIDMetadata: NSObject { } // swiftlint:disable:next cyclomatic_complexity - init(changeset: PubNubUUIDMetadataChangeset) { + init(changeset: PubNubUserMetadataChangeset) { self.id = changeset.metadataId self.updated = DateFormatter.iso8601.string(from: changeset.updated) self.eTag = changeset.eTag @@ -305,7 +305,7 @@ public class KMPUUIDMetadata: NSObject { } } - init(metadata: PubNubUUIDMetadata) { + init(metadata: PubNubUserMetadata) { self.id = metadata.metadataId self.name = metadata.name self.externalId = metadata.externalId @@ -326,17 +326,19 @@ public class KMPMembershipMetadata: NSObject { @objc public var uuidMetadataId: String @objc public var channelMetadataId: String @objc public var status: String? - @objc public var uuid: KMPUUIDMetadata? + @objc public var type: String? + @objc public var user: KMPUserMetadata? @objc public var channel: KMPChannelMetadata? @objc public var updated: String? @objc public var eTag: String? @objc public var custom: [String: Any]? init(from: PubNubMembershipMetadata) { - self.uuidMetadataId = from.uuidMetadataId + self.uuidMetadataId = from.userMetadataId self.channelMetadataId = from.channelMetadataId self.status = from.status - self.uuid = if let uuid = from.uuid { KMPUUIDMetadata(metadata: uuid) } else { nil } + self.type = from.type + self.user = if let user = from.user { KMPUserMetadata(metadata: user) } else { nil } self.channel = if let channel = from.channel { KMPChannelMetadata(metadata: channel) } else { nil } self.updated = if let date = from.updated { DateFormatter.iso8601.string(from: date) } else { nil } self.eTag = from.eTag diff --git a/Sources/PubNub/KMP/Wrappers/KMPMessage.swift b/Sources/PubNub/KMP/Wrappers/KMPMessage.swift index 2bbc2984..2f1d9007 100644 --- a/Sources/PubNub/KMP/Wrappers/KMPMessage.swift +++ b/Sources/PubNub/KMP/Wrappers/KMPMessage.swift @@ -28,6 +28,7 @@ public class KMPMessage: NSObject { self.published = message.published self.metadata = if let value = message.metadata { KMPAnyJSON(value.codableValue) } else { nil } self.messageType = message.messageType.rawValue + self.customMessageType = message.customMessageType self.error = message.error } @@ -39,5 +40,6 @@ public class KMPMessage: NSObject { @objc public let published: Timetoken @objc public let metadata: KMPAnyJSON? @objc public let messageType: Int + @objc public let customMessageType: String? @objc public let error: Error? } diff --git a/Sources/PubNub/Models/PubNubChannelMetadata.swift b/Sources/PubNub/Models/PubNubChannelMetadata.swift index 76512bad..959beb07 100644 --- a/Sources/PubNub/Models/PubNubChannelMetadata.swift +++ b/Sources/PubNub/Models/PubNubChannelMetadata.swift @@ -31,7 +31,7 @@ public protocol PubNubChannelMetadata { /// All custom fields set on the object var custom: [String: JSONCodableScalar]? { get set } - /// Allows for other PubNubUUIDMetadata objects to transcode between themselves + /// Allows for other PubNubChannelMetadata objects to transcode between themselves init(from other: PubNubChannelMetadata) throws } diff --git a/Sources/PubNub/Models/PubNubMembershipMetadata.swift b/Sources/PubNub/Models/PubNubMembershipMetadata.swift index 55ea0c05..fc2fc383 100644 --- a/Sources/PubNub/Models/PubNubMembershipMetadata.swift +++ b/Sources/PubNub/Models/PubNubMembershipMetadata.swift @@ -15,13 +15,21 @@ import Foundation /// A object capable of representing PubNub Membership Metadata public protocol PubNubMembershipMetadata { /// The unique identifier of the associated UUID + @available(*, deprecated, renamed: "userMetadataId") var uuidMetadataId: String { get } + /// The unique identifier of the associated User + var userMetadataId: String { get } /// The unique identifier of the associated Channel var channelMetadataId: String { get } - /// The current state of the MembershipMetadata + /// The current status of the MembershipMetadata var status: String? { get set } + /// The current type of the MembershipMetadata + var type: String? { get set } /// The associated UUID metadata - var uuid: PubNubUUIDMetadata? { get set } + @available(*, deprecated, renamed: "user") + var uuid: PubNubUserMetadata? { get set } + /// The associated User metadata + var user: PubNubUserMetadata? { get set } /// The associated Channel metadata var channel: PubNubChannelMetadata? { get set } /// The last updated timestamp for the object @@ -31,7 +39,7 @@ public protocol PubNubMembershipMetadata { /// All custom fields set on the object var custom: [String: JSONCodableScalar]? { get set } - /// Allows for other PubNubUUIDMetadata objects to transcode between themselves + /// Allows for other PubNubMembershipMetadata objects to transcode between themselves init(from other: PubNubMembershipMetadata) throws } @@ -61,62 +69,112 @@ public extension PubNubMembershipMetadata { /// The default implementation of the `PubNubMembershipMetadata` protocol public struct PubNubMembershipMetadataBase: PubNubMembershipMetadata, Hashable { - public let uuidMetadataId: String + /// The unique identifier of the associated UUID + @available(*, deprecated, renamed: "userMetadataId") + public private(set) var uuidMetadataId: String + /// The unique identifier of the associated Channel public let channelMetadataId: String - + /// The current status of the MembershipMetadata public var status: String? + /// The current type of the MembershipMetadata + public var type: String? + /// The last updated timestamp for the object + public var updated: Date? + /// The caching identifier for the object + public var eTag: String? - var concreteUUID: PubNubUUIDMetadataBase? - public var uuid: PubNubUUIDMetadata? { - get { concreteUUID } - set { - concreteUUID = try? newValue?.transcode() + var concreteUser: PubNubUserMetadataBase? + var concreteChannel: PubNubChannelMetadataBase? + var concreteCustom: [String: JSONCodableScalarType]? + + /// The associated User metadata + public var user: (any PubNubUserMetadata)? { + get { + uuid + } set { + uuid = newValue } } - var concreteChannel: PubNubChannelMetadataBase? + /// The unique identifier of the associated User + public var userMetadataId: String { + get { + uuidMetadataId + } set { + uuidMetadataId = newValue + } + } + + @available(*, deprecated, renamed: "user") + public var uuid: PubNubUserMetadata? { + get { concreteUser } + set { concreteUser = try? newValue?.transcode() } + } + public var channel: PubNubChannelMetadata? { get { concreteChannel } - set { - concreteChannel = try? newValue?.transcode() - } + set { concreteChannel = try? newValue?.transcode() } } - var concreteCustom: [String: JSONCodableScalarType]? public var custom: [String: JSONCodableScalar]? { get { return concreteCustom } set { concreteCustom = newValue?.mapValues { $0.scalarValue } } } - public var updated: Date? - public var eTag: String? - + @available(*, deprecated, renamed: "init(userMetadataId:channelMetadataId:status:type:user:channel:custom:updated:eTag:)") public init( uuidMetadataId: String, channelMetadataId: String, status: String? = nil, - uuid: PubNubUUIDMetadataBase? = nil, + type: String? = nil, + uuid: PubNubUserMetadataBase? = nil, channel: PubNubChannelMetadataBase? = nil, custom concreteCustom: [String: JSONCodableScalar]? = nil, updated: Date? = nil, eTag: String? = nil ) { - self.uuidMetadataId = uuidMetadataId + self.init( + userMetadataId: uuidMetadataId, + channelMetadataId: channelMetadataId, + status: status, + type: type, + user: uuid, + channel: channel, + custom: concreteCustom, + updated: updated, + eTag: eTag + ) + } + + public init( + userMetadataId: String, + channelMetadataId: String, + status: String? = nil, + type: String? = nil, + user: PubNubUserMetadataBase? = nil, + channel: PubNubChannelMetadataBase? = nil, + custom concreteCustom: [String: JSONCodableScalar]? = nil, + updated: Date? = nil, + eTag: String? = nil + ) { + self.uuidMetadataId = userMetadataId self.channelMetadataId = channelMetadataId - self.uuid = uuid + self.uuid = user self.channel = channel self.concreteCustom = concreteCustom?.mapValues { $0.scalarValue } self.status = status + self.type = type self.updated = updated self.eTag = eTag } public init(from other: PubNubMembershipMetadata) throws { self.init( - uuidMetadataId: other.uuidMetadataId, + userMetadataId: other.userMetadataId, channelMetadataId: other.channelMetadataId, status: other.status, - uuid: try other.uuid?.transcode(), + type: other.type, + user: try other.user?.transcode(), channel: try other.channel?.transcode(), custom: other.custom, updated: other.updated, @@ -127,19 +185,21 @@ public struct PubNubMembershipMetadataBase: PubNubMembershipMetadata, Hashable { public init?(from partial: ObjectMetadataPartial, other identifier: String) { if let uuid = partial.uuid { self.init( - uuidMetadataId: uuid.metadataId, + userMetadataId: uuid.metadataId, channelMetadataId: identifier, status: partial.status, - uuid: uuid.metadataObject, + type: partial.type, + user: uuid.metadataObject, custom: partial.custom, updated: partial.updated, eTag: partial.eTag ) } else if let channel = partial.channel { self.init( - uuidMetadataId: identifier, + userMetadataId: identifier, channelMetadataId: channel.metadataId, status: partial.status, + type: partial.type, channel: channel.metadataObject, custom: partial.custom, updated: partial.updated, @@ -156,6 +216,7 @@ extension PubNubMembershipMetadataBase: Codable { case uuid case channel case status + case type case custom case updated case eTag @@ -170,6 +231,9 @@ extension PubNubMembershipMetadataBase: Codable { updated = try container.decodeIfPresent(Date.self, forKey: .updated) eTag = try container.decodeIfPresent(String.self, forKey: .eTag) concreteCustom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom) + status = try container.decodeIfPresent(String.self, forKey: .status) + type = try container.decodeIfPresent(String.self, forKey: .type) + if let concreteChannel = try? container.decodeIfPresent(PubNubChannelMetadataBase.self, forKey: .channel) { self.concreteChannel = concreteChannel channelMetadataId = concreteChannel.metadataId @@ -179,13 +243,13 @@ extension PubNubMembershipMetadataBase: Codable { concreteChannel = nil } - if let concreteUUID = try? container.decodeIfPresent(PubNubUUIDMetadataBase.self, forKey: .uuid) { - self.concreteUUID = concreteUUID + if let concreteUUID = try? container.decodeIfPresent(PubNubUserMetadataBase.self, forKey: .uuid) { + self.concreteUser = concreteUUID uuidMetadataId = concreteUUID.metadataId } else { let uuidContainer = try container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .uuid) uuidMetadataId = try uuidContainer.decode(String.self, forKey: .id) - concreteUUID = nil + concreteUser = nil } } @@ -194,6 +258,8 @@ extension PubNubMembershipMetadataBase: Codable { try container.encodeIfPresent(updated, forKey: .updated) try container.encodeIfPresent(eTag, forKey: .eTag) try container.encodeIfPresent(custom?.mapValues { $0.scalarValue }, forKey: .custom) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(type, forKey: .type) if let channelObject = concreteChannel { try container.encode(channelObject, forKey: .channel) @@ -202,11 +268,11 @@ extension PubNubMembershipMetadataBase: Codable { try channelContainer.encode(channelMetadataId, forKey: .id) } - if let uuidObject = concreteUUID { + if let uuidObject = concreteUser { try container.encode(uuidObject, forKey: .uuid) } else { var uuidContainer = container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .uuid) - try uuidContainer.encode(uuidMetadataId, forKey: .id) + try uuidContainer.encode(userMetadataId, forKey: .id) } } } diff --git a/Sources/PubNub/Models/PubNubObjectMetadataPatcher.swift b/Sources/PubNub/Models/PubNubObjectMetadataPatcher.swift index 00cea468..99e92cba 100644 --- a/Sources/PubNub/Models/PubNubObjectMetadataPatcher.swift +++ b/Sources/PubNub/Models/PubNubObjectMetadataPatcher.swift @@ -18,12 +18,17 @@ public enum PubNubMetadataChange { case customOptional(WritableKeyPath, [String: JSONCodableScalar]?) } +/// Alias for `PubNubUserMetadataChangeset`, maintained for backward compatibility with existing code using `PubNubUUIDMetadataChangeset`. +/// Please update your code to use `PubNubUserMetadataChangeset` directly, as `PubNubUUIDMetadataChangeset` is deprecated and will be removed in a future version. +@available(*, deprecated, message: "Use `PubNubUserMetadataChangeset` instead.") +public typealias PubNubUUIDMetadataChangeset = PubNubUserMetadataChangeset + /// A UUID Metadata changeset that can be used to update existing objects -public struct PubNubUUIDMetadataChangeset { +public struct PubNubUserMetadataChangeset { /// The unique identifier of the object that was changed public let metadataId: String /// The changes that will be made to the object - public let changes: [PubNubMetadataChange] + public let changes: [PubNubMetadataChange] /// The timestamp of the change public let updated: Date /// The cache identifier of the change @@ -32,7 +37,7 @@ public struct PubNubUUIDMetadataChangeset { /// Default init for the object public init( metadataId: String, - changes: [PubNubMetadataChange], + changes: [PubNubMetadataChange], updated: Date, eTag: String ) { @@ -47,7 +52,7 @@ public struct PubNubUUIDMetadataChangeset { /// The changes will be applied only if the ids of the object matches /// - Parameter to: The Object that will be patched /// - Returns: A copy of the object with the patched chagnes, or the passed object if changes could not be applied - public func apply(to object: PubNubUUIDMetadata) -> PubNubUUIDMetadata { + public func apply(to object: PubNubUserMetadata) -> PubNubUserMetadata { guard metadataId == object.metadataId, eTag != object.eTag, updated.timeIntervalSince(object.updated ?? Date.distantPast) > 0 diff --git a/Sources/PubNub/Models/PubNubUUIDMetadata.swift b/Sources/PubNub/Models/PubNubUserMetadata.swift similarity index 69% rename from Sources/PubNub/Models/PubNubUUIDMetadata.swift rename to Sources/PubNub/Models/PubNubUserMetadata.swift index 3a0cf161..89a2225c 100644 --- a/Sources/PubNub/Models/PubNubUUIDMetadata.swift +++ b/Sources/PubNub/Models/PubNubUserMetadata.swift @@ -1,5 +1,5 @@ // -// PubNubUUIDMetadata.swift +// PubNubUserMetadata.swift // // Copyright (c) PubNub Inc. // All rights reserved. @@ -12,15 +12,20 @@ import Foundation // MARK: Outbound Protocol -/// A object capable of representing PubNub UUID Metadata -public protocol PubNubUUIDMetadata { - /// The unique identifier of the UUID +/// Typealias for backward compatibility with existing code using `PubNubUUIDMetadata`. +/// Please update your code to use `PubNubUserMetadata` directly, as `PubNubUUIDMetadata` is deprecated and will be removed in a future version. +@available(*, deprecated, message: "Use `PubNubUserMetadata` instead.") +public typealias PubNubUUIDMetadata = PubNubUserMetadata + +/// A object capable of representing PubNub User Metadata +public protocol PubNubUserMetadata { + /// The unique identifier of the User var metadataId: String { get } - /// The name of the UUID + /// The name of the User var name: String? { get set } - /// The classification of UUIDMetadata + /// The classification of the User var type: String? { get set } - /// The current state of the UUIDMetadata + /// The current state of the User var status: String? { get set } /// The external identifier for the object var externalId: String? { get set } @@ -36,22 +41,22 @@ public protocol PubNubUUIDMetadata { var custom: [String: JSONCodableScalar]? { get set } /// Allows for other PubNubUUIDMetadata objects to transcode between themselves - init(from other: PubNubUUIDMetadata) throws + init(from other: PubNubUserMetadata) throws } -public extension PubNubUUIDMetadata { +public extension PubNubUserMetadata { /// Converts this protocol into a custom type /// - Parameter into: The explicit type for the returned value /// - Returns: The protocol intiailized as a custom type /// - Throws: An error why the custom type was unable to be created using this protocol instance - func transcode(into _: T.Type) throws -> T { + func transcode(into _: T.Type) throws -> T { return try transcode() } /// Converts this protocol into a custom type /// - Returns: The protocol intiailized as a custom type /// - Throws: An error why the custom type was unable to be created using this protocol instance - func transcode() throws -> T { + func transcode() throws -> T { // Check if we're already that object, and return if let custom = self as? T { return custom @@ -63,8 +68,13 @@ public extension PubNubUUIDMetadata { // MARK: Concrete Base Class -/// The default implementation of the `PubNubUUIDMetadata` protocol -public struct PubNubUUIDMetadataBase: PubNubUUIDMetadata, Hashable { +/// Typealias for backward compatibility with existing code using `PubNubUUIDMetadataBase`. +/// Please update your code to use `PubNubUserMetadataBase` directly, as `PubNubUUIDMetadataBase` is deprecated and will be removed in a future version. +@available(*, deprecated, message: "Use `PubNubUserMetadataBase` instead.") +public typealias PubNubUUIDMetadataBase = PubNubUserMetadataBase + +/// The default implementation of the `PubNubUserMetadata` protocol +public struct PubNubUserMetadataBase: PubNubUserMetadata, Hashable { public let metadataId: String public var name: String? public var type: String? @@ -105,7 +115,7 @@ public struct PubNubUUIDMetadataBase: PubNubUUIDMetadata, Hashable { self.eTag = eTag } - public init(from other: PubNubUUIDMetadata) throws { + public init(from other: PubNubUserMetadata) throws { self.init( metadataId: other.metadataId, name: other.name, @@ -121,7 +131,7 @@ public struct PubNubUUIDMetadataBase: PubNubUUIDMetadata, Hashable { } } -extension PubNubUUIDMetadataBase: Codable { +extension PubNubUserMetadataBase: Codable { enum CodingKeys: String, CodingKey { case metadataId = "id" case name diff --git a/Sources/PubNub/Networking/Routers/MembershipObjectsRouter.swift b/Sources/PubNub/Networking/Routers/MembershipObjectsRouter.swift deleted file mode 100644 index 4a5d0fc1..00000000 --- a/Sources/PubNub/Networking/Routers/MembershipObjectsRouter.swift +++ /dev/null @@ -1,12 +0,0 @@ -// -// MembershipObjectsRouter.swift -// -// Copyright (c) PubNub Inc. -// All rights reserved. -// -// This source code is licensed under the license found in the -// LICENSE file in the root directory of this source tree. -// -// - -import Foundation diff --git a/Sources/PubNub/Networking/Routers/ObjectsChannelRouter.swift b/Sources/PubNub/Networking/Routers/ObjectsChannelRouter.swift index dd4c05bf..bd126a93 100644 --- a/Sources/PubNub/Networking/Routers/ObjectsChannelRouter.swift +++ b/Sources/PubNub/Networking/Routers/ObjectsChannelRouter.swift @@ -10,13 +10,17 @@ import Foundation +extension Array where Element == ObjectsChannelRouter.Include { + func values() -> String { + return map { $0.rawValue }.csvString + } +} + public struct ObjectsChannelRouter: HTTPRouter { public enum Endpoint: CustomStringConvertible { - case all( - customFields: Bool, totalCount: Bool, filter: String?, sort: [String], limit: Int?, start: String?, end: String? - ) - case fetch(metadataId: String, customFields: Bool) - case set(metadata: PubNubChannelMetadata, customFields: Bool) + case all(include: [Include]?, totalCount: Bool, filter: String?, sort: [String], limit: Int?, start: String?, end: String?) + case fetch(metadataId: String, include: [Include]?) + case set(metadata: PubNubChannelMetadata, include: [Include]?) case remove(metadataId: String) public var description: String { @@ -42,19 +46,13 @@ public struct ObjectsChannelRouter: HTTPRouter { var custom: [String: JSONCodableScalarType]? } - enum Include { - static let custom = "custom" - static let status = "status" - static let type = "type" - - static func includes(custom: Bool) -> [String] { - var includes = [Include.status, Include.type] - - if custom { - includes.append(Include.custom) - } + public enum Include: String { + case custom + case status + case type - return includes + static func includes(from array: [Include]?) -> String? { + array?.map { $0.rawValue }.csvString } } @@ -96,18 +94,18 @@ public struct ObjectsChannelRouter: HTTPRouter { var query = defaultQueryItems switch endpoint { - case let .all(customFields, totalCount, filter, sort, limit, start, end): + case let .all(includeFields, totalCount, filter, sort, limit, start, end): query.appendIfPresent(key: .filter, value: filter) query.appendIfNotEmpty(key: .sort, value: sort) query.appendIfPresent(key: .limit, value: limit?.description) - query.appendIfPresent(key: .include, value: Include.includes(custom: customFields).csvString) + query.appendIfPresent(key: .include, value: Include.includes(from: includeFields)) query.appendIfPresent(key: .count, value: totalCount ? totalCount.description : nil) query.appendIfPresent(key: .start, value: start?.description) query.appendIfPresent(key: .end, value: end?.description) - case let .fetch(_, customFields): - query.appendIfPresent(key: .include, value: Include.includes(custom: customFields).csvString) - case let .set(_, customFields): - query.appendIfPresent(key: .include, value: Include.includes(custom: customFields).csvString) + case let .fetch(_, includeFields): + query.appendIfPresent(key: .include, value: Include.includes(from: includeFields)) + case let .set(_, includeFields): + query.appendIfPresent(key: .include, value: Include.includes(from: includeFields)) case .remove: break } diff --git a/Sources/PubNub/Networking/Routers/ObjectsMembershipsRouter.swift b/Sources/PubNub/Networking/Routers/ObjectsMembershipsRouter.swift index 4bce6646..1b348d05 100644 --- a/Sources/PubNub/Networking/Routers/ObjectsMembershipsRouter.swift +++ b/Sources/PubNub/Networking/Routers/ObjectsMembershipsRouter.swift @@ -76,13 +76,10 @@ public struct ObjectsMembershipsRouter: HTTPRouter { case uuidType = "uuid.type" case uuidStatus = "uuid.status" case status + case type - static func merge(_ other: [Include]?) -> [String] { - var includes = [Include.status] - - includes.append(contentsOf: other ?? []) - - return includes.map { $0.rawValue } + static func csvString(from includes: [Include]?) -> String? { + return includes?.map { $0.rawValue }.csvString } } @@ -102,12 +99,14 @@ public struct ObjectsMembershipsRouter: HTTPRouter { public struct MembershipChange: JSONCodable, Equatable { let metadataId: String let status: String? + let type: String? let custom: [String: JSONCodableScalar]? // swiftlint:disable:next nesting enum CodingKeys: String, CodingKey { case object = "channel" case status + case type case custom } @@ -116,9 +115,10 @@ public struct ObjectsMembershipsRouter: HTTPRouter { case metadataId = "id" } - public init(metadataId: String, status: String?, custom: [String: JSONCodableScalar]?) { + public init(metadataId: String, status: String?, type: String?, custom: [String: JSONCodableScalar]?) { self.metadataId = metadataId self.status = status + self.type = type self.custom = custom } @@ -126,6 +126,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { let container = try decoder.container(keyedBy: CodingKeys.self) custom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom) status = try container.decodeIfPresent(String.self, forKey: .status) + type = try container.decodeIfPresent(String.self, forKey: .type) let nestedContainer = try container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .object) metadataId = try nestedContainer.decode(String.self, forKey: .metadataId) @@ -135,6 +136,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(custom?.mapValues { $0.scalarValue }, forKey: .custom) try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(type, forKey: .type) var nestedContainer = container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .object) try nestedContainer.encode(metadataId, forKey: .metadataId) @@ -146,9 +148,8 @@ public struct ObjectsMembershipsRouter: HTTPRouter { ) -> Bool { return lhs.metadataId == rhs.metadataId && lhs.status == rhs.status && - lhs.custom? - .mapValues { $0.codableValue } == rhs.custom? - .mapValues { $0.codableValue } + lhs.type == rhs.type && + lhs.custom?.mapValues { $0.codableValue } == rhs.custom?.mapValues { $0.codableValue } } } @@ -168,11 +169,13 @@ public struct ObjectsMembershipsRouter: HTTPRouter { public struct MemberChange: JSONCodable, Equatable { let metadataId: String let status: String? + let type: String? let custom: [String: JSONCodableScalar]? - public init(metadataId: String, status: String?, custom: [String: JSONCodableScalar]?) { + public init(metadataId: String, status: String?, type: String?, custom: [String: JSONCodableScalar]?) { self.metadataId = metadataId self.status = status + self.type = type self.custom = custom } @@ -180,6 +183,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { enum CodingKeys: String, CodingKey { case object = "uuid" case status + case type case custom } @@ -192,6 +196,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { let container = try decoder.container(keyedBy: CodingKeys.self) custom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom) status = try container.decodeIfPresent(String.self, forKey: .status) + type = try container.decodeIfPresent(String.self, forKey: .type) let nestedContainer = try container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .object) metadataId = try nestedContainer.decode(String.self, forKey: .metadataId) @@ -201,6 +206,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(custom?.mapValues { $0.scalarValue }, forKey: .custom) try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(type, forKey: .type) var nestedContainer = container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .object) try nestedContainer.encode(metadataId, forKey: .metadataId) @@ -212,9 +218,8 @@ public struct ObjectsMembershipsRouter: HTTPRouter { ) -> Bool { return lhs.metadataId == rhs.metadataId && lhs.status == rhs.status && - lhs.custom? - .mapValues { $0.codableValue } == rhs.custom? - .mapValues { $0.codableValue } + lhs.type == rhs.type && + lhs.custom?.mapValues { $0.codableValue } == rhs.custom?.mapValues { $0.codableValue } } } @@ -261,7 +266,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { query.appendIfPresent(key: .filter, value: filter) query.appendIfNotEmpty(key: .sort, value: sort) query.appendIfPresent(key: .limit, value: limit?.description) - query.appendIfPresent(key: .include, value: Include.merge(customFields).csvString) + query.appendIfPresent(key: .include, value: Include.csvString(from: customFields)) query.appendIfPresent(key: .count, value: totalCount ? totalCount.description : nil) query.appendIfPresent(key: .start, value: start?.description) query.appendIfPresent(key: .end, value: end?.description) @@ -270,7 +275,7 @@ public struct ObjectsMembershipsRouter: HTTPRouter { query.appendIfPresent(key: .filter, value: filter) query.appendIfNotEmpty(key: .sort, value: sort) query.appendIfPresent(key: .limit, value: limit?.description) - query.appendIfPresent(key: .include, value: Include.merge(customFields).csvString) + query.appendIfPresent(key: .include, value: Include.csvString(from: customFields)) query.appendIfPresent(key: .count, value: totalCount ? totalCount.description : nil) query.appendIfPresent(key: .start, value: start?.description) query.appendIfPresent(key: .end, value: end?.description) @@ -412,8 +417,9 @@ public struct PubNubMembershipsResponsePayload: Codable { public struct ObjectMetadataPartial: Codable { let channel: PartialMetadata? - let uuid: PartialMetadata? + let uuid: PartialMetadata? let status: String? + let type: String? let custom: [String: JSONCodableScalarType]? let updated: Date let eTag: String @@ -427,6 +433,7 @@ public struct ObjectMetadataPartial: Codable { case channel case uuid case status + case type case custom case updated case eTag @@ -438,8 +445,9 @@ public struct ObjectMetadataPartial: Codable { init( channel: PartialMetadata?, - uuid: PartialMetadata?, + uuid: PartialMetadata?, status: String?, + type: String?, updated: Date, eTag: String, custom: [String: JSONCodableScalarType]? @@ -448,6 +456,7 @@ public struct ObjectMetadataPartial: Codable { self.uuid = uuid self.updated = updated self.status = status + self.type = type self.eTag = eTag self.custom = custom } @@ -457,13 +466,13 @@ public struct ObjectMetadataPartial: Codable { custom = try container.decodeIfPresent([String: JSONCodableScalarType].self, forKey: .custom) updated = try container.decode(Date.self, forKey: .updated) eTag = try container.decode(String.self, forKey: .eTag) - status = try container.decodeIfPresent(String.self, forKey: .status) + type = try container.decodeIfPresent(String.self, forKey: .type) if let channel = try? container.decodeIfPresent(PubNubChannelMetadataBase.self, forKey: .channel) { self.channel = .init(metadataId: channel.metadataId, metadataObject: channel) uuid = nil - } else if let uuid = try? container.decodeIfPresent(PubNubUUIDMetadataBase.self, forKey: .uuid) { + } else if let uuid = try? container.decodeIfPresent(PubNubUserMetadataBase.self, forKey: .uuid) { self.uuid = .init(metadataId: uuid.metadataId, metadataObject: uuid) channel = nil } else { @@ -477,6 +486,7 @@ public struct ObjectMetadataPartial: Codable { try container.encode(updated, forKey: .updated) try container.encode(eTag, forKey: .eTag) try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(type, forKey: .type) try container.encodeIfPresent(custom, forKey: .custom) if uuid?.metadataObject != nil || channel?.metadataObject != nil { diff --git a/Sources/PubNub/Networking/Routers/ObjectsUUIDRouter.swift b/Sources/PubNub/Networking/Routers/ObjectsUserRouter.swift similarity index 79% rename from Sources/PubNub/Networking/Routers/ObjectsUUIDRouter.swift rename to Sources/PubNub/Networking/Routers/ObjectsUserRouter.swift index ad85d305..0a9a8f70 100644 --- a/Sources/PubNub/Networking/Routers/ObjectsUUIDRouter.swift +++ b/Sources/PubNub/Networking/Routers/ObjectsUserRouter.swift @@ -10,13 +10,11 @@ import Foundation -public struct ObjectsUUIDRouter: HTTPRouter { +public struct ObjectsUserRouter: HTTPRouter { public enum Endpoint: CustomStringConvertible { - case all( - customFields: Bool, totalCount: Bool, filter: String?, sort: [String], limit: Int?, start: String?, end: String? - ) - case fetch(metadataId: String, customFields: Bool) - case set(metadata: PubNubUUIDMetadata, customFields: Bool) + case all(include: [Include]?, totalCount: Bool, filter: String?, sort: [String], limit: Int?, start: String?, end: String?) + case fetch(metadataId: String, include: [Include]?) + case set(metadata: PubNubUserMetadata, include: [Include]?) case remove(metadataId: String) public var description: String { @@ -55,19 +53,13 @@ public struct ObjectsUUIDRouter: HTTPRouter { } } - enum Include { - static let custom = "custom" - static let status = "status" - static let type = "type" + public enum Include: String { + case custom + case status + case type - static func includes(custom: Bool) -> [String] { - var includes = [Include.status, Include.type] - - if custom { - includes.append(Include.custom) - } - - return includes + static func includes(from array: [Include]?) -> String? { + array?.map { $0.rawValue }.csvString } } @@ -113,14 +105,14 @@ public struct ObjectsUUIDRouter: HTTPRouter { query.appendIfPresent(key: .filter, value: filter) query.appendIfNotEmpty(key: .sort, value: sort) query.appendIfPresent(key: .limit, value: limit?.description) - query.appendIfPresent(key: .include, value: Include.includes(custom: customFields).csvString) + query.appendIfPresent(key: .include, value: Include.includes(from: customFields)) query.appendIfPresent(key: .count, value: totalCount ? totalCount.description : nil) query.appendIfPresent(key: .start, value: start?.description) query.appendIfPresent(key: .end, value: end?.description) case let .fetch(_, customFields): - query.appendIfPresent(key: .include, value: Include.includes(custom: customFields).csvString) + query.appendIfPresent(key: .include, value: Include.includes(from: customFields)) case let .set(_, customFields): - query.appendIfPresent(key: .include, value: Include.includes(custom: customFields).csvString) + query.appendIfPresent(key: .include, value: Include.includes(from: customFields)) case .remove: break } @@ -173,22 +165,18 @@ public struct ObjectsUUIDRouter: HTTPRouter { } } -extension ObjectsUUIDRouter.Endpoint: Equatable { +extension ObjectsUserRouter.Endpoint: Equatable { public static func == ( - lhs: ObjectsUUIDRouter.Endpoint, rhs: ObjectsUUIDRouter.Endpoint + lhs: ObjectsUserRouter.Endpoint, rhs: ObjectsUserRouter.Endpoint ) -> Bool { switch (lhs, rhs) { - case let ( - .all(lhs1, lhs2, lhs3, lhs4, lhs5, lhs6, lhs7), - .all(rhs1, rhs2, rhs3, rhs4, rhs5, rhs6, rhs7) - ): - return lhs1 == rhs1 && lhs2 == rhs2 && lhs3 == rhs3 && - lhs4 == rhs4 && lhs5 == rhs5 && lhs6 == rhs6 && lhs7 == rhs7 + case let (.all(lhs1, lhs2, lhs3, lhs4, lhs5, lhs6, lhs7), .all(rhs1, rhs2, rhs3, rhs4, rhs5, rhs6, rhs7)): + return lhs1 == rhs1 && lhs2 == rhs2 && lhs3 == rhs3 && lhs4 == rhs4 && lhs5 == rhs5 && lhs6 == rhs6 && lhs7 == rhs7 case let (.fetch(lhs1, lhs2), .fetch(rhs1, rhs2)): return lhs1 == rhs1 && lhs2 == rhs2 case let (.set(lhs1, lhs2), .set(rhs1, rhs2)): - let lhsUser = try? PubNubUUIDMetadataBase(from: lhs1) - let rhsUser = try? PubNubUUIDMetadataBase(from: rhs1) + let lhsUser = try? PubNubUserMetadataBase(from: lhs1) + let rhsUser = try? PubNubUserMetadataBase(from: rhs1) return lhsUser == rhsUser && lhs2 == rhs2 case let (.remove(lhsParam), .remove(rhsParam)): return lhsParam == rhsParam @@ -200,14 +188,14 @@ extension ObjectsUUIDRouter.Endpoint: Equatable { // MARK: - Response Decoder -public typealias PubNubUUIDsMetadataResponseDecoder = FetchMultipleValueResponseDecoder +public typealias PubNubUsersMetadataResponseDecoder = FetchMultipleValueResponseDecoder public struct FetchMultipleValueResponseDecoder: ResponseDecoder { public typealias Payload = FetchMultipleResponse public init() {} } -public typealias PubNubUUIDMetadataResponseDecoder = FetchSingleValueResponseDecoder +public typealias PubNubUserMetadataResponseDecoder = FetchSingleValueResponseDecoder public struct FetchSingleValueResponseDecoder: ResponseDecoder { public typealias Payload = FetchSingleResponse diff --git a/Sources/PubNub/Networking/Routers/Subscribe Payloads/SubscribeObjectPayload.swift b/Sources/PubNub/Networking/Routers/Subscribe Payloads/SubscribeObjectPayload.swift index 951224bc..c89b23e4 100644 --- a/Sources/PubNub/Networking/Routers/Subscribe Payloads/SubscribeObjectPayload.swift +++ b/Sources/PubNub/Networking/Routers/Subscribe Payloads/SubscribeObjectPayload.swift @@ -53,7 +53,7 @@ extension SubscribeObjectMetadataPayload: Codable { switch (type, event) { case (.uuid, .set): subscribeEvent = .uuidMetadataSet( - try container.decode(PubNubUUIDMetadataChangeset.self, forKey: .subscribeEvent) + try container.decode(PubNubUserMetadataChangeset.self, forKey: .subscribeEvent) ) case (.uuid, .delete): let nestedContainer = try container.nestedContainer(keyedBy: NestedCodingKeys.self, forKey: .subscribeEvent) @@ -103,9 +103,9 @@ extension SubscribeObjectMetadataPayload: Codable { } } -// MARK: - PubNubUUIDMetadataChangeset Coders +// MARK: - PubNubUserMetadataChangeset Coders -extension PubNubUUIDMetadataChangeset: Codable { +extension PubNubUserMetadataChangeset: Codable { enum CodingKeys: String, CodingKey { case metadataId = "id" case name @@ -125,7 +125,7 @@ extension PubNubUUIDMetadataChangeset: Codable { updated = try container.decode(Date.self, forKey: .updated) eTag = try container.decode(String.self, forKey: .eTag) - var changes = [PubNubMetadataChange]() + var changes = [PubNubMetadataChange]() if container.contains(.name) { changes.append(.stringOptional(\.name, try container.decodeIfPresent(String.self, forKey: .name))) } diff --git a/Tests/PubNubContractTest/PubNubContractTestCase.swift b/Tests/PubNubContractTest/PubNubContractTestCase.swift index 89bc86f8..29ba3250 100644 --- a/Tests/PubNubContractTest/PubNubContractTestCase.swift +++ b/Tests/PubNubContractTest/PubNubContractTestCase.swift @@ -250,7 +250,7 @@ let defaultPublishKey = "demo-36" /// Objects acceptance testins. PubNubObjectsContractTests().setup() PubNubObjectsChannelMetadataContractTestSteps().setup() - PubNubObjectsUUIDMetadataContractTestSteps().setup() + PubNubObjectsUserMetadataContractTestSteps().setup() PubNubObjectsMembershipsContractTestSteps().setup() PubNubObjectsMembersContractTestSteps().setup() } diff --git a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsChannelMetadataContractTestSteps.swift b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsChannelMetadataContractTestSteps.swift index 552992d7..2cafc460 100644 --- a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsChannelMetadataContractTestSteps.swift +++ b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsChannelMetadataContractTestSteps.swift @@ -85,7 +85,7 @@ public class PubNubObjectsChannelMetadataContractTestSteps: PubNubObjectsContrac return } - self.client.remove(channel: channelMetadataId) { result in + self.client.removeChannelMetadata(channelMetadataId) { result in switch result { case let .success(removedChannelMetadataId): self.handleResult(result: removedChannelMetadataId) diff --git a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsContractTests.swift b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsContractTests.swift index 831b413d..17847329 100644 --- a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsContractTests.swift +++ b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsContractTests.swift @@ -15,7 +15,7 @@ import PubNubSDK @objc public class PubNubObjectsContractTests: PubNubContractTestCase { public static var membershipMetadata: [String: PubNubTestMembershipForAction?] = [:] public static var channelsMetadata: [String: PubNubChannelMetadata?] = [:] - public static var uuidsMetadata: [String: PubNubUUIDMetadata?] = [:] + public static var uuidsMetadata: [String: PubNubUserMetadata?] = [:] private static var _setUserIdAsCurrentUser: Bool = false public var membershipsMetadata: [String: PubNubTestMembershipForAction?] { @@ -28,7 +28,7 @@ import PubNubSDK set { Self.channelsMetadata = newValue } } - public var uuidsMetadata: [String: PubNubUUIDMetadata?] { + public var uuidsMetadata: [String: PubNubUserMetadata?] { get { Self.uuidsMetadata } set { Self.uuidsMetadata = newValue } } @@ -129,7 +129,7 @@ import PubNubSDK XCTAssertNotNil(uuidMetadata.metadataId) if usedDataType == "id" { - self.uuidsMetadata[uuidMetadata.metadataId] = PubNubUUIDMetadataBase(metadataId: uuidMetadata.metadataId) + self.uuidsMetadata[uuidMetadata.metadataId] = PubNubUserMetadataBase(metadataId: uuidMetadata.metadataId) } else { self.uuidsMetadata[uuidMetadata.metadataId] = uuidMetadata } diff --git a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsTestHelpers.swift b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsTestHelpers.swift index adbd75e6..f8691845 100644 --- a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsTestHelpers.swift +++ b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsTestHelpers.swift @@ -38,15 +38,15 @@ extension PubNubContractTestCase { /// Retrieve `UUID metadata` object information using owner name. /// /// - Parameter name: Entity name which is the same as name of file in which it is stored. - /// - Returns: Parsed `PubNubUUIDMetadata` object or `nil` in case of parse / load error. - func uuidMetadata(with name: String) -> PubNubUUIDMetadata? { - guard let uuidData = loadDataFile(entityDataPathByName(name)) else { return nil } - guard let uuidMetadata = try? Constant.jsonDecoder.decode(PubNubUUIDMetadataBase.self, from: uuidData) else { + /// - Returns: Parsed `PubNubUserMetadata` object or `nil` in case of parse / load error. + func uuidMetadata(with name: String) -> PubNubUserMetadata? { + guard let userData = loadDataFile(entityDataPathByName(name)) else { return nil } + guard let userMetadata = try? Constant.jsonDecoder.decode(PubNubUserMetadataBase.self, from: userData) else { XCTAssert(false, "Unable to load / parse data for '\(name)' persona.") return nil } - return uuidMetadata + return userMetadata } /// Retrieve `membership metadata` object information using owner name. diff --git a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsUUIDMetadataContractTestSteps.swift b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsUserMetadataContractTestSteps.swift similarity index 53% rename from Tests/PubNubContractTest/Steps/Objects/PubNubObjectsUUIDMetadataContractTestSteps.swift rename to Tests/PubNubContractTest/Steps/Objects/PubNubObjectsUserMetadataContractTestSteps.swift index cbce935b..96e6be76 100644 --- a/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsUUIDMetadataContractTestSteps.swift +++ b/Tests/PubNubContractTest/Steps/Objects/PubNubObjectsUserMetadataContractTestSteps.swift @@ -13,12 +13,12 @@ import Foundation import PubNubSDK import XCTest -public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTests { +public class PubNubObjectsUserMetadataContractTestSteps: PubNubObjectsContractTests { override public func setup() { startCucumberHookEventsListening() When("^I get the UUID metadata(.*)$") { args, _ in - let fetchUUIDMetadataExpect = self.expectation(description: "Fetch UUID metadata response") + let fetchUserMetadataExpect = self.expectation(description: "Fetch UUID metadata response") var includeCustom = false let uuidMetadata = self.uuidsMetadata.compactMap { $1 }.first @@ -31,9 +31,9 @@ public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTe includeCustom = flags.contains("with custom") } - self.client.fetch( - uuid: self.setUserIdAsCurrentUser ? nil : uuidMetadataId, - include: includeCustom + self.client.fetchUserMetadata( + self.setUserIdAsCurrentUser ? nil : uuidMetadataId, + include: PubNub.UserIncludeFields(custom: true) ) { result in switch result { case let .success(metadata): @@ -42,12 +42,12 @@ public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTe self.handleResult(result: error) } - fetchUUIDMetadataExpect.fulfill() + fetchUserMetadataExpect.fulfill() } - self.wait(for: [fetchUUIDMetadataExpect], timeout: 60.0) + self.wait(for: [fetchUserMetadataExpect], timeout: 60.0) - let result = self.lastResult() as? PubNubUUIDMetadata + let result = self.lastResult() as? PubNubUserMetadata XCTAssertNotNil(result, "Fetch UUID metadata didn't returned any response or it had unexpected format") if includeCustom { @@ -56,36 +56,36 @@ public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTe } When("I set the UUID metadata") { _, _ in - let setUUIDExpect = self.expectation(description: "Set UUID metadata response") + let setUserMetadataExpect = self.expectation(description: "Set UUID metadata response") let uuidMetadata = self.uuidsMetadata.compactMap { $1 }.first - self.client.set(uuid: uuidMetadata!) { result in + self.client.setUserMetadata(uuidMetadata!) { result in switch result { case let .success(metadata): self.handleResult(result: metadata) case let .failure(error): self.handleResult(result: error) } - setUUIDExpect.fulfill() + setUserMetadataExpect.fulfill() } - self.wait(for: [setUUIDExpect], timeout: 60.0) + self.wait(for: [setUserMetadataExpect], timeout: 60.0) - let result = self.lastResult() as? PubNubUUIDMetadata + let result = self.lastResult() as? PubNubUserMetadata XCTAssertNotNil(result, "Set UUID metadata didn't returned any response or it had unexpected format") } When("^I remove the UUID metadata(.*)$") { args, _ in - let uuidMetadata = self.uuidsMetadata.compactMap { $1 }.first - var metadataId = uuidMetadata?.metadataId + let userMetadata = self.uuidsMetadata.compactMap { $1 }.first + var metadataId = userMetadata?.metadataId if args?.count == 1, let flags = args?.first, flags.contains("current user") { metadataId = nil } - let removeUUIDMetadataExpect = self.expectation(description: "Remove UUID metadata response") + let removeUserMetadataExpect = self.expectation(description: "Remove UUID metadata response") - self.client.remove(uuid: metadataId) { result in + self.client.removeUserMetadata(metadataId) { result in switch result { case let .success(removedUUID): self.handleResult(result: removedUUID) @@ -93,28 +93,28 @@ public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTe self.handleResult(result: error) } - removeUUIDMetadataExpect.fulfill() + removeUserMetadataExpect.fulfill() } - self.wait(for: [removeUUIDMetadataExpect], timeout: 60.0) + self.wait(for: [removeUserMetadataExpect], timeout: 60.0) let result = self.lastResult() as? String XCTAssertNotNil(result, "Remove UUID metadata didn't returned any response or it had unexpected format") - XCTAssertEqual(result, uuidMetadata?.metadataId) + XCTAssertEqual(result, userMetadata?.metadataId) } When("^I get all UUID metadata(.*)$") { args, _ in - let fetchAllUUIDMetadataExpect = self.expectation(description: "Fetch all UUID metadata response") + let fetchAllUserMetadataExpect = self.expectation(description: "Fetch all UUID metadata response") var includeCustom = PubNub.IncludeFields(custom: false, totalCount: false) if args?.count == 1, let flags = args?.first { includeCustom = PubNub.IncludeFields(custom: flags.contains("with custom"), totalCount: false) } - self.client.allUUIDMetadata(include: includeCustom) { result in + self.client.allUserMetadata(include: PubNub.UserIncludeFields(custom: true)) { result in switch result { case let .success(metadata): - for uuidMetadata in metadata.uuids { + for uuidMetadata in metadata.users { XCTAssert( includeCustom.customFields && uuidMetadata.custom != nil || !includeCustom.customFields && uuidMetadata.custom == nil, @@ -127,26 +127,26 @@ public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTe self.handleResult(result: error) } - fetchAllUUIDMetadataExpect.fulfill() + fetchAllUserMetadataExpect.fulfill() } - self.wait(for: [fetchAllUUIDMetadataExpect], timeout: 60.0) + self.wait(for: [fetchAllUserMetadataExpect], timeout: 60.0) } Match(["And"], "^the UUID metadata for '(.*)' persona(.*)$") { args, _ in - guard let result = self.lastResult() as? PubNubUUIDMetadata else { return } - guard let uuidName = args?.first?.lowercased() else { return } - guard let uuidMetadata = self.uuidMetadata(with: uuidName) else { return } - - XCTAssertEqual(result.metadataId, uuidMetadata.metadataId) - XCTAssertEqual(result.name, uuidMetadata.name) - XCTAssertEqual(result.type, uuidMetadata.type) - XCTAssertEqual(result.status, uuidMetadata.status) - XCTAssertEqual(result.externalId, uuidMetadata.externalId) - XCTAssertEqual(result.profileURL, uuidMetadata.profileURL) - XCTAssertEqual(result.email, uuidMetadata.email) - XCTAssertEqual(result.updated, uuidMetadata.updated) - XCTAssertEqual(result.eTag, uuidMetadata.eTag) + guard let result = self.lastResult() as? PubNubUserMetadata else { return } + guard let userName = args?.first?.lowercased() else { return } + guard let userMetadata = self.uuidMetadata(with: userName) else { return } + + XCTAssertEqual(result.metadataId, userMetadata.metadataId) + XCTAssertEqual(result.name, userMetadata.name) + XCTAssertEqual(result.type, userMetadata.type) + XCTAssertEqual(result.status, userMetadata.status) + XCTAssertEqual(result.externalId, userMetadata.externalId) + XCTAssertEqual(result.profileURL, userMetadata.profileURL) + XCTAssertEqual(result.email, userMetadata.email) + XCTAssertEqual(result.updated, userMetadata.updated) + XCTAssertEqual(result.eTag, userMetadata.eTag) if args?.count == 2, let flags = args?.last, flags.contains("contains updated") { XCTAssertNotNil(result.updated) @@ -154,27 +154,7 @@ public class PubNubObjectsUUIDMetadataContractTestSteps: PubNubObjectsContractTe } Match(["And"], "^the response contains list with '(.*)' and '(.*)' UUID metadata$") { _, _ in -// let result = self.lastResult() as? ((uuids:[PubNubUUIDMetadata], next: PubNubHashedPage)) -// XCTAssertNotNil(result, "Fetch all UUID metadata didn't returned any response or it had unexpected format") -// guard let receivedUUIDs = result?.uuids else { return } -// -// XCTAssertEqual(args?.count, 2, "Not all UUID names specified") -// XCTAssertEqual(receivedUUIDs.count, 2) -// -// var uuids: [PubNubUUIDMetadata] = [] -// for userName in args ?? [] { -// guard let uuidMetadata = self.uuidMetadata(with: userName.lowercased()) else { -// XCTAssert(false, "Persona file not parsed.") -// return -// } -// -// uuids.append(uuidMetadata) -// } -// -// for uuidMetadata in uuids { -// XCTAssert(receivedUUIDs.map { $0.metadataId }.contains(uuidMetadata.metadataId), -// "\(uuidMetadata.metadataId) is missing from received UUIDs list.") -// } + } } } diff --git a/Tests/PubNubTests/Extensions/Collection+PubNubTests.swift b/Tests/PubNubTests/Extensions/Collection+PubNubTests.swift index d12e4f5d..6141b151 100644 --- a/Tests/PubNubTests/Extensions/Collection+PubNubTests.swift +++ b/Tests/PubNubTests/Extensions/Collection+PubNubTests.swift @@ -12,7 +12,7 @@ import XCTest final class CollectionPubNubTests: XCTestCase { - func testPubNubUUID() { + func testCSVString() { let csvInput = ["one", "two", "three", "four"] let csvOutput = "one,two,three,four" diff --git a/Tests/PubNubTests/Integration/ChannelObjectsEndpointIntegrationTests.swift b/Tests/PubNubTests/Integration/ChannelObjectsEndpointIntegrationTests.swift index 3bbfc6f5..e331e852 100644 --- a/Tests/PubNubTests/Integration/ChannelObjectsEndpointIntegrationTests.swift +++ b/Tests/PubNubTests/Integration/ChannelObjectsEndpointIntegrationTests.swift @@ -40,8 +40,8 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { metadataId: "testCreateAndFetchEndpoint", name: "Swift ITest" ) - client.set(channel: testChannel) { _ in - client.fetch(channel: testChannel.metadataId) { result in + client.setChannelMetadata(testChannel) { _ in + client.fetchChannelMetadata(testChannel.metadataId) { result in switch result { case let .success(channel): XCTAssertEqual(channel.metadataId, testChannel.metadataId) @@ -64,8 +64,8 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { metadataId: "testDeleteAndCreateEndpoint", name: "Swift ITest" ) - client.remove(channel: testChannel.metadataId) { _ in - client.set(channel: testChannel) { result in + client.removeChannelMetadata(testChannel.metadataId) { _ in + client.setChannelMetadata(testChannel) { result in switch result { case let .success(channel): XCTAssertEqual(channel.metadataId, testChannel.metadataId) @@ -88,8 +88,8 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { metadataId: "testCreateAndDeleteEndpoint", name: "Swift ITest" ) - client.set(channel: testChannel) { _ in - client.remove(channel: testChannel.metadataId) { result in + client.setChannelMetadata(testChannel) { _ in + client.removeChannelMetadata(testChannel.metadataId) { result in switch result { case let .success(metadataId): XCTAssertEqual(metadataId, testChannel.metadataId) @@ -108,21 +108,22 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testFetchMembersUUID", name: "Swift ITest" ) let testChannel = PubNubChannelMetadataBase( metadataId: "testFetchMembersChannel", name: "Swift ITest" ) let membership = PubNubMembershipMetadataBase( - uuidMetadataId: testUser.metadataId, + userMetadataId: testUser.metadataId, channelMetadataId: testChannel.metadataId, - uuid: testUser, channel: testChannel + user: testUser, + channel: testChannel ) - client.set(uuid: testUser) { _ in - client.set(channel: testChannel) { _ in - client.setMembers(channel: testChannel.metadataId, uuids: [membership]) { _ in + client.setUserMetadata(testUser) { _ in + client.setChannelMetadata(testChannel) { _ in + client.setMembers(channel: testChannel.metadataId, users: [membership]) { _ in client.fetchMembers( channel: testChannel.metadataId, include: .init(uuidFields: true, uuidCustomFields: true) @@ -131,7 +132,7 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { case let .success((memberships, _)): XCTAssertTrue( memberships.contains( - where: { $0.channelMetadataId == testChannel.metadataId && $0.uuidMetadataId == testUser.metadataId } + where: { $0.channelMetadataId == testChannel.metadataId && $0.userMetadataId == testUser.metadataId } ) ) case let .failure(error): @@ -151,20 +152,21 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testManageMembersUUID", name: "Swift ITest" ) let testChannel = PubNubChannelMetadataBase( metadataId: "testManageMembersChannel", name: "Swift ITest" ) let membership = PubNubMembershipMetadataBase( - uuidMetadataId: testUser.metadataId, + userMetadataId: testUser.metadataId, channelMetadataId: testChannel.metadataId, - uuid: testUser, channel: testChannel + user: testUser, + channel: testChannel ) - client.set(uuid: testUser) { _ in - client.set(channel: testChannel) { _ in + client.setUserMetadata(testUser) { _ in + client.setChannelMetadata(testChannel) { _ in client.manageMembers( channel: testChannel.metadataId, setting: [membership], @@ -176,7 +178,7 @@ class ChannelObjectsEndpointIntegrationTests: XCTestCase { case let .success((memberships, _)): XCTAssertTrue( memberships.contains( - where: { $0.channelMetadataId == testChannel.metadataId && $0.uuidMetadataId == testUser.metadataId } + where: { $0.channelMetadataId == testChannel.metadataId && $0.userMetadataId == testUser.metadataId } ) ) case let .failure(error): diff --git a/Tests/PubNubTests/Integration/UUIDObjectsEndpointIntegrationTests.swift b/Tests/PubNubTests/Integration/UUIDObjectsEndpointIntegrationTests.swift index 5adc27ef..bdb01f4f 100644 --- a/Tests/PubNubTests/Integration/UUIDObjectsEndpointIntegrationTests.swift +++ b/Tests/PubNubTests/Integration/UUIDObjectsEndpointIntegrationTests.swift @@ -37,7 +37,7 @@ class UUIDObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testUserCreateAndFetchEndpoint", name: "Swift ITest", profileURL: "http://example.com" ) @@ -62,7 +62,7 @@ class UUIDObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testUserDeleteAndCreateEndpoint", name: "Swift ITest" ) @@ -86,7 +86,7 @@ class UUIDObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testUserCreateAndDeleteEndpoint", name: "Swift ITest" ) @@ -110,7 +110,7 @@ class UUIDObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testUserFetchMemberships", name: "Swift ITest" ) let testChannel = PubNubChannelMetadataBase( @@ -155,7 +155,7 @@ class UUIDObjectsEndpointIntegrationTests: XCTestCase { let client = PubNub(configuration: config) - let testUser = PubNubUUIDMetadataBase( + let testUser = PubNubUserMetadataBase( metadataId: "testUpdateMemberships", name: "Swift ITest" ) let testChannel = PubNubChannelMetadataBase( diff --git a/Tests/PubNubTests/Networking/Routers/ObjectsChannelRouterTests.swift b/Tests/PubNubTests/Networking/Routers/ObjectsChannelRouterTests.swift index d845d183..24a81844 100644 --- a/Tests/PubNubTests/Networking/Routers/ObjectsChannelRouterTests.swift +++ b/Tests/PubNubTests/Networking/Routers/ObjectsChannelRouterTests.swift @@ -22,8 +22,10 @@ final class ObjectsChannelRouterTests: XCTestCase { extension ObjectsChannelRouterTests { func testAll_Router() { let router = ObjectsChannelRouter( - .all(customFields: true, totalCount: true, filter: "filter", - sort: ["sort"], limit: 100, start: "start", end: "end"), + .all( + include: [.custom], totalCount: true, filter: "filter", + sort: ["sort"], limit: 100, start: "start", end: "end" + ), configuration: config ) @@ -34,21 +36,26 @@ extension ObjectsChannelRouterTests { func testAll_Router_ValidationError() { let router = ObjectsChannelRouter( - .all(customFields: true, totalCount: true, filter: "filter", - sort: ["sort"], limit: 100, start: "start", end: "end"), + .all( + include: [.custom], totalCount: true, filter: "filter", + sort: ["sort"], limit: 100, start: "start", end: "end" + ), configuration: config ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testAll_Success() { let expectation = self.expectation(description: "Fetch All Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_channel_all_success"]), - let firstDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:55.44977Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:59.326105Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_channel_all_success"]), + let firstDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:55.44977Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:59.326105Z") else { return XCTFail("Could not create mock url session") } @@ -62,9 +69,17 @@ extension ObjectsChannelRouterTests { custom: ["info": "JMGXDNYF"], updated: lastDate, eTag: "AeH55Y3T0a78Ew" ) - let page = PubNubHashedPageBase(start: "NextPage", end: "PrevPage", totalCount: 2) + let page = PubNubHashedPageBase( + start: "NextPage", + end: "PrevPage", + totalCount: 2 + ) - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.allChannelMetadata { result in switch result { case let .success((metadataObjects, nextPage)): @@ -87,8 +102,8 @@ extension ObjectsChannelRouterTests { } let testPage = PubNubHashedPageBase(totalCount: 0) - let pubnub = PubNub(configuration: config, session: sessions.session) + pubnub.allChannelMetadata { result in switch result { case let .success((metadataObjects, nextPage)): @@ -110,7 +125,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.allChannelMetadata { result in switch result { case .success: @@ -131,7 +150,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.allChannelMetadata { result in switch result { case .success: @@ -152,7 +175,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.allChannelMetadata { result in switch result { case .success: @@ -173,7 +200,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.allChannelMetadata { result in switch result { case .success: @@ -192,8 +223,10 @@ extension ObjectsChannelRouterTests { extension ObjectsChannelRouterTests { func testFetch_Router() { - let router = ObjectsChannelRouter(.fetch(metadataId: "OtherUser", customFields: true), - configuration: config) + let router = ObjectsChannelRouter( + .fetch(metadataId: "OtherUser", include: [.custom]), + configuration: config + ) XCTAssertEqual(router.endpoint.description, "Fetch Metadata for a Channel") XCTAssertEqual(router.category, "Fetch Metadata for a Channel") @@ -201,17 +234,23 @@ extension ObjectsChannelRouterTests { } func testFetch_Router_ValidationError() { - let router = ObjectsChannelRouter(.fetch(metadataId: "", customFields: true), configuration: config) + let router = ObjectsChannelRouter( + .fetch(metadataId: "", include: [.custom]), + configuration: config + ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testFetch_Success() { let expectation = self.expectation(description: "Fetch Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_channel_fetch_success"]), - let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_channel_fetch_success"]), + let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") else { return XCTFail("Could not create mock url session") } @@ -223,8 +262,12 @@ extension ObjectsChannelRouterTests { updated: firstDate, eTag: "AfuB8q7/s+qCwAE" ) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(channel: "TestChannel") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchChannelMetadata("TestChannel") { result in switch result { case let .success(responseObject): XCTAssertEqual(try? responseObject.transcode(), testObject) @@ -244,8 +287,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(channel: "TestChannel") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchChannelMetadata("TestChannel") { result in switch result { case .success: XCTFail("Request should fail.") @@ -265,8 +312,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(channel: "TestChannel") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchChannelMetadata("TestChannel") { result in switch result { case .success: XCTFail("Request should fail.") @@ -286,8 +337,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(channel: "TestChannel") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchChannelMetadata("TestChannel") { result in switch result { case .success: XCTFail("Request should fail.") @@ -307,8 +362,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(channel: "TestChannel") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchChannelMetadata("TestChannel") { result in switch result { case .success: XCTFail("Request should fail.") @@ -328,8 +387,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(channel: "TestChannel") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchChannelMetadata("TestChannel") { result in switch result { case .success: XCTFail("Request should fail.") @@ -347,7 +410,10 @@ extension ObjectsChannelRouterTests { extension ObjectsChannelRouterTests { func testSet_Router() { - let router = ObjectsChannelRouter(.set(metadata: testChannel, customFields: true), configuration: config) + let router = ObjectsChannelRouter( + .set(metadata: testChannel, include: [.custom]), + configuration: config + ) XCTAssertEqual(router.endpoint.description, "Set Metadata for a Channel") XCTAssertEqual(router.category, "Set Metadata for a Channel") @@ -355,17 +421,23 @@ extension ObjectsChannelRouterTests { } func testSet_Router_ValidationError() { - let router = ObjectsChannelRouter(.set(metadata: invalidUser, customFields: true), configuration: config) + let router = ObjectsChannelRouter( + .set(metadata: invalidUser, include: [.custom]), + configuration: config + ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testSet_Success() { let expectation = self.expectation(description: "Create Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_channel_fetch_success"]), - let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_channel_fetch_success"]), + let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") else { return XCTFail("Could not create mock url session") } @@ -377,8 +449,12 @@ extension ObjectsChannelRouterTests { updated: firstDate, eTag: "AfuB8q7/s+qCwAE" ) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case let .success(responseObject): XCTAssertEqual(try? responseObject.transcode(), testObject) @@ -398,8 +474,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -419,8 +499,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -440,8 +524,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -461,8 +549,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -482,8 +574,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -503,8 +599,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -524,8 +624,12 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(channel: testChannel) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setChannelMetadata(testChannel) { result in switch result { case .success: XCTFail("Request should fail.") @@ -553,8 +657,10 @@ extension ObjectsChannelRouterTests { func testRemove_Router_ValidationError() { let router = ObjectsChannelRouter(.remove(metadataId: ""), configuration: config) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testRemove_Success() { @@ -564,7 +670,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.remove(channel: "TestChannel") { result in switch result { case let .success(metadataId): @@ -585,7 +695,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.remove(channel: "TestChannel") { result in switch result { case .success: @@ -606,7 +720,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.remove(channel: "TestChannel") { result in switch result { case .success: @@ -627,7 +745,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.remove(channel: "TestChannel") { result in switch result { case .success: @@ -648,7 +770,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.remove(channel: "TestChannel") { result in switch result { case .success: @@ -669,7 +795,11 @@ extension ObjectsChannelRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + pubnub.remove(channel: "TestChannel") { result in switch result { case .success: diff --git a/Tests/PubNubTests/Networking/Routers/ObjectsMembershipsRouterTests.swift b/Tests/PubNubTests/Networking/Routers/ObjectsMembershipsRouterTests.swift index 3815db0c..ff0ce30e 100644 --- a/Tests/PubNubTests/Networking/Routers/ObjectsMembershipsRouterTests.swift +++ b/Tests/PubNubTests/Networking/Routers/ObjectsMembershipsRouterTests.swift @@ -14,7 +14,7 @@ import XCTest final class ObjectsMembershipsRouterTests: XCTestCase { let config = PubNubConfiguration(publishKey: "FakeTestString", subscribeKey: "FakeTestString", userId: UUID().uuidString) let testChannel = PubNubChannelMetadataBase(name: "TestChannel") - let testUser = PubNubUUIDMetadataBase(name: "TestUser") + let testUser = PubNubUserMetadataBase(name: "TestUser") } // MARK: - Fetch Memberships Tests @@ -22,8 +22,10 @@ final class ObjectsMembershipsRouterTests: XCTestCase { extension ObjectsMembershipsRouterTests { func testMembershipFetch_Router() { let router = ObjectsMembershipsRouter( - .fetchMemberships(uuidMetadataId: "TestUser", customFields: [], totalCount: false, - filter: nil, sort: [], limit: nil, start: nil, end: nil), + .fetchMemberships( + uuidMetadataId: "TestUser", customFields: [], + totalCount: false, filter: nil, sort: [], limit: nil, start: nil, end: nil + ), configuration: config ) @@ -41,17 +43,20 @@ extension ObjectsMembershipsRouterTests { configuration: config ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testMembershipFetch_Success() { let expectation = self.expectation(description: "Fetch Memberships Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_membership_success"]), - let channeDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), - let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_membership_success"]), + let channeDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), + let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") else { return XCTFail("Could not create mock url session") } @@ -60,23 +65,28 @@ extension ObjectsMembershipsRouterTests { metadataId: "FirstChannel", name: "First Channel", channelDescription: "Channel Description", updated: channeDate, eTag: "ChanneleTag" ) - - let lastChannel = PubNubChannelMetadataBase(metadataId: "LastChannel") + let lastChannel = PubNubChannelMetadataBase( + metadataId: "LastChannel" + ) let firstMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUser", channelMetadataId: firstChannel.metadataId, + userMetadataId: "TestUser", channelMetadataId: firstChannel.metadataId, channel: firstChannel, updated: firstDate, eTag: "FirstETag" ) let lastMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUser", channelMetadataId: "LastChannel", + userMetadataId: "TestUser", channelMetadataId: "LastChannel", channel: lastChannel, updated: lastDate, eTag: "LastETag" ) let page = PubNubHashedPageBase(start: "NextPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetchMemberships(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchMemberships(userId: "TestUser") { result in switch result { case let .success((memberships, nextPage)): XCTAssertEqual(memberships.compactMap { try? $0.transcode() }, [firstMembership, lastMembership]) @@ -98,14 +108,13 @@ extension ObjectsMembershipsRouterTests { } let testPage = PubNubHashedPageBase(start: "NextPage") - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetchMemberships(uuid: "TestUser") { result in + + pubnub.fetchMemberships(userId: "TestUser") { result in switch result { case let .success((memberships, nextPage)): XCTAssertTrue(memberships.isEmpty) XCTAssertEqual(try? nextPage?.transcode(), testPage) - case let .failure(error): XCTFail("Fetch Memberships request failed with error: \(error.localizedDescription)") } @@ -121,9 +130,10 @@ extension ObjectsMembershipsRouterTests { extension ObjectsMembershipsRouterTests { func testMembershipSet_Router() { let router = ObjectsMembershipsRouter( - .setMemberships(uuidMetadataId: "TestUUID", customFields: [], totalCount: true, - changes: .init(set: [], delete: []), - filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last"), + .setMemberships( + uuidMetadataId: "TestUUID", customFields: [], totalCount: true, changes: .init(set: [], delete: []), + filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last" + ), configuration: config ) @@ -134,23 +144,27 @@ extension ObjectsMembershipsRouterTests { func testMembershipSet_Router_ValidationError() { let router = ObjectsMembershipsRouter( - .setMemberships(uuidMetadataId: "", customFields: [], totalCount: true, - changes: .init(set: [], delete: []), - filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last"), + .setMemberships( + uuidMetadataId: "", customFields: [], totalCount: true, changes: .init(set: [], delete: []), + filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last" + ), configuration: config ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testMembershipSet_Success() { let expectation = self.expectation(description: "Update Memberships Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_membership_success"]), - let channeDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), - let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_membership_success"]), + let channeDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), + let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") else { return XCTFail("Could not create mock url session") } @@ -159,22 +173,24 @@ extension ObjectsMembershipsRouterTests { metadataId: "FirstChannel", name: "First Channel", channelDescription: "Channel Description", updated: channeDate, eTag: "ChanneleTag" ) - let lastChannel = PubNubChannelMetadataBase(metadataId: "LastChannel") + let lastChannel = PubNubChannelMetadataBase( + metadataId: "LastChannel" + ) let firstMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUser", channelMetadataId: firstChannel.metadataId, + userMetadataId: "TestUser", channelMetadataId: firstChannel.metadataId, channel: firstChannel, updated: firstDate, eTag: "FirstETag" ) let lastMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUser", channelMetadataId: "LastChannel", + userMetadataId: "TestUser", channelMetadataId: "LastChannel", channel: lastChannel, updated: lastDate, eTag: "LastETag" ) let page = PubNubHashedPageBase(start: "NextPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.setMemberships(uuid: "TestUser", channels: [firstMembership]) { result in + + pubnub.setMemberships(userId: "TestUser", channels: [firstMembership]) { result in switch result { case let .success((memberships, nextPage)): XCTAssertEqual(memberships.compactMap { try? $0.transcode() }, [firstMembership, lastMembership]) @@ -191,10 +207,11 @@ extension ObjectsMembershipsRouterTests { func testMembershipRemove_Success() { let expectation = self.expectation(description: "Update Memberships Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_membership_success"]), - let channeDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), - let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_membership_success"]), + let channeDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), + let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") else { return XCTFail("Could not create mock url session") } @@ -203,22 +220,24 @@ extension ObjectsMembershipsRouterTests { metadataId: "FirstChannel", name: "First Channel", channelDescription: "Channel Description", updated: channeDate, eTag: "ChanneleTag" ) - let lastChannel = PubNubChannelMetadataBase(metadataId: "LastChannel") + let lastChannel = PubNubChannelMetadataBase( + metadataId: "LastChannel" + ) let firstMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUser", channelMetadataId: firstChannel.metadataId, + userMetadataId: "TestUser", channelMetadataId: firstChannel.metadataId, channel: firstChannel, updated: firstDate, eTag: "FirstETag" ) let lastMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUser", channelMetadataId: "LastChannel", + userMetadataId: "TestUser", channelMetadataId: "LastChannel", channel: lastChannel, updated: lastDate, eTag: "LastETag" ) let page = PubNubHashedPageBase(start: "NextPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.removeMemberships(uuid: "TestUser", channels: [firstMembership]) { result in + + pubnub.removeMemberships(userId: "TestUser", channels: [firstMembership]) { result in switch result { case let .success((memberships, nextPage)): XCTAssertEqual(memberships.compactMap { try? $0.transcode() }, [firstMembership, lastMembership]) @@ -238,8 +257,10 @@ extension ObjectsMembershipsRouterTests { extension ObjectsMembershipsRouterTests { func testFetchMembers_Router() { let router = ObjectsMembershipsRouter( - .fetchMembers(channelMetadataId: "TestUser", customFields: [], totalCount: false, - filter: nil, sort: [], limit: nil, start: nil, end: nil), + .fetchMembers( + channelMetadataId: "TestUser", customFields: [], totalCount: false, filter: nil, + sort: [], limit: nil, start: nil, end: nil + ), configuration: config ) @@ -250,48 +271,55 @@ extension ObjectsMembershipsRouterTests { func testFetchMembers_Router_ValidationError() { let router = ObjectsMembershipsRouter( - .fetchMembers(channelMetadataId: "", customFields: [], totalCount: false, - filter: nil, sort: [], limit: nil, start: nil, end: nil), + .fetchMembers( + channelMetadataId: "", customFields: [], totalCount: false, filter: nil, + sort: [], limit: nil, start: nil, end: nil + ), configuration: config ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testFetchMember_Success() { let expectation = self.expectation(description: "Fetch Members Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_members_success"]), - let uuidDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), - let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_members_success"]), + let uuidDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), + let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") else { return XCTFail("Could not create mock url session") } - let firstUUID = PubNubUUIDMetadataBase( + let firstUser = PubNubUserMetadataBase( metadataId: "FirstUser", name: "First User", updated: uuidDate, eTag: "UserETag" ) - let lastUUID = PubNubUUIDMetadataBase(metadataId: "LastUser") - + let lastUser = PubNubUserMetadataBase( + metadataId: "LastUser" + ) + let firstMembership = PubNubMembershipMetadataBase( - uuidMetadataId: firstUUID.metadataId, channelMetadataId: "TestChannel", + userMetadataId: firstUser.metadataId, channelMetadataId: "TestChannel", status: "Test Status", - uuid: firstUUID, + user: firstUser, updated: firstDate, eTag: "FirstETag" ) let lastMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "LastUser", channelMetadataId: "TestChannel", + userMetadataId: "LastUser", channelMetadataId: "TestChannel", status: "Test Status", - uuid: lastUUID, + user: lastUser, custom: ["starred": true], updated: lastDate, eTag: "LastETag" ) let page = PubNubHashedPageBase(start: "NextPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) + pubnub.fetchMembers(channel: "TestChannel") { result in switch result { case let .success((memberships, nextPage)): @@ -318,14 +346,13 @@ extension ObjectsMembershipsRouterTests { } let testPage = PubNubHashedPageBase(start: "NextPage") - let pubnub = PubNub(configuration: config, session: sessions.session) + pubnub.fetchMembers(channel: "TestChannel") { result in switch result { case let .success((memberships, nextPage)): XCTAssertTrue(memberships.isEmpty) XCTAssertEqual(try? nextPage?.transcode(), testPage) - case let .failure(error): XCTFail("Fetch Memberships request failed with error: \(error.localizedDescription)") } @@ -341,9 +368,10 @@ extension ObjectsMembershipsRouterTests { extension ObjectsMembershipsRouterTests { func testMembersSet_Router() { let router = ObjectsMembershipsRouter( - .setMembers(channelMetadataId: "TestUUID", customFields: [], totalCount: true, - changes: .init(set: [], delete: []), - filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last"), + .setMembers( + channelMetadataId: "TestUUID", customFields: [], totalCount: true, changes: .init(set: [], delete: []), + filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last" + ), configuration: config ) @@ -354,49 +382,54 @@ extension ObjectsMembershipsRouterTests { func testMembersSet_Router_ValidationError() { let router = ObjectsMembershipsRouter( - .setMembers(channelMetadataId: "", customFields: [], totalCount: true, - changes: .init(set: [], delete: []), - filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last"), + .setMembers( + channelMetadataId: "", customFields: [], totalCount: true, changes: .init(set: [], delete: []), + filter: "filter", sort: ["sort"], limit: 100, start: "Next", end: "last" + ), configuration: config ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testMember_Set_Success() { let expectation = self.expectation(description: "Set Members Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_members_success"]), - let uuidDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), - let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_members_success"]), + let uuidDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), + let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") else { return XCTFail("Could not create mock url session") } - let firstUUID = PubNubUUIDMetadataBase( + let firstUser = PubNubUserMetadataBase( metadataId: "FirstUser", name: "First User", updated: uuidDate, eTag: "UserETag" ) - let lastUUID = PubNubUUIDMetadataBase(metadataId: "LastUser") - + let lastUser = PubNubUserMetadataBase( + metadataId: "LastUser" + ) let firstMembership = PubNubMembershipMetadataBase( - uuidMetadataId: firstUUID.metadataId, channelMetadataId: "TestChannel", + userMetadataId: firstUser.metadataId, channelMetadataId: "TestChannel", status: "Test Status", - uuid: firstUUID, + user: firstUser, updated: firstDate, eTag: "FirstETag" ) let lastMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "LastUser", channelMetadataId: "TestChannel", + userMetadataId: "LastUser", channelMetadataId: "TestChannel", status: "Test Status", - uuid: lastUUID, + user: lastUser, custom: ["starred": true], updated: lastDate, eTag: "LastETag" ) let page = PubNubHashedPageBase(start: "NextPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) + pubnub.setMembers(channel: "TestChannel", uuids: [firstMembership]) { result in switch result { case let .success((memberships, nextPage)): @@ -414,36 +447,38 @@ extension ObjectsMembershipsRouterTests { func testMember_Remove_Success() { let expectation = self.expectation(description: "Remove Members Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_members_success"]), - let uuidDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), - let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_members_success"]), + let uuidDate = DateFormatter.iso8601.date(from: "2019-09-29T13:07:45.807503Z"), + let firstDate = DateFormatter.iso8601.date(from: "2019-10-02T18:07:52.858703Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-09-29T19:46:28.84402Z") else { return XCTFail("Could not create mock url session") } - let firstUUID = PubNubUUIDMetadataBase( + let firstUser = PubNubUserMetadataBase( metadataId: "FirstUser", name: "First User", updated: uuidDate, eTag: "UserETag" ) - let lastUUID = PubNubUUIDMetadataBase(metadataId: "LastUser") - + let lastUser = PubNubUserMetadataBase( + metadataId: "LastUser" + ) let firstMembership = PubNubMembershipMetadataBase( - uuidMetadataId: firstUUID.metadataId, channelMetadataId: "TestChannel", + userMetadataId: firstUser.metadataId, channelMetadataId: "TestChannel", status: "Test Status", - uuid: firstUUID, + user: firstUser, updated: firstDate, eTag: "FirstETag" ) let lastMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "LastUser", channelMetadataId: "TestChannel", + userMetadataId: "LastUser", channelMetadataId: "TestChannel", status: "Test Status", - uuid: lastUUID, + user: lastUser, custom: ["starred": true], updated: lastDate, eTag: "LastETag" ) let page = PubNubHashedPageBase(start: "NextPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) + pubnub.setMembers(channel: "TestChannel", uuids: [firstMembership]) { result in switch result { case let .success((memberships, nextPage)): diff --git a/Tests/PubNubTests/Networking/Routers/ObjectsUUIDRouterTests.swift b/Tests/PubNubTests/Networking/Routers/ObjectsUserRouterTests.swift similarity index 75% rename from Tests/PubNubTests/Networking/Routers/ObjectsUUIDRouterTests.swift rename to Tests/PubNubTests/Networking/Routers/ObjectsUserRouterTests.swift index 7ae7eba7..b474b54c 100644 --- a/Tests/PubNubTests/Networking/Routers/ObjectsUUIDRouterTests.swift +++ b/Tests/PubNubTests/Networking/Routers/ObjectsUserRouterTests.swift @@ -11,19 +11,21 @@ @testable import PubNubSDK import XCTest -final class ObjectsUUIDRouterTests: XCTestCase { +final class ObjectsUserRouterTests: XCTestCase { let config = PubNubConfiguration(publishKey: "FakeTestString", subscribeKey: "FakeTestString", userId: UUID().uuidString) - let testUser = PubNubUUIDMetadataBase(name: "TestUser") - let invalidUser = PubNubUUIDMetadataBase(name: "") + let testUser = PubNubUserMetadataBase(name: "TestUser") + let invalidUser = PubNubUserMetadataBase(name: "") } // MARK: - All Tests -extension ObjectsUUIDRouterTests { +extension ObjectsUserRouterTests { func testAll_Router() { - let router = ObjectsUUIDRouter( - .all(customFields: true, totalCount: true, filter: "filter", - sort: ["sort"], limit: 100, start: "start", end: "end"), + let router = ObjectsUserRouter( + .all( + include: [.custom], totalCount: true, filter: "filter", + sort: ["sort"], limit: 100, start: "start", end: "end" + ), configuration: config ) @@ -33,39 +35,45 @@ extension ObjectsUUIDRouterTests { } func testAll_Router_ValidationError() { - let router = ObjectsUUIDRouter( - .all(customFields: true, totalCount: true, filter: "filter", - sort: ["sort"], limit: 100, start: "start", end: "end"), + let router = ObjectsUserRouter( + .all( + include: [.custom], totalCount: true, filter: "filter", + sort: ["sort"], limit: 100, start: "start", end: "end" + ), configuration: config ) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testAll_Success() { let expectation = self.expectation(description: "Fetch All Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_uuid_all_success"]), - let firstDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:55.44977Z"), - let lastDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:59.326105Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_uuid_all_success"]), + let firstDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:55.44977Z"), + let lastDate = DateFormatter.iso8601.date(from: "2019-08-18T11:25:59.326105Z") else { return XCTFail("Could not create mock url session") } - let firstTest = PubNubUUIDMetadataBase( + let firstTest = PubNubUserMetadataBase( metadataId: "WGWPWPJBRJ", name: "HNNCTGRURF", updated: firstDate, eTag: "AY/Cz7edr46A3wE" ) - let lastTest = PubNubUUIDMetadataBase( + let lastTest = PubNubUserMetadataBase( metadataId: "OSPULBRLGN", name: "VDUVIGRMWF", custom: ["string": "String", "int": 1, "double": 1.1, "bool": true], updated: lastDate, eTag: "AeH55Y3T0a78Ew" ) + let page = PubNubHashedPageBase(start: "NextPage", end: "PrevPage", totalCount: 2) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.allUUIDMetadata { result in + + pubnub.allUserMetadata { result in switch result { case let .success((metadataObjects, nextPage)): XCTAssertEqual(metadataObjects.compactMap { try? $0.transcode() }, [firstTest, lastTest]) @@ -89,7 +97,7 @@ extension ObjectsUUIDRouterTests { let testPage = PubNubHashedPageBase(start: "NextPage") let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.allUUIDMetadata { result in + pubnub.allUserMetadata { result in switch result { case let .success((metadataObjects, nextPage)): XCTAssertTrue(metadataObjects.isEmpty) @@ -111,7 +119,7 @@ extension ObjectsUUIDRouterTests { } let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.allUUIDMetadata { result in + pubnub.allUserMetadata { result in switch result { case .success: XCTFail("Request should fail.") @@ -132,7 +140,7 @@ extension ObjectsUUIDRouterTests { } let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.allUUIDMetadata { result in + pubnub.allUserMetadata { result in switch result { case .success: XCTFail("Request should fail.") @@ -153,7 +161,7 @@ extension ObjectsUUIDRouterTests { } let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.allUUIDMetadata { result in + pubnub.allUserMetadata { result in switch result { case .success: XCTFail("Request should fail.") @@ -174,7 +182,7 @@ extension ObjectsUUIDRouterTests { } let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.allUUIDMetadata { result in + pubnub.allUserMetadata { result in switch result { case .success: XCTFail("Request should fail.") @@ -190,10 +198,12 @@ extension ObjectsUUIDRouterTests { // MARK: - Fetch Tests -extension ObjectsUUIDRouterTests { +extension ObjectsUserRouterTests { func testFetch_Router() { - let router = ObjectsUUIDRouter(.fetch(metadataId: "OtherUser", customFields: true), - configuration: config) + let router = ObjectsUserRouter( + .fetch(metadataId: "OtherUser", include: [.custom]), + configuration: config + ) XCTAssertEqual(router.endpoint.description, "Fetch Metadata for a UUID") XCTAssertEqual(router.category, "Fetch Metadata for a UUID") @@ -201,30 +211,37 @@ extension ObjectsUUIDRouterTests { } func testFetch_Router_ValidationError() { - let router = ObjectsUUIDRouter(.fetch(metadataId: "", customFields: true), configuration: config) + let router = ObjectsUserRouter(.fetch(metadataId: "", include: [.custom]), configuration: config) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testFetch_Success() { let expectation = self.expectation(description: "Fetch Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_uuid_fetch_success"]), - let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_uuid_fetch_success"]), + let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") else { return XCTFail("Could not create mock url session") } - let testObject = PubNubUUIDMetadataBase( + let testObject = PubNubUserMetadataBase( metadataId: "TestUser", name: "Test User", type: "Test Type", status: "Test Status", custom: ["string": "String", "int": 1, "double": 1.1, "bool": true], updated: firstDate, eTag: "AfuB8q7/s+qCwAE" ) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchUserMetadata("TestUser") { result in switch result { case let .success(responseObject): XCTAssertEqual(try? responseObject.transcode(), testObject) @@ -244,8 +261,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -265,8 +286,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -286,8 +311,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -307,8 +336,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -328,8 +361,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.fetch(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.fetchUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -345,9 +382,9 @@ extension ObjectsUUIDRouterTests { // MARK: - Set Tests -extension ObjectsUUIDRouterTests { +extension ObjectsUserRouterTests { func testSet_Router() { - let router = ObjectsUUIDRouter(.set(metadata: testUser, customFields: true), configuration: config) + let router = ObjectsUserRouter(.set(metadata: testUser, include: [.custom]), configuration: config) XCTAssertEqual(router.endpoint.description, "Set Metadata for a UUID") XCTAssertEqual(router.category, "Set Metadata for a UUID") @@ -355,29 +392,36 @@ extension ObjectsUUIDRouterTests { } func testSet_Router_ValidationError() { - let router = ObjectsUUIDRouter(.set(metadata: invalidUser, customFields: true), configuration: config) + let router = ObjectsUserRouter(.set(metadata: invalidUser, include: [.custom]), configuration: config) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testSet_Success() { let expectation = self.expectation(description: "Create Endpoint Expectation") - guard let sessions = try? MockURLSession.mockSession(for: ["objects_uuid_fetch_success"]), - let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") + guard + let sessions = try? MockURLSession.mockSession(for: ["objects_uuid_fetch_success"]), + let firstDate = DateFormatter.iso8601.date(from: "2019-09-03T02:47:38.609257Z") else { return XCTFail("Could not create mock url session") } - let testObject = PubNubUUIDMetadataBase( + let testObject = PubNubUserMetadataBase( metadataId: "TestUser", name: "Test User", type: "Test Type", status: "Test Status", custom: ["string": "String", "int": 1, "double": 1.1, "bool": true], updated: firstDate, eTag: "AfuB8q7/s+qCwAE" ) - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case let .success(responseObject): XCTAssertEqual(try? responseObject.transcode(), testObject) @@ -397,8 +441,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -418,8 +466,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -439,8 +491,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -460,8 +516,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -481,8 +541,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -502,8 +566,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -523,8 +591,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.set(uuid: testUser) { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.setUserMetadata(testUser) { result in switch result { case .success: XCTFail("Request should fail.") @@ -540,9 +612,9 @@ extension ObjectsUUIDRouterTests { // MARK: - Remove Tests -extension ObjectsUUIDRouterTests { +extension ObjectsUserRouterTests { func testRemove_Router() { - let router = ObjectsUUIDRouter(.remove(metadataId: "TestUser"), configuration: config) + let router = ObjectsUserRouter(.remove(metadataId: "TestUser"), configuration: config) XCTAssertEqual(router.endpoint.description, "Remove Metadata from a UUID") XCTAssertEqual(router.category, "Remove Metadata from a UUID") @@ -550,10 +622,12 @@ extension ObjectsUUIDRouterTests { } func testRemove_Router_ValidationError() { - let router = ObjectsUUIDRouter(.remove(metadataId: ""), configuration: config) + let router = ObjectsUserRouter(.remove(metadataId: ""), configuration: config) - XCTAssertNotEqual(router.validationError?.pubNubError, - PubNubError(.invalidEndpointType, router: router)) + XCTAssertNotEqual( + router.validationError?.pubNubError, + PubNubError(.invalidEndpointType, router: router) + ) } func testRemove_Success() { @@ -563,8 +637,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata("TestUser") { result in switch result { case let .success(metadataId): XCTAssertEqual(metadataId, "TestUser") @@ -584,8 +662,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: nil) { [weak self] result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata(nil) { [weak self] result in switch result { case let .success(metadataId): XCTAssertEqual(metadataId, self?.config.uuid) @@ -605,8 +687,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -626,8 +712,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -647,8 +737,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -668,8 +762,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") @@ -689,8 +787,12 @@ extension ObjectsUUIDRouterTests { return XCTFail("Could not create mock url session") } - let pubnub = PubNub(configuration: config, session: sessions.session) - pubnub.remove(uuid: "TestUser") { result in + let pubnub = PubNub( + configuration: config, + session: sessions.session + ) + + pubnub.removeUserMetadata("TestUser") { result in switch result { case .success: XCTFail("Request should fail.") diff --git a/Tests/PubNubTests/Networking/Routers/SubscribeRouterTests.swift b/Tests/PubNubTests/Networking/Routers/SubscribeRouterTests.swift index 7fcf3ece..25348fe7 100644 --- a/Tests/PubNubTests/Networking/Routers/SubscribeRouterTests.swift +++ b/Tests/PubNubTests/Networking/Routers/SubscribeRouterTests.swift @@ -337,11 +337,11 @@ extension SubscribeRouterTests { let objectListenerExpect = XCTestExpectation(description: "Object Listener Event") let pubnub = PubNub(configuration: configuration) - let baseUser = PubNubUUIDMetadataBase( + let baseUser = PubNubUserMetadataBase( metadataId: "TestUserID", name: "Not Real Name" ) - let patchedObjectUser = PubNubUUIDMetadataBase( + let patchedObjectUser = PubNubUserMetadataBase( metadataId: "TestUserID", name: "Test Name", type: "Test Type", status: "Test Status", updated: DateFormatter.iso8601.date(from: "2019-10-06T01:55:50.645685Z"), @@ -563,15 +563,18 @@ extension SubscribeRouterTests { let objectListenerExpect = XCTestExpectation(description: "Object Listener Event") let channel = PubNubChannelMetadataBase(metadataId: "TestSpaceID") - let uuid = PubNubUUIDMetadataBase(metadataId: "TestUserID") + let uuid = PubNubUserMetadataBase(metadataId: "TestUserID") let pubnub = PubNub(configuration: configuration) let testMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUserID", + userMetadataId: "TestUserID", channelMetadataId: "TestSpaceID", - uuid: uuid, channel: channel, + status: "Test Status", + user: uuid, + channel: channel, custom: ["something": true], - updated: DateFormatter.iso8601.date(from: "2019-10-05T23:35:38.457823306Z"), eTag: "TestETag" + updated: DateFormatter.iso8601.date(from: "2019-10-05T23:35:38.457823306Z"), + eTag: "TestETag" ) mockResult.listener.didReceiveSubscription = { [unowned self] event in @@ -625,12 +628,12 @@ extension SubscribeRouterTests { let statusExpect = XCTestExpectation(description: "Status Event") let objectListenerExpect = XCTestExpectation(description: "Object Listener Event") let channel = PubNubChannelMetadataBase(metadataId: "TestSpaceID") - let uuid = PubNubUUIDMetadataBase(metadataId: "TestUserID") + let uuid = PubNubUserMetadataBase(metadataId: "TestUserID") let pubnub = PubNub(configuration: configuration) let testMembership = PubNubMembershipMetadataBase( - uuidMetadataId: "TestUserID", channelMetadataId: "TestSpaceID", - uuid: uuid, channel: channel, + userMetadataId: "TestUserID", channelMetadataId: "TestSpaceID", + user: uuid, channel: channel, updated: DateFormatter.iso8601.date(from: "2019-10-05T23:35:38.457823306Z"), eTag: "TestETag" )