diff --git a/HiBit.xcodeproj/project.pbxproj b/HiBit.xcodeproj/project.pbxproj index 403f4f7..8bbf255 100644 --- a/HiBit.xcodeproj/project.pbxproj +++ b/HiBit.xcodeproj/project.pbxproj @@ -7,28 +7,29 @@ objects = { /* Begin PBXBuildFile section */ - 916351232C12AFE800593047 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 916351222C12AFE800593047 /* AppDelegate.m */; }; - 916351262C12AFE800593047 /* SceneDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 916351252C12AFE800593047 /* SceneDelegate.m */; }; - 916351292C12AFE800593047 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 916351282C12AFE800593047 /* ViewController.m */; }; - 9163512C2C12AFE800593047 /* Base in Resources */ = {isa = PBXBuildFile; fileRef = 9163512B2C12AFE800593047 /* Base */; }; 9163512E2C12AFEA00593047 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9163512D2C12AFEA00593047 /* Assets.xcassets */; }; 916351312C12AFEA00593047 /* Base in Resources */ = {isa = PBXBuildFile; fileRef = 916351302C12AFEA00593047 /* Base */; }; 916351342C12AFEA00593047 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 916351332C12AFEA00593047 /* main.m */; }; + 916351402C12B12F00593047 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 9163513F2C12B12F00593047 /* AppDelegate.m */; }; + 916351432C12B13700593047 /* SceneDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 916351422C12B13700593047 /* SceneDelegate.m */; }; + AC39FB6C929D30EFDAAC6CEB /* Pods_HiBit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7603423F984179550EE5476E /* Pods_HiBit.framework */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ + 1B0AEA883685A7D77ED99F7E /* Pods-HiBit.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-HiBit.release.xcconfig"; path = "Target Support Files/Pods-HiBit/Pods-HiBit.release.xcconfig"; sourceTree = ""; }; + 7603423F984179550EE5476E /* Pods_HiBit.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_HiBit.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 776EF1D90F08398428F51390 /* Pods-HiBit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-HiBit.debug.xcconfig"; path = "Target Support Files/Pods-HiBit/Pods-HiBit.debug.xcconfig"; sourceTree = ""; }; 9163511E2C12AFE800593047 /* HiBit.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = HiBit.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 916351212C12AFE800593047 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; - 916351222C12AFE800593047 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; - 916351242C12AFE800593047 /* SceneDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SceneDelegate.h; sourceTree = ""; }; - 916351252C12AFE800593047 /* SceneDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = SceneDelegate.m; sourceTree = ""; }; - 916351272C12AFE800593047 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; - 916351282C12AFE800593047 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; - 9163512B2C12AFE800593047 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 9163512D2C12AFEA00593047 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 916351302C12AFEA00593047 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 916351322C12AFEA00593047 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 916351332C12AFEA00593047 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + 9163513E2C12B12F00593047 /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + 9163513F2C12B12F00593047 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + 916351412C12B13700593047 /* SceneDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SceneDelegate.h; sourceTree = ""; }; + 916351422C12B13700593047 /* SceneDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SceneDelegate.m; sourceTree = ""; }; + 916351492C12B49B00593047 /* PrefixHeader.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PrefixHeader.pch; sourceTree = ""; }; + 9163514A2C12B4D800593047 /* HiBit-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "HiBit-Bridging-Header.h"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -36,17 +37,29 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + AC39FB6C929D30EFDAAC6CEB /* Pods_HiBit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 3BDF198760D91541D6520AC2 /* Pods */ = { + isa = PBXGroup; + children = ( + 776EF1D90F08398428F51390 /* Pods-HiBit.debug.xcconfig */, + 1B0AEA883685A7D77ED99F7E /* Pods-HiBit.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; 916351152C12AFE800593047 = { isa = PBXGroup; children = ( 916351202C12AFE800593047 /* HiBit */, 9163511F2C12AFE800593047 /* Products */, + 3BDF198760D91541D6520AC2 /* Pods */, + B36329ED094310C499FEBA2F /* Frameworks */, ); sourceTree = ""; }; @@ -61,21 +74,52 @@ 916351202C12AFE800593047 /* HiBit */ = { isa = PBXGroup; children = ( - 916351212C12AFE800593047 /* AppDelegate.h */, - 916351222C12AFE800593047 /* AppDelegate.m */, - 916351242C12AFE800593047 /* SceneDelegate.h */, - 916351252C12AFE800593047 /* SceneDelegate.m */, - 916351272C12AFE800593047 /* ViewController.h */, - 916351282C12AFE800593047 /* ViewController.m */, - 9163512A2C12AFE800593047 /* Main.storyboard */, - 9163512D2C12AFEA00593047 /* Assets.xcassets */, - 9163512F2C12AFEA00593047 /* LaunchScreen.storyboard */, - 916351322C12AFEA00593047 /* Info.plist */, - 916351332C12AFEA00593047 /* main.m */, + 9163513B2C12B0A200593047 /* Project */, + 9163513D2C12B11A00593047 /* AppDelegate */, + 916351472C12B40900593047 /* Basics */, ); path = HiBit; sourceTree = ""; }; + 9163513B2C12B0A200593047 /* Project */ = { + isa = PBXGroup; + children = ( + 916351322C12AFEA00593047 /* Info.plist */, + 916351332C12AFEA00593047 /* main.m */, + 9163512D2C12AFEA00593047 /* Assets.xcassets */, + 9163512F2C12AFEA00593047 /* LaunchScreen.storyboard */, + 916351492C12B49B00593047 /* PrefixHeader.pch */, + 9163514A2C12B4D800593047 /* HiBit-Bridging-Header.h */, + ); + path = Project; + sourceTree = ""; + }; + 9163513D2C12B11A00593047 /* AppDelegate */ = { + isa = PBXGroup; + children = ( + 9163513E2C12B12F00593047 /* AppDelegate.h */, + 9163513F2C12B12F00593047 /* AppDelegate.m */, + 916351412C12B13700593047 /* SceneDelegate.h */, + 916351422C12B13700593047 /* SceneDelegate.m */, + ); + path = AppDelegate; + sourceTree = ""; + }; + 916351472C12B40900593047 /* Basics */ = { + isa = PBXGroup; + children = ( + ); + path = Basics; + sourceTree = ""; + }; + B36329ED094310C499FEBA2F /* Frameworks */ = { + isa = PBXGroup; + children = ( + 7603423F984179550EE5476E /* Pods_HiBit.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -83,6 +127,7 @@ isa = PBXNativeTarget; buildConfigurationList = 916351372C12AFEA00593047 /* Build configuration list for PBXNativeTarget "HiBit" */; buildPhases = ( + 0DF2CEAEB1C33630445A7424 /* [CP] Check Pods Manifest.lock */, 9163511A2C12AFE800593047 /* Sources */, 9163511B2C12AFE800593047 /* Frameworks */, 9163511C2C12AFE800593047 /* Resources */, @@ -107,6 +152,7 @@ TargetAttributes = { 9163511D2C12AFE800593047 = { CreatedOnToolsVersion = 15.4; + LastSwiftMigration = 1540; }; }; }; @@ -135,35 +181,50 @@ files = ( 9163512E2C12AFEA00593047 /* Assets.xcassets in Resources */, 916351312C12AFEA00593047 /* Base in Resources */, - 9163512C2C12AFE800593047 /* Base in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 0DF2CEAEB1C33630445A7424 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-HiBit-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 9163511A2C12AFE800593047 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - 916351292C12AFE800593047 /* ViewController.m in Sources */, - 916351232C12AFE800593047 /* AppDelegate.m in Sources */, + 916351402C12B12F00593047 /* AppDelegate.m in Sources */, + 916351432C12B13700593047 /* SceneDelegate.m in Sources */, 916351342C12AFEA00593047 /* main.m in Sources */, - 916351262C12AFE800593047 /* SceneDelegate.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ - 9163512A2C12AFE800593047 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 9163512B2C12AFE800593047 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; 9163512F2C12AFEA00593047 /* LaunchScreen.storyboard */ = { isa = PBXVariantGroup; children = ( @@ -227,7 +288,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 17.5; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; @@ -282,7 +343,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 17.5; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; @@ -293,14 +354,17 @@ }; 916351382C12AFEA00593047 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 776EF1D90F08398428F51390 /* Pods-HiBit.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CLANG_ENABLE_MODULES = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 38X8FL2527; + GCC_PREFIX_HEADER = "$(SRCROOT)/Hibit/Project/PrefixHeader.pch"; GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_FILE = HiBit/Info.plist; + INFOPLIST_FILE = HiBit/Project/Info.plist; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; INFOPLIST_KEY_UIMainStoryboardFile = Main; @@ -314,20 +378,26 @@ PRODUCT_BUNDLE_IDENTIFIER = com.qinjiu.HiBit; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OBJC_BRIDGING_HEADER = "HiBit/Project/HiBit-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; 916351392C12AFEA00593047 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 1B0AEA883685A7D77ED99F7E /* Pods-HiBit.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CLANG_ENABLE_MODULES = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 38X8FL2527; + GCC_PREFIX_HEADER = "$(SRCROOT)/Hibit/Project/PrefixHeader.pch"; GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_FILE = HiBit/Info.plist; + INFOPLIST_FILE = HiBit/Project/Info.plist; INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; INFOPLIST_KEY_UIMainStoryboardFile = Main; @@ -341,6 +411,8 @@ PRODUCT_BUNDLE_IDENTIFIER = com.qinjiu.HiBit; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OBJC_BRIDGING_HEADER = "HiBit/Project/HiBit-Bridging-Header.h"; + SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; diff --git a/HiBit.xcodeproj/xcuserdata/loser.xcuserdatad/xcschemes/xcschememanagement.plist b/HiBit.xcodeproj/xcuserdata/loser.xcuserdatad/xcschemes/xcschememanagement.plist index 6bc35a9..f457723 100644 --- a/HiBit.xcodeproj/xcuserdata/loser.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/HiBit.xcodeproj/xcuserdata/loser.xcuserdatad/xcschemes/xcschememanagement.plist @@ -7,7 +7,7 @@ HiBit.xcscheme_^#shared#^_ orderHint - 0 + 1 diff --git a/HiBit.xcworkspace/contents.xcworkspacedata b/HiBit.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..aa25c0e --- /dev/null +++ b/HiBit.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/HiBit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/HiBit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/HiBit.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/HiBit/AppDelegate.h b/HiBit/AppDelegate/AppDelegate.h similarity index 100% rename from HiBit/AppDelegate.h rename to HiBit/AppDelegate/AppDelegate.h diff --git a/HiBit/AppDelegate.m b/HiBit/AppDelegate/AppDelegate.m similarity index 100% rename from HiBit/AppDelegate.m rename to HiBit/AppDelegate/AppDelegate.m diff --git a/HiBit/SceneDelegate.h b/HiBit/AppDelegate/SceneDelegate.h similarity index 100% rename from HiBit/SceneDelegate.h rename to HiBit/AppDelegate/SceneDelegate.h diff --git a/HiBit/SceneDelegate.m b/HiBit/AppDelegate/SceneDelegate.m similarity index 100% rename from HiBit/SceneDelegate.m rename to HiBit/AppDelegate/SceneDelegate.m diff --git a/HiBit/Base.lproj/LaunchScreen.storyboard b/HiBit/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 865e932..0000000 --- a/HiBit/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/HiBit/Base.lproj/Main.storyboard b/HiBit/Base.lproj/Main.storyboard deleted file mode 100644 index 808a21c..0000000 --- a/HiBit/Base.lproj/Main.storyboard +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/HiBit/Assets.xcassets/AccentColor.colorset/Contents.json b/HiBit/Project/Assets.xcassets/AccentColor.colorset/Contents.json similarity index 100% rename from HiBit/Assets.xcassets/AccentColor.colorset/Contents.json rename to HiBit/Project/Assets.xcassets/AccentColor.colorset/Contents.json diff --git a/HiBit/Assets.xcassets/AppIcon.appiconset/Contents.json b/HiBit/Project/Assets.xcassets/AppIcon.appiconset/Contents.json similarity index 100% rename from HiBit/Assets.xcassets/AppIcon.appiconset/Contents.json rename to HiBit/Project/Assets.xcassets/AppIcon.appiconset/Contents.json diff --git a/HiBit/Assets.xcassets/Contents.json b/HiBit/Project/Assets.xcassets/Contents.json similarity index 100% rename from HiBit/Assets.xcassets/Contents.json rename to HiBit/Project/Assets.xcassets/Contents.json diff --git a/HiBit/Project/Base.lproj/LaunchScreen.storyboard b/HiBit/Project/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..a4c4a8a --- /dev/null +++ b/HiBit/Project/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/HiBit/Project/HiBit-Bridging-Header.h b/HiBit/Project/HiBit-Bridging-Header.h new file mode 100644 index 0000000..1b2cb5d --- /dev/null +++ b/HiBit/Project/HiBit-Bridging-Header.h @@ -0,0 +1,4 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// + diff --git a/HiBit/Info.plist b/HiBit/Project/Info.plist similarity index 90% rename from HiBit/Info.plist rename to HiBit/Project/Info.plist index 81ed29b..1be49b1 100644 --- a/HiBit/Info.plist +++ b/HiBit/Project/Info.plist @@ -15,8 +15,6 @@ Default Configuration UISceneDelegateClassName SceneDelegate - UISceneStoryboardFile - Main diff --git a/HiBit/Project/PrefixHeader.pch b/HiBit/Project/PrefixHeader.pch new file mode 100644 index 0000000..bdbd526 --- /dev/null +++ b/HiBit/Project/PrefixHeader.pch @@ -0,0 +1,14 @@ +// +// PrefixHeader.pch +// HiBit +// +// Created by HI_LOSER on 2024/6/7. +// + +#ifndef PrefixHeader_pch +#define PrefixHeader_pch + +// Include any system framework and library headers here that should be included in all compilation units. +// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file. + +#endif /* PrefixHeader_pch */ diff --git a/HiBit/Project/en.lproj/LaunchScreen.storyboard b/HiBit/Project/en.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..a4c4a8a --- /dev/null +++ b/HiBit/Project/en.lproj/LaunchScreen.storyboard @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/HiBit/main.m b/HiBit/Project/main.m similarity index 100% rename from HiBit/main.m rename to HiBit/Project/main.m diff --git a/HiBit/ViewController.h b/HiBit/ViewController.h deleted file mode 100644 index f18c195..0000000 --- a/HiBit/ViewController.h +++ /dev/null @@ -1,14 +0,0 @@ -// -// ViewController.h -// HiBit -// -// Created by HI_LOSER on 2024/6/7. -// - -#import - -@interface ViewController : UIViewController - - -@end - diff --git a/HiBit/ViewController.m b/HiBit/ViewController.m deleted file mode 100644 index ef20c98..0000000 --- a/HiBit/ViewController.m +++ /dev/null @@ -1,22 +0,0 @@ -// -// ViewController.m -// HiBit -// -// Created by HI_LOSER on 2024/6/7. -// - -#import "ViewController.h" - -@interface ViewController () - -@end - -@implementation ViewController - -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view. -} - - -@end diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..1b4ec08 --- /dev/null +++ b/Podfile @@ -0,0 +1,61 @@ +# Uncomment the next line to define a global platform for your project + platform :ios, '13.0' + +target 'HiBit' do + inhibit_all_warnings! + use_modular_headers! + + pod 'AFNetworking' # 网络请求 + pod 'Masonry' # 布局 + pod 'HXPhotoPicker' # 相册 + pod 'BaiduMobAdSDK' # BaiDu AD + pod 'KSAdSDK' # KuaiShou AD + pod 'Ads-Global' # Pangle AD + pod 'AppsFlyerFramework' # AppsFlyer + pod 'AppLovinSDK' # AppLovin + pod 'MJExtension' # 模型转换 + pod 'MJRefresh' # 下拉刷新 + pod 'FBSDKCoreKit' # Facebook 基础 + pod 'FBSDKLoginKit' # Facebook 登录 + pod 'FBSDKShareKit' # Facebook 分享 + pod 'TikTokOpenSDKCore' # TikTok 登录 + pod 'TikTokOpenAuthSDK' # TikTok 验证 + pod 'TikTokOpenShareSDK' # TikTok 分享 + pod 'GoogleSignIn' # Google 登录 + pod 'IGListKit' # 列表 + pod 'EllipsePageControl' # 轮播图下标 + pod 'GKCycleScrollView' # 轮播图控件 + pod 'SDWebImage' # 网络图片 + pod 'HBDNavigationBar' # 导航栏 + pod 'ZFPlayer/AVPlayer' # 播放器 + pod 'GKVideoScrollView' # 播放滚动控件 + pod 'DZNEmptyDataSet' # 空数据展示 + pod 'YYText' # 富文本 + pod 'AXWebViewController' # web + pod 'DZNEmptyDataSet' # 空数据展示 + pod 'JXPagingView/Pager' # 分页控制器 + pod 'JXCategoryView' # 分页控制器 + pod 'Toast' # 吐司提示 + pod 'GKVideoScrollView' # 视频滑动播放器 + pod 'GKSliderView' # 进度条 + pod 'SAMKeychain' # KeyChain + pod 'HWPanModal' # 模态底部弹出控制器 + pod 'KTVHTTPCache' # 视频缓存 + pod 'FMDB' # 数据库 + pod 'RMStore' # 内购 + +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + target.build_configurations.each do |config| + config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0' + end + + installer.pods_project.build_configurations.each do |config| + config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64" + end + + end +end + diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..c6cba5e --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,3 @@ +PODFILE CHECKSUM: 5f5502bee9be7cac8e3859df29113a48ce18b584 + +COCOAPODS: 1.15.2 diff --git a/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h b/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h new file mode 100644 index 0000000..1f0ab26 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFCompatibilityMacros.h @@ -0,0 +1,49 @@ +// AFCompatibilityMacros.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#ifndef AFCompatibilityMacros_h +#define AFCompatibilityMacros_h + +#ifdef API_AVAILABLE + #define AF_API_AVAILABLE(...) API_AVAILABLE(__VA_ARGS__) +#else + #define AF_API_AVAILABLE(...) +#endif // API_AVAILABLE + +#ifdef API_UNAVAILABLE + #define AF_API_UNAVAILABLE(...) API_UNAVAILABLE(__VA_ARGS__) +#else + #define AF_API_UNAVAILABLE(...) +#endif // API_UNAVAILABLE + +#if __has_warning("-Wunguarded-availability-new") + #define AF_CAN_USE_AT_AVAILABLE 1 +#else + #define AF_CAN_USE_AT_AVAILABLE 0 +#endif + +#if ((__IPHONE_OS_VERSION_MAX_ALLOWED && __IPHONE_OS_VERSION_MAX_ALLOWED < 100000) || (__MAC_OS_VERSION_MAX_ALLOWED && __MAC_OS_VERSION_MAX_ALLOWED < 101200) ||(__WATCH_OS_MAX_VERSION_ALLOWED && __WATCH_OS_MAX_VERSION_ALLOWED < 30000) ||(__TV_OS_MAX_VERSION_ALLOWED && __TV_OS_MAX_VERSION_ALLOWED < 100000)) + #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 0 +#else + #define AF_CAN_INCLUDE_SESSION_TASK_METRICS 1 +#endif + +#endif /* AFCompatibilityMacros_h */ diff --git a/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h new file mode 100644 index 0000000..943fc22 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.h @@ -0,0 +1,285 @@ +// AFHTTPSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#if !TARGET_OS_WATCH +#import +#endif +#import + +#import "AFURLSessionManager.h" + +/** + `AFHTTPSessionManager` is a subclass of `AFURLSessionManager` with convenience methods for making HTTP requests. When a `baseURL` is provided, requests made with the `GET` / `POST` / et al. convenience methods can be made with relative paths. + + ## Subclassing Notes + + Developers targeting iOS 7 or Mac OS X 10.9 or later that deal extensively with a web service are encouraged to subclass `AFHTTPSessionManager`, providing a class method that returns a shared singleton object on which authentication and other configuration can be shared across the application. + + ## Methods to Override + + To change the behavior of all data task operation construction, which is also used in the `GET` / `POST` / et al. convenience methods, override `dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler:`. + + ## Serialization + + Requests created by an HTTP client will contain default headers and encode parameters according to the `requestSerializer` property, which is an object conforming to ``. + + Responses received from the server are automatically validated and serialized by the `responseSerializers` property, which is an object conforming to `` + + ## URL Construction Using Relative Paths + + For HTTP convenience methods, the request serializer constructs URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`, when provided. If `baseURL` is `nil`, `path` needs to resolve to a valid `NSURL` object using `NSURL +URLWithString:`. + + Below are a few examples of how `baseURL` and relative paths interact: + + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ + + Also important to note is that a trailing slash will be added to any `baseURL` without one. This would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFHTTPSessionManager : AFURLSessionManager + +/** + The URL used to construct requests from relative paths in methods like `requestWithMethod:URLString:parameters:`, and the `GET` / `POST` / et al. convenience methods. + */ +@property (readonly, nonatomic, strong, nullable) NSURL *baseURL; + +/** + Requests created with `requestWithMethod:URLString:parameters:` & `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:` are constructed with a set of default headers using a parameter serialization specified by this property. By default, this is set to an instance of `AFHTTPRequestSerializer`, which serializes query string parameters for `GET`, `HEAD`, and `DELETE` requests, or otherwise URL-form-encodes HTTP message bodies. + + @warning `requestSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPRequestSerializer * requestSerializer; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) AFHTTPResponseSerializer * responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. A security policy configured with `AFSSLPinningModePublicKey` or `AFSSLPinningModeCertificate` can only be applied on a session manager initialized with a secure base URL (i.e. https). Applying a security policy with pinning enabled on an insecure session manager throws an `Invalid Security Policy` exception. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns an `AFHTTPSessionManager` object. + */ ++ (instancetype)manager; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + @param url The base URL for the HTTP client. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url; + +/** + Initializes an `AFHTTPSessionManager` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. + @param configuration The configuration used to create the managed session. + + @return The newly-initialized HTTP client + */ +- (instancetype)initWithBaseURL:(nullable NSURL *)url + sessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates and runs an `NSURLSessionDataTask` with a `GET` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `HEAD` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes a single arguments: the data task. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a multipart `POST` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + constructingBodyWithBlock:(nullable void (^)(id formData))block + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PUT` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `PATCH` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates and runs an `NSURLSessionDataTask` with a `DELETE` request. + + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:completionHandler: + */ +- (nullable NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +/** + Creates an `NSURLSessionDataTask` with a custom `HTTPMethod` request. + + @param method The HTTPMethod string used to create the request. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded according to the client request serializer. + @param headers The headers appended to the default headers for this request. + @param uploadProgress A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgress A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param success A block object to be executed when the task finishes successfully. This block has no return value and takes two arguments: the data task, and the response object created by the client response serializer. + @param failure A block object to be executed when the task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the data task and the error describing the network or parsing error that occurred. + + @see -dataTaskWithRequest:uploadProgress:downloadProgress:completionHandler: + */ +- (nullable NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m new file mode 100644 index 0000000..b4ab591 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFHTTPSessionManager.m @@ -0,0 +1,357 @@ +// AFHTTPSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFHTTPSessionManager.h" + +#import "AFURLRequestSerialization.h" +#import "AFURLResponseSerialization.h" + +#import +#import +#import + +#import +#import +#import +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +@interface AFHTTPSessionManager () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@end + +@implementation AFHTTPSessionManager +@dynamic responseSerializer; + ++ (instancetype)manager { + return [[[self class] alloc] initWithBaseURL:nil]; +} + +- (instancetype)init { + return [self initWithBaseURL:nil]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url sessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + return [self initWithBaseURL:nil sessionConfiguration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url + sessionConfiguration:(NSURLSessionConfiguration *)configuration +{ + self = [super initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + return self; +} + +#pragma mark - + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + NSParameterAssert(requestSerializer); + + _requestSerializer = requestSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + NSParameterAssert(responseSerializer); + + [super setResponseSerializer:responseSerializer]; +} + +@dynamic securityPolicy; + +- (void)setSecurityPolicy:(AFSecurityPolicy *)securityPolicy { + if (securityPolicy.SSLPinningMode != AFSSLPinningModeNone && ![self.baseURL.scheme isEqualToString:@"https"]) { + NSString *pinningMode = @"Unknown Pinning Mode"; + switch (securityPolicy.SSLPinningMode) { + case AFSSLPinningModeNone: pinningMode = @"AFSSLPinningModeNone"; break; + case AFSSLPinningModeCertificate: pinningMode = @"AFSSLPinningModeCertificate"; break; + case AFSSLPinningModePublicKey: pinningMode = @"AFSSLPinningModePublicKey"; break; + } + NSString *reason = [NSString stringWithFormat:@"A security policy configured with `%@` can only be applied on a manager with a secure base URL (i.e. https)", pinningMode]; + @throw [NSException exceptionWithName:@"Invalid Security Policy" reason:reason userInfo:nil]; + } + + [super setSecurityPolicy:securityPolicy]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)GET:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress * _Nonnull))downloadProgress + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"GET" + URLString:URLString + parameters:parameters + headers:headers + uploadProgress:nil + downloadProgress:downloadProgress + success:success + failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)HEAD:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"HEAD" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask *task, __unused id responseObject) { + if (success) { + success(task); + } + } failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (nullable NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"POST" URLString:URLString parameters:parameters headers:headers uploadProgress:uploadProgress downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)POST:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + constructingBodyWithBlock:(nullable void (^)(id _Nonnull))block + progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress + success:(nullable void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError]; + for (NSString *headerField in headers.keyEnumerator) { + [request setValue:headers[headerField] forHTTPHeaderField:headerField]; + } + if (serializationError) { + if (failure) { + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); + } + + return nil; + } + + __block NSURLSessionDataTask *task = [self uploadTaskWithStreamedRequest:request progress:uploadProgress completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(task, error); + } + } else { + if (success) { + success(task, responseObject); + } + } + }]; + + [task resume]; + + return task; +} + +- (NSURLSessionDataTask *)PUT:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PUT" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)PATCH:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"PATCH" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + +- (NSURLSessionDataTask *)DELETE:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + success:(nullable void (^)(NSURLSessionDataTask *task, id responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask *task, NSError *error))failure +{ + NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:@"DELETE" URLString:URLString parameters:parameters headers:headers uploadProgress:nil downloadProgress:nil success:success failure:failure]; + + [dataTask resume]; + + return dataTask; +} + + +- (NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + headers:(nullable NSDictionary *)headers + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgress + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgress + success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success + failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure +{ + NSError *serializationError = nil; + NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError]; + for (NSString *headerField in headers.keyEnumerator) { + [request setValue:headers[headerField] forHTTPHeaderField:headerField]; + } + if (serializationError) { + if (failure) { + dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{ + failure(nil, serializationError); + }); + } + + return nil; + } + + __block NSURLSessionDataTask *dataTask = nil; + dataTask = [self dataTaskWithRequest:request + uploadProgress:uploadProgress + downloadProgress:downloadProgress + completionHandler:^(NSURLResponse * __unused response, id responseObject, NSError *error) { + if (error) { + if (failure) { + failure(dataTask, error); + } + } else { + if (success) { + success(dataTask, responseObject); + } + } + }]; + + return dataTask; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.session, self.operationQueue]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURL *baseURL = [decoder decodeObjectOfClass:[NSURL class] forKey:NSStringFromSelector(@selector(baseURL))]; + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + if (!configuration) { + NSString *configurationIdentifier = [decoder decodeObjectOfClass:[NSString class] forKey:@"identifier"]; + if (configurationIdentifier) { + configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationIdentifier]; + } + } + + self = [self initWithBaseURL:baseURL sessionConfiguration:configuration]; + if (!self) { + return nil; + } + + self.requestSerializer = [decoder decodeObjectOfClass:[AFHTTPRequestSerializer class] forKey:NSStringFromSelector(@selector(requestSerializer))]; + self.responseSerializer = [decoder decodeObjectOfClass:[AFHTTPResponseSerializer class] forKey:NSStringFromSelector(@selector(responseSerializer))]; + AFSecurityPolicy *decodedPolicy = [decoder decodeObjectOfClass:[AFSecurityPolicy class] forKey:NSStringFromSelector(@selector(securityPolicy))]; + if (decodedPolicy) { + self.securityPolicy = decodedPolicy; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.baseURL forKey:NSStringFromSelector(@selector(baseURL))]; + if ([self.session.configuration conformsToProtocol:@protocol(NSCoding)]) { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; + } else { + [coder encodeObject:self.session.configuration.identifier forKey:@"identifier"]; + } + [coder encodeObject:self.requestSerializer forKey:NSStringFromSelector(@selector(requestSerializer))]; + [coder encodeObject:self.responseSerializer forKey:NSStringFromSelector(@selector(responseSerializer))]; + [coder encodeObject:self.securityPolicy forKey:NSStringFromSelector(@selector(securityPolicy))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPSessionManager *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL sessionConfiguration:self.session.configuration]; + + HTTPClient.requestSerializer = [self.requestSerializer copyWithZone:zone]; + HTTPClient.responseSerializer = [self.responseSerializer copyWithZone:zone]; + HTTPClient.securityPolicy = [self.securityPolicy copyWithZone:zone]; + return HTTPClient; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h new file mode 100644 index 0000000..21982a0 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.h @@ -0,0 +1,216 @@ +// AFNetworkReachabilityManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if !TARGET_OS_WATCH +#import + +typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +}; + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + + Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. + + See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) + + @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. + */ +@interface AFNetworkReachabilityManager : NSObject + +/** + The current network reachability status. + */ +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; + +/** + Whether or not the network is currently reachable. + */ +@property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; + +/** + Whether or not the network is currently reachable via WWAN. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; + +/** + Whether or not the network is currently reachable via WiFi. + */ +@property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Returns the shared network reachability manager. + */ ++ (instancetype)sharedManager; + +/** + Creates and returns a network reachability manager with the default socket address. + + @return An initialized network reachability manager, actively monitoring the default socket address. + */ ++ (instancetype)manager; + +/** + Creates and returns a network reachability manager for the specified domain. + + @param domain The domain used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified domain. + */ ++ (instancetype)managerForDomain:(NSString *)domain; + +/** + Creates and returns a network reachability manager for the socket address. + + @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. + + @return An initialized network reachability manager, actively monitoring the specified socket address. + */ ++ (instancetype)managerForAddress:(const void *)address; + +/** + Initializes an instance of a network reachability manager from the specified reachability object. + + @param reachability The reachability object to monitor. + + @return An initialized network reachability manager, actively monitoring the specified reachability. + */ +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; + +/** + * Unavailable initializer + */ ++ (instancetype)new NS_UNAVAILABLE; + +/** + * Unavailable initializer + */ +- (instancetype)init NS_UNAVAILABLE; + +///-------------------------------------------------- +/// @name Starting & Stopping Reachability Monitoring +///-------------------------------------------------- + +/** + Starts monitoring for changes in network reachability status. + */ +- (void)startMonitoring; + +/** + Stops monitoring for changes in network reachability status. + */ +- (void)stopMonitoring; + +///------------------------------------------------- +/// @name Getting Localized Reachability Description +///------------------------------------------------- + +/** + Returns a localized string representation of the current network reachability status. + */ +- (NSString *)localizedNetworkReachabilityStatusString; + +///--------------------------------------------------- +/// @name Setting Network Reachability Change Callback +///--------------------------------------------------- + +/** + Sets a callback to be executed when the network availability of the `baseURL` host changes. + + @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. + */ +- (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. + + enum { + AFNetworkReachabilityStatusUnknown, + AFNetworkReachabilityStatusNotReachable, + AFNetworkReachabilityStatusReachableViaWWAN, + AFNetworkReachabilityStatusReachableViaWiFi, + } + + `AFNetworkReachabilityStatusUnknown` + The `baseURL` host reachability is not known. + + `AFNetworkReachabilityStatusNotReachable` + The `baseURL` host cannot be reached. + + `AFNetworkReachabilityStatusReachableViaWWAN` + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. + + `AFNetworkReachabilityStatusReachableViaWiFi` + The `baseURL` host can be reached via a Wi-Fi connection. + + ### Keys for Notification UserInfo Dictionary + + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. + + `AFNetworkingReachabilityNotificationStatusItem` + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. + */ + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when network reachability changes. + This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. + + @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; +FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; + +///-------------------- +/// @name Functions +///-------------------- + +/** + Returns a localized string representation of an `AFNetworkReachabilityStatus` value. + */ +FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); + +NS_ASSUME_NONNULL_END +#endif diff --git a/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m new file mode 100644 index 0000000..0322bf9 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworkReachabilityManager.m @@ -0,0 +1,269 @@ +// AFNetworkReachabilityManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkReachabilityManager.h" +#if !TARGET_OS_WATCH + +#import +#import +#import +#import +#import + +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); +typedef AFNetworkReachabilityManager * (^AFNetworkReachabilityStatusCallback)(AFNetworkReachabilityStatus status); + +NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status) { + switch (status) { + case AFNetworkReachabilityStatusNotReachable: + return NSLocalizedStringFromTable(@"Not Reachable", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWWAN: + return NSLocalizedStringFromTable(@"Reachable via WWAN", @"AFNetworking", nil); + case AFNetworkReachabilityStatusReachableViaWiFi: + return NSLocalizedStringFromTable(@"Reachable via WiFi", @"AFNetworking", nil); + case AFNetworkReachabilityStatusUnknown: + default: + return NSLocalizedStringFromTable(@"Unknown", @"AFNetworking", nil); + } +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +/** + * Queue a status change notification for the main thread. + * + * This is done to ensure that the notifications are received in the same order + * as they are sent. If notifications are sent directly, it is possible that + * a queued notification (for an earlier status condition) is processed after + * the later update, resulting in the listener being left in the wrong state. + */ +static void AFPostReachabilityStatusChange(SCNetworkReachabilityFlags flags, AFNetworkReachabilityStatusCallback block) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + dispatch_async(dispatch_get_main_queue(), ^{ + AFNetworkReachabilityManager *manager = nil; + if (block) { + manager = block(status); + } + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + NSDictionary *userInfo = @{ AFNetworkingReachabilityNotificationStatusItem: @(status) }; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:manager userInfo:userInfo]; + }); +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFPostReachabilityStatusChange(flags, (__bridge AFNetworkReachabilityStatusCallback)info); +} + + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +@interface AFNetworkReachabilityManager () +@property (readonly, nonatomic, assign) SCNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +@end + +@implementation AFNetworkReachabilityManager + ++ (instancetype)sharedManager { + static AFNetworkReachabilityManager *_sharedManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _sharedManager = [self manager]; + }); + + return _sharedManager; +} + ++ (instancetype)managerForDomain:(NSString *)domain { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [domain UTF8String]); + + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)managerForAddress:(const void *)address { + SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)address); + AFNetworkReachabilityManager *manager = [[self alloc] initWithReachability:reachability]; + + CFRelease(reachability); + + return manager; +} + ++ (instancetype)manager +{ +#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000) || (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101100) + struct sockaddr_in6 address; + bzero(&address, sizeof(address)); + address.sin6_len = sizeof(address); + address.sin6_family = AF_INET6; +#else + struct sockaddr_in address; + bzero(&address, sizeof(address)); + address.sin_len = sizeof(address); + address.sin_family = AF_INET; +#endif + return [self managerForAddress:&address]; +} + +- (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability { + self = [super init]; + if (!self) { + return nil; + } + + _networkReachability = CFRetain(reachability); + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + + return self; +} + +- (instancetype)init +{ + @throw [NSException exceptionWithName:NSGenericException + reason:@"`-init` unavailable. Use `-initWithReachability:` instead" + userInfo:nil]; + return nil; +} + +- (void)dealloc { + [self stopMonitoring]; + + if (_networkReachability != NULL) { + CFRelease(_networkReachability); + } +} + +#pragma mark - + +- (BOOL)isReachable { + return [self isReachableViaWWAN] || [self isReachableViaWiFi]; +} + +- (BOOL)isReachableViaWWAN { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN; +} + +- (BOOL)isReachableViaWiFi { + return self.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi; +} + +#pragma mark - + +- (void)startMonitoring { + [self stopMonitoring]; + + if (!self.networkReachability) { + return; + } + + __weak __typeof(self)weakSelf = self; + AFNetworkReachabilityStatusCallback callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + + return strongSelf; + }; + + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ + SCNetworkReachabilityFlags flags; + if (SCNetworkReachabilityGetFlags(self.networkReachability, &flags)) { + AFPostReachabilityStatusChange(flags, callback); + } + }); +} + +- (void)stopMonitoring { + if (!self.networkReachability) { + return; + } + + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +#pragma mark - + +- (NSString *)localizedNetworkReachabilityStatusString { + return AFStringFromNetworkReachabilityStatus(self.networkReachabilityStatus); +} + +#pragma mark - + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingValueForKey:(NSString *)key { + if ([key isEqualToString:@"reachable"] || [key isEqualToString:@"reachableViaWWAN"] || [key isEqualToString:@"reachableViaWiFi"]) { + return [NSSet setWithObject:@"networkReachabilityStatus"]; + } + + return [super keyPathsForValuesAffectingValueForKey:key]; +} + +@end +#endif diff --git a/Pods/AFNetworking/AFNetworking/AFNetworking.h b/Pods/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 0000000..e2fb2f4 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,41 @@ +// AFNetworking.h +// +// Copyright (c) 2013 AFNetworking (http://afnetworking.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLRequestSerialization.h" + #import "AFURLResponseSerialization.h" + #import "AFSecurityPolicy.h" + +#if !TARGET_OS_WATCH + #import "AFNetworkReachabilityManager.h" +#endif + + #import "AFURLSessionManager.h" + #import "AFHTTPSessionManager.h" + +#endif /* _AFNETWORKING_ */ diff --git a/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h new file mode 100644 index 0000000..9b966a5 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.h @@ -0,0 +1,161 @@ +// AFSecurityPolicy.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, +}; + +/** + `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + + Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFSecurityPolicy : NSObject + +/** + The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. + */ +@property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; + +/** + The certificates used to evaluate server trust according to the SSL pinning mode. + + Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. + + @see policyWithPinningMode:withPinnedCertificates: + */ +@property (nonatomic, strong, nullable) NSSet *pinnedCertificates; + +/** + Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowInvalidCertificates; + +/** + Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. + */ +@property (nonatomic, assign) BOOL validatesDomainName; + +///----------------------------------------- +/// @name Getting Certificates from the Bundle +///----------------------------------------- + +/** + Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. + + @return The certificates included in the given bundle. + */ ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle; + +///----------------------------------------- +/// @name Getting Specific Security Policies +///----------------------------------------- + +/** + Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. + + @return The default security policy. + */ ++ (instancetype)defaultPolicy; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a security policy with the specified pinning mode. + + Certificates with the `.cer` extension found in the main bundle will be pinned. If you want more control over which certificates are pinned, please use `policyWithPinningMode:withPinnedCertificates:` instead. + + @param pinningMode The SSL pinning mode. + + @return A new security policy. + + @see -policyWithPinningMode:withPinnedCertificates: + */ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; + +/** + Creates and returns a security policy with the specified pinning mode. + + @param pinningMode The SSL pinning mode. + @param pinnedCertificates The certificates to pin against. + + @return A new security policy. + + @see +certificatesInBundle: + @see -pinnedCertificates +*/ ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; + +///------------------------------ +/// @name Evaluating Server Trust +///------------------------------ + +/** + Whether or not the specified server trust should be accepted, based on the security policy. + + This method should be used when responding to an authentication challenge from a server. + + @param serverTrust The X.509 certificate trust of the server. + @param domain The domain of serverTrust. If `nil`, the domain will not be validated. + + @return Whether or not to trust the server. + */ +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(nullable NSString *)domain; + +@end + +NS_ASSUME_NONNULL_END + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Modes + + The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not used pinned certificates to validate servers. + + `AFSSLPinningModePublicKey` + Validate host certificates against public keys of pinned certificates. + + `AFSSLPinningModeCertificate` + Validate host certificates against pinned certificates. +*/ diff --git a/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m new file mode 100644 index 0000000..da199aa --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFSecurityPolicy.m @@ -0,0 +1,341 @@ +// AFSecurityPolicy.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFSecurityPolicy.h" + +#import + +#if !TARGET_OS_IOS && !TARGET_OS_WATCH && !TARGET_OS_TV +static NSData * AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + __Require_noErr_Quiet(SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data), _out); + + return (__bridge_transfer NSData *)data; + +_out: + if (data) { + CFRelease(data); + } + + return nil; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +static id AFPublicKeyForCertificate(NSData *certificate) { + id allowedPublicKey = nil; + SecCertificateRef allowedCertificate; + SecPolicyRef policy = nil; + SecTrustRef allowedTrust = nil; + SecTrustResultType result; + + allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificate); + __Require_Quiet(allowedCertificate != NULL, _out); + + policy = SecPolicyCreateBasicX509(); + __Require_noErr_Quiet(SecTrustCreateWithCertificates(allowedCertificate, policy, &allowedTrust), _out); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + __Require_noErr_Quiet(SecTrustEvaluate(allowedTrust, &result), _out); +#pragma clang diagnostic pop + + allowedPublicKey = (__bridge_transfer id)SecTrustCopyPublicKey(allowedTrust); + +_out: + if (allowedTrust) { + CFRelease(allowedTrust); + } + + if (policy) { + CFRelease(policy); + } + + if (allowedCertificate) { + CFRelease(allowedCertificate); + } + + return allowedPublicKey; +} + +static BOOL AFServerTrustIsValid(SecTrustRef serverTrust) { + BOOL isValid = NO; + SecTrustResultType result; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + __Require_noErr_Quiet(SecTrustEvaluate(serverTrust, &result), _out); +#pragma clang diagnostic pop + + isValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed); + +_out: + return isValid; +} + +static NSArray * AFCertificateTrustChainForServerTrust(SecTrustRef serverTrust) { + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } + + return [NSArray arrayWithArray:trustChain]; +} + +static NSArray * AFPublicKeyTrustChainForServerTrust(SecTrustRef serverTrust) { + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:(NSUInteger)certificateCount]; + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust; + __Require_noErr_Quiet(SecTrustCreateWithCertificates(certificates, policy, &trust), _out); + SecTrustResultType result; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + __Require_noErr_Quiet(SecTrustEvaluate(trust, &result), _out); +#pragma clang diagnostic pop + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + + _out: + if (trust) { + CFRelease(trust); + } + + if (certificates) { + CFRelease(certificates); + } + + continue; + } + CFRelease(policy); + + return [NSArray arrayWithArray:trustChain]; +} + +#pragma mark - + +@interface AFSecurityPolicy() +@property (readwrite, nonatomic, assign) AFSSLPinningMode SSLPinningMode; +@property (readwrite, nonatomic, strong) NSSet *pinnedPublicKeys; +@end + +@implementation AFSecurityPolicy + ++ (NSSet *)certificatesInBundle:(NSBundle *)bundle { + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableSet *certificates = [NSMutableSet setWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + return [NSSet setWithSet:certificates]; +} + ++ (instancetype)defaultPolicy { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = AFSSLPinningModeNone; + + return securityPolicy; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode { + NSSet *defaultPinnedCertificates = [self certificatesInBundle:[NSBundle mainBundle]]; + return [self policyWithPinningMode:pinningMode withPinnedCertificates:defaultPinnedCertificates]; +} + ++ (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates { + AFSecurityPolicy *securityPolicy = [[self alloc] init]; + securityPolicy.SSLPinningMode = pinningMode; + + [securityPolicy setPinnedCertificates:pinnedCertificates]; + + return securityPolicy; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.validatesDomainName = YES; + + return self; +} + +- (void)setPinnedCertificates:(NSSet *)pinnedCertificates { + _pinnedCertificates = pinnedCertificates; + + if (self.pinnedCertificates) { + NSMutableSet *mutablePinnedPublicKeys = [NSMutableSet setWithCapacity:[self.pinnedCertificates count]]; + for (NSData *certificate in self.pinnedCertificates) { + id publicKey = AFPublicKeyForCertificate(certificate); + if (!publicKey) { + continue; + } + [mutablePinnedPublicKeys addObject:publicKey]; + } + self.pinnedPublicKeys = [NSSet setWithSet:mutablePinnedPublicKeys]; + } else { + self.pinnedPublicKeys = nil; + } +} + +#pragma mark - + +- (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust + forDomain:(NSString *)domain +{ + if (domain && self.allowInvalidCertificates && self.validatesDomainName && (self.SSLPinningMode == AFSSLPinningModeNone || [self.pinnedCertificates count] == 0)) { + // https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/NetworkingTopics/Articles/OverridingSSLChainValidationCorrectly.html + // According to the docs, you should only trust your provided certs for evaluation. + // Pinned certificates are added to the trust. Without pinned certificates, + // there is nothing to evaluate against. + // + // From Apple Docs: + // "Do not implicitly trust self-signed certificates as anchors (kSecTrustOptionImplicitAnchors). + // Instead, add your own (self-signed) CA certificate to the list of trusted anchors." + NSLog(@"In order to validate a domain name for self signed certificates, you MUST use pinning."); + return NO; + } + + NSMutableArray *policies = [NSMutableArray array]; + if (self.validatesDomainName) { + [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)domain)]; + } else { + [policies addObject:(__bridge_transfer id)SecPolicyCreateBasicX509()]; + } + + SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies); + + if (self.SSLPinningMode == AFSSLPinningModeNone) { + return self.allowInvalidCertificates || AFServerTrustIsValid(serverTrust); + } else if (!self.allowInvalidCertificates && !AFServerTrustIsValid(serverTrust)) { + return NO; + } + + switch (self.SSLPinningMode) { + case AFSSLPinningModeCertificate: { + NSMutableArray *pinnedCertificates = [NSMutableArray array]; + for (NSData *certificateData in self.pinnedCertificates) { + [pinnedCertificates addObject:(__bridge_transfer id)SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certificateData)]; + } + SecTrustSetAnchorCertificates(serverTrust, (__bridge CFArrayRef)pinnedCertificates); + + if (!AFServerTrustIsValid(serverTrust)) { + return NO; + } + + // obtain the chain after being validated, which *should* contain the pinned certificate in the last position (if it's the Root CA) + NSArray *serverCertificates = AFCertificateTrustChainForServerTrust(serverTrust); + + for (NSData *trustChainCertificate in [serverCertificates reverseObjectEnumerator]) { + if ([self.pinnedCertificates containsObject:trustChainCertificate]) { + return YES; + } + } + + return NO; + } + case AFSSLPinningModePublicKey: { + NSUInteger trustedPublicKeyCount = 0; + NSArray *publicKeys = AFPublicKeyTrustChainForServerTrust(serverTrust); + + for (id trustChainPublicKey in publicKeys) { + for (id pinnedPublicKey in self.pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)trustChainPublicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + trustedPublicKeyCount += 1; + } + } + } + return trustedPublicKeyCount > 0; + } + + default: + return NO; + } + + return NO; +} + +#pragma mark - NSKeyValueObserving + ++ (NSSet *)keyPathsForValuesAffectingPinnedPublicKeys { + return [NSSet setWithObject:@"pinnedCertificates"]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + + self = [self init]; + if (!self) { + return nil; + } + + self.SSLPinningMode = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(SSLPinningMode))] unsignedIntegerValue]; + self.allowInvalidCertificates = [decoder decodeBoolForKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + self.validatesDomainName = [decoder decodeBoolForKey:NSStringFromSelector(@selector(validatesDomainName))]; + self.pinnedCertificates = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(pinnedCertificates))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:[NSNumber numberWithUnsignedInteger:self.SSLPinningMode] forKey:NSStringFromSelector(@selector(SSLPinningMode))]; + [coder encodeBool:self.allowInvalidCertificates forKey:NSStringFromSelector(@selector(allowInvalidCertificates))]; + [coder encodeBool:self.validatesDomainName forKey:NSStringFromSelector(@selector(validatesDomainName))]; + [coder encodeObject:self.pinnedCertificates forKey:NSStringFromSelector(@selector(pinnedCertificates))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFSecurityPolicy *securityPolicy = [[[self class] allocWithZone:zone] init]; + securityPolicy.SSLPinningMode = self.SSLPinningMode; + securityPolicy.allowInvalidCertificates = self.allowInvalidCertificates; + securityPolicy.validatesDomainName = self.validatesDomainName; + securityPolicy.pinnedCertificates = [self.pinnedCertificates copyWithZone:zone]; + + return securityPolicy; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h new file mode 100644 index 0000000..b17e871 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.h @@ -0,0 +1,479 @@ +// AFURLRequestSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import +#elif TARGET_OS_WATCH +#import +#endif + +NS_ASSUME_NONNULL_BEGIN + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + + @param string The string to be percent-escaped. + + @return The percent-escaped string. + */ +FOUNDATION_EXPORT NSString * AFPercentEscapedStringFromString(NSString *string); + +/** + A helper method to generate encoded url query parameters for appending to the end of a URL. + + @param parameters A dictionary of key/values to be encoded. + + @return A url encoded query string + */ +FOUNDATION_EXPORT NSString * AFQueryStringFromParameters(NSDictionary *parameters); + +/** + The `AFURLRequestSerialization` protocol is adopted by an object that encodes parameters for a specified HTTP requests. Request serializers may encode parameters as query strings, HTTP bodies, setting the appropriate HTTP header fields as necessary. + + For example, a JSON request serializer may set the HTTP body of the request to a JSON representation, and set the `Content-Type` HTTP header field value to `application/json`. + */ +@protocol AFURLRequestSerialization + +/** + Returns a request with the specified parameters encoded into a copy of the original request. + + @param request The original request. + @param parameters The parameters to be encoded. + @param error The error that occurred while attempting to encode the request parameters. + + @return A serialized request. + */ +- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + + */ +typedef NS_ENUM(NSUInteger, AFHTTPRequestQueryStringSerializationStyle) { + AFHTTPRequestQueryStringDefaultStyle = 0, +}; + +@protocol AFMultipartFormData; + +/** + `AFHTTPRequestSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPRequestSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPRequestSerializer : NSObject + +/** + The string encoding used to serialize parameters. `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + Whether created requests can use the device’s cellular radio (if present). `YES` by default. + + @see NSMutableURLRequest -setAllowsCellularAccess: + */ +@property (nonatomic, assign) BOOL allowsCellularAccess; + +/** + The cache policy of created requests. `NSURLRequestUseProtocolCachePolicy` by default. + + @see NSMutableURLRequest -setCachePolicy: + */ +@property (nonatomic, assign) NSURLRequestCachePolicy cachePolicy; + +/** + Whether created requests should use the default cookie handling. `YES` by default. + + @see NSMutableURLRequest -setHTTPShouldHandleCookies: + */ +@property (nonatomic, assign) BOOL HTTPShouldHandleCookies; + +/** + Whether created requests can continue transmitting data before receiving a response from an earlier transmission. `NO` by default + + @see NSMutableURLRequest -setHTTPShouldUsePipelining: + */ +@property (nonatomic, assign) BOOL HTTPShouldUsePipelining; + +/** + The network service type for created requests. `NSURLNetworkServiceTypeDefault` by default. + + @see NSMutableURLRequest -setNetworkServiceType: + */ +@property (nonatomic, assign) NSURLRequestNetworkServiceType networkServiceType; + +/** + The timeout interval, in seconds, for created requests. The default timeout interval is 60 seconds. + + @see NSMutableURLRequest -setTimeoutInterval: + */ +@property (nonatomic, assign) NSTimeInterval timeoutInterval; + +///--------------------------------------- +/// @name Configuring HTTP Request Headers +///--------------------------------------- + +/** + Default HTTP header field values to be applied to serialized requests. By default, these include the following: + + - `Accept-Language` with the contents of `NSLocale +preferredLanguages` + - `User-Agent` with the contents of various bundle identifiers and OS designations + + @discussion To add or remove default request headers, use `setValue:forHTTPHeaderField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *HTTPRequestHeaders; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +/** + Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. + + @param field The HTTP header to set a default value for + @param value The value set as default for the specified header, or `nil` + */ +- (void)setValue:(nullable NSString *)value +forHTTPHeaderField:(NSString *)field; + +/** + Returns the value for the HTTP headers set in the request serializer. + + @param field The HTTP header to retrieve the default value for + + @return The value set as default for the specified header, or `nil` + */ +- (nullable NSString *)valueForHTTPHeaderField:(NSString *)field; + +/** + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. + + @param username The HTTP basic auth username + @param password The HTTP basic auth password + */ +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password; + +/** + Clears any existing value for the "Authorization" HTTP header. + */ +- (void)clearAuthorizationHeader; + +///------------------------------------------------------- +/// @name Configuring Query String Parameter Serialization +///------------------------------------------------------- + +/** + HTTP methods for which serialized requests will encode parameters as a query string. `GET`, `HEAD`, and `DELETE` by default. + */ +@property (nonatomic, strong) NSSet *HTTPMethodsEncodingParametersInURI; + +/** + Set the method of query string serialization according to one of the pre-defined styles. + + @param style The serialization style. + + @see AFHTTPRequestQueryStringSerializationStyle + */ +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style; + +/** + Set the a custom method of query string serialization according to the specified block. + + @param block A block that defines a process of encoding parameters into a query string. This block returns the query string and takes three arguments: the request, the parameters to encode, and the error that occurred when attempting to encode parameters for the given request. + */ +- (void)setQueryStringSerializationWithBlock:(nullable NSString * _Nullable (^)(NSURLRequest *request, id parameters, NSError * __autoreleasing *error))block; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URL string. + + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. + + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object. + */ +- (nullable NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable id)parameters + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and URLString, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 + + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. + + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. + @param URLString The URL string used to create the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. + @param error The error that occurred while constructing the request. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(nullable NSDictionary *)parameters + constructingBodyWithBlock:(nullable void (^)(id formData))block + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Creates an `NSMutableURLRequest` by removing the `HTTPBodyStream` from a request, and asynchronously writing its contents into the specified file, invoking the completion handler when finished. + + @param request The multipart form request. The `HTTPBodyStream` property of `request` must not be `nil`. + @param fileURL The file URL to write multipart form contents to. + @param handler A handler block to execute. + + @discussion There is a bug in `NSURLSessionTask` that causes requests to not send a `Content-Length` header when streaming contents from an HTTP body, which is notably problematic when interacting with the Amazon S3 webservice. As a workaround, this method takes a request constructed with `multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:error:`, or any other request with an `HTTPBodyStream`, writes the contents to the specified file and returns a copy of the original request with the `HTTPBodyStream` property set to `nil`. From here, the file can either be passed to `AFURLSessionManager -uploadTaskWithRequest:fromFile:progress:completionHandler:`, or have its contents read into an `NSData` that's assigned to the `HTTPBody` property of the request. + + @see https://github.com/AFNetworking/AFNetworking/issues/1398 + */ +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(nullable void (^)(NSError * _Nullable error))handler; + +@end + +#pragma mark - + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPRequestSerializer -multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:`. + */ +@protocol AFMultipartFormData + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. + + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended, otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * _Nullable __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. + + @param inputStream The input stream to be appended to the form data + @param name The name to be associated with the specified input stream. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. + @param length The length of the specified input stream in bytes. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithInputStream:(nullable NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + */ + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name; + + +/** + Appends HTTP headers, followed by the encoded data and the multipart form boundary. + + @param headers The HTTP headers to be appended to the form data. + @param body The data to be encoded and appended to the form data. This parameter must not be `nil`. + */ +- (void)appendPartWithHeaders:(nullable NSDictionary *)headers + body:(NSData *)body; + +/** + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. + + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, there is no definite way to distinguish between a 3G, EDGE, or LTE connection over `NSURLConnection`. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. + + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 16kb. + @param delay Duration of delay each time a packet is read. By default, no delay is set. + */ +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay; + +@end + +#pragma mark - + +/** + `AFJSONRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSJSONSerialization`, setting the `Content-Type` of the encoded request to `application/json`. + */ +@interface AFJSONRequestSerializer : AFHTTPRequestSerializer + +/** + Options for writing the request JSON data from Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONWritingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONWritingOptions writingOptions; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param writingOptions The specified JSON writing options. + */ ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions; + +@end + +#pragma mark - + +/** + `AFPropertyListRequestSerializer` is a subclass of `AFHTTPRequestSerializer` that encodes parameters as JSON using `NSPropertyListSerializer`, setting the `Content-Type` of the encoded request to `application/x-plist`. + */ +@interface AFPropertyListRequestSerializer : AFHTTPRequestSerializer + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + @warning The `writeOptions` property is currently unused. + */ +@property (nonatomic, assign) NSPropertyListWriteOptions writeOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param writeOptions The property list write options. + + @warning The `writeOptions` property is currently unused. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions; + +@end + +#pragma mark - + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLRequestSerializationErrorDomain` + + ### Constants + + `AFURLRequestSerializationErrorDomain` + AFURLRequestSerializer errors. Error codes for `AFURLRequestSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLRequestSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLRequestErrorKey` + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFURLRequestSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLRequestErrorKey; + +/** + ## Throttling Bandwidth for HTTP Request Input Streams + + @see -throttleBandwidthWithPacketSize:delay: + + ### Constants + + `kAFUploadStream3GSuggestedPacketSize` + Maximum packet size, in number of bytes. Equal to 16kb. + + `kAFUploadStream3GSuggestedDelay` + Duration of delay each time a packet is read. Equal to 0.2 seconds. + */ +FOUNDATION_EXPORT NSUInteger const kAFUploadStream3GSuggestedPacketSize; +FOUNDATION_EXPORT NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m new file mode 100644 index 0000000..f60b6f9 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLRequestSerialization.m @@ -0,0 +1,1399 @@ +// AFURLRequestSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLRequestSerialization.h" + +#if TARGET_OS_IOS || TARGET_OS_WATCH || TARGET_OS_TV +#import +#else +#import +#endif + +NSString * const AFURLRequestSerializationErrorDomain = @"com.alamofire.error.serialization.request"; +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"com.alamofire.serialization.request.error.response"; + +typedef NSString * (^AFQueryStringSerializationBlock)(NSURLRequest *request, id parameters, NSError *__autoreleasing *error); + +/** + Returns a percent-escaped string following RFC 3986 for a query string key or value. + RFC 3986 states that the following characters are "reserved" characters. + - General Delimiters: ":", "#", "[", "]", "@", "?", "/" + - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" + + In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow + query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" + should be percent-escaped in the query string. + - parameter string: The string to be percent-escaped. + - returns: The percent-escaped string. + */ +NSString * AFPercentEscapedStringFromString(NSString *string) { + static NSString * const kAFCharactersGeneralDelimitersToEncode = @":#[]@"; // does not include "?" or "/" due to RFC 3986 - Section 3.4 + static NSString * const kAFCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kAFCharactersGeneralDelimitersToEncode stringByAppendingString:kAFCharactersSubDelimitersToEncode]]; + + // FIXME: https://github.com/AFNetworking/AFNetworking/pull/3028 + // return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + NSUInteger length = MIN(string.length - index, batchSize); + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (instancetype)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValue; +@end + +@implementation AFQueryStringPair + +- (instancetype)initWithField:(id)field value:(id)value { + self = [super init]; + if (!self) { + return nil; + } + + self.field = field; + self.value = value; + + return self; +} + +- (NSString *)URLEncodedStringValue { + if (!self.value || [self.value isEqual:[NSNull null]]) { + return AFPercentEscapedStringFromString([self.field description]); + } else { + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedStringFromString([self.field description]), AFPercentEscapedStringFromString([self.value description])]; + } +} + +@end + +#pragma mark - + +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +FOUNDATION_EXPORT NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +NSString * AFQueryStringFromParameters(NSDictionary *parameters) { + NSMutableArray *mutablePairs = [NSMutableArray array]; + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + [mutablePairs addObject:[pair URLEncodedStringValue]]; + } + + return [mutablePairs componentsJoinedByString:@"&"]; +} + +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { + return AFQueryStringPairsFromKeyAndValue(nil, dictionary); +} + +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; + + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(compare:)]; + + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictionary = value; + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + id nestedValue = dictionary[nestedKey]; + if (nestedValue) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; + } + } + } else if ([value isKindOfClass:[NSArray class]]) { + NSArray *array = value; + for (id nestedValue in array) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; + } + } else if ([value isKindOfClass:[NSSet class]]) { + NSSet *set = value; + for (id obj in [set sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; + } + } else { + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; + } + + return mutableQueryStringComponents; +} + +#pragma mark - + +@interface AFStreamingMultipartFormData : NSObject +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; +@end + +#pragma mark - + +static NSArray * AFHTTPRequestSerializerObservedKeyPaths() { + static NSArray *_AFHTTPRequestSerializerObservedKeyPaths = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _AFHTTPRequestSerializerObservedKeyPaths = @[NSStringFromSelector(@selector(allowsCellularAccess)), NSStringFromSelector(@selector(cachePolicy)), NSStringFromSelector(@selector(HTTPShouldHandleCookies)), NSStringFromSelector(@selector(HTTPShouldUsePipelining)), NSStringFromSelector(@selector(networkServiceType)), NSStringFromSelector(@selector(timeoutInterval))]; + }); + + return _AFHTTPRequestSerializerObservedKeyPaths; +} + +static void *AFHTTPRequestSerializerObserverContext = &AFHTTPRequestSerializerObserverContext; + +@interface AFHTTPRequestSerializer () +@property (readwrite, nonatomic, strong) NSMutableSet *mutableObservedChangedKeyPaths; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableHTTPRequestHeaders; +@property (readwrite, nonatomic, strong) dispatch_queue_t requestHeaderModificationQueue; +@property (readwrite, nonatomic, assign) AFHTTPRequestQueryStringSerializationStyle queryStringSerializationStyle; +@property (readwrite, nonatomic, copy) AFQueryStringSerializationBlock queryStringSerialization; +@end + +@implementation AFHTTPRequestSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = NSUTF8StringEncoding; + + self.mutableHTTPRequestHeaders = [NSMutableDictionary dictionary]; + self.requestHeaderModificationQueue = dispatch_queue_create("requestHeaderModificationQueue", DISPATCH_QUEUE_CONCURRENT); + + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + float q = 1.0f - (idx * 0.1f); + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; + *stop = q <= 0.5f; + }]; + [self setValue:[acceptLanguagesComponents componentsJoinedByString:@", "] forHTTPHeaderField:@"Accept-Language"]; + + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + NSString *userAgent = nil; +#if TARGET_OS_IOS + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif TARGET_OS_TV + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; tvOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; +#elif TARGET_OS_WATCH + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; watchOS %@; Scale/%0.2f)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[WKInterfaceDevice currentDevice] model], [[WKInterfaceDevice currentDevice] systemVersion], [[WKInterfaceDevice currentDevice] screenScale]]; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleExecutableKey] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleIdentifierKey], [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"] ?: [[NSBundle mainBundle] infoDictionary][(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; +#endif + if (userAgent) { + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { + NSMutableString *mutableUserAgent = [userAgent mutableCopy]; + if (CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, (__bridge CFStringRef)@"Any-Latin; Latin-ASCII; [:^ASCII:] Remove", false)) { + userAgent = mutableUserAgent; + } + } + [self setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + + // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + self.HTTPMethodsEncodingParametersInURI = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil]; + + self.mutableObservedChangedKeyPaths = [NSMutableSet set]; + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionNew context:AFHTTPRequestSerializerObserverContext]; + } + } + + return self; +} + +- (void)dealloc { + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self respondsToSelector:NSSelectorFromString(keyPath)]) { + [self removeObserver:self forKeyPath:keyPath context:AFHTTPRequestSerializerObserverContext]; + } + } +} + +#pragma mark - + +// Workarounds for crashing behavior using Key-Value Observing with XCTest +// See https://github.com/AFNetworking/AFNetworking/issues/2523 + +- (void)setAllowsCellularAccess:(BOOL)allowsCellularAccess { + [self willChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; + _allowsCellularAccess = allowsCellularAccess; + [self didChangeValueForKey:NSStringFromSelector(@selector(allowsCellularAccess))]; +} + +- (void)setCachePolicy:(NSURLRequestCachePolicy)cachePolicy { + [self willChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; + _cachePolicy = cachePolicy; + [self didChangeValueForKey:NSStringFromSelector(@selector(cachePolicy))]; +} + +- (void)setHTTPShouldHandleCookies:(BOOL)HTTPShouldHandleCookies { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; + _HTTPShouldHandleCookies = HTTPShouldHandleCookies; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldHandleCookies))]; +} + +- (void)setHTTPShouldUsePipelining:(BOOL)HTTPShouldUsePipelining { + [self willChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; + _HTTPShouldUsePipelining = HTTPShouldUsePipelining; + [self didChangeValueForKey:NSStringFromSelector(@selector(HTTPShouldUsePipelining))]; +} + +- (void)setNetworkServiceType:(NSURLRequestNetworkServiceType)networkServiceType { + [self willChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; + _networkServiceType = networkServiceType; + [self didChangeValueForKey:NSStringFromSelector(@selector(networkServiceType))]; +} + +- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval { + [self willChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; + _timeoutInterval = timeoutInterval; + [self didChangeValueForKey:NSStringFromSelector(@selector(timeoutInterval))]; +} + +#pragma mark - + +- (NSDictionary *)HTTPRequestHeaders { + NSDictionary __block *value; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders]; + }); + return value; +} + +- (void)setValue:(NSString *)value +forHTTPHeaderField:(NSString *)field +{ + dispatch_barrier_sync(self.requestHeaderModificationQueue, ^{ + [self.mutableHTTPRequestHeaders setValue:value forKey:field]; + }); +} + +- (NSString *)valueForHTTPHeaderField:(NSString *)field { + NSString __block *value; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + value = [self.mutableHTTPRequestHeaders valueForKey:field]; + }); + return value; +} + +- (void)setAuthorizationHeaderFieldWithUsername:(NSString *)username + password:(NSString *)password +{ + NSData *basicAuthCredentials = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]; + NSString *base64AuthCredentials = [basicAuthCredentials base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0]; + [self setValue:[NSString stringWithFormat:@"Basic %@", base64AuthCredentials] forHTTPHeaderField:@"Authorization"]; +} + +- (void)clearAuthorizationHeader { + dispatch_barrier_sync(self.requestHeaderModificationQueue, ^{ + [self.mutableHTTPRequestHeaders removeObjectForKey:@"Authorization"]; + }); +} + +#pragma mark - + +- (void)setQueryStringSerializationWithStyle:(AFHTTPRequestQueryStringSerializationStyle)style { + self.queryStringSerializationStyle = style; + self.queryStringSerialization = nil; +} + +- (void)setQueryStringSerializationWithBlock:(NSString *(^)(NSURLRequest *, id, NSError *__autoreleasing *))block { + self.queryStringSerialization = block; +} + +#pragma mark - + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(URLString); + + NSURL *url = [NSURL URLWithString:URLString]; + + NSParameterAssert(url); + + NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url]; + mutableRequest.HTTPMethod = method; + + for (NSString *keyPath in AFHTTPRequestSerializerObservedKeyPaths()) { + if ([self.mutableObservedChangedKeyPaths containsObject:keyPath]) { + [mutableRequest setValue:[self valueForKeyPath:keyPath] forKey:keyPath]; + } + } + + mutableRequest = [[self requestBySerializingRequest:mutableRequest withParameters:parameters error:error] mutableCopy]; + + return mutableRequest; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + URLString:(NSString *)URLString + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(method); + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); + + NSMutableURLRequest *mutableRequest = [self requestWithMethod:method URLString:URLString parameters:nil error:error]; + + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:mutableRequest stringEncoding:NSUTF8StringEncoding]; + + if (parameters) { + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + NSData *data = nil; + if ([pair.value isKindOfClass:[NSData class]]) { + data = pair.value; + } else if ([pair.value isEqual:[NSNull null]]) { + data = [NSData data]; + } else { + data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; + } + + if (data) { + [formData appendPartWithFormData:data name:[pair.field description]]; + } + } + } + + if (block) { + block(formData); + } + + return [formData requestByFinalizingMultipartFormData]; +} + +- (NSMutableURLRequest *)requestWithMultipartFormRequest:(NSURLRequest *)request + writingStreamContentsToFile:(NSURL *)fileURL + completionHandler:(void (^)(NSError *error))handler +{ + NSParameterAssert(request.HTTPBodyStream); + NSParameterAssert([fileURL isFileURL]); + + NSInputStream *inputStream = request.HTTPBodyStream; + NSOutputStream *outputStream = [[NSOutputStream alloc] initWithURL:fileURL append:NO]; + __block NSError *error = nil; + + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + + [inputStream open]; + [outputStream open]; + + while ([inputStream hasBytesAvailable] && [outputStream hasSpaceAvailable]) { + uint8_t buffer[1024]; + + NSInteger bytesRead = [inputStream read:buffer maxLength:1024]; + if (inputStream.streamError || bytesRead < 0) { + error = inputStream.streamError; + break; + } + + NSInteger bytesWritten = [outputStream write:buffer maxLength:(NSUInteger)bytesRead]; + if (outputStream.streamError || bytesWritten < 0) { + error = outputStream.streamError; + break; + } + + if (bytesRead == 0 && bytesWritten == 0) { + break; + } + } + + [outputStream close]; + [inputStream close]; + + if (handler) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler(error); + }); + } + }); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.HTTPBodyStream = nil; + + return mutableRequest; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + NSString *query = nil; + if (parameters) { + if (self.queryStringSerialization) { + NSError *serializationError; + query = self.queryStringSerialization(request, parameters, &serializationError); + + if (serializationError) { + if (error) { + *error = serializationError; + } + + return nil; + } + } else { + switch (self.queryStringSerializationStyle) { + case AFHTTPRequestQueryStringDefaultStyle: + query = AFQueryStringFromParameters(parameters); + break; + } + } + } + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + if (query && query.length > 0) { + mutableRequest.URL = [NSURL URLWithString:[[mutableRequest.URL absoluteString] stringByAppendingFormat:mutableRequest.URL.query ? @"&%@" : @"?%@", query]]; + } + } else { + // #2864: an empty string is a valid x-www-form-urlencoded payload + if (!query) { + query = @""; + } + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; + } + [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]]; + } + + return mutableRequest; +} + +#pragma mark - NSKeyValueObserving + ++ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key { + if ([AFHTTPRequestSerializerObservedKeyPaths() containsObject:key]) { + return NO; + } + + return [super automaticallyNotifiesObserversForKey:key]; +} + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(__unused id)object + change:(NSDictionary *)change + context:(void *)context +{ + if (context == AFHTTPRequestSerializerObserverContext) { + if ([change[NSKeyValueChangeNewKey] isEqual:[NSNull null]]) { + [self.mutableObservedChangedKeyPaths removeObject:keyPath]; + } else { + [self.mutableObservedChangedKeyPaths addObject:keyPath]; + } + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.mutableHTTPRequestHeaders = [[decoder decodeObjectOfClass:[NSDictionary class] forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))] mutableCopy]; + self.queryStringSerializationStyle = (AFHTTPRequestQueryStringSerializationStyle)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + dispatch_sync(self.requestHeaderModificationQueue, ^{ + [coder encodeObject:self.mutableHTTPRequestHeaders forKey:NSStringFromSelector(@selector(mutableHTTPRequestHeaders))]; + }); + [coder encodeObject:@(self.queryStringSerializationStyle) forKey:NSStringFromSelector(@selector(queryStringSerializationStyle))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPRequestSerializer *serializer = [[[self class] allocWithZone:zone] init]; + dispatch_sync(self.requestHeaderModificationQueue, ^{ + serializer.mutableHTTPRequestHeaders = [self.mutableHTTPRequestHeaders mutableCopyWithZone:zone]; + }); + serializer.queryStringSerializationStyle = self.queryStringSerializationStyle; + serializer.queryStringSerialization = self.queryStringSerialization; + + return serializer; +} + +@end + +#pragma mark - + +static NSString * AFCreateMultipartFormBoundary() { + return [NSString stringWithFormat:@"Boundary+%08X%08X", arc4random(), arc4random()]; +} + +static NSString * const kAFMultipartFormCRLF = @"\r\n"; + +static inline NSString * AFMultipartFormInitialBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"--%@%@", boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormEncapsulationBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormFinalBoundary(NSString *boundary) { + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, boundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFContentTypeForPathExtension(NSString *extension) { + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); + if (!contentType) { + return @"application/octet-stream"; + } else { + return contentType; + } +} + +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, copy) NSString *boundary; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) unsigned long long bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; + +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; + +@property (readonly, nonatomic, assign, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (readonly, nonatomic, assign) unsigned long long contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@interface AFMultipartBodyStream : NSInputStream +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; +@property (nonatomic, assign) NSTimeInterval delay; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (readonly, nonatomic, assign) unsigned long long contentLength; +@property (readonly, nonatomic, assign, getter = isEmpty) BOOL empty; + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding; +- (void)setInitialAndFinalBoundaries; +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; +@end + +#pragma mark - + +@interface AFStreamingMultipartFormData () +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, copy) NSString *boundary; +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; +@end + +@implementation AFStreamingMultipartFormData + +- (instancetype)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding +{ + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + self.stringEncoding = encoding; + self.boundary = AFCreateMultipartFormBoundary(); + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; + + return self; +} + +- (void)setRequest:(NSMutableURLRequest *)request +{ + _request = [request mutableCopy]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + + NSString *fileName = [fileURL lastPathComponent]; + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); + + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + if (![fileURL isFileURL]) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil)}; + if (error) { + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } + + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:error]; + if (!fileAttributes) { + return NO; + } + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = fileURL; + bodyPart.bodyContentLength = [fileAttributes[NSFileSize] unsignedLongLongValue]; + [self.bodyStream appendHTTPBodyPart:bodyPart]; + + return YES; +} + +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(int64_t)length + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.boundary = self.boundary; + bodyPart.body = inputStream; + + bodyPart.bodyContentLength = (unsigned long long)length; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name +{ + NSParameterAssert(name); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body +{ + NSParameterAssert(body); + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = headers; + bodyPart.boundary = self.boundary; + bodyPart.bodyContentLength = [body length]; + bodyPart.body = body; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay +{ + self.bodyStream.numberOfBytesInPacket = numberOfBytes; + self.bodyStream.delay = delay; +} + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { + if ([self.bodyStream isEmpty]) { + return self.request; + } + + // Reset the initial and final boundaries to ensure correct Content-Length + [self.bodyStream setInitialAndFinalBoundaries]; + [self.request setHTTPBodyStream:self.bodyStream]; + + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", self.boundary] forHTTPHeaderField:@"Content-Type"]; + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; + + return self.request; +} + +@end + +#pragma mark - + +@interface NSStream () +@property (readwrite) NSStreamStatus streamStatus; +@property (readwrite, copy) NSError *streamError; +@end + +@interface AFMultipartBodyStream () +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@property (readwrite, nonatomic, strong) NSMutableArray *HTTPBodyParts; +@property (readwrite, nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; +@property (readwrite, nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; +@property (readwrite, nonatomic, strong) NSOutputStream *outputStream; +@property (readwrite, nonatomic, strong) NSMutableData *buffer; +@end + +@implementation AFMultipartBodyStream +#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1100) +@synthesize delegate; +#endif +@synthesize streamStatus; +@synthesize streamError; + +- (instancetype)initWithStringEncoding:(NSStringEncoding)encoding { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = encoding; + self.HTTPBodyParts = [NSMutableArray array]; + self.numberOfBytesInPacket = NSIntegerMax; + + return self; +} + +- (void)setInitialAndFinalBoundaries { + if ([self.HTTPBodyParts count] > 0) { + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + bodyPart.hasInitialBoundary = NO; + bodyPart.hasFinalBoundary = NO; + } + + [[self.HTTPBodyParts firstObject] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; + } +} + +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { + [self.HTTPBodyParts addObject:bodyPart]; +} + +- (BOOL)isEmpty { + return [self.HTTPBodyParts count] == 0; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + if ([self streamStatus] == NSStreamStatusClosed) { + return 0; + } + + NSInteger totalNumberOfBytesRead = 0; + + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = MIN(length, self.numberOfBytesInPacket) - (NSUInteger)totalNumberOfBytesRead; + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; + if (numberOfBytesRead == -1) { + self.streamError = self.currentHTTPBodyPart.inputStream.streamError; + break; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if (self.delay > 0.0f) { + [NSThread sleepForTimeInterval:self.delay]; + } + } + } + } + + return totalNumberOfBytesRead; +} + +- (BOOL)getBuffer:(__unused uint8_t **)buffer + length:(__unused NSUInteger *)len +{ + return NO; +} + +- (BOOL)hasBytesAvailable { + return [self streamStatus] == NSStreamStatusOpen; +} + +#pragma mark - NSStream + +- (void)open { + if (self.streamStatus == NSStreamStatusOpen) { + return; + } + + self.streamStatus = NSStreamStatusOpen; + + [self setInitialAndFinalBoundaries]; + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; +} + +- (void)close { + self.streamStatus = NSStreamStatusClosed; +} + +- (id)propertyForKey:(__unused NSString *)key { + return nil; +} + +- (BOOL)setProperty:(__unused id)property + forKey:(__unused NSString *)key +{ + return NO; +} + +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + length += [bodyPart contentLength]; + } + + return length; +} + +#pragma mark - Undocumented CFReadStream Bridged Methods + +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags + callback:(__unused CFReadStreamClientCallBack)inCallback + context:(__unused CFStreamClientContext *)inContext { + return NO; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; + + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; + } + + [bodyStreamCopy setInitialAndFinalBoundaries]; + + return bodyStreamCopy; +} + +@end + +#pragma mark - + +typedef enum { + AFEncapsulationBoundaryPhase = 1, + AFHeaderPhase = 2, + AFBodyPhase = 3, + AFFinalBoundaryPhase = 4, +} AFHTTPBodyPartReadPhase; + +@interface AFHTTPBodyPart () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + [self transitionToNextPhase]; + + return self; +} + +- (void)dealloc { + if (_inputStream) { + [_inputStream close]; + _inputStream = nil; + } +} + +- (NSInputStream *)inputStream { + if (!_inputStream) { + if ([self.body isKindOfClass:[NSData class]]) { + _inputStream = [NSInputStream inputStreamWithData:self.body]; + } else if ([self.body isKindOfClass:[NSURL class]]) { + _inputStream = [NSInputStream inputStreamWithURL:self.body]; + } else if ([self.body isKindOfClass:[NSInputStream class]]) { + _inputStream = self.body; + } else { + _inputStream = [NSInputStream inputStreamWithData:[NSData data]]; + } + } + + return _inputStream; +} + +- (NSString *)stringForHeaders { + NSMutableString *headerString = [NSMutableString string]; + for (NSString *field in [self.headers allKeys]) { + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; + } + [headerString appendString:kAFMultipartFormCRLF]; + + return [NSString stringWithString:headerString]; +} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + length += [encapsulationBoundaryData length]; + + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + length += [headersData length]; + + length += _bodyContentLength; + + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + length += [closingBoundaryData length]; + + return length; +} + +- (BOOL)hasBytesAvailable { + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer + if (_phase == AFFinalBoundaryPhase) { + return YES; + } + + switch (self.inputStream.streamStatus) { + case NSStreamStatusNotOpen: + case NSStreamStatusOpening: + case NSStreamStatusOpen: + case NSStreamStatusReading: + case NSStreamStatusWriting: + return YES; + case NSStreamStatusAtEnd: + case NSStreamStatusClosed: + case NSStreamStatusError: + default: + return NO; + } +} + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSInteger totalNumberOfBytesRead = 0; + + if (_phase == AFEncapsulationBoundaryPhase) { + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary(self.boundary) : AFMultipartFormEncapsulationBoundary(self.boundary)) dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFHeaderPhase) { + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFBodyPhase) { + NSInteger numberOfBytesRead = 0; + + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + if (numberOfBytesRead == -1) { + return -1; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { + [self transitionToNextPhase]; + } + } + } + + if (_phase == AFFinalBoundaryPhase) { + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary(self.boundary) dataUsingEncoding:self.stringEncoding] : [NSData data]); + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + return totalNumberOfBytesRead; +} + +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; + + _phaseReadOffset += range.length; + + if (((NSUInteger)_phaseReadOffset) >= [data length]) { + [self transitionToNextPhase]; + } + + return (NSInteger)range.length; +} + +- (BOOL)transitionToNextPhase { + if (![[NSThread currentThread] isMainThread]) { + dispatch_sync(dispatch_get_main_queue(), ^{ + [self transitionToNextPhase]; + }); + return YES; + } + + switch (_phase) { + case AFEncapsulationBoundaryPhase: + _phase = AFHeaderPhase; + break; + case AFHeaderPhase: + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.inputStream open]; + _phase = AFBodyPhase; + break; + case AFBodyPhase: + [self.inputStream close]; + _phase = AFFinalBoundaryPhase; + break; + case AFFinalBoundaryPhase: + default: + _phase = AFEncapsulationBoundaryPhase; + break; + } + _phaseReadOffset = 0; + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; + + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = self.headers; + bodyPart.bodyContentLength = self.bodyContentLength; + bodyPart.body = self.body; + bodyPart.boundary = self.boundary; + + return bodyPart; +} + +@end + +#pragma mark - + +@implementation AFJSONRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithWritingOptions:(NSJSONWritingOptions)0]; +} + ++ (instancetype)serializerWithWritingOptions:(NSJSONWritingOptions)writingOptions +{ + AFJSONRequestSerializer *serializer = [[self alloc] init]; + serializer.writingOptions = writingOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerialization + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; + } + + if (![NSJSONSerialization isValidJSONObject:parameters]) { + if (error) { + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)}; + *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; + } + return nil; + } + + NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]; + + if (!jsonData) { + return nil; + } + + [mutableRequest setHTTPBody:jsonData]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.writingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writingOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.writingOptions) forKey:NSStringFromSelector(@selector(writingOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.writingOptions = self.writingOptions; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFPropertyListRequestSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 writeOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + writeOptions:(NSPropertyListWriteOptions)writeOptions +{ + AFPropertyListRequestSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.writeOptions = writeOptions; + + return serializer; +} + +#pragma mark - AFURLRequestSerializer + +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + NSParameterAssert(request); + + if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) { + if (![request valueForHTTPHeaderField:field]) { + [mutableRequest setValue:value forHTTPHeaderField:field]; + } + }]; + + if (parameters) { + if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) { + [mutableRequest setValue:@"application/x-plist" forHTTPHeaderField:@"Content-Type"]; + } + + NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:parameters format:self.format options:self.writeOptions error:error]; + + if (!plistData) { + return nil; + } + + [mutableRequest setHTTPBody:plistData]; + } + + return mutableRequest; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.writeOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(writeOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.writeOptions) forKey:NSStringFromSelector(@selector(writeOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListRequestSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.writeOptions = self.writeOptions; + + return serializer; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h new file mode 100644 index 0000000..56a4d28 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.h @@ -0,0 +1,313 @@ +// AFURLResponseSerialization.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + Recursively removes `NSNull` values from a JSON object. +*/ +FOUNDATION_EXPORT id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions); + +/** + The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data. + + For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object. + */ +@protocol AFURLResponseSerialization + +/** + The response object decoded from the data associated with a specified response. + + @param response The response to be processed. + @param data The response data to be decoded. + @param error The error that occurred while attempting to decode the response data. + + @return The object decoded from the specified response data. + */ +- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW; + +@end + +#pragma mark - + +/** + `AFHTTPResponseSerializer` conforms to the `AFURLRequestSerialization` & `AFURLResponseSerialization` protocols, offering a concrete base implementation of query string / URL form-encoded parameter serialization and default request headers, as well as response status code and content type validation. + + Any request or response serializer dealing with HTTP is encouraged to subclass `AFHTTPResponseSerializer` in order to ensure consistent default behavior. + */ +@interface AFHTTPResponseSerializer : NSObject + +- (instancetype)init; + +/** + Creates and returns a serializer with default configuration. + */ ++ (instancetype)serializer; + +///----------------------------------------- +/// @name Configuring Response Serialization +///----------------------------------------- + +/** + The acceptable HTTP status codes for responses. When non-`nil`, responses with status codes not contained by the set will result in an error during validation. + + See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + */ +@property (nonatomic, copy, nullable) NSIndexSet *acceptableStatusCodes; + +/** + The acceptable MIME types for responses. When non-`nil`, responses with a `Content-Type` with MIME types that do not intersect with the set will result in an error during validation. + */ +@property (nonatomic, copy, nullable) NSSet *acceptableContentTypes; + +/** + Validates the specified response and data. + + In its base implementation, this method checks for an acceptable status code and content type. Subclasses may wish to add other domain-specific checks. + + @param response The response to be validated. + @param data The data associated with the response. + @param error The error that occurred while attempting to validate the response. + + @return `YES` if the response is valid, otherwise `NO`. + */ +- (BOOL)validateResponse:(nullable NSHTTPURLResponse *)response + data:(nullable NSData *)data + error:(NSError * _Nullable __autoreleasing *)error; + +@end + +#pragma mark - + + +/** + `AFJSONResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes JSON responses. + + By default, `AFJSONResponseSerializer` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + - `text/javascript` + + In RFC 7159 - Section 8.1, it states that JSON text is required to be encoded in UTF-8, UTF-16, or UTF-32, and the default encoding is UTF-8. NSJSONSerialization provides support for all the encodings listed in the specification, and recommends UTF-8 for efficiency. Using an unsupported encoding will result in serialization error. See the `NSJSONSerialization` documentation for more details. + */ +@interface AFJSONResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". `0` by default. + */ +@property (nonatomic, assign) NSJSONReadingOptions readingOptions; + +/** + Whether to remove keys with `NSNull` values from response JSON. Defaults to `NO`. + */ +@property (nonatomic, assign) BOOL removesKeysWithNullValues; + +/** + Creates and returns a JSON serializer with specified reading and writing options. + + @param readingOptions The specified JSON reading options. + */ ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions; + +@end + +#pragma mark - + +/** + `AFXMLParserResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLParser` objects. + + By default, `AFXMLParserResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLParserResponseSerializer : AFHTTPResponseSerializer + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +/** + `AFXMLDocumentResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFXMLDocumentResponseSerializer` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + */ +@interface AFXMLDocumentResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + Input and output options specifically intended for `NSXMLDocument` objects. For possible values, see the `NSXMLDocument` documentation section "Input and Output Options". `0` by default. + */ +@property (nonatomic, assign) NSUInteger options; + +/** + Creates and returns an XML document serializer with the specified options. + + @param mask The XML document options. + */ ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask; + +@end + +#endif + +#pragma mark - + +/** + `AFPropertyListResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes XML responses as an `NSXMLDocument` objects. + + By default, `AFPropertyListResponseSerializer` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListResponseSerializer : AFHTTPResponseSerializer + +- (instancetype)init; + +/** + The property list format. Possible values are described in "NSPropertyListFormat". + */ +@property (nonatomic, assign) NSPropertyListFormat format; + +/** + The property list reading options. Possible values are described in "NSPropertyListMutabilityOptions." + */ +@property (nonatomic, assign) NSPropertyListReadOptions readOptions; + +/** + Creates and returns a property list serializer with a specified format, read options, and write options. + + @param format The property list format. + @param readOptions The property list reading options. + */ ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions; + +@end + +#pragma mark - + +/** + `AFImageResponseSerializer` is a subclass of `AFHTTPResponseSerializer` that validates and decodes image responses. + + By default, `AFImageResponseSerializer` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + + - `image/tiff` + - `image/jpeg` + - `image/gif` + - `image/png` + - `image/ico` + - `image/x-icon` + - `image/bmp` + - `image/x-bmp` + - `image/x-xbitmap` + - `image/x-win-bitmap` + */ +@interface AFImageResponseSerializer : AFHTTPResponseSerializer + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +/** + The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. + */ +@property (nonatomic, assign) CGFloat imageScale; + +/** + Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. + */ +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; +#endif + +@end + +#pragma mark - + +/** + `AFCompoundSerializer` is a subclass of `AFHTTPResponseSerializer` that delegates the response serialization to the first `AFHTTPResponseSerializer` object that returns an object for `responseObjectForResponse:data:error:`, falling back on the default behavior of `AFHTTPResponseSerializer`. This is useful for supporting multiple potential types and structures of server responses with a single serializer. + */ +@interface AFCompoundResponseSerializer : AFHTTPResponseSerializer + +/** + The component response serializers. + */ +@property (readonly, nonatomic, copy) NSArray > *responseSerializers; + +/** + Creates and returns a compound serializer comprised of the specified response serializers. + + @warning Each response serializer specified must be a subclass of `AFHTTPResponseSerializer`, and response to `-validateResponse:data:error:`. + */ ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray > *)responseSerializers; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFURLResponseSerializationErrorDomain` + + ### Constants + + `AFURLResponseSerializationErrorDomain` + AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFURLResponseSerializationErrorDomain; + +/** + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + + `AFNetworkingOperationFailingURLResponseDataErrorKey` + The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +FOUNDATION_EXPORT NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m new file mode 100755 index 0000000..2715a1b --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLResponseSerialization.m @@ -0,0 +1,836 @@ +// AFURLResponseSerialization.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLResponseSerialization.h" + +#import + +#if TARGET_OS_IOS +#import +#elif TARGET_OS_WATCH +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +NSString * const AFURLResponseSerializationErrorDomain = @"com.alamofire.error.serialization.response"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"com.alamofire.serialization.response.error.response"; +NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey = @"com.alamofire.serialization.response.error.data"; + +static NSError * AFErrorWithUnderlyingError(NSError *error, NSError *underlyingError) { + if (!error) { + return underlyingError; + } + + if (!underlyingError || error.userInfo[NSUnderlyingErrorKey]) { + return error; + } + + NSMutableDictionary *mutableUserInfo = [error.userInfo mutableCopy]; + mutableUserInfo[NSUnderlyingErrorKey] = underlyingError; + + return [[NSError alloc] initWithDomain:error.domain code:error.code userInfo:mutableUserInfo]; +} + +static BOOL AFErrorOrUnderlyingErrorHasCodeInDomain(NSError *error, NSInteger code, NSString *domain) { + if ([error.domain isEqualToString:domain] && error.code == code) { + return YES; + } else if (error.userInfo[NSUnderlyingErrorKey]) { + return AFErrorOrUnderlyingErrorHasCodeInDomain(error.userInfo[NSUnderlyingErrorKey], code, domain); + } + + return NO; +} + +id AFJSONObjectByRemovingKeysWithNullValues(id JSONObject, NSJSONReadingOptions readingOptions) { + if ([JSONObject isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]]; + for (id value in (NSArray *)JSONObject) { + if (![value isEqual:[NSNull null]]) { + [mutableArray addObject:AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions)]; + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray]; + } else if ([JSONObject isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject]; + for (id key in [(NSDictionary *)JSONObject allKeys]) { + id value = (NSDictionary *)JSONObject[key]; + if (!value || [value isEqual:[NSNull null]]) { + [mutableDictionary removeObjectForKey:key]; + } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) { + mutableDictionary[key] = AFJSONObjectByRemovingKeysWithNullValues(value, readingOptions); + } + } + + return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary]; + } + + return JSONObject; +} + +@implementation AFHTTPResponseSerializer + ++ (instancetype)serializer { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; + self.acceptableContentTypes = nil; + + return self; +} + +#pragma mark - + +- (BOOL)validateResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError * __autoreleasing *)error +{ + BOOL responseIsValid = YES; + NSError *validationError = nil; + + if ([response isKindOfClass:[NSHTTPURLResponse class]]) { + if (self.acceptableContentTypes && ![self.acceptableContentTypes containsObject:[response MIMEType]] && + !([response MIMEType] == nil && [data length] == 0)) { + + if ([data length] > 0 && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: unacceptable content-type: %@", @"AFNetworking", nil), [response MIMEType]], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:mutableUserInfo], validationError); + } + + responseIsValid = NO; + } + + if (self.acceptableStatusCodes && ![self.acceptableStatusCodes containsIndex:(NSUInteger)response.statusCode] && [response URL]) { + NSMutableDictionary *mutableUserInfo = [@{ + NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedStringFromTable(@"Request failed: %@ (%ld)", @"AFNetworking", nil), [NSHTTPURLResponse localizedStringForStatusCode:response.statusCode], (long)response.statusCode], + NSURLErrorFailingURLErrorKey:[response URL], + AFNetworkingOperationFailingURLResponseErrorKey: response, + } mutableCopy]; + + if (data) { + mutableUserInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] = data; + } + + validationError = AFErrorWithUnderlyingError([NSError errorWithDomain:AFURLResponseSerializationErrorDomain code:NSURLErrorBadServerResponse userInfo:mutableUserInfo], validationError); + + responseIsValid = NO; + } + } + + if (error && !responseIsValid) { + *error = validationError; + } + + return responseIsValid; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + [self validateResponse:(NSHTTPURLResponse *)response data:data error:error]; + + return data; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [self init]; + if (!self) { + return nil; + } + + self.acceptableStatusCodes = [decoder decodeObjectOfClass:[NSIndexSet class] forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + self.acceptableContentTypes = [decoder decodeObjectOfClass:[NSSet class] forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.acceptableStatusCodes forKey:NSStringFromSelector(@selector(acceptableStatusCodes))]; + [coder encodeObject:self.acceptableContentTypes forKey:NSStringFromSelector(@selector(acceptableContentTypes))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFHTTPResponseSerializer *serializer = [[[self class] allocWithZone:zone] init]; + serializer.acceptableStatusCodes = [self.acceptableStatusCodes copyWithZone:zone]; + serializer.acceptableContentTypes = [self.acceptableContentTypes copyWithZone:zone]; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFJSONResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:(NSJSONReadingOptions)0]; +} + ++ (instancetype)serializerWithReadingOptions:(NSJSONReadingOptions)readingOptions { + AFJSONResponseSerializer *serializer = [[self alloc] init]; + serializer.readingOptions = readingOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + BOOL isSpace = [data isEqualToData:[NSData dataWithBytes:" " length:1]]; + + if (data.length == 0 || isSpace) { + return nil; + } + + NSError *serializationError = nil; + + id responseObject = [NSJSONSerialization JSONObjectWithData:data options:self.readingOptions error:&serializationError]; + + if (!responseObject) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + if (self.removesKeysWithNullValues) { + return AFJSONObjectByRemovingKeysWithNullValues(responseObject, self.readingOptions); + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.readingOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readingOptions))] unsignedIntegerValue]; + self.removesKeysWithNullValues = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.readingOptions) forKey:NSStringFromSelector(@selector(readingOptions))]; + [coder encodeObject:@(self.removesKeysWithNullValues) forKey:NSStringFromSelector(@selector(removesKeysWithNullValues))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFJSONResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.readingOptions = self.readingOptions; + serializer.removesKeysWithNullValues = self.removesKeysWithNullValues; + + return serializer; +} + +@end + +#pragma mark - + +@implementation AFXMLParserResponseSerializer + ++ (instancetype)serializer { + AFXMLParserResponseSerializer *serializer = [[self alloc] init]; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSHTTPURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + return [[NSXMLParser alloc] initWithData:data]; +} + +@end + +#pragma mark - + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED + +@implementation AFXMLDocumentResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithXMLDocumentOptions:0]; +} + ++ (instancetype)serializerWithXMLDocumentOptions:(NSUInteger)mask { + AFXMLDocumentResponseSerializer *serializer = [[self alloc] init]; + serializer.options = mask; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/xml", @"text/xml", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + NSError *serializationError = nil; + NSXMLDocument *document = [[NSXMLDocument alloc] initWithData:data options:self.options error:&serializationError]; + + if (!document) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + return document; +} + +#pragma mark - NSSecureCoding + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.options = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(options))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.options) forKey:NSStringFromSelector(@selector(options))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFXMLDocumentResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.options = self.options; + + return serializer; +} + +@end + +#endif + +#pragma mark - + +@implementation AFPropertyListResponseSerializer + ++ (instancetype)serializer { + return [self serializerWithFormat:NSPropertyListXMLFormat_v1_0 readOptions:0]; +} + ++ (instancetype)serializerWithFormat:(NSPropertyListFormat)format + readOptions:(NSPropertyListReadOptions)readOptions +{ + AFPropertyListResponseSerializer *serializer = [[self alloc] init]; + serializer.format = format; + serializer.readOptions = readOptions; + + return serializer; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"application/x-plist", nil]; + + return self; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + + if (!data) { + return nil; + } + + NSError *serializationError = nil; + + id responseObject = [NSPropertyListSerialization propertyListWithData:data options:self.readOptions format:NULL error:&serializationError]; + + if (!responseObject) + { + if (error) { + *error = AFErrorWithUnderlyingError(serializationError, *error); + } + return nil; + } + + return responseObject; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + self.format = (NSPropertyListFormat)[[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(format))] unsignedIntegerValue]; + self.readOptions = [[decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(readOptions))] unsignedIntegerValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:@(self.format) forKey:NSStringFromSelector(@selector(format))]; + [coder encodeObject:@(self.readOptions) forKey:NSStringFromSelector(@selector(readOptions))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFPropertyListResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.format = self.format; + serializer.readOptions = self.readOptions; + + return serializer; +} + +@end + +#pragma mark - + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH +#import +#import + +@interface UIImage (AFNetworkingSafeImageLoading) ++ (UIImage *)af_safeImageWithData:(NSData *)data; +@end + +static NSLock* imageLock = nil; + +@implementation UIImage (AFNetworkingSafeImageLoading) + ++ (UIImage *)af_safeImageWithData:(NSData *)data { + UIImage* image = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + imageLock = [[NSLock alloc] init]; + }); + + [imageLock lock]; + image = [UIImage imageWithData:data]; + [imageLock unlock]; + return image; +} + +@end + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [UIImage af_safeImageWithData:data]; + if (image.images) { + return image; + } + + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; +} + +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { + if (!data || [data length] == 0) { + return nil; + } + + CGImageRef imageRef = NULL; + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + + if ([response.MIMEType isEqualToString:@"image/png"]) { + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + + if (imageRef) { + CGColorSpaceRef imageColorSpace = CGImageGetColorSpace(imageRef); + CGColorSpaceModel imageColorSpaceModel = CGColorSpaceGetModel(imageColorSpace); + + // CGImageCreateWithJPEGDataProvider does not properly handle CMKY, so fall back to AFImageWithDataAtScale + if (imageColorSpaceModel == kCGColorSpaceModelCMYK) { + CGImageRelease(imageRef); + imageRef = NULL; + } + } + } + + CGDataProviderRelease(dataProvider); + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (!imageRef) { + if (image.images || !image) { + return image; + } + + imageRef = CGImageCreateCopy([image CGImage]); + if (!imageRef) { + return nil; + } + } + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + + if (width * height > 1024 * 1024 || bitsPerComponent > 8) { + CGImageRelease(imageRef); + + return image; + } + + // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate + size_t bytesPerRow = 0; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (colorSpaceModel == kCGColorSpaceModelRGB) { + uint32_t alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wassign-enum" + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } +#pragma clang diagnostic pop + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, width, height), imageRef); + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); + + CGContextRelease(context); + + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; + + CGImageRelease(inflatedImageRef); + CGImageRelease(imageRef); + + return inflatedImage; +} +#endif + + +@implementation AFImageResponseSerializer + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + + self.acceptableContentTypes = [[NSSet alloc] initWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; + +#if TARGET_OS_IOS || TARGET_OS_TV + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#elif TARGET_OS_WATCH + self.imageScale = [[WKInterfaceDevice currentDevice] screenScale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + +#pragma mark - AFURLResponseSerializer + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + if (![self validateResponse:(NSHTTPURLResponse *)response data:data error:error]) { + if (!error || AFErrorOrUnderlyingErrorHasCodeInDomain(*error, NSURLErrorCannotDecodeContentData, AFURLResponseSerializationErrorDomain)) { + return nil; + } + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + if (self.automaticallyInflatesResponseImage) { + return AFInflatedImageFromResponseWithDataAtScale((NSHTTPURLResponse *)response, data, self.imageScale); + } else { + return AFImageWithDataAtScale(data, self.imageScale); + } +#else + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:data]; + NSImage *image = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [image addRepresentation:bitimage]; + + return image; +#endif + + return nil; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + NSNumber *imageScale = [decoder decodeObjectOfClass:[NSNumber class] forKey:NSStringFromSelector(@selector(imageScale))]; +#if CGFLOAT_IS_DOUBLE + self.imageScale = [imageScale doubleValue]; +#else + self.imageScale = [imageScale floatValue]; +#endif + + self.automaticallyInflatesResponseImage = [decoder decodeBoolForKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + [coder encodeObject:@(self.imageScale) forKey:NSStringFromSelector(@selector(imageScale))]; + [coder encodeBool:self.automaticallyInflatesResponseImage forKey:NSStringFromSelector(@selector(automaticallyInflatesResponseImage))]; +#endif +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFImageResponseSerializer *serializer = [super copyWithZone:zone]; + +#if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH + serializer.imageScale = self.imageScale; + serializer.automaticallyInflatesResponseImage = self.automaticallyInflatesResponseImage; +#endif + + return serializer; +} + +@end + +#pragma mark - + +@interface AFCompoundResponseSerializer () +@property (readwrite, nonatomic, copy) NSArray *responseSerializers; +@end + +@implementation AFCompoundResponseSerializer + ++ (instancetype)compoundSerializerWithResponseSerializers:(NSArray *)responseSerializers { + AFCompoundResponseSerializer *serializer = [[self alloc] init]; + serializer.responseSerializers = responseSerializers; + + return serializer; +} + +#pragma mark - AFURLResponseSerialization + +- (id)responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error +{ + for (id serializer in self.responseSerializers) { + if (![serializer isKindOfClass:[AFHTTPResponseSerializer class]]) { + continue; + } + + NSError *serializerError = nil; + id responseObject = [serializer responseObjectForResponse:response data:data error:&serializerError]; + if (responseObject) { + if (error) { + *error = AFErrorWithUnderlyingError(serializerError, *error); + } + + return responseObject; + } + } + + return [super responseObjectForResponse:response data:data error:error]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + self = [super initWithCoder:decoder]; + if (!self) { + return nil; + } + + NSSet *classes = [NSSet setWithArray:@[[NSArray class], [AFHTTPResponseSerializer class]]]; + self.responseSerializers = [decoder decodeObjectOfClasses:classes forKey:NSStringFromSelector(@selector(responseSerializers))]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [super encodeWithCoder:coder]; + + [coder encodeObject:self.responseSerializers forKey:NSStringFromSelector(@selector(responseSerializers))]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + AFCompoundResponseSerializer *serializer = [super copyWithZone:zone]; + serializer.responseSerializers = self.responseSerializers; + + return serializer; +} + +@end diff --git a/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h new file mode 100644 index 0000000..88700c3 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.h @@ -0,0 +1,516 @@ +// AFURLSessionManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#import + +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" +#import "AFSecurityPolicy.h" +#import "AFCompatibilityMacros.h" +#if !TARGET_OS_WATCH +#import "AFNetworkReachabilityManager.h" +#endif + +/** + `AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + + ## Subclassing Notes + + This is the base class for `AFHTTPSessionManager`, which adds functionality specific to making HTTP requests. If you are looking to extend `AFURLSessionManager` specifically for HTTP, consider subclassing `AFHTTPSessionManager` instead. + + ## NSURLSession & NSURLSessionTask Delegate Methods + + `AFURLSessionManager` implements the following delegate methods: + + ### `NSURLSessionDelegate` + + - `URLSession:didBecomeInvalidWithError:` + - `URLSession:didReceiveChallenge:completionHandler:` + - `URLSessionDidFinishEventsForBackgroundURLSession:` + + ### `NSURLSessionTaskDelegate` + + - `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:` + - `URLSession:task:didReceiveChallenge:completionHandler:` + - `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:` + - `URLSession:task:needNewBodyStream:` + - `URLSession:task:didCompleteWithError:` + + ### `NSURLSessionDataDelegate` + + - `URLSession:dataTask:didReceiveResponse:completionHandler:` + - `URLSession:dataTask:didBecomeDownloadTask:` + - `URLSession:dataTask:didReceiveData:` + - `URLSession:dataTask:willCacheResponse:completionHandler:` + + ### `NSURLSessionDownloadDelegate` + + - `URLSession:downloadTask:didFinishDownloadingToURL:` + - `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:` + - `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Network Reachability Monitoring + + Network reachability status and change monitoring is available through the `reachabilityManager` property. Applications may choose to monitor network reachability conditions in order to prevent or suspend any outbound requests. See `AFNetworkReachabilityManager` for more details. + + ## NSCoding Caveats + + - Encoded managers do not include any block properties. Be sure to set delegate callback blocks when using `-initWithCoder:` or `NSKeyedUnarchiver`. + + ## NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new manager with a new `NSURLSession` created from the configuration of the original. + - Operation copies do not include any delegate callback blocks, as they often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ session manager when copied. + + @warning Managers for background sessions must be owned for the duration of their use. This can be accomplished by creating an application-wide or shared singleton instance. + */ + +NS_ASSUME_NONNULL_BEGIN + +@interface AFURLSessionManager : NSObject + +/** + The managed session. + */ +@property (readonly, nonatomic, strong) NSURLSession *session; + +/** + The operation queue on which delegate callbacks are run. + */ +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; + +/** + Responses sent from the server in data tasks created with `dataTaskWithRequest:success:failure:` and run using the `GET` / `POST` / et al. convenience methods are automatically validated and serialized by the response serializer. By default, this property is set to an instance of `AFJSONResponseSerializer`. + + @warning `responseSerializer` must not be `nil`. + */ +@property (nonatomic, strong) id responseSerializer; + +///------------------------------- +/// @name Managing Security Policy +///------------------------------- + +/** + The security policy used by created session to evaluate server trust for secure connections. `AFURLSessionManager` uses the `defaultPolicy` unless otherwise specified. + */ +@property (nonatomic, strong) AFSecurityPolicy *securityPolicy; + +#if !TARGET_OS_WATCH +///-------------------------------------- +/// @name Monitoring Network Reachability +///-------------------------------------- + +/** + The network reachability manager. `AFURLSessionManager` uses the `sharedManager` by default. + */ +@property (readwrite, nonatomic, strong) AFNetworkReachabilityManager *reachabilityManager; +#endif + +///---------------------------- +/// @name Getting Session Tasks +///---------------------------- + +/** + The data, upload, and download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *tasks; + +/** + The data tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *dataTasks; + +/** + The upload tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *uploadTasks; + +/** + The download tasks currently run by the managed session. + */ +@property (readonly, nonatomic, strong) NSArray *downloadTasks; + +///------------------------------- +/// @name Managing Callback Queues +///------------------------------- + +/** + The dispatch queue for `completionBlock`. If `NULL` (default), the main queue is used. + */ +@property (nonatomic, strong, nullable) dispatch_queue_t completionQueue; + +/** + The dispatch group for `completionBlock`. If `NULL` (default), a private dispatch group is used. + */ +@property (nonatomic, strong, nullable) dispatch_group_t completionGroup; + +///--------------------- +/// @name Initialization +///--------------------- + +/** + Creates and returns a manager for a session created with the specified configuration. This is the designated initializer. + + @param configuration The configuration used to create the managed session. + + @return A manager for a newly-created session. + */ +- (instancetype)initWithSessionConfiguration:(nullable NSURLSessionConfiguration *)configuration NS_DESIGNATED_INITIALIZER; + +/** + Invalidates the managed session, optionally canceling pending tasks and optionally resets given session. + + @param cancelPendingTasks Whether or not to cancel pending tasks. + @param resetSession Whether or not to reset the session of the manager. + */ +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession; + +///------------------------- +/// @name Running Data Tasks +///------------------------- + +/** + Creates an `NSURLSessionDataTask` with the specified request. + + @param request The HTTP request for the request. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///--------------------------- +/// @name Running Upload Tasks +///--------------------------- + +/** + Creates an `NSURLSessionUploadTask` with the specified request for a local file. + + @param request The HTTP request for the request. + @param fileURL A URL to the local file to be uploaded. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + + @see `attemptsToRecreateUploadTasksForBackgroundSessions` + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified request for an HTTP body. + + @param request The HTTP request for the request. + @param bodyData A data object containing the HTTP body to be uploaded. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(nullable NSData *)bodyData + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionUploadTask` with the specified streaming request. + + @param request The HTTP request for the request. + @param uploadProgressBlock A block object to be executed when the upload progress is updated. Note this block is called on the session queue, not the main queue. + @param completionHandler A block object to be executed when the task finishes. This block has no return value and takes three arguments: the server response, the response object created by that serializer, and the error that occurred, if any. + */ +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *uploadProgress))uploadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler; + +///----------------------------- +/// @name Running Download Tasks +///----------------------------- + +/** + Creates an `NSURLSessionDownloadTask` with the specified request. + + @param request The HTTP request for the request. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + + @warning If using a background `NSURLSessionConfiguration` on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use `-setDownloadTaskDidFinishDownloadingBlock:` to specify the URL for saving the downloaded file, rather than the destination block of this method. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +/** + Creates an `NSURLSessionDownloadTask` with the specified resume data. + + @param resumeData The data used to resume downloading. + @param downloadProgressBlock A block object to be executed when the download progress is updated. Note this block is called on the session queue, not the main queue. + @param destination A block object to be executed in order to determine the destination of the downloaded file. This block takes two arguments, the target path & the server response, and returns the desired file URL of the resulting download. The temporary file used during the download will be automatically deleted after being moved to the returned URL. + @param completionHandler A block to be executed when a task finishes. This block has no return value and takes three arguments: the server response, the path of the downloaded file, and the error describing the network or parsing error that occurred, if any. + */ +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(nullable void (^)(NSProgress *downloadProgress))downloadProgressBlock + destination:(nullable NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(nullable void (^)(NSURLResponse *response, NSURL * _Nullable filePath, NSError * _Nullable error))completionHandler; + +///--------------------------------- +/// @name Getting Progress for Tasks +///--------------------------------- + +/** + Returns the upload progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the upload progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task; + +/** + Returns the download progress of the specified task. + + @param task The session task. Must not be `nil`. + + @return An `NSProgress` object reporting the download progress of a task, or `nil` if the progress is unavailable. + */ +- (nullable NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task; + +///----------------------------------------- +/// @name Setting Session Delegate Callbacks +///----------------------------------------- + +/** + Sets a block to be executed when the managed session becomes invalid, as handled by the `NSURLSessionDelegate` method `URLSession:didBecomeInvalidWithError:`. + + @param block A block object to be executed when the managed session becomes invalid. The block has no return value, and takes two arguments: the session, and the error related to the cause of invalidation. + */ +- (void)setSessionDidBecomeInvalidBlock:(nullable void (^)(NSURLSession *session, NSError *error))block; + +/** + Sets a block to be executed when a connection level authentication challenge has occurred, as handled by the `NSURLSessionDelegate` method `URLSession:didReceiveChallenge:completionHandler:`. + + @param block A block object to be executed when a connection level authentication challenge has occurred. The block returns the disposition of the authentication challenge, and takes three arguments: the session, the authentication challenge, and a pointer to the credential that should be used to resolve the challenge. + + @warning Implementing a session authentication challenge handler yourself totally bypasses AFNetworking's security policy defined in `AFSecurityPolicy`. Make sure you fully understand the implications before implementing a custom session authentication challenge handler. If you do not want to bypass AFNetworking's security policy, use `setTaskDidReceiveAuthenticationChallengeBlock:` instead. + + @see -securityPolicy + @see -setTaskDidReceiveAuthenticationChallengeBlock: + */ +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(nullable NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * _Nullable __autoreleasing * _Nullable credential))block; + +///-------------------------------------- +/// @name Setting Task Delegate Callbacks +///-------------------------------------- + +/** + Sets a block to be executed when a task requires a new request body stream to send to the remote server, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:needNewBodyStream:`. + + @param block A block object to be executed when a task requires a new request body stream. + */ +- (void)setTaskNeedNewBodyStreamBlock:(nullable NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block; + +/** + Sets a block to be executed when an HTTP request is attempting to perform a redirection to a different URL, as handled by the `NSURLSessionTaskDelegate` method `URLSession:willPerformHTTPRedirection:newRequest:completionHandler:`. + + @param block A block object to be executed when an HTTP request is attempting to perform a redirection to a different URL. The block returns the request to be made for the redirection, and takes four arguments: the session, the task, the redirection response, and the request corresponding to the redirection response. + */ +- (void)setTaskWillPerformHTTPRedirectionBlock:(nullable NSURLRequest * _Nullable (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block; + +/** + Sets a block to be executed when a session task has received a request specific authentication challenge, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didReceiveChallenge:completionHandler:`. + + @param authenticationChallengeHandler A block object to be executed when a session task has received a request specific authentication challenge. + + When implementing an authentication challenge handler, you should check the authentication method first (`challenge.protectionSpace.authenticationMethod `) to decide if you want to handle the authentication challenge yourself or if you want AFNetworking to handle it. If you want AFNetworking to handle the authentication challenge, just return `@(NSURLSessionAuthChallengePerformDefaultHandling)`. For example, you certainly want AFNetworking to handle certificate validation (i.e. authentication method == `NSURLAuthenticationMethodServerTrust`) as defined by the security policy. If you want to handle the challenge yourself, you have four options: + + 1. Return `nil` from the authentication challenge handler. You **MUST** call the completion handler with a disposition and credentials yourself. Use this if you need to present a user interface to let the user enter their credentials. + 2. Return an `NSError` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSError `. The returned error will be reported in the completion handler of the task. Use this if you need to abort an authentication challenge with a specific error. + 3. Return an `NSURLCredential` object from the authentication challenge handler. You **MUST NOT** call the completion handler when returning an `NSURLCredential`. The returned credentials will be used to fulfil the challenge. Use this when you can get credentials without presenting a user interface. + 4. Return an `NSNumber` object wrapping an `NSURLSessionAuthChallengeDisposition`. Supported values are `@(NSURLSessionAuthChallengePerformDefaultHandling)`, `@(NSURLSessionAuthChallengeCancelAuthenticationChallenge)` and `@(NSURLSessionAuthChallengeRejectProtectionSpace)`. You **MUST NOT** call the completion handler when returning an `NSNumber`. + + If you return anything else from the authentication challenge handler, an exception will be thrown. + + For more information about how URL sessions handle the different types of authentication challenges, see [NSURLSession](https://developer.apple.com/reference/foundation/nsurlsession?language=objc) and [URL Session Programming Guide](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html). + + @see -securityPolicy + */ +- (void)setAuthenticationChallengeHandler:(id (^)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition , NSURLCredential * _Nullable)))authenticationChallengeHandler; + +/** + Sets a block to be executed periodically to track upload progress, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes five arguments: the session, the task, the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setTaskDidSendBodyDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block; + +/** + Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task. + */ +- (void)setTaskDidCompleteBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSError * _Nullable error))block; + +/** + Sets a block to be executed when metrics are finalized related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didFinishCollectingMetrics:`. + + @param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any metrics that were collected in the process of executing the task. + */ +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)setTaskDidFinishCollectingMetricsBlock:(nullable void (^)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * _Nullable metrics))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif +///------------------------------------------- +/// @name Setting Data Task Delegate Callbacks +///------------------------------------------- + +/** + Sets a block to be executed when a data task has received a response, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveResponse:completionHandler:`. + + @param block A block object to be executed when a data task has received a response. The block returns the disposition of the session response, and takes three arguments: the session, the data task, and the received response. + */ +- (void)setDataTaskDidReceiveResponseBlock:(nullable NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block; + +/** + Sets a block to be executed when a data task has become a download task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didBecomeDownloadTask:`. + + @param block A block object to be executed when a data task has become a download task. The block has no return value, and takes three arguments: the session, the data task, and the download task it has become. + */ +- (void)setDataTaskDidBecomeDownloadTaskBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block; + +/** + Sets a block to be executed when a data task receives data, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:didReceiveData:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the session, the data task, and the data received. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDataTaskDidReceiveDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block; + +/** + Sets a block to be executed to determine the caching behavior of a data task, as handled by the `NSURLSessionDataDelegate` method `URLSession:dataTask:willCacheResponse:completionHandler:`. + + @param block A block object to be executed to determine the caching behavior of a data task. The block returns the response to cache, and takes three arguments: the session, the data task, and the proposed cached URL response. + */ +- (void)setDataTaskWillCacheResponseBlock:(nullable NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block; + +/** + Sets a block to be executed once all messages enqueued for a session have been delivered, as handled by the `NSURLSessionDataDelegate` method `URLSessionDidFinishEventsForBackgroundURLSession:`. + + @param block A block object to be executed once all messages enqueued for a session have been delivered. The block has no return value and takes a single argument: the session. + */ +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(nullable void (^)(NSURLSession *session))block AF_API_UNAVAILABLE(macos); + +///----------------------------------------------- +/// @name Setting Download Task Delegate Callbacks +///----------------------------------------------- + +/** + Sets a block to be executed when a download task has completed a download, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didFinishDownloadingToURL:`. + + @param block A block object to be executed when a download task has completed. The block returns the URL the download should be moved to, and takes three arguments: the session, the download task, and the temporary location of the downloaded file. If the file manager encounters an error while attempting to move the temporary file to the destination, an `AFURLSessionDownloadTaskDidFailToMoveFileNotification` will be posted, with the download task as its object, and the user info of the error. + */ +- (void)setDownloadTaskDidFinishDownloadingBlock:(nullable NSURL * _Nullable (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block; + +/** + Sets a block to be executed periodically to track download progress, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes five arguments: the session, the download task, the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the session manager operation queue. + */ +- (void)setDownloadTaskDidWriteDataBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block; + +/** + Sets a block to be executed when a download task has been resumed, as handled by the `NSURLSessionDownloadDelegate` method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. + + @param block A block object to be executed when a download task has been resumed. The block has no return value and takes four arguments: the session, the download task, the file offset of the resumed download, and the total number of bytes expected to be downloaded. + */ +- (void)setDownloadTaskDidResumeBlock:(nullable void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block; + +@end + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when a task resumes. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidResumeNotification; + +/** + Posted when a task finishes executing. Includes a userInfo dictionary with additional information about the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteNotification; + +/** + Posted when a task suspends its execution. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidSuspendNotification; + +/** + Posted when a session is invalidated. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDidInvalidateNotification; + +/** + Posted when a session download task finished moving the temporary download file to a specified destination successfully. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification; + +/** + Posted when a session download task encountered an error when moving the temporary download file to a specified destination. + */ +FOUNDATION_EXPORT NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification; + +/** + The raw response data of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if response data exists for the task. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseDataKey; + +/** + The serialized response object of the task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the response was serialized. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey; + +/** + The response serializer used to serialize the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if the task has an associated response serializer. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey; + +/** + The file path associated with the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an the response data has been stored directly to disk. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteAssetPathKey; + +/** + Any error associated with the task, or the serialization of the response. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteNotification` if an error exists. + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteErrorKey; + +/** + The session task metrics taken from the download task. Included in the userInfo dictionary of the `AFNetworkingTaskDidCompleteSessionTaskMetrics` + */ +FOUNDATION_EXPORT NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m new file mode 100644 index 0000000..c8b6810 --- /dev/null +++ b/Pods/AFNetworking/AFNetworking/AFURLSessionManager.m @@ -0,0 +1,1274 @@ +// AFURLSessionManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLSessionManager.h" +#import + +static dispatch_queue_t url_session_manager_processing_queue() { + static dispatch_queue_t af_url_session_manager_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_processing_queue = dispatch_queue_create("com.alamofire.networking.session.manager.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_url_session_manager_processing_queue; +} + +static dispatch_group_t url_session_manager_completion_group() { + static dispatch_group_t af_url_session_manager_completion_group; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_url_session_manager_completion_group = dispatch_group_create(); + }); + + return af_url_session_manager_completion_group; +} + +NSString * const AFNetworkingTaskDidResumeNotification = @"com.alamofire.networking.task.resume"; +NSString * const AFNetworkingTaskDidCompleteNotification = @"com.alamofire.networking.task.complete"; +NSString * const AFNetworkingTaskDidSuspendNotification = @"com.alamofire.networking.task.suspend"; +NSString * const AFURLSessionDidInvalidateNotification = @"com.alamofire.networking.session.invalidate"; +NSString * const AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification = @"com.alamofire.networking.session.download.file-manager-succeed"; +NSString * const AFURLSessionDownloadTaskDidFailToMoveFileNotification = @"com.alamofire.networking.session.download.file-manager-error"; + +NSString * const AFNetworkingTaskDidCompleteSerializedResponseKey = @"com.alamofire.networking.task.complete.serializedresponse"; +NSString * const AFNetworkingTaskDidCompleteResponseSerializerKey = @"com.alamofire.networking.task.complete.responseserializer"; +NSString * const AFNetworkingTaskDidCompleteResponseDataKey = @"com.alamofire.networking.complete.finish.responsedata"; +NSString * const AFNetworkingTaskDidCompleteErrorKey = @"com.alamofire.networking.task.complete.error"; +NSString * const AFNetworkingTaskDidCompleteAssetPathKey = @"com.alamofire.networking.task.complete.assetpath"; +NSString * const AFNetworkingTaskDidCompleteSessionTaskMetrics = @"com.alamofire.networking.complete.sessiontaskmetrics"; + +static NSString * const AFURLSessionManagerLockName = @"com.alamofire.networking.session.manager.lock"; + +typedef void (^AFURLSessionDidBecomeInvalidBlock)(NSURLSession *session, NSError *error); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); + +typedef NSURLRequest * (^AFURLSessionTaskWillPerformHTTPRedirectionBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request); +typedef NSURLSessionAuthChallengeDisposition (^AFURLSessionTaskDidReceiveAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential); +typedef id (^AFURLSessionTaskAuthenticationChallengeBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, void (^completionHandler)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential)); +typedef void (^AFURLSessionDidFinishEventsForBackgroundURLSessionBlock)(NSURLSession *session); + +typedef NSInputStream * (^AFURLSessionTaskNeedNewBodyStreamBlock)(NSURLSession *session, NSURLSessionTask *task); +typedef void (^AFURLSessionTaskDidSendBodyDataBlock)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend); +typedef void (^AFURLSessionTaskDidCompleteBlock)(NSURLSession *session, NSURLSessionTask *task, NSError *error); +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +typedef void (^AFURLSessionTaskDidFinishCollectingMetricsBlock)(NSURLSession *session, NSURLSessionTask *task, NSURLSessionTaskMetrics * metrics) AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif + +typedef NSURLSessionResponseDisposition (^AFURLSessionDataTaskDidReceiveResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response); +typedef void (^AFURLSessionDataTaskDidBecomeDownloadTaskBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask); +typedef void (^AFURLSessionDataTaskDidReceiveDataBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data); +typedef NSCachedURLResponse * (^AFURLSessionDataTaskWillCacheResponseBlock)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse); + +typedef NSURL * (^AFURLSessionDownloadTaskDidFinishDownloadingBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location); +typedef void (^AFURLSessionDownloadTaskDidWriteDataBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite); +typedef void (^AFURLSessionDownloadTaskDidResumeBlock)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes); +typedef void (^AFURLSessionTaskProgressBlock)(NSProgress *); + +typedef void (^AFURLSessionTaskCompletionHandler)(NSURLResponse *response, id responseObject, NSError *error); + +#pragma mark - + +@interface AFURLSessionManagerTaskDelegate : NSObject +- (instancetype)initWithTask:(NSURLSessionTask *)task; +@property (nonatomic, weak) AFURLSessionManager *manager; +@property (nonatomic, strong) NSMutableData *mutableData; +@property (nonatomic, strong) NSProgress *uploadProgress; +@property (nonatomic, strong) NSProgress *downloadProgress; +@property (nonatomic, copy) NSURL *downloadFileURL; +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +@property (nonatomic, strong) NSURLSessionTaskMetrics *sessionTaskMetrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif +@property (nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock uploadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskProgressBlock downloadProgressBlock; +@property (nonatomic, copy) AFURLSessionTaskCompletionHandler completionHandler; +@end + +@implementation AFURLSessionManagerTaskDelegate + +- (instancetype)initWithTask:(NSURLSessionTask *)task { + self = [super init]; + if (!self) { + return nil; + } + + _mutableData = [NSMutableData data]; + _uploadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + _downloadProgress = [[NSProgress alloc] initWithParent:nil userInfo:nil]; + + __weak __typeof__(task) weakTask = task; + for (NSProgress *progress in @[ _uploadProgress, _downloadProgress ]) + { + progress.totalUnitCount = NSURLSessionTransferSizeUnknown; + progress.cancellable = YES; + progress.cancellationHandler = ^{ + [weakTask cancel]; + }; + progress.pausable = YES; + progress.pausingHandler = ^{ + [weakTask suspend]; + }; +#if AF_CAN_USE_AT_AVAILABLE + if (@available(macOS 10.11, *)) +#else + if ([progress respondsToSelector:@selector(setResumingHandler:)]) +#endif + { + progress.resumingHandler = ^{ + [weakTask resume]; + }; + } + + [progress addObserver:self + forKeyPath:NSStringFromSelector(@selector(fractionCompleted)) + options:NSKeyValueObservingOptionNew + context:NULL]; + } + return self; +} + +- (void)dealloc { + [self.downloadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; + [self.uploadProgress removeObserver:self forKeyPath:NSStringFromSelector(@selector(fractionCompleted))]; +} + +#pragma mark - NSProgress Tracking + +- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + if ([object isEqual:self.downloadProgress]) { + if (self.downloadProgressBlock) { + self.downloadProgressBlock(object); + } + } + else if ([object isEqual:self.uploadProgress]) { + if (self.uploadProgressBlock) { + self.uploadProgressBlock(object); + } + } +} + +static const void * const AuthenticationChallengeErrorKey = &AuthenticationChallengeErrorKey; + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(__unused NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + error = objc_getAssociatedObject(task, AuthenticationChallengeErrorKey) ?: error; + __strong AFURLSessionManager *manager = self.manager; + + __block id responseObject = nil; + + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[AFNetworkingTaskDidCompleteResponseSerializerKey] = manager.responseSerializer; + + //Performance Improvement from #2672 + NSData *data = nil; + if (self.mutableData) { + data = [self.mutableData copy]; + //We no longer need the reference, so nil it out to gain back some memory. + self.mutableData = nil; + } + +#if AF_CAN_USE_AT_AVAILABLE && AF_CAN_INCLUDE_SESSION_TASK_METRICS + if (@available(iOS 10, macOS 10.12, watchOS 3, tvOS 10, *)) { + if (self.sessionTaskMetrics) { + userInfo[AFNetworkingTaskDidCompleteSessionTaskMetrics] = self.sessionTaskMetrics; + } + } +#endif + + if (self.downloadFileURL) { + userInfo[AFNetworkingTaskDidCompleteAssetPathKey] = self.downloadFileURL; + } else if (data) { + userInfo[AFNetworkingTaskDidCompleteResponseDataKey] = data; + } + + if (error) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = error; + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, error); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + } else { + dispatch_async(url_session_manager_processing_queue(), ^{ + NSError *serializationError = nil; + responseObject = [manager.responseSerializer responseObjectForResponse:task.response data:data error:&serializationError]; + + if (self.downloadFileURL) { + responseObject = self.downloadFileURL; + } + + if (responseObject) { + userInfo[AFNetworkingTaskDidCompleteSerializedResponseKey] = responseObject; + } + + if (serializationError) { + userInfo[AFNetworkingTaskDidCompleteErrorKey] = serializationError; + } + + dispatch_group_async(manager.completionGroup ?: url_session_manager_completion_group(), manager.completionQueue ?: dispatch_get_main_queue(), ^{ + if (self.completionHandler) { + self.completionHandler(task.response, responseObject, serializationError); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidCompleteNotification object:task userInfo:userInfo]; + }); + }); + }); + } +} + +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) { + self.sessionTaskMetrics = metrics; +} +#endif + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(__unused NSURLSession *)session + dataTask:(__unused NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + self.downloadProgress.totalUnitCount = dataTask.countOfBytesExpectedToReceive; + self.downloadProgress.completedUnitCount = dataTask.countOfBytesReceived; + + [self.mutableData appendData:data]; +} + +- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend{ + + self.uploadProgress.totalUnitCount = task.countOfBytesExpectedToSend; + self.uploadProgress.completedUnitCount = task.countOfBytesSent; +} + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ + + self.downloadProgress.totalUnitCount = totalBytesExpectedToWrite; + self.downloadProgress.completedUnitCount = totalBytesWritten; +} + +- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes{ + + self.downloadProgress.totalUnitCount = expectedTotalBytes; + self.downloadProgress.completedUnitCount = fileOffset; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + self.downloadFileURL = nil; + + if (self.downloadTaskDidFinishDownloading) { + self.downloadFileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (self.downloadFileURL) { + NSError *fileManagerError = nil; + + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; + } else { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification object:downloadTask userInfo:nil]; + } + } + } +} + +@end + +#pragma mark - + +/** + * A workaround for issues related to key-value observing the `state` of an `NSURLSessionTask`. + * + * See: + * - https://github.com/AFNetworking/AFNetworking/issues/1477 + * - https://github.com/AFNetworking/AFNetworking/issues/2638 + * - https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + +static inline void af_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector) { + Method originalMethod = class_getInstanceMethod(theClass, originalSelector); + Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector); + method_exchangeImplementations(originalMethod, swizzledMethod); +} + +static inline BOOL af_addMethod(Class theClass, SEL selector, Method method) { + return class_addMethod(theClass, selector, method_getImplementation(method), method_getTypeEncoding(method)); +} + +static NSString * const AFNSURLSessionTaskDidResumeNotification = @"com.alamofire.networking.nsurlsessiontask.resume"; +static NSString * const AFNSURLSessionTaskDidSuspendNotification = @"com.alamofire.networking.nsurlsessiontask.suspend"; + +@interface _AFURLSessionTaskSwizzling : NSObject + +@end + +@implementation _AFURLSessionTaskSwizzling + ++ (void)load { + /** + WARNING: Trouble Ahead + https://github.com/AFNetworking/AFNetworking/pull/2702 + */ + + if (NSClassFromString(@"NSURLSessionTask")) { + /** + iOS 7 and iOS 8 differ in NSURLSessionTask implementation, which makes the next bit of code a bit tricky. + Many Unit Tests have been built to validate as much of this behavior has possible. + Here is what we know: + - NSURLSessionTasks are implemented with class clusters, meaning the class you request from the API isn't actually the type of class you will get back. + - Simply referencing `[NSURLSessionTask class]` will not work. You need to ask an `NSURLSession` to actually create an object, and grab the class from there. + - On iOS 7, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `__NSCFURLSessionTask`. + - On iOS 8, `localDataTask` is a `__NSCFLocalDataTask`, which inherits from `__NSCFLocalSessionTask`, which inherits from `NSURLSessionTask`. + - On iOS 7, `__NSCFLocalSessionTask` and `__NSCFURLSessionTask` are the only two classes that have their own implementations of `resume` and `suspend`, and `__NSCFLocalSessionTask` DOES NOT CALL SUPER. This means both classes need to be swizzled. + - On iOS 8, `NSURLSessionTask` is the only class that implements `resume` and `suspend`. This means this is the only class that needs to be swizzled. + - Because `NSURLSessionTask` is not involved in the class hierarchy for every version of iOS, its easier to add the swizzled methods to a dummy class and manage them there. + + Some Assumptions: + - No implementations of `resume` or `suspend` call super. If this were to change in a future version of iOS, we'd need to handle it. + - No background task classes override `resume` or `suspend` + + The current solution: + 1) Grab an instance of `__NSCFLocalDataTask` by asking an instance of `NSURLSession` for a data task. + 2) Grab a pointer to the original implementation of `af_resume` + 3) Check to see if the current class has an implementation of resume. If so, continue to step 4. + 4) Grab the super class of the current class. + 5) Grab a pointer for the current class to the current implementation of `resume`. + 6) Grab a pointer for the super class to the current implementation of `resume`. + 7) If the current class implementation of `resume` is not equal to the super class implementation of `resume` AND the current implementation of `resume` is not equal to the original implementation of `af_resume`, THEN swizzle the methods + 8) Set the current class to the super class, and repeat steps 3-8 + */ + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wnonnull" + NSURLSessionDataTask *localDataTask = [session dataTaskWithURL:nil]; +#pragma clang diagnostic pop + IMP originalAFResumeIMP = method_getImplementation(class_getInstanceMethod([self class], @selector(af_resume))); + Class currentClass = [localDataTask class]; + + while (class_getInstanceMethod(currentClass, @selector(resume))) { + Class superClass = [currentClass superclass]; + IMP classResumeIMP = method_getImplementation(class_getInstanceMethod(currentClass, @selector(resume))); + IMP superclassResumeIMP = method_getImplementation(class_getInstanceMethod(superClass, @selector(resume))); + if (classResumeIMP != superclassResumeIMP && + originalAFResumeIMP != classResumeIMP) { + [self swizzleResumeAndSuspendMethodForClass:currentClass]; + } + currentClass = [currentClass superclass]; + } + + [localDataTask cancel]; + [session finishTasksAndInvalidate]; + } +} + ++ (void)swizzleResumeAndSuspendMethodForClass:(Class)theClass { + Method afResumeMethod = class_getInstanceMethod(self, @selector(af_resume)); + Method afSuspendMethod = class_getInstanceMethod(self, @selector(af_suspend)); + + if (af_addMethod(theClass, @selector(af_resume), afResumeMethod)) { + af_swizzleSelector(theClass, @selector(resume), @selector(af_resume)); + } + + if (af_addMethod(theClass, @selector(af_suspend), afSuspendMethod)) { + af_swizzleSelector(theClass, @selector(suspend), @selector(af_suspend)); + } +} + +- (NSURLSessionTaskState)state { + NSAssert(NO, @"State method should never be called in the actual dummy class"); + return NSURLSessionTaskStateCanceling; +} + +- (void)af_resume { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_resume]; + + if (state != NSURLSessionTaskStateRunning) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidResumeNotification object:self]; + } +} + +- (void)af_suspend { + NSAssert([self respondsToSelector:@selector(state)], @"Does not respond to state"); + NSURLSessionTaskState state = [self state]; + [self af_suspend]; + + if (state != NSURLSessionTaskStateSuspended) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFNSURLSessionTaskDidSuspendNotification object:self]; + } +} +@end + +#pragma mark - + +@interface AFURLSessionManager () +@property (readwrite, nonatomic, strong) NSURLSessionConfiguration *sessionConfiguration; +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; +@property (readwrite, nonatomic, strong) NSURLSession *session; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableTaskDelegatesKeyedByTaskIdentifier; +@property (readonly, nonatomic, copy) NSString *taskDescriptionForSessionTasks; +@property (readwrite, nonatomic, strong) NSLock *lock; +@property (readwrite, nonatomic, copy) AFURLSessionDidBecomeInvalidBlock sessionDidBecomeInvalid; +@property (readwrite, nonatomic, copy) AFURLSessionDidReceiveAuthenticationChallengeBlock sessionDidReceiveAuthenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLSessionDidFinishEventsForBackgroundURLSessionBlock didFinishEventsForBackgroundURLSession AF_API_UNAVAILABLE(macos); +@property (readwrite, nonatomic, copy) AFURLSessionTaskWillPerformHTTPRedirectionBlock taskWillPerformHTTPRedirection; +@property (readwrite, nonatomic, copy) AFURLSessionTaskAuthenticationChallengeBlock authenticationChallengeHandler; +@property (readwrite, nonatomic, copy) AFURLSessionTaskNeedNewBodyStreamBlock taskNeedNewBodyStream; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidSendBodyDataBlock taskDidSendBodyData; +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidCompleteBlock taskDidComplete; +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +@property (readwrite, nonatomic, copy) AFURLSessionTaskDidFinishCollectingMetricsBlock taskDidFinishCollectingMetrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)); +#endif +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveResponseBlock dataTaskDidReceiveResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidBecomeDownloadTaskBlock dataTaskDidBecomeDownloadTask; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskDidReceiveDataBlock dataTaskDidReceiveData; +@property (readwrite, nonatomic, copy) AFURLSessionDataTaskWillCacheResponseBlock dataTaskWillCacheResponse; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidFinishDownloadingBlock downloadTaskDidFinishDownloading; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidWriteDataBlock downloadTaskDidWriteData; +@property (readwrite, nonatomic, copy) AFURLSessionDownloadTaskDidResumeBlock downloadTaskDidResume; +@end + +@implementation AFURLSessionManager + +- (instancetype)init { + return [self initWithSessionConfiguration:nil]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + self = [super init]; + if (!self) { + return nil; + } + + if (!configuration) { + configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + } + + self.sessionConfiguration = configuration; + + self.operationQueue = [[NSOperationQueue alloc] init]; + self.operationQueue.maxConcurrentOperationCount = 1; + + self.responseSerializer = [AFJSONResponseSerializer serializer]; + + self.securityPolicy = [AFSecurityPolicy defaultPolicy]; + +#if !TARGET_OS_WATCH + self.reachabilityManager = [AFNetworkReachabilityManager sharedManager]; +#endif + + self.mutableTaskDelegatesKeyedByTaskIdentifier = [[NSMutableDictionary alloc] init]; + + self.lock = [[NSLock alloc] init]; + self.lock.name = AFURLSessionManagerLockName; + + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + for (NSURLSessionDataTask *task in dataTasks) { + [self addDelegateForDataTask:task uploadProgress:nil downloadProgress:nil completionHandler:nil]; + } + + for (NSURLSessionUploadTask *uploadTask in uploadTasks) { + [self addDelegateForUploadTask:uploadTask progress:nil completionHandler:nil]; + } + + for (NSURLSessionDownloadTask *downloadTask in downloadTasks) { + [self addDelegateForDownloadTask:downloadTask progress:nil destination:nil completionHandler:nil]; + } + }]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - + +- (NSURLSession *)session { + + @synchronized (self) { + if (!_session) { + _session = [NSURLSession sessionWithConfiguration:self.sessionConfiguration delegate:self delegateQueue:self.operationQueue]; + } + } + return _session; +} + +#pragma mark - + + +- (NSString *)taskDescriptionForSessionTasks { + return [NSString stringWithFormat:@"%p", self]; +} + +- (void)taskDidResume:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidResumeNotification object:task]; + }); + } + } +} + +- (void)taskDidSuspend:(NSNotification *)notification { + NSURLSessionTask *task = notification.object; + if ([task respondsToSelector:@selector(taskDescription)]) { + if ([task.taskDescription isEqualToString:self.taskDescriptionForSessionTasks]) { + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingTaskDidSuspendNotification object:task]; + }); + } + } +} + +#pragma mark - + +- (AFURLSessionManagerTaskDelegate *)delegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + AFURLSessionManagerTaskDelegate *delegate = nil; + [self.lock lock]; + delegate = self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)]; + [self.lock unlock]; + + return delegate; +} + +- (void)setDelegate:(AFURLSessionManagerTaskDelegate *)delegate + forTask:(NSURLSessionTask *)task +{ + NSParameterAssert(task); + NSParameterAssert(delegate); + + [self.lock lock]; + self.mutableTaskDelegatesKeyedByTaskIdentifier[@(task.taskIdentifier)] = delegate; + [self addNotificationObserverForTask:task]; + [self.lock unlock]; +} + +- (void)addDelegateForDataTask:(NSURLSessionDataTask *)dataTask + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:dataTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + dataTask.taskDescription = self.taskDescriptionForSessionTasks; + [self setDelegate:delegate forTask:dataTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)addDelegateForUploadTask:(NSURLSessionUploadTask *)uploadTask + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:uploadTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + uploadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:uploadTask]; + + delegate.uploadProgressBlock = uploadProgressBlock; +} + +- (void)addDelegateForDownloadTask:(NSURLSessionDownloadTask *)downloadTask + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + AFURLSessionManagerTaskDelegate *delegate = [[AFURLSessionManagerTaskDelegate alloc] initWithTask:downloadTask]; + delegate.manager = self; + delegate.completionHandler = completionHandler; + + if (destination) { + delegate.downloadTaskDidFinishDownloading = ^NSURL * (NSURLSession * __unused session, NSURLSessionDownloadTask *task, NSURL *location) { + return destination(location, task.response); + }; + } + + downloadTask.taskDescription = self.taskDescriptionForSessionTasks; + + [self setDelegate:delegate forTask:downloadTask]; + + delegate.downloadProgressBlock = downloadProgressBlock; +} + +- (void)removeDelegateForTask:(NSURLSessionTask *)task { + NSParameterAssert(task); + + [self.lock lock]; + [self removeNotificationObserverForTask:task]; + [self.mutableTaskDelegatesKeyedByTaskIdentifier removeObjectForKey:@(task.taskIdentifier)]; + [self.lock unlock]; +} + +#pragma mark - + +- (NSArray *)tasksForKeyPath:(NSString *)keyPath { + __block NSArray *tasks = nil; + dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) { + tasks = dataTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) { + tasks = uploadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) { + tasks = downloadTasks; + } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) { + tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"]; + } + + dispatch_semaphore_signal(semaphore); + }]; + + dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); + + return tasks; +} + +- (NSArray *)tasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)dataTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)uploadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +- (NSArray *)downloadTasks { + return [self tasksForKeyPath:NSStringFromSelector(_cmd)]; +} + +#pragma mark - + +- (void)invalidateSessionCancelingTasks:(BOOL)cancelPendingTasks resetSession:(BOOL)resetSession { + if (cancelPendingTasks) { + [self.session invalidateAndCancel]; + } else { + [self.session finishTasksAndInvalidate]; + } + if (resetSession) { + self.session = nil; + } +} + +#pragma mark - + +- (void)setResponseSerializer:(id )responseSerializer { + NSParameterAssert(responseSerializer); + + _responseSerializer = responseSerializer; +} + +#pragma mark - +- (void)addNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidResume:) name:AFNSURLSessionTaskDidResumeNotification object:task]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(taskDidSuspend:) name:AFNSURLSessionTaskDidSuspendNotification object:task]; +} + +- (void)removeNotificationObserverForTask:(NSURLSessionTask *)task { + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidSuspendNotification object:task]; + [[NSNotificationCenter defaultCenter] removeObserver:self name:AFNSURLSessionTaskDidResumeNotification object:task]; +} + +#pragma mark - + +- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request + uploadProgress:(nullable void (^)(NSProgress *uploadProgress)) uploadProgressBlock + downloadProgress:(nullable void (^)(NSProgress *downloadProgress)) downloadProgressBlock + completionHandler:(nullable void (^)(NSURLResponse *response, id _Nullable responseObject, NSError * _Nullable error))completionHandler { + + NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:request]; + + [self addDelegateForDataTask:dataTask uploadProgress:uploadProgressBlock downloadProgress:downloadProgressBlock completionHandler:completionHandler]; + + return dataTask; +} + +#pragma mark - + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromFile:(NSURL *)fileURL + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromFile:fileURL]; + + if (uploadTask) { + [self addDelegateForUploadTask:uploadTask + progress:uploadProgressBlock + completionHandler:completionHandler]; + } + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request + fromData:(NSData *)bodyData + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithRequest:request fromData:bodyData]; + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +- (NSURLSessionUploadTask *)uploadTaskWithStreamedRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock + completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler +{ + NSURLSessionUploadTask *uploadTask = [self.session uploadTaskWithStreamedRequest:request]; + + [self addDelegateForUploadTask:uploadTask progress:uploadProgressBlock completionHandler:completionHandler]; + + return uploadTask; +} + +#pragma mark - + +- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request]; + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +- (NSURLSessionDownloadTask *)downloadTaskWithResumeData:(NSData *)resumeData + progress:(void (^)(NSProgress *downloadProgress)) downloadProgressBlock + destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination + completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler +{ + NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithResumeData:resumeData]; + + [self addDelegateForDownloadTask:downloadTask progress:downloadProgressBlock destination:destination completionHandler:completionHandler]; + + return downloadTask; +} + +#pragma mark - +- (NSProgress *)uploadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] uploadProgress]; +} + +- (NSProgress *)downloadProgressForTask:(NSURLSessionTask *)task { + return [[self delegateForTask:task] downloadProgress]; +} + +#pragma mark - + +- (void)setSessionDidBecomeInvalidBlock:(void (^)(NSURLSession *session, NSError *error))block { + self.sessionDidBecomeInvalid = block; +} + +- (void)setSessionDidReceiveAuthenticationChallengeBlock:(NSURLSessionAuthChallengeDisposition (^)(NSURLSession *session, NSURLAuthenticationChallenge *challenge, NSURLCredential * __autoreleasing *credential))block { + self.sessionDidReceiveAuthenticationChallenge = block; +} + +#if !TARGET_OS_OSX +- (void)setDidFinishEventsForBackgroundURLSessionBlock:(void (^)(NSURLSession *session))block { + self.didFinishEventsForBackgroundURLSession = block; +} +#endif + +#pragma mark - + +- (void)setTaskNeedNewBodyStreamBlock:(NSInputStream * (^)(NSURLSession *session, NSURLSessionTask *task))block { + self.taskNeedNewBodyStream = block; +} + +- (void)setTaskWillPerformHTTPRedirectionBlock:(NSURLRequest * (^)(NSURLSession *session, NSURLSessionTask *task, NSURLResponse *response, NSURLRequest *request))block { + self.taskWillPerformHTTPRedirection = block; +} + +- (void)setTaskDidSendBodyDataBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend))block { + self.taskDidSendBodyData = block; +} + +- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block { + self.taskDidComplete = block; +} + +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)setTaskDidFinishCollectingMetricsBlock:(void (^)(NSURLSession * _Nonnull, NSURLSessionTask * _Nonnull, NSURLSessionTaskMetrics * _Nullable))block AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) { + self.taskDidFinishCollectingMetrics = block; +} +#endif + +#pragma mark - + +- (void)setDataTaskDidReceiveResponseBlock:(NSURLSessionResponseDisposition (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response))block { + self.dataTaskDidReceiveResponse = block; +} + +- (void)setDataTaskDidBecomeDownloadTaskBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask))block { + self.dataTaskDidBecomeDownloadTask = block; +} + +- (void)setDataTaskDidReceiveDataBlock:(void (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data))block { + self.dataTaskDidReceiveData = block; +} + +- (void)setDataTaskWillCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLSession *session, NSURLSessionDataTask *dataTask, NSCachedURLResponse *proposedResponse))block { + self.dataTaskWillCacheResponse = block; +} + +#pragma mark - + +- (void)setDownloadTaskDidFinishDownloadingBlock:(NSURL * (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location))block { + self.downloadTaskDidFinishDownloading = block; +} + +- (void)setDownloadTaskDidWriteDataBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite))block { + self.downloadTaskDidWriteData = block; +} + +- (void)setDownloadTaskDidResumeBlock:(void (^)(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t fileOffset, int64_t expectedTotalBytes))block { + self.downloadTaskDidResume = block; +} + +#pragma mark - NSObject + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, session: %@, operationQueue: %@>", NSStringFromClass([self class]), self, self.session, self.operationQueue]; +} + +- (BOOL)respondsToSelector:(SEL)selector { + if (selector == @selector(URLSession:didReceiveChallenge:completionHandler:)) { + return self.sessionDidReceiveAuthenticationChallenge != nil; + } else if (selector == @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)) { + return self.taskWillPerformHTTPRedirection != nil; + } else if (selector == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) { + return self.dataTaskDidReceiveResponse != nil; + } else if (selector == @selector(URLSession:dataTask:willCacheResponse:completionHandler:)) { + return self.dataTaskWillCacheResponse != nil; + } +#if !TARGET_OS_OSX + else if (selector == @selector(URLSessionDidFinishEventsForBackgroundURLSession:)) { + return self.didFinishEventsForBackgroundURLSession != nil; + } +#endif + + return [[self class] instancesRespondToSelector:selector]; +} + +#pragma mark - NSURLSessionDelegate + +- (void)URLSession:(NSURLSession *)session +didBecomeInvalidWithError:(NSError *)error +{ + if (self.sessionDidBecomeInvalid) { + self.sessionDidBecomeInvalid(session, error); + } + + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDidInvalidateNotification object:session]; +} + +- (void)URLSession:(NSURLSession *)session +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + NSAssert(self.sessionDidReceiveAuthenticationChallenge != nil, @"`respondsToSelector:` implementation forces `URLSession:didReceiveChallenge:completionHandler:` to be called only if `self.sessionDidReceiveAuthenticationChallenge` is not nil"); + + NSURLCredential *credential = nil; + NSURLSessionAuthChallengeDisposition disposition = self.sessionDidReceiveAuthenticationChallenge(session, challenge, &credential); + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +#pragma mark - NSURLSessionTaskDelegate + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler +{ + NSURLRequest *redirectRequest = request; + + if (self.taskWillPerformHTTPRedirection) { + redirectRequest = self.taskWillPerformHTTPRedirection(session, task, response, request); + } + + if (completionHandler) { + completionHandler(redirectRequest); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler +{ + BOOL evaluateServerTrust = NO; + NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling; + NSURLCredential *credential = nil; + + if (self.authenticationChallengeHandler) { + id result = self.authenticationChallengeHandler(session, task, challenge, completionHandler); + if (result == nil) { + return; + } else if ([result isKindOfClass:NSError.class]) { + objc_setAssociatedObject(task, AuthenticationChallengeErrorKey, result, OBJC_ASSOCIATION_RETAIN); + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } else if ([result isKindOfClass:NSURLCredential.class]) { + credential = result; + disposition = NSURLSessionAuthChallengeUseCredential; + } else if ([result isKindOfClass:NSNumber.class]) { + disposition = [result integerValue]; + NSAssert(disposition == NSURLSessionAuthChallengePerformDefaultHandling || disposition == NSURLSessionAuthChallengeCancelAuthenticationChallenge || disposition == NSURLSessionAuthChallengeRejectProtectionSpace, @""); + evaluateServerTrust = disposition == NSURLSessionAuthChallengePerformDefaultHandling && [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; + } else { + @throw [NSException exceptionWithName:@"Invalid Return Value" reason:@"The return value from the authentication challenge handler must be nil, an NSError, an NSURLCredential or an NSNumber." userInfo:nil]; + } + } else { + evaluateServerTrust = [challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; + } + + if (evaluateServerTrust) { + if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) { + disposition = NSURLSessionAuthChallengeUseCredential; + credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; + } else { + objc_setAssociatedObject(task, AuthenticationChallengeErrorKey, + [self serverTrustErrorForServerTrust:challenge.protectionSpace.serverTrust url:task.currentRequest.URL], + OBJC_ASSOCIATION_RETAIN); + disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge; + } + } + + if (completionHandler) { + completionHandler(disposition, credential); + } +} + +- (nonnull NSError *)serverTrustErrorForServerTrust:(nullable SecTrustRef)serverTrust url:(nullable NSURL *)url +{ + NSBundle *CFNetworkBundle = [NSBundle bundleWithIdentifier:@"com.apple.CFNetwork"]; + NSString *defaultValue = @"The certificate for this server is invalid. You might be connecting to a server that is pretending to be “%@” which could put your confidential information at risk."; + NSString *descriptionFormat = NSLocalizedStringWithDefaultValue(@"Err-1202.w", nil, CFNetworkBundle, defaultValue, @"") ?: defaultValue; + NSString *localizedDescription = [descriptionFormat componentsSeparatedByString:@"%@"].count <= 2 ? [NSString localizedStringWithFormat:descriptionFormat, url.host] : descriptionFormat; + NSMutableDictionary *userInfo = [@{ + NSLocalizedDescriptionKey: localizedDescription + } mutableCopy]; + + if (serverTrust) { + userInfo[NSURLErrorFailingURLPeerTrustErrorKey] = (__bridge id)serverTrust; + } + + if (url) { + userInfo[NSURLErrorFailingURLErrorKey] = url; + + if (url.absoluteString) { + userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString; + } + } + + return [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorServerCertificateUntrusted userInfo:userInfo]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))completionHandler +{ + NSInputStream *inputStream = nil; + + if (self.taskNeedNewBodyStream) { + inputStream = self.taskNeedNewBodyStream(session, task); + } else if (task.originalRequest.HTTPBodyStream && [task.originalRequest.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) { + inputStream = [task.originalRequest.HTTPBodyStream copy]; + } + + if (completionHandler) { + completionHandler(inputStream); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend +{ + + int64_t totalUnitCount = totalBytesExpectedToSend; + if (totalUnitCount == NSURLSessionTransferSizeUnknown) { + NSString *contentLength = [task.originalRequest valueForHTTPHeaderField:@"Content-Length"]; + if (contentLength) { + totalUnitCount = (int64_t) [contentLength longLongValue]; + } + } + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + if (delegate) { + [delegate URLSession:session task:task didSendBodyData:bytesSent totalBytesSent:totalBytesSent totalBytesExpectedToSend:totalBytesExpectedToSend]; + } + + if (self.taskDidSendBodyData) { + self.taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalUnitCount); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + + // delegate may be nil when completing a task in the background + if (delegate) { + [delegate URLSession:session task:task didCompleteWithError:error]; + + [self removeDelegateForTask:task]; + } + + if (self.taskDidComplete) { + self.taskDidComplete(session, task, error); + } +} + +#if AF_CAN_INCLUDE_SESSION_TASK_METRICS +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didFinishCollectingMetrics:(NSURLSessionTaskMetrics *)metrics AF_API_AVAILABLE(ios(10), macosx(10.12), watchos(3), tvos(10)) +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:task]; + // Metrics may fire after URLSession:task:didCompleteWithError: is called, delegate may be nil + if (delegate) { + [delegate URLSession:session task:task didFinishCollectingMetrics:metrics]; + } + + if (self.taskDidFinishCollectingMetrics) { + self.taskDidFinishCollectingMetrics(session, task, metrics); + } +} +#endif + +#pragma mark - NSURLSessionDataDelegate + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler +{ + NSURLSessionResponseDisposition disposition = NSURLSessionResponseAllow; + + if (self.dataTaskDidReceiveResponse) { + disposition = self.dataTaskDidReceiveResponse(session, dataTask, response); + } + + if (completionHandler) { + completionHandler(disposition); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + if (delegate) { + [self removeDelegateForTask:dataTask]; + [self setDelegate:delegate forTask:downloadTask]; + } + + if (self.dataTaskDidBecomeDownloadTask) { + self.dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:dataTask]; + [delegate URLSession:session dataTask:dataTask didReceiveData:data]; + + if (self.dataTaskDidReceiveData) { + self.dataTaskDidReceiveData(session, dataTask, data); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler +{ + NSCachedURLResponse *cachedResponse = proposedResponse; + + if (self.dataTaskWillCacheResponse) { + cachedResponse = self.dataTaskWillCacheResponse(session, dataTask, proposedResponse); + } + + if (completionHandler) { + completionHandler(cachedResponse); + } +} + +#if !TARGET_OS_OSX +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + if (self.didFinishEventsForBackgroundURLSession) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.didFinishEventsForBackgroundURLSession(session); + }); + } +} +#endif + +#pragma mark - NSURLSessionDownloadDelegate + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location +{ + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + if (self.downloadTaskDidFinishDownloading) { + NSURL *fileURL = self.downloadTaskDidFinishDownloading(session, downloadTask, location); + if (fileURL) { + delegate.downloadFileURL = fileURL; + NSError *error = nil; + + if (![[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error]) { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:error.userInfo]; + } else { + [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidMoveFileSuccessfullyNotification object:downloadTask userInfo:nil]; + } + + return; + } + } + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite]; + } + + if (self.downloadTaskDidWriteData) { + self.downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes +{ + + AFURLSessionManagerTaskDelegate *delegate = [self delegateForTask:downloadTask]; + + if (delegate) { + [delegate URLSession:session downloadTask:downloadTask didResumeAtOffset:fileOffset expectedTotalBytes:expectedTotalBytes]; + } + + if (self.downloadTaskDidResume) { + self.downloadTaskDidResume(session, downloadTask, fileOffset, expectedTotalBytes); + } +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder { + NSURLSessionConfiguration *configuration = [decoder decodeObjectOfClass:[NSURLSessionConfiguration class] forKey:@"sessionConfiguration"]; + + self = [self initWithSessionConfiguration:configuration]; + if (!self) { + return nil; + } + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)coder { + [coder encodeObject:self.session.configuration forKey:@"sessionConfiguration"]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(NSZone *)zone { + return [[[self class] allocWithZone:zone] initWithSessionConfiguration:self.session.configuration]; +} + +@end diff --git a/Pods/AFNetworking/LICENSE b/Pods/AFNetworking/LICENSE new file mode 100644 index 0000000..f611f42 --- /dev/null +++ b/Pods/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011-2020 Alamofire Software Foundation (http://alamofire.org/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Pods/AFNetworking/README.md b/Pods/AFNetworking/README.md new file mode 100644 index 0000000..d193dfe --- /dev/null +++ b/Pods/AFNetworking/README.md @@ -0,0 +1,298 @@ +

+ AFNetworking +

+ +[![Build Status](https://github.com/AFNetworking/AFNetworking/workflows/AFNetworking%20CI/badge.svg?branch=master)](https://github.com/AFNetworking/AFNetworking/actions) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/AFNetworking.svg)](https://img.shields.io/cocoapods/v/AFNetworking.svg) +[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Platform](https://img.shields.io/cocoapods/p/AFNetworking.svg?style=flat)](http://cocoadocs.org/docsets/AFNetworking) +[![Twitter](https://img.shields.io/badge/twitter-@AFNetworking-blue.svg?style=flat)](http://twitter.com/AFNetworking) + +AFNetworking is a delightful networking library for iOS, macOS, watchOS, and tvOS. It's built on top of the [Foundation URL Loading System](https://developer.apple.com/documentation/foundation/url_loading_system), extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. + +Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. + +## How To Get Started + +- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/archive/master.zip) and try out the included Mac and iPhone example apps +- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles on the Wiki](https://github.com/AFNetworking/AFNetworking/wiki) + +## Communication + +- If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). (Tag 'afnetworking') +- If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking). +- If you **found a bug**, _and can provide steps to reliably reproduce it_, open an issue. +- If you **have a feature request**, open an issue. +- If you **want to contribute**, submit a pull request. + +## Installation +AFNetworking supports multiple methods for installing the library in a project. + +## Installation with CocoaPods + +To integrate AFNetworking into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +pod 'AFNetworking', '~> 4.0' +``` + +### Installation with Swift Package Manager + +Once you have your Swift package set up, adding AFNetworking as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +```swift +dependencies: [ + .package(url: "https://github.com/AFNetworking/AFNetworking.git", .upToNextMajor(from: "4.0.0")) +] +``` + +> Note: AFNetworking's Swift package does not include it's UIKit extensions. + +### Installation with Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AFNetworking, add the following to your `Cartfile`. + +```ogdl +github "AFNetworking/AFNetworking" ~> 4.0 +``` + +## Requirements + +| AFNetworking Version | Minimum iOS Target | Minimum macOS Target | Minimum watchOS Target | Minimum tvOS Target | Notes | +|:--------------------:|:---------------------------:|:----------------------------:|:----------------------------:|:----------------------------:|:-------------------------------------------------------------------------:| +| 4.x | iOS 9 | macOS 10.10 | watchOS 2.0 | tvOS 9.0 | Xcode 11+ is required. | +| 3.x | iOS 7 | OS X 10.9 | watchOS 2.0 | tvOS 9.0 | Xcode 7+ is required. `NSURLConnectionOperation` support has been removed. | +| 2.6 -> 2.6.3 | iOS 7 | OS X 10.9 | watchOS 2.0 | n/a | Xcode 7+ is required. | +| 2.0 -> 2.5.4 | iOS 6 | OS X 10.8 | n/a | n/a | Xcode 5+ is required. `NSURLSession` subspec requires iOS 7 or OS X 10.9. | +| 1.x | iOS 5 | Mac OS X 10.7 | n/a | n/a | +| 0.10.x | iOS 4 | Mac OS X 10.6 | n/a | n/a | + +(macOS projects must support [64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)). + +> Programming in Swift? Try [Alamofire](https://github.com/Alamofire/Alamofire) for a more conventional set of APIs. + +## Architecture + +### NSURLSession + +- `AFURLSessionManager` +- `AFHTTPSessionManager` + +### Serialization + +* `` + - `AFHTTPRequestSerializer` + - `AFJSONRequestSerializer` + - `AFPropertyListRequestSerializer` +* `` + - `AFHTTPResponseSerializer` + - `AFJSONResponseSerializer` + - `AFXMLParserResponseSerializer` + - `AFXMLDocumentResponseSerializer` _(macOS)_ + - `AFPropertyListResponseSerializer` + - `AFImageResponseSerializer` + - `AFCompoundResponseSerializer` + +### Additional Functionality + +- `AFSecurityPolicy` +- `AFNetworkReachabilityManager` + +## Usage + +### AFURLSessionManager + +`AFURLSessionManager` creates and manages an `NSURLSession` object based on a specified `NSURLSessionConfiguration` object, which conforms to ``, ``, ``, and ``. + +#### Creating a Download Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/download.zip"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { + NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil]; + return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; +} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { + NSLog(@"File downloaded to: %@", filePath); +}]; +[downloadTask resume]; +``` + +#### Creating an Upload Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURL *filePath = [NSURL fileURLWithPath:@"file://path/to/image.png"]; +NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"Success: %@ %@", response, responseObject); + } +}]; +[uploadTask resume]; +``` + +#### Creating an Upload Task for a Multi-Part Request, with Progress + +```objective-c +NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { + [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; + } error:nil]; + +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + +NSURLSessionUploadTask *uploadTask; +uploadTask = [manager + uploadTaskWithStreamedRequest:request + progress:^(NSProgress * _Nonnull uploadProgress) { + // This is not called back on the main queue. + // You are responsible for dispatching to the main queue for UI updates + dispatch_async(dispatch_get_main_queue(), ^{ + //Update the progress view + [progressView setProgress:uploadProgress.fractionCompleted]; + }); + } + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } + }]; + +[uploadTask resume]; +``` + +#### Creating a Data Task + +```objective-c +NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; + +NSURL *URL = [NSURL URLWithString:@"http://httpbin.org/get"]; +NSURLRequest *request = [NSURLRequest requestWithURL:URL]; + +NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + if (error) { + NSLog(@"Error: %@", error); + } else { + NSLog(@"%@ %@", response, responseObject); + } +}]; +[dataTask resume]; +``` + +--- + +### Request Serialization + +Request serializers create requests from URL strings, encoding parameters as either a query string or HTTP body. + +```objective-c +NSString *URLString = @"http://example.com"; +NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@1, @2, @3]}; +``` + +#### Query String Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; +``` + + GET http://example.com?foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### URL Form Parameter Encoding + +```objective-c +[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/x-www-form-urlencoded + + foo=bar&baz[]=1&baz[]=2&baz[]=3 + +#### JSON Parameter Encoding + +```objective-c +[[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters error:nil]; +``` + + POST http://example.com/ + Content-Type: application/json + + {"foo": "bar", "baz": [1,2,3]} + +--- + +### Network Reachability Manager + +`AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. + +* Do not use Reachability to determine if the original request should be sent. + * You should try to send it. +* You can use Reachability to determine when a request should be automatically retried. + * Although it may still fail, a Reachability notification that the connectivity is available is a good time to retry something. +* Network reachability is a useful tool for determining why a request might have failed. + * After a network request has failed, telling the user they're offline is better than giving them a more technical but accurate error, such as "request timed out." + +See also [WWDC 2012 session 706, "Networking Best Practices."](https://developer.apple.com/videos/play/wwdc2012-706/). + +#### Shared Network Reachability + +```objective-c +[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); +}]; + +[[AFNetworkReachabilityManager sharedManager] startMonitoring]; +``` + +--- + +### Security Policy + +`AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. + +Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. + +#### Allowing Invalid SSL Certificates + +```objective-c +AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; +manager.securityPolicy.allowInvalidCertificates = YES; // not recommended for production +``` + +--- + +## Unit Tests + +AFNetworking includes a suite of unit tests within the Tests subdirectory. These tests can be run simply be executed the test action on the platform framework you would like to test. + +## Credits + +AFNetworking is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). + +AFNetworking was originally created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). + +AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +### Security Disclosure + +If you believe you have identified a security vulnerability with AFNetworking, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## License + +AFNetworking is released under the MIT license. See [LICENSE](https://github.com/AFNetworking/AFNetworking/blob/master/LICENSE) for details. diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h new file mode 100644 index 0000000..1a27bb4 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.h @@ -0,0 +1,160 @@ +// AFAutoPurgingImageCache.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if TARGET_OS_IOS || TARGET_OS_TV +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. + */ +@protocol AFImageCache + +/** + Adds the image to the cache with the given identifier. + + @param image The image to cache. + @param identifier The unique identifier for the image in the cache. + */ +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; + +/** + Removes the image from the cache matching the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return A BOOL indicating whether or not the image was removed from the cache. + */ +- (BOOL)removeImageWithIdentifier:(NSString *)identifier; + +/** + Removes all images from the cache. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeAllImages; + +/** + Returns the image in the cache associated with the given identifier. + + @param identifier The unique identifier for the image in the cache. + + @return An image for the matching identifier, or nil. + */ +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; +@end + + +/** + The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. + */ +@protocol AFImageRequestCache + +/** + Asks if the image should be cached using an identifier created from the request and additional identifier. + + @param image The image to be cached. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching. + */ +- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Adds the image to the cache using an identifier created from the request and additional identifier. + + @param image The image to cache. + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + */ +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Removes the image from the cache using an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return A BOOL indicating whether or not all images were removed from the cache. + */ +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +/** + Returns the image from the cache associated with an identifier created from the request and additional identifier. + + @param request The unique URL request identifing the image asset. + @param identifier The additional identifier to apply to the URL request to identify the image. + + @return An image for the matching request and identifier, or nil. + */ +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; + +@end + +/** + The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. + */ +@interface AFAutoPurgingImageCache : NSObject + +/** + The total memory capacity of the cache in bytes. + */ +@property (nonatomic, assign) UInt64 memoryCapacity; + +/** + The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. + */ +@property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; + +/** + The current total memory usage in bytes of all images stored within the cache. + */ +@property (nonatomic, assign, readonly) UInt64 memoryUsage; + +/** + Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)init; + +/** + Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage + after purge limit. + + @param memoryCapacity The total memory capacity of the cache in bytes. + @param preferredMemoryCapacity The preferred memory usage after purge in bytes. + + @return The new `AutoPurgingImageCache` instance. + */ +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; + +@end + +NS_ASSUME_NONNULL_END + +#endif + diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m new file mode 100644 index 0000000..a09e87c --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFAutoPurgingImageCache.m @@ -0,0 +1,205 @@ +// AFAutoPurgingImageCache.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFAutoPurgingImageCache.h" + +@interface AFCachedImage : NSObject + +@property (nonatomic, strong) UIImage *image; +@property (nonatomic, copy) NSString *identifier; +@property (nonatomic, assign) UInt64 totalBytes; +@property (nonatomic, strong) NSDate *lastAccessDate; +@property (nonatomic, assign) UInt64 currentMemoryUsage; + +@end + +@implementation AFCachedImage + +- (instancetype)initWithImage:(UIImage *)image identifier:(NSString *)identifier { + if (self = [self init]) { + self.image = image; + self.identifier = identifier; + + CGSize imageSize = CGSizeMake(image.size.width * image.scale, image.size.height * image.scale); + CGFloat bytesPerPixel = 4.0; + CGFloat bytesPerSize = imageSize.width * imageSize.height; + self.totalBytes = (UInt64)bytesPerPixel * (UInt64)bytesPerSize; + self.lastAccessDate = [NSDate date]; + } + return self; +} + +- (UIImage *)accessImage { + self.lastAccessDate = [NSDate date]; + return self.image; +} + +- (NSString *)description { + NSString *descriptionString = [NSString stringWithFormat:@"Idenfitier: %@ lastAccessDate: %@ ", self.identifier, self.lastAccessDate]; + return descriptionString; + +} + +@end + +@interface AFAutoPurgingImageCache () +@property (nonatomic, strong) NSMutableDictionary *cachedImages; +@property (nonatomic, assign) UInt64 currentMemoryUsage; +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@end + +@implementation AFAutoPurgingImageCache + +- (instancetype)init { + return [self initWithMemoryCapacity:100 * 1024 * 1024 preferredMemoryCapacity:60 * 1024 * 1024]; +} + +- (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity { + if (self = [super init]) { + self.memoryCapacity = memoryCapacity; + self.preferredMemoryUsageAfterPurge = preferredMemoryCapacity; + self.cachedImages = [[NSMutableDictionary alloc] init]; + + NSString *queueName = [NSString stringWithFormat:@"com.alamofire.autopurgingimagecache-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([queueName cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + + [[NSNotificationCenter defaultCenter] + addObserver:self + selector:@selector(removeAllImages) + name:UIApplicationDidReceiveMemoryWarningNotification + object:nil]; + + } + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (UInt64)memoryUsage { + __block UInt64 result = 0; + dispatch_sync(self.synchronizationQueue, ^{ + result = self.currentMemoryUsage; + }); + return result; +} + +- (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier { + dispatch_barrier_async(self.synchronizationQueue, ^{ + AFCachedImage *cacheImage = [[AFCachedImage alloc] initWithImage:image identifier:identifier]; + + AFCachedImage *previousCachedImage = self.cachedImages[identifier]; + if (previousCachedImage != nil) { + self.currentMemoryUsage -= previousCachedImage.totalBytes; + } + + self.cachedImages[identifier] = cacheImage; + self.currentMemoryUsage += cacheImage.totalBytes; + }); + + dispatch_barrier_async(self.synchronizationQueue, ^{ + if (self.currentMemoryUsage > self.memoryCapacity) { + UInt64 bytesToPurge = self.currentMemoryUsage - self.preferredMemoryUsageAfterPurge; + NSMutableArray *sortedImages = [NSMutableArray arrayWithArray:self.cachedImages.allValues]; + NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastAccessDate" + ascending:YES]; + [sortedImages sortUsingDescriptors:@[sortDescriptor]]; + + UInt64 bytesPurged = 0; + + for (AFCachedImage *cachedImage in sortedImages) { + [self.cachedImages removeObjectForKey:cachedImage.identifier]; + bytesPurged += cachedImage.totalBytes; + if (bytesPurged >= bytesToPurge) { + break; + } + } + self.currentMemoryUsage -= bytesPurged; + } + }); +} + +- (BOOL)removeImageWithIdentifier:(NSString *)identifier { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + if (cachedImage != nil) { + [self.cachedImages removeObjectForKey:identifier]; + self.currentMemoryUsage -= cachedImage.totalBytes; + removed = YES; + } + }); + return removed; +} + +- (BOOL)removeAllImages { + __block BOOL removed = NO; + dispatch_barrier_sync(self.synchronizationQueue, ^{ + if (self.cachedImages.count > 0) { + [self.cachedImages removeAllObjects]; + self.currentMemoryUsage = 0; + removed = YES; + } + }); + return removed; +} + +- (nullable UIImage *)imageWithIdentifier:(NSString *)identifier { + __block UIImage *image = nil; + dispatch_sync(self.synchronizationQueue, ^{ + AFCachedImage *cachedImage = self.cachedImages[identifier]; + image = [cachedImage accessImage]; + }); + return image; +} + +- (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + [self addImage:image withIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self removeImageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)identifier { + return [self imageWithIdentifier:[self imageCacheKeyFromURLRequest:request withAdditionalIdentifier:identifier]]; +} + +- (NSString *)imageCacheKeyFromURLRequest:(NSURLRequest *)request withAdditionalIdentifier:(NSString *)additionalIdentifier { + NSString *key = request.URL.absoluteString; + if (additionalIdentifier != nil) { + key = [key stringByAppendingString:additionalIdentifier]; + } + return key; +} + +- (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier { + return YES; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h new file mode 100644 index 0000000..3bf5a32 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.h @@ -0,0 +1,171 @@ +// AFImageDownloader.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import +#import "AFAutoPurgingImageCache.h" +#import "AFHTTPSessionManager.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { + AFImageDownloadPrioritizationFIFO, + AFImageDownloadPrioritizationLIFO +}; + +/** + The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. + */ +@interface AFImageDownloadReceipt : NSObject + +/** + The data task created by the `AFImageDownloader`. +*/ +@property (nonatomic, strong) NSURLSessionDataTask *task; + +/** + The unique identifier for the success and failure blocks when duplicate requests are made. + */ +@property (nonatomic, strong) NSUUID *receiptID; +@end + +/** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. + */ +@interface AFImageDownloader : NSObject + +/** + The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. + */ +@property (nonatomic, strong, nullable) id imageCache; + +/** + The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. + */ +@property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritization; + +/** + The shared default instance of `AFImageDownloader` initialized with default values. + */ ++ (instancetype)defaultInstance; + +/** + Creates a default `NSURLCache` with common usage parameter values. + + @returns The default `NSURLCache` instance. + */ ++ (NSURLCache *)defaultURLCache; + +/** + The default `NSURLSessionConfiguration` with common usage parameter values. + */ ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration; + +/** + Default initializer + + @return An instance of `AFImageDownloader` initialized with default values. + */ +- (instancetype)init; + +/** + Initializer with specific `URLSessionConfiguration` + + @param configuration The `NSURLSessionConfiguration` to be be used + + @return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration` + */ +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; + +/** + Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. + + @param sessionManager The session manager to use to download images. + @param downloadPrioritization The download prioritization of the download queue. + @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. + @param imageCache The image cache used to store all downloaded images in. + + @return The new `AFImageDownloader` instance. + */ +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(nullable id )imageCache; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Creates a data task using the `sessionManager` instance for the specified URL request. + + If the same data task is already in the queue or currently being downloaded, the success and failure blocks are + appended to the already existing task. Once the task completes, all success or failure blocks attached to the + task are executed in the order they were added. + + @param request The URL request. + @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + + @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. + cache and the URL request cache policy allows the cache to be used. + */ +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. + + If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. + + @param imageDownloadReceipt The image download receipt to cancel. + */ +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; + +@end + +#endif + +NS_ASSUME_NONNULL_END diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m new file mode 100644 index 0000000..008a782 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFImageDownloader.m @@ -0,0 +1,421 @@ +// AFImageDownloader.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" +#import "AFHTTPSessionManager.h" + +@interface AFImageDownloaderResponseHandler : NSObject +@property (nonatomic, strong) NSUUID *uuid; +@property (nonatomic, copy) void (^successBlock)(NSURLRequest *, NSHTTPURLResponse *, UIImage *); +@property (nonatomic, copy) void (^failureBlock)(NSURLRequest *, NSHTTPURLResponse *, NSError *); +@end + +@implementation AFImageDownloaderResponseHandler + +- (instancetype)initWithUUID:(NSUUID *)uuid + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + if (self = [self init]) { + self.uuid = uuid; + self.successBlock = success; + self.failureBlock = failure; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat: @"UUID: %@", [self.uuid UUIDString]]; +} + +@end + +@interface AFImageDownloaderMergedTask : NSObject +@property (nonatomic, strong) NSString *URLIdentifier; +@property (nonatomic, strong) NSUUID *identifier; +@property (nonatomic, strong) NSURLSessionDataTask *task; +@property (nonatomic, strong) NSMutableArray *responseHandlers; + +@end + +@implementation AFImageDownloaderMergedTask + +- (instancetype)initWithURLIdentifier:(NSString *)URLIdentifier identifier:(NSUUID *)identifier task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.URLIdentifier = URLIdentifier; + self.task = task; + self.identifier = identifier; + self.responseHandlers = [[NSMutableArray alloc] init]; + } + return self; +} + +- (void)addResponseHandler:(AFImageDownloaderResponseHandler *)handler { + [self.responseHandlers addObject:handler]; +} + +- (void)removeResponseHandler:(AFImageDownloaderResponseHandler *)handler { + [self.responseHandlers removeObject:handler]; +} + +@end + +@implementation AFImageDownloadReceipt + +- (instancetype)initWithReceiptID:(NSUUID *)receiptID task:(NSURLSessionDataTask *)task { + if (self = [self init]) { + self.receiptID = receiptID; + self.task = task; + } + return self; +} + +@end + +@interface AFImageDownloader () + +@property (nonatomic, strong) dispatch_queue_t synchronizationQueue; +@property (nonatomic, strong) dispatch_queue_t responseQueue; + +@property (nonatomic, assign) NSInteger maximumActiveDownloads; +@property (nonatomic, assign) NSInteger activeRequestCount; + +@property (nonatomic, strong) NSMutableArray *queuedMergedTasks; +@property (nonatomic, strong) NSMutableDictionary *mergedTasks; + +@end + +@implementation AFImageDownloader + ++ (NSURLCache *)defaultURLCache { + NSUInteger memoryCapacity = 20 * 1024 * 1024; // 20MB + NSUInteger diskCapacity = 150 * 1024 * 1024; // 150MB + NSURL *cacheURL = [[[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory + inDomain:NSUserDomainMask + appropriateForURL:nil + create:YES + error:nil] + URLByAppendingPathComponent:@"com.alamofire.imagedownloader"]; + +#if TARGET_OS_MACCATALYST + return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity + diskCapacity:diskCapacity + directoryURL:cacheURL]; +#else + return [[NSURLCache alloc] initWithMemoryCapacity:memoryCapacity + diskCapacity:diskCapacity + diskPath:[cacheURL path]]; +#endif +} + ++ (NSURLSessionConfiguration *)defaultURLSessionConfiguration { + NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; + + //TODO set the default HTTP headers + + configuration.HTTPShouldSetCookies = YES; + configuration.HTTPShouldUsePipelining = NO; + + configuration.requestCachePolicy = NSURLRequestUseProtocolCachePolicy; + configuration.allowsCellularAccess = YES; + configuration.timeoutIntervalForRequest = 60.0; + configuration.URLCache = [AFImageDownloader defaultURLCache]; + + return configuration; +} + +- (instancetype)init { + NSURLSessionConfiguration *defaultConfiguration = [self.class defaultURLSessionConfiguration]; + return [self initWithSessionConfiguration:defaultConfiguration]; +} + +- (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration { + AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration]; + sessionManager.responseSerializer = [AFImageResponseSerializer serializer]; + + return [self initWithSessionManager:sessionManager + downloadPrioritization:AFImageDownloadPrioritizationFIFO + maximumActiveDownloads:4 + imageCache:[[AFAutoPurgingImageCache alloc] init]]; +} + +- (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager + downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization + maximumActiveDownloads:(NSInteger)maximumActiveDownloads + imageCache:(id )imageCache { + if (self = [super init]) { + self.sessionManager = sessionManager; + + self.downloadPrioritization = downloadPrioritization; + self.maximumActiveDownloads = maximumActiveDownloads; + self.imageCache = imageCache; + + self.queuedMergedTasks = [[NSMutableArray alloc] init]; + self.mergedTasks = [[NSMutableDictionary alloc] init]; + self.activeRequestCount = 0; + + NSString *name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.synchronizationqueue-%@", [[NSUUID UUID] UUIDString]]; + self.synchronizationQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL); + + name = [NSString stringWithFormat:@"com.alamofire.imagedownloader.responsequeue-%@", [[NSUUID UUID] UUIDString]]; + self.responseQueue = dispatch_queue_create([name cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_CONCURRENT); + } + + return self; +} + ++ (instancetype)defaultInstance { + static AFImageDownloader *sharedInstance = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedInstance = [[self alloc] init]; + }); + return sharedInstance; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, UIImage * _Nonnull))success + failure:(void (^)(NSURLRequest * _Nonnull, NSHTTPURLResponse * _Nullable, NSError * _Nonnull))failure { + return [self downloadImageForURLRequest:request withReceiptID:[NSUUID UUID] success:success failure:failure]; +} + +- (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request + withReceiptID:(nonnull NSUUID *)receiptID + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure { + __block NSURLSessionDataTask *task = nil; + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = request.URL.absoluteString; + if (URLIdentifier == nil) { + if (failure) { + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + failure(request, nil, error); + }); + } + return; + } + + // 1) Append the success and failure blocks to a pre-existing request if it already exists + AFImageDownloaderMergedTask *existingMergedTask = self.mergedTasks[URLIdentifier]; + if (existingMergedTask != nil) { + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID success:success failure:failure]; + [existingMergedTask addResponseHandler:handler]; + task = existingMergedTask.task; + return; + } + + // 2) Attempt to load the image from the image cache if the cache policy allows it + switch (request.cachePolicy) { + case NSURLRequestUseProtocolCachePolicy: + case NSURLRequestReturnCacheDataElseLoad: + case NSURLRequestReturnCacheDataDontLoad: { + UIImage *cachedImage = [self.imageCache imageforRequest:request withAdditionalIdentifier:nil]; + if (cachedImage != nil) { + if (success) { + dispatch_async(dispatch_get_main_queue(), ^{ + success(request, nil, cachedImage); + }); + } + return; + } + break; + } + default: + break; + } + + // 3) Create the request and set up authentication, validation and response serialization + NSUUID *mergedTaskIdentifier = [NSUUID UUID]; + NSURLSessionDataTask *createdTask; + __weak __typeof__(self) weakSelf = self; + + createdTask = [self.sessionManager + dataTaskWithRequest:request + uploadProgress:nil + downloadProgress:nil + completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + dispatch_async(self.responseQueue, ^{ + __strong __typeof__(weakSelf) strongSelf = weakSelf; + AFImageDownloaderMergedTask *mergedTask = [strongSelf safelyGetMergedTask:URLIdentifier]; + if ([mergedTask.identifier isEqual:mergedTaskIdentifier]) { + mergedTask = [strongSelf safelyRemoveMergedTaskWithURLIdentifier:URLIdentifier]; + if (error) { + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(request, (NSHTTPURLResponse *)response, error); + }); + } + } + } else { + if ([strongSelf.imageCache shouldCacheImage:responseObject forRequest:request withAdditionalIdentifier:nil]) { + [strongSelf.imageCache addImage:responseObject forRequest:request withAdditionalIdentifier:nil]; + } + + for (AFImageDownloaderResponseHandler *handler in mergedTask.responseHandlers) { + if (handler.successBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.successBlock(request, (NSHTTPURLResponse *)response, responseObject); + }); + } + } + + } + } + [strongSelf safelyDecrementActiveTaskCount]; + [strongSelf safelyStartNextTaskIfNecessary]; + }); + }]; + + // 4) Store the response handler for use when the request completes + AFImageDownloaderResponseHandler *handler = [[AFImageDownloaderResponseHandler alloc] initWithUUID:receiptID + success:success + failure:failure]; + AFImageDownloaderMergedTask *mergedTask = [[AFImageDownloaderMergedTask alloc] + initWithURLIdentifier:URLIdentifier + identifier:mergedTaskIdentifier + task:createdTask]; + [mergedTask addResponseHandler:handler]; + self.mergedTasks[URLIdentifier] = mergedTask; + + // 5) Either start the request or enqueue it depending on the current active request count + if ([self isActiveRequestCountBelowMaximumLimit]) { + [self startMergedTask:mergedTask]; + } else { + [self enqueueMergedTask:mergedTask]; + } + + task = mergedTask.task; + }); + if (task) { + return [[AFImageDownloadReceipt alloc] initWithReceiptID:receiptID task:task]; + } else { + return nil; + } +} + +- (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + dispatch_sync(self.synchronizationQueue, ^{ + NSString *URLIdentifier = imageDownloadReceipt.task.originalRequest.URL.absoluteString; + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + NSUInteger index = [mergedTask.responseHandlers indexOfObjectPassingTest:^BOOL(AFImageDownloaderResponseHandler * _Nonnull handler, __unused NSUInteger idx, __unused BOOL * _Nonnull stop) { + return handler.uuid == imageDownloadReceipt.receiptID; + }]; + + if (index != NSNotFound) { + AFImageDownloaderResponseHandler *handler = mergedTask.responseHandlers[index]; + [mergedTask removeResponseHandler:handler]; + NSString *failureReason = [NSString stringWithFormat:@"ImageDownloader cancelled URL request: %@",imageDownloadReceipt.task.originalRequest.URL.absoluteString]; + NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey:failureReason}; + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + if (handler.failureBlock) { + dispatch_async(dispatch_get_main_queue(), ^{ + handler.failureBlock(imageDownloadReceipt.task.originalRequest, nil, error); + }); + } + } + + if (mergedTask.responseHandlers.count == 0) { + [mergedTask.task cancel]; + [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + } + }); +} + +- (AFImageDownloaderMergedTask *)safelyRemoveMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask = nil; + dispatch_sync(self.synchronizationQueue, ^{ + mergedTask = [self removeMergedTaskWithURLIdentifier:URLIdentifier]; + }); + return mergedTask; +} + +//This method should only be called from safely within the synchronizationQueue +- (AFImageDownloaderMergedTask *)removeMergedTaskWithURLIdentifier:(NSString *)URLIdentifier { + AFImageDownloaderMergedTask *mergedTask = self.mergedTasks[URLIdentifier]; + [self.mergedTasks removeObjectForKey:URLIdentifier]; + return mergedTask; +} + +- (void)safelyDecrementActiveTaskCount { + dispatch_sync(self.synchronizationQueue, ^{ + if (self.activeRequestCount > 0) { + self.activeRequestCount -= 1; + } + }); +} + +- (void)safelyStartNextTaskIfNecessary { + dispatch_sync(self.synchronizationQueue, ^{ + if ([self isActiveRequestCountBelowMaximumLimit]) { + while (self.queuedMergedTasks.count > 0) { + AFImageDownloaderMergedTask *mergedTask = [self dequeueMergedTask]; + if (mergedTask.task.state == NSURLSessionTaskStateSuspended) { + [self startMergedTask:mergedTask]; + break; + } + } + } + }); +} + +- (void)startMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + [mergedTask.task resume]; + ++self.activeRequestCount; +} + +- (void)enqueueMergedTask:(AFImageDownloaderMergedTask *)mergedTask { + switch (self.downloadPrioritization) { + case AFImageDownloadPrioritizationFIFO: + [self.queuedMergedTasks addObject:mergedTask]; + break; + case AFImageDownloadPrioritizationLIFO: + [self.queuedMergedTasks insertObject:mergedTask atIndex:0]; + break; + } +} + +- (AFImageDownloaderMergedTask *)dequeueMergedTask { + AFImageDownloaderMergedTask *mergedTask = nil; + mergedTask = [self.queuedMergedTasks firstObject]; + [self.queuedMergedTasks removeObject:mergedTask]; + return mergedTask; +} + +- (BOOL)isActiveRequestCountBelowMaximumLimit { + return self.activeRequestCount < self.maximumActiveDownloads; +} + +- (AFImageDownloaderMergedTask *)safelyGetMergedTask:(NSString *)URLIdentifier { + __block AFImageDownloaderMergedTask *mergedTask; + dispatch_sync(self.synchronizationQueue, ^(){ + mergedTask = self.mergedTasks[URLIdentifier]; + }); + return mergedTask; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 0000000..3bcf289 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,103 @@ +// AFNetworkActivityIndicatorManager.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. + + You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: + + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; + + By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. + + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 + */ +NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") +@interface AFNetworkActivityIndicatorManager : NSObject + +/** + A Boolean value indicating whether the manager is enabled. + + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. + */ +@property (nonatomic, assign, getter = isEnabled) BOOL enabled; + +/** + A Boolean value indicating whether the network activity indicator manager is currently active. +*/ +@property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +/** + A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. + + Apple's HIG describes the following: + + > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. + + */ +@property (nonatomic, assign) NSTimeInterval activationDelay; + +/** + A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. + */ + +@property (nonatomic, assign) NSTimeInterval completionDelay; + +/** + Returns the shared network activity indicator manager object for the system. + + @return The systemwide network activity indicator manager. + */ ++ (instancetype)sharedManager; + +/** + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. + */ +- (void)incrementActivityCount; + +/** + Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +/** + Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. + + @param block A block to be executed when the network activity indicator status changes. + */ +- (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 0000000..8cb5677 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,239 @@ +// AFNetworkActivityIndicatorManager.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkActivityIndicatorManager.h" + +#if TARGET_OS_IOS +#import "AFURLSessionManager.h" + +typedef NS_ENUM(NSInteger, AFNetworkActivityManagerState) { + AFNetworkActivityManagerStateNotActive, + AFNetworkActivityManagerStateDelayingStart, + AFNetworkActivityManagerStateActive, + AFNetworkActivityManagerStateDelayingEnd +}; + +static NSTimeInterval const kDefaultAFNetworkActivityManagerActivationDelay = 1.0; +static NSTimeInterval const kDefaultAFNetworkActivityManagerCompletionDelay = 0.17; + +static NSURLRequest * AFNetworkRequestFromNotification(NSNotification *notification) { + if ([[notification object] respondsToSelector:@selector(originalRequest)]) { + return [(NSURLSessionTask *)[notification object] originalRequest]; + } else { + return nil; + } +} + +typedef void (^AFNetworkActivityActionBlock)(BOOL networkActivityIndicatorVisible); + +@interface AFNetworkActivityIndicatorManager () +@property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, strong) NSTimer *activationDelayTimer; +@property (readwrite, nonatomic, strong) NSTimer *completionDelayTimer; +@property (readonly, nonatomic, getter = isNetworkActivityOccurring) BOOL networkActivityOccurring; +@property (nonatomic, copy) AFNetworkActivityActionBlock networkActivityActionBlock; +@property (nonatomic, assign) AFNetworkActivityManagerState currentState; +@property (nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateCurrentStateForNetworkActivityChange; +@end + +@implementation AFNetworkActivityIndicatorManager + ++ (instancetype)sharedManager { + static AFNetworkActivityIndicatorManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + +- (instancetype)init { + self = [super init]; + if (!self) { + return nil; + } + self.currentState = AFNetworkActivityManagerStateNotActive; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidStart:) name:AFNetworkingTaskDidResumeNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidSuspendNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkRequestDidFinish:) name:AFNetworkingTaskDidCompleteNotification object:nil]; + self.activationDelay = kDefaultAFNetworkActivityManagerActivationDelay; + self.completionDelay = kDefaultAFNetworkActivityManagerCompletionDelay; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [_activationDelayTimer invalidate]; + [_completionDelayTimer invalidate]; +} + +- (void)setEnabled:(BOOL)enabled { + _enabled = enabled; + if (enabled == NO) { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)setNetworkingActivityActionWithBlock:(void (^)(BOOL networkActivityIndicatorVisible))block { + self.networkActivityActionBlock = block; +} + +- (BOOL)isNetworkActivityOccurring { + @synchronized(self) { + return self.activityCount > 0; + } +} + +- (void)setNetworkActivityIndicatorVisible:(BOOL)networkActivityIndicatorVisible { + if (_networkActivityIndicatorVisible != networkActivityIndicatorVisible) { + @synchronized(self) { + _networkActivityIndicatorVisible = networkActivityIndicatorVisible; + } + if (self.networkActivityActionBlock) { + self.networkActivityActionBlock(networkActivityIndicatorVisible); + } else { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:networkActivityIndicatorVisible]; + } + } +} + + +- (void)incrementActivityCount { + @synchronized(self) { + self.activityCount++; + } + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)decrementActivityCount { + @synchronized(self) { + self.activityCount = MAX(_activityCount - 1, 0); + } + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateCurrentStateForNetworkActivityChange]; + }); +} + +- (void)networkRequestDidStart:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self incrementActivityCount]; + } +} + +- (void)networkRequestDidFinish:(NSNotification *)notification { + if ([AFNetworkRequestFromNotification(notification) URL]) { + [self decrementActivityCount]; + } +} + +#pragma mark - Internal State Management +- (void)setCurrentState:(AFNetworkActivityManagerState)currentState { + @synchronized(self) { + if (_currentState != currentState) { + _currentState = currentState; + switch (currentState) { + case AFNetworkActivityManagerStateNotActive: + [self cancelActivationDelayTimer]; + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:NO]; + break; + case AFNetworkActivityManagerStateDelayingStart: + [self startActivationDelayTimer]; + break; + case AFNetworkActivityManagerStateActive: + [self cancelCompletionDelayTimer]; + [self setNetworkActivityIndicatorVisible:YES]; + break; + case AFNetworkActivityManagerStateDelayingEnd: + [self startCompletionDelayTimer]; + break; + } + } + } +} + +- (void)updateCurrentStateForNetworkActivityChange { + if (self.enabled) { + switch (self.currentState) { + case AFNetworkActivityManagerStateNotActive: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingStart]; + } + break; + case AFNetworkActivityManagerStateDelayingStart: + //No op. Let the delay timer finish out. + break; + case AFNetworkActivityManagerStateActive: + if (!self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateDelayingEnd]; + } + break; + case AFNetworkActivityManagerStateDelayingEnd: + if (self.isNetworkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } + break; + } + } +} + +- (void)startActivationDelayTimer { + self.activationDelayTimer = [NSTimer + timerWithTimeInterval:self.activationDelay target:self selector:@selector(activationDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.activationDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)activationDelayTimerFired { + if (self.networkActivityOccurring) { + [self setCurrentState:AFNetworkActivityManagerStateActive]; + } else { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; + } +} + +- (void)startCompletionDelayTimer { + [self.completionDelayTimer invalidate]; + self.completionDelayTimer = [NSTimer timerWithTimeInterval:self.completionDelay target:self selector:@selector(completionDelayTimerFired) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.completionDelayTimer forMode:NSRunLoopCommonModes]; +} + +- (void)completionDelayTimerFired { + [self setCurrentState:AFNetworkActivityManagerStateNotActive]; +} + +- (void)cancelActivationDelayTimer { + [self.activationDelayTimer invalidate]; +} + +- (void)cancelCompletionDelayTimer { + [self.completionDelayTimer invalidate]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h new file mode 100644 index 0000000..d424c9b --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.h @@ -0,0 +1,48 @@ +// UIActivityIndicatorView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +/** + This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. + */ +@interface UIActivityIndicatorView (AFNetworking) + +///---------------------------------- +/// @name Animating for Session Tasks +///---------------------------------- + +/** + Binds the animating state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m new file mode 100644 index 0000000..602a72d --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIActivityIndicatorView+AFNetworking.m @@ -0,0 +1,114 @@ +// UIActivityIndicatorView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIActivityIndicatorView+AFNetworking.h" +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +@interface AFActivityIndicatorViewNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIActivityIndicatorView *activityIndicatorView; +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView; + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIActivityIndicatorView (AFNetworking) + +- (AFActivityIndicatorViewNotificationObserver *)af_notificationObserver { + AFActivityIndicatorViewNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFActivityIndicatorViewNotificationObserver alloc] initWithActivityIndicatorView:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setAnimatingWithStateOfTask:task]; +} + +@end + +@implementation AFActivityIndicatorViewNotificationObserver + +- (instancetype)initWithActivityIndicatorView:(UIActivityIndicatorView *)activityIndicatorView +{ + self = [super init]; + if (self) { + _activityIndicatorView = activityIndicatorView; + } + return self; +} + +- (void)setAnimatingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + if (task.state != NSURLSessionTaskStateCompleted) { + UIActivityIndicatorView *activityIndicatorView = self.activityIndicatorView; + if (task.state == NSURLSessionTaskStateRunning) { + [activityIndicatorView startAnimating]; + } else { + [activityIndicatorView stopAnimating]; + } + + [notificationCenter addObserver:self selector:@selector(af_startAnimating) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_stopAnimating) name:AFNetworkingTaskDidSuspendNotification object:task]; + } + } +} + +#pragma mark - + +- (void)af_startAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.activityIndicatorView startAnimating]; + }); +} + +- (void)af_stopAnimating { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.activityIndicatorView stopAnimating]; + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h new file mode 100644 index 0000000..d33e0d4 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.h @@ -0,0 +1,175 @@ +// UIButton+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. + + @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. + */ +@interface UIButton (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. +*/ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + */ +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------- +/// @name Setting Background Image +///------------------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. + + If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + @param state The control state. + @param url The URL used for the background image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. + + @param state The control state. + @param urlRequest The URL request used for the image request. + @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + + +///------------------------------ +/// @name Canceling Image Loading +///------------------------------ + +/** + Cancels any executing image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelImageDownloadTaskForState:(UIControlState)state; + +/** + Cancels any executing background image task for the specified control state of the receiver, if one exists. + + @param state The control state. + */ +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m new file mode 100644 index 0000000..03aaf2a --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIButton+AFNetworking.m @@ -0,0 +1,302 @@ +// UIButton+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIButton+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "UIImageView+AFNetworking.h" +#import "AFImageDownloader.h" + +@interface UIButton (_AFNetworking) +@end + +@implementation UIButton (_AFNetworking) + +#pragma mark - + +static char AFImageDownloadReceiptNormal; +static char AFImageDownloadReceiptHighlighted; +static char AFImageDownloadReceiptSelected; +static char AFImageDownloadReceiptDisabled; + +static const char * af_imageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_imageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_imageDownloadReceiptKeyForState(state)); +} + +- (void)af_setImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_imageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +static char AFBackgroundImageDownloadReceiptNormal; +static char AFBackgroundImageDownloadReceiptHighlighted; +static char AFBackgroundImageDownloadReceiptSelected; +static char AFBackgroundImageDownloadReceiptDisabled; + +static const char * af_backgroundImageDownloadReceiptKeyForState(UIControlState state) { + switch (state) { + case UIControlStateHighlighted: + return &AFBackgroundImageDownloadReceiptHighlighted; + case UIControlStateSelected: + return &AFBackgroundImageDownloadReceiptSelected; + case UIControlStateDisabled: + return &AFBackgroundImageDownloadReceiptDisabled; + case UIControlStateNormal: + default: + return &AFBackgroundImageDownloadReceiptNormal; + } +} + +- (AFImageDownloadReceipt *)af_backgroundImageDownloadReceiptForState:(UIControlState)state { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state)); +} + +- (void)af_setBackgroundImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt + forState:(UIControlState)state +{ + objc_setAssociatedObject(self, af_backgroundImageDownloadReceiptKeyForState(state), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIButton (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + + return objc_getAssociatedObject([UIButton class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject([UIButton class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setImage:cachedImage forState:state]; + } + [self af_setImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if (responseObject) { + [strongSelf setImage:responseObject forState:state]; + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_imageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url +{ + [self setBackgroundImageForState:state withURL:url placeholderImage:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setBackgroundImageForState:state withURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setBackgroundImageForState:(UIControlState)state + withURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([self isActiveBackgroundTaskURLEqualToURLRequest:urlRequest forState:state]) { + return; + } + + [self cancelBackgroundImageDownloadTaskForState:state]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + [self setBackgroundImage:cachedImage forState:state]; + } + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } else { + if (placeholderImage) { + [self setBackgroundImage:placeholderImage forState:state]; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if (responseObject) { + [strongSelf setBackgroundImage:responseObject forState:state]; + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([[strongSelf af_backgroundImageDownloadReceiptForState:state].receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf af_setBackgroundImageDownloadReceipt:nil forState:state]; + } + }]; + + [self af_setBackgroundImageDownloadReceipt:receipt forState:state]; + } +} + +#pragma mark - + +- (void)cancelImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setImageDownloadReceipt:nil forState:state]; + } +} + +- (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + if (receipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:receipt]; + [self af_setBackgroundImageDownloadReceipt:nil forState:state]; + } +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_imageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +- (BOOL)isActiveBackgroundTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest forState:(UIControlState)state { + AFImageDownloadReceipt *receipt = [self af_backgroundImageDownloadReceiptForState:state]; + return [receipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 0000000..8929252 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,109 @@ +// UIImageView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFImageDownloader; + +/** + This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. + */ +@interface UIImageView (AFNetworking) + +///------------------------------------ +/// @name Accessing the Image Downloader +///------------------------------------ + +/** + Set the shared image downloader used to download images. + + @param imageDownloader The shared image downloader used to download images. + */ ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; + +/** + The shared image downloader used to download images. + */ ++ (AFImageDownloader *)sharedImageDownloader; + +///-------------------- +/// @name Setting Image +///-------------------- + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + */ +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(nullable UIImage *)placeholderImage; + +/** + Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. + + If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. + + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. + @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(nullable UIImage *)placeholderImage + success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; + +/** + Cancels any executing image operation for the receiver, if one exists. + */ +- (void)cancelImageDownloadTask; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 0000000..8ae4950 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,159 @@ +// UIImageView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIImageView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFImageDownloader.h" + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setActiveImageDownloadReceipt:) AFImageDownloadReceipt *af_activeImageDownloadReceipt; +@end + +@implementation UIImageView (_AFNetworking) + +- (AFImageDownloadReceipt *)af_activeImageDownloadReceipt { + return (AFImageDownloadReceipt *)objc_getAssociatedObject(self, @selector(af_activeImageDownloadReceipt)); +} + +- (void)af_setActiveImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt { + objc_setAssociatedObject(self, @selector(af_activeImageDownloadReceipt), imageDownloadReceipt, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) + ++ (AFImageDownloader *)sharedImageDownloader { + return objc_getAssociatedObject([UIImageView class], @selector(sharedImageDownloader)) ?: [AFImageDownloader defaultInstance]; +} + ++ (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader { + objc_setAssociatedObject([UIImageView class], @selector(sharedImageDownloader), imageDownloader, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil]; +} + +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure +{ + if ([urlRequest URL] == nil) { + self.image = placeholderImage; + if (failure) { + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadURL userInfo:nil]; + failure(urlRequest, nil, error); + } + return; + } + + if ([self isActiveTaskURLEqualToURLRequest:urlRequest]) { + return; + } + + [self cancelImageDownloadTask]; + + AFImageDownloader *downloader = [[self class] sharedImageDownloader]; + id imageCache = downloader.imageCache; + + //Use the image from the image cache if it exists + UIImage *cachedImage = [imageCache imageforRequest:urlRequest withAdditionalIdentifier:nil]; + if (cachedImage) { + if (success) { + success(urlRequest, nil, cachedImage); + } else { + self.image = cachedImage; + } + [self clearActiveDownloadInformation]; + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + __weak __typeof(self)weakSelf = self; + NSUUID *downloadID = [NSUUID UUID]; + AFImageDownloadReceipt *receipt; + receipt = [downloader + downloadImageForURLRequest:urlRequest + withReceiptID:downloadID + success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull responseObject) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (success) { + success(request, response, responseObject); + } else if (responseObject) { + strongSelf.image = responseObject; + } + [strongSelf clearActiveDownloadInformation]; + } + + } + failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if ([strongSelf.af_activeImageDownloadReceipt.receiptID isEqual:downloadID]) { + if (failure) { + failure(request, response, error); + } + [strongSelf clearActiveDownloadInformation]; + } + }]; + + self.af_activeImageDownloadReceipt = receipt; + } +} + +- (void)cancelImageDownloadTask { + if (self.af_activeImageDownloadReceipt != nil) { + [[self.class sharedImageDownloader] cancelTaskForImageDownloadReceipt:self.af_activeImageDownloadReceipt]; + [self clearActiveDownloadInformation]; + } +} + +- (void)clearActiveDownloadInformation { + self.af_activeImageDownloadReceipt = nil; +} + +- (BOOL)isActiveTaskURLEqualToURLRequest:(NSURLRequest *)urlRequest { + return [self.af_activeImageDownloadReceipt.task.originalRequest.URL.absoluteString isEqualToString:urlRequest.URL.absoluteString]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h new file mode 100644 index 0000000..aa9c0b0 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIKit+AFNetworking.h @@ -0,0 +1,43 @@ +// UIKit+AFNetworking.h +// +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#ifndef _UIKIT_AFNETWORKING_ + #define _UIKIT_AFNETWORKING_ + +#if TARGET_OS_IOS || TARGET_OS_TV + #import "AFAutoPurgingImageCache.h" + #import "AFImageDownloader.h" + #import "UIActivityIndicatorView+AFNetworking.h" + #import "UIButton+AFNetworking.h" + #import "UIImageView+AFNetworking.h" + #import "UIProgressView+AFNetworking.h" +#endif + +#if TARGET_OS_IOS + #import "AFNetworkActivityIndicatorManager.h" + #import "UIRefreshControl+AFNetworking.h" + #import "WKWebView+AFNetworking.h" +#endif + +#endif /* _UIKIT_AFNETWORKING_ */ diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h new file mode 100644 index 0000000..8ea0a73 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.h @@ -0,0 +1,64 @@ +// UIProgressView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import + +NS_ASSUME_NONNULL_BEGIN + + +/** + This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. + */ +@interface UIProgressView (AFNetworking) + +///------------------------------------ +/// @name Setting Session Task Progress +///------------------------------------ + +/** + Binds the progress to the upload progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated; + +/** + Binds the progress to the download progress of the specified session task. + + @param task The session task. + @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. + */ +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m new file mode 100644 index 0000000..2ae753e --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIProgressView+AFNetworking.m @@ -0,0 +1,126 @@ +// UIProgressView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIProgressView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS || TARGET_OS_TV + +#import "AFURLSessionManager.h" + +static void * AFTaskCountOfBytesSentContext = &AFTaskCountOfBytesSentContext; +static void * AFTaskCountOfBytesReceivedContext = &AFTaskCountOfBytesReceivedContext; + +#pragma mark - + +@implementation UIProgressView (AFNetworking) + +- (BOOL)af_uploadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_uploadProgressAnimated)) boolValue]; +} + +- (void)af_setUploadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_uploadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (BOOL)af_downloadProgressAnimated { + return [(NSNumber *)objc_getAssociatedObject(self, @selector(af_downloadProgressAnimated)) boolValue]; +} + +- (void)af_setDownloadProgressAnimated:(BOOL)animated { + objc_setAssociatedObject(self, @selector(af_downloadProgressAnimated), @(animated), OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task + animated:(BOOL)animated +{ + if (task.state == NSURLSessionTaskStateCompleted) { + return; + } + + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + [task addObserver:self forKeyPath:@"countOfBytesSent" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesSentContext]; + + [self af_setUploadProgressAnimated:animated]; +} + +- (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task + animated:(BOOL)animated +{ + if (task.state == NSURLSessionTaskStateCompleted) { + return; + } + + [task addObserver:self forKeyPath:@"state" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + [task addObserver:self forKeyPath:@"countOfBytesReceived" options:(NSKeyValueObservingOptions)0 context:AFTaskCountOfBytesReceivedContext]; + + [self af_setDownloadProgressAnimated:animated]; +} + +#pragma mark - NSKeyValueObserving + +- (void)observeValueForKeyPath:(NSString *)keyPath + ofObject:(id)object + change:(__unused NSDictionary *)change + context:(void *)context +{ + if (context == AFTaskCountOfBytesSentContext || context == AFTaskCountOfBytesReceivedContext) { + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesSent))]) { + if ([object countOfBytesExpectedToSend] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesSent] / ([object countOfBytesExpectedToSend] * 1.0f) animated:self.af_uploadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(countOfBytesReceived))]) { + if ([object countOfBytesExpectedToReceive] > 0) { + dispatch_async(dispatch_get_main_queue(), ^{ + [self setProgress:[object countOfBytesReceived] / ([object countOfBytesExpectedToReceive] * 1.0f) animated:self.af_downloadProgressAnimated]; + }); + } + } + + if ([keyPath isEqualToString:NSStringFromSelector(@selector(state))]) { + if ([(NSURLSessionTask *)object state] == NSURLSessionTaskStateCompleted) { + @try { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(state))]; + + if (context == AFTaskCountOfBytesSentContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesSent))]; + } + + if (context == AFTaskCountOfBytesReceivedContext) { + [object removeObserver:self forKeyPath:NSStringFromSelector(@selector(countOfBytesReceived))]; + } + } + @catch (NSException * __unused exception) {} + } + } + } +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h new file mode 100644 index 0000000..215eafc --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.h @@ -0,0 +1,53 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import + +NS_ASSUME_NONNULL_BEGIN + +/** + This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. + */ +@interface UIRefreshControl (AFNetworking) + +///----------------------------------- +/// @name Refreshing for Session Tasks +///----------------------------------- + +/** + Binds the refreshing state to the state of the specified task. + + @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. + */ +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m new file mode 100644 index 0000000..cd46916 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/UIRefreshControl+AFNetworking.m @@ -0,0 +1,113 @@ +// UIRefreshControl+AFNetworking.m +// +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "UIRefreshControl+AFNetworking.h" +#import + +#if TARGET_OS_IOS + +#import "AFURLSessionManager.h" + +@interface AFRefreshControlNotificationObserver : NSObject +@property (readonly, nonatomic, weak) UIRefreshControl *refreshControl; +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl; + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; + +@end + +@implementation UIRefreshControl (AFNetworking) + +- (AFRefreshControlNotificationObserver *)af_notificationObserver { + AFRefreshControlNotificationObserver *notificationObserver = objc_getAssociatedObject(self, @selector(af_notificationObserver)); + if (notificationObserver == nil) { + notificationObserver = [[AFRefreshControlNotificationObserver alloc] initWithActivityRefreshControl:self]; + objc_setAssociatedObject(self, @selector(af_notificationObserver), notificationObserver, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + } + return notificationObserver; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + [[self af_notificationObserver] setRefreshingWithStateOfTask:task]; +} + +@end + +@implementation AFRefreshControlNotificationObserver + +- (instancetype)initWithActivityRefreshControl:(UIRefreshControl *)refreshControl +{ + self = [super init]; + if (self) { + _refreshControl = refreshControl; + } + return self; +} + +- (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + + if (task) { + UIRefreshControl *refreshControl = self.refreshControl; + if (task.state == NSURLSessionTaskStateRunning) { + [refreshControl beginRefreshing]; + + [notificationCenter addObserver:self selector:@selector(af_beginRefreshing) name:AFNetworkingTaskDidResumeNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidCompleteNotification object:task]; + [notificationCenter addObserver:self selector:@selector(af_endRefreshing) name:AFNetworkingTaskDidSuspendNotification object:task]; + } else { + [refreshControl endRefreshing]; + } + } +} + +#pragma mark - + +- (void)af_beginRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.refreshControl beginRefreshing]; + }); +} + +- (void)af_endRefreshing { + dispatch_async(dispatch_get_main_queue(), ^{ + [self.refreshControl endRefreshing]; + }); +} + +#pragma mark - + +- (void)dealloc { + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + + [notificationCenter removeObserver:self name:AFNetworkingTaskDidCompleteNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidResumeNotification object:nil]; + [notificationCenter removeObserver:self name:AFNetworkingTaskDidSuspendNotification object:nil]; +} + +@end + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h new file mode 100644 index 0000000..680fedf --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.h @@ -0,0 +1,80 @@ +// WkWebView+AFNetworking.h +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if TARGET_OS_IOS + +#import +#import + +NS_ASSUME_NONNULL_BEGIN + +@class AFHTTPSessionManager; + +@interface WKWebView (AFNetworking) + +/** + The session manager used to download all request + */ +@property (nonatomic, strong) AFHTTPSessionManager *sessionManager; + +/** + Asynchronously loads the specified request. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`. + @param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure; + +/** + Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. + + @param request A URL request identifying the location of the content to load. This must not be `nil`. + @param navigation The WKNavigation object that containts information for tracking the loading progress of a webpage. This must not be `nil`. + @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. + @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. + @param progress A progress object monitoring the current download progress. + @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. + @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. + */ +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m new file mode 100644 index 0000000..6eca3c3 --- /dev/null +++ b/Pods/AFNetworking/UIKit+AFNetworking/WKWebView+AFNetworking.m @@ -0,0 +1,154 @@ +// WkWebView+AFNetworking.m +// Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "WKWebView+AFNetworking.h" + +#import + +#if TARGET_OS_IOS + +#import "AFHTTPSessionManager.h" +#import "AFURLResponseSerialization.h" +#import "AFURLRequestSerialization.h" + +@interface WKWebView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setURLSessionTask:) NSURLSessionDataTask *af_URLSessionTask; +@end + +@implementation WKWebView (_AFNetworking) + +- (NSURLSessionDataTask *)af_URLSessionTask { + return (NSURLSessionDataTask *)objc_getAssociatedObject(self, @selector(af_URLSessionTask)); +} + +- (void)af_setURLSessionTask:(NSURLSessionDataTask *)af_URLSessionTask { + objc_setAssociatedObject(self, @selector(af_URLSessionTask), af_URLSessionTask, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +@end + +#pragma mark - + +@implementation WKWebView (AFNetworking) + +- (AFHTTPSessionManager *)sessionManager { + static AFHTTPSessionManager *_af_defaultHTTPSessionManager = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultHTTPSessionManager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; + _af_defaultHTTPSessionManager.requestSerializer = [AFHTTPRequestSerializer serializer]; + _af_defaultHTTPSessionManager.responseSerializer = [AFHTTPResponseSerializer serializer]; + }); + + return objc_getAssociatedObject(self, @selector(sessionManager)) ?: _af_defaultHTTPSessionManager; +} + +- (void)setSessionManager:(AFHTTPSessionManager *)sessionManager { + objc_setAssociatedObject(self, @selector(sessionManager), sessionManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +- (AFHTTPResponseSerializer *)responseSerializer { + static AFHTTPResponseSerializer *_af_defaultResponseSerializer = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_defaultResponseSerializer = [AFHTTPResponseSerializer serializer]; + }); + + return objc_getAssociatedObject(self, @selector(responseSerializer)) ?: _af_defaultResponseSerializer; +} + +- (void)setResponseSerializer:(AFHTTPResponseSerializer *)responseSerializer { + objc_setAssociatedObject(self, @selector(responseSerializer), responseSerializer, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + +#pragma mark - + +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success + failure:(nullable void (^)(NSError *error))failure { + [self loadRequest:request navigation:navigation MIMEType:nil textEncodingName:nil progress:progress success:^NSData * _Nonnull(NSHTTPURLResponse * _Nonnull response, NSData * _Nonnull data) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (response.textEncodingName) { + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)response.textEncodingName); + if (encoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(encoding); + } + } + + NSString *string = [[NSString alloc] initWithData:data encoding:stringEncoding]; + if (success) { + string = success(response, string); + } + + return [string dataUsingEncoding:stringEncoding]; + } failure:failure]; +} + +- (void)loadRequest:(NSURLRequest *)request + navigation:(WKNavigation * _Nonnull)navigation + MIMEType:(nullable NSString *)MIMEType + textEncodingName:(nullable NSString *)textEncodingName + progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress + success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success + failure:(nullable void (^)(NSError *error))failure { + NSParameterAssert(request); + + if (self.af_URLSessionTask.state == NSURLSessionTaskStateRunning || self.af_URLSessionTask.state == NSURLSessionTaskStateSuspended) { + [self.af_URLSessionTask cancel]; + } + self.af_URLSessionTask = nil; + + __weak __typeof(self)weakSelf = self; + __block NSURLSessionDataTask *dataTask; + __strong __typeof(weakSelf) strongSelf = weakSelf; + __strong __typeof(weakSelf.navigationDelegate) strongSelfDelegate = strongSelf.navigationDelegate; + dataTask = [self.sessionManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { + if (error) { + if (failure) { + failure(error); + } + } else { + if (success) { + success((NSHTTPURLResponse *)response, responseObject); + } + [strongSelf loadData:responseObject MIMEType:MIMEType characterEncodingName:textEncodingName baseURL:[dataTask.currentRequest URL]]; + + if ([strongSelfDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) { + [strongSelfDelegate webView:strongSelf didFinishNavigation:navigation]; + } + } + }]; + self.af_URLSessionTask = dataTask; + if (progress != nil) { + *progress = [self.sessionManager downloadProgressForTask:dataTask]; + } + [self.af_URLSessionTask resume]; + + if ([strongSelfDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) { + [strongSelfDelegate webView:self didStartProvisionalNavigation:navigation]; + } +} + +@end + +#endif diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXActivityIndicatorView.h b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXActivityIndicatorView.h new file mode 100644 index 0000000..6b1790e --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXActivityIndicatorView.h @@ -0,0 +1,42 @@ +// +// AXActivityIndicatorView.h +// AXIndicatorView +// +// Created by devedbox on 2016/10/7. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import + +IB_DESIGNABLE +@interface AXActivityIndicatorView : UIView +/// Line width. +@property(assign, nonatomic) IBInspectable CGFloat lineWidth; +/// Drawing percent of the components. +@property(assign, nonatomic) IBInspectable int64_t drawingComponents; +/// Animating. +@property(assign, nonatomic, getter=isAnimating) IBInspectable BOOL animating; +/// Should gradient color index. +@property(assign, nonatomic) IBInspectable BOOL shouldGradientColorIndex; +/// Begin angle offset. +@property(assign, nonatomic) IBInspectable CGFloat angleOffset; + +- (void)initializer; +@end diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXActivityIndicatorView.m b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXActivityIndicatorView.m new file mode 100644 index 0000000..8fa9d98 --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXActivityIndicatorView.m @@ -0,0 +1,240 @@ +// +// AXActivityIndicatorView.m +// AXIndicatorView +// +// Created by devedbox on 2016/10/7. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXActivityIndicatorView.h" +@class _AXActivityIndicatorLayerView; +@interface AXActivityIndicatorView () +/// Color index layer. +@property(strong, nonatomic) _AXActivityIndicatorLayerView *colorIndexLayerView; +@end +IB_DESIGNABLE +@interface _AXActivityIndicatorLayerView : UIView +/// Line width. +@property(assign, nonatomic) CGFloat lineWidth; +/// Drawing percent of the components. +@property(assign, nonatomic) int64_t drawingComponents; +/// Animating. +@property(assign, nonatomic) BOOL animating; +/// Should gradient color index. +@property(assign, nonatomic) BOOL shouldGradientColorIndex; +/// Begin angle offset. +@property(assign, nonatomic) CGFloat angleOffset; +- (void)drawComponents; +- (void)drawLineWithAngle:(CGFloat)angle context:(CGContextRef)context tintColor:(UIColor *)tintColor; +@end +@implementation AXActivityIndicatorView +@synthesize animating = _animating; +#pragma mark - Initializer +- (instancetype)init { + if (self = [super init]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + if (self = [super initWithCoder:aDecoder]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)awakeFromNib { + [super awakeFromNib]; + + [self initializer]; +} + +- (void)initializer { + self.lineWidth = 3.0; + self.drawingComponents = 12; + self.angleOffset = -(M_PI * 2 / _drawingComponents)*2; + self.shouldGradientColorIndex = YES; + + [self addSubview:self.colorIndexLayerView]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +- (void)layoutSubviews { + [super layoutSubviews]; + + _colorIndexLayerView.frame = [self bounds]; +} + +#pragma mark - Getters +- (_AXActivityIndicatorLayerView *)colorIndexLayerView { + if (_colorIndexLayerView) return _colorIndexLayerView; + _colorIndexLayerView = [_AXActivityIndicatorLayerView new]; + _colorIndexLayerView.backgroundColor = [UIColor clearColor]; + _colorIndexLayerView.lineWidth = _lineWidth; + _colorIndexLayerView.drawingComponents = _drawingComponents; + _colorIndexLayerView.animating = _animating; + _colorIndexLayerView.shouldGradientColorIndex = _shouldGradientColorIndex; + _colorIndexLayerView.angleOffset = _angleOffset; + return _colorIndexLayerView; +} + +- (BOOL)isAnimating { + return _animating; +} + +#pragma mark - Setters +- (void)setLineWidth:(CGFloat)lineWidth { + _lineWidth = lineWidth; + self.colorIndexLayerView.lineWidth = _lineWidth; + if (_animating) { + [_colorIndexLayerView.layer removeAnimationForKey:@"transform.rotation"]; + [self addColorIndexAnimation]; + } +} + +- (void)setDrawingComponents:(int64_t)drawingComponents { + _drawingComponents = MIN(12, drawingComponents); + self.colorIndexLayerView.drawingComponents = _drawingComponents; + if (_animating) { + [_colorIndexLayerView.layer removeAnimationForKey:@"transform.rotation"]; + [self addColorIndexAnimation]; + } +} + +- (void)setShouldGradientColorIndex:(BOOL)shouldGradientColorIndex { + _shouldGradientColorIndex = shouldGradientColorIndex; + [self.colorIndexLayerView setShouldGradientColorIndex:_shouldGradientColorIndex]; + if (_animating) { + [_colorIndexLayerView.layer removeAnimationForKey:@"transform.rotation"]; + [self addColorIndexAnimation]; + } +} + +- (void)setAngleOffset:(CGFloat)angleOffset { + _angleOffset = angleOffset; + [self.colorIndexLayerView setAngleOffset:_angleOffset]; + if (_animating) { + [_colorIndexLayerView.layer removeAnimationForKey:@"transform.rotation"]; + [self addColorIndexAnimation]; + } +} + +- (void)setAnimating:(BOOL)animating { + _animating = animating; + self.colorIndexLayerView.animating = _animating; + if (animating) { + [self addColorIndexAnimation]; + } else { + [_colorIndexLayerView.layer removeAnimationForKey:@"transform.rotation"]; + } +} + +#pragma mark - Helper +- (void)didBecomActive:(id)noti { + if (_animating) [self setAnimating:_animating]; +} + +- (void)addColorIndexAnimation { + CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"]; + NSMutableArray *values = [@[] mutableCopy]; + for (int i = 0; i < _drawingComponents; i++) { + [values addObject:@((i*M_PI/6)-M_PI_2+_angleOffset)]; + } + animation.values = values; + animation.duration = 1.0; + animation.repeatCount = CGFLOAT_MAX; + animation.calculationMode = kCAAnimationDiscrete; + animation.removedOnCompletion = NO; + [_colorIndexLayerView.layer addAnimation:animation forKey:@"transform.rotation"]; +} +@end + +@implementation _AXActivityIndicatorLayerView +- (void)setAnimating:(BOOL)animating { + _animating = animating; + [self setNeedsDisplay]; +} + +- (void)setDrawingComponents:(int64_t)drawingComponents { + _drawingComponents = MIN(12, drawingComponents); + [self setNeedsDisplay]; +} + +- (void)setShouldGradientColorIndex:(BOOL)shouldGradientColorIndex { + _shouldGradientColorIndex = shouldGradientColorIndex; + [self setNeedsDisplay]; +} + +- (void)setAngleOffset:(CGFloat)angleOffset { + _angleOffset = angleOffset; + [self setNeedsDisplay]; +} + +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + + [self drawComponents]; +} + +- (void)drawComponents { + // Get the 12 components of the bounds. + CGFloat angle = M_PI*2/12; + CGContextRef cxt = UIGraphicsGetCurrentContext(); + UIColor *tintColor = self.tintColor?:[UIColor blackColor]; + // Draw all the possilbe line using the proper tint color. + for (int64_t i = 0; i < _drawingComponents; i++) [self drawLineWithAngle:angle*i-M_PI_2+_angleOffset context:cxt tintColor:/*_animating&&*/_shouldGradientColorIndex?[tintColor colorWithAlphaComponent:MAX(0.3, ((float)i)/_drawingComponents)]:tintColor]; +} +#pragma mark - Helper +- (void)drawLineWithAngle:(CGFloat)angle context:(CGContextRef)context tintColor:(UIColor *)tintColor { + CGContextSetStrokeColorWithColor(context, tintColor.CGColor); + CGContextSetLineWidth(context, _lineWidth); + CGContextSetLineCap(context, kCGLineCapRound); + + CGRect box = CGRectInset(self.bounds, _lineWidth/2, _lineWidth/2); + CGFloat deatla = MIN(box.size.width, box.size.height); + box.origin.x += fabs(box.size.width-deatla)*.5; + box.origin.y += fabs(box.size.height-deatla)*.5; + box.size.width = deatla; + box.size.height = deatla; + + // Get the begin point of the bounds. + CGFloat radius = CGRectGetWidth(box)/2; + CGFloat inner = radius * 0.5+_lineWidth/2; + CGPoint beginPoint = CGPointMake(self.center.x-self.frame.origin.x+inner*cos(angle), self.center.y-self.frame.origin.y+inner*sin(angle)); + CGPoint endPoint = CGPointMake(self.center.x-self.frame.origin.x+radius*cos(angle), self.center.y-self.frame.origin.y+radius*sin(angle)); + + CGContextMoveToPoint(context, beginPoint.x, beginPoint.y); + CGContextAddLineToPoint(context, endPoint.x, endPoint.y); + + CGContextStrokePath(context); +} +@end diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXBreachedAnnulusIndicatorView.h b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXBreachedAnnulusIndicatorView.h new file mode 100644 index 0000000..ca20ed4 --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXBreachedAnnulusIndicatorView.h @@ -0,0 +1,37 @@ +// +// AXBreachedAnnulusIndicatorView.h +// AXIndicatorView +// +// Created by devedbox on 2016/10/7. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import + +@interface AXBreachedAnnulusIndicatorView : UIView +/// Line width. +@property(assign, nonatomic) CGFloat lineWidth; +/// Breached angle. +@property(assign, nonatomic) CGFloat breach; +/// Duration. +@property(assign, nonatomic) NSTimeInterval duration; +/// Animating. +@property(assign, nonatomic, getter=isAnimating) BOOL animating; +@end diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXBreachedAnnulusIndicatorView.m b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXBreachedAnnulusIndicatorView.m new file mode 100644 index 0000000..33a159c --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXBreachedAnnulusIndicatorView.m @@ -0,0 +1,128 @@ +// +// AXBreachedAnnulusIndicatorView.m +// AXIndicatorView +// +// Created by devedbox on 2016/10/7. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXBreachedAnnulusIndicatorView.h" + +@implementation AXBreachedAnnulusIndicatorView +@synthesize animating = _animating; +#pragma mark - Initializer +- (instancetype)init { + if (self = [super init]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + if (self = [super initWithCoder:aDecoder]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)awakeFromNib { + [super awakeFromNib]; + + [self initializer]; +} + +- (void)initializer { + _lineWidth = 2.0; + _breach = M_PI_4; + _duration = 1.6; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - Override + +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + + CGContextRef context = UIGraphicsGetCurrentContext(); + UIColor *tintColor = self.tintColor?:[UIColor blackColor]; + + CGContextSetStrokeColorWithColor(context, tintColor.CGColor); + CGContextSetLineWidth(context, _lineWidth); + CGContextSetLineCap(context, kCGLineCapRound); + + CGRect box = CGRectInset(self.bounds, _lineWidth, _lineWidth); + CGFloat deatla = MIN(box.size.width, box.size.height); + box.origin.x += fabs(box.size.width-deatla)*.5; + box.origin.y += fabs(box.size.height-deatla)*.5; + box.size.width = deatla; + box.size.height = deatla; + + // Drawing. + CGContextAddArc(context, CGRectGetMidX(box), CGRectGetMidY(box), deatla/2, 0, M_PI*2-_breach, 0); + CGContextStrokePath(context); +} + +- (void)setTintColor:(UIColor *)tintColor { + [super setTintColor:tintColor]; + + [self setNeedsDisplay]; +} + +#pragma mark - Setters +- (void)setLineWidth:(CGFloat)lineWidth { + _lineWidth = lineWidth; + [self setNeedsDisplay]; +} + +- (void)setBreach:(CGFloat)breach { + _breach = breach; + [self setNeedsDisplay]; +} + +- (void)setAnimating:(BOOL)animating { + _animating = animating; + + if (animating) { + CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; + rotate.toValue = @(M_PI*2); + rotate.duration = _duration; + rotate.repeatCount = CGFLOAT_MAX; + rotate.removedOnCompletion = NO; + [self.layer addAnimation:rotate forKey:@"rotate"]; + } else { + [self.layer removeAnimationForKey:@"rotate"]; + } +} + +- (void)_didBecomeActive:(id)arg { + if (_animating) [self setAnimating:_animating]; +} +@end diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.bundle/SpinningWaitCursor@2x.png b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.bundle/SpinningWaitCursor@2x.png new file mode 100755 index 0000000..d6f31ba Binary files /dev/null and b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.bundle/SpinningWaitCursor@2x.png differ diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.bundle/SpinningWaitCursor@3x.png b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.bundle/SpinningWaitCursor@3x.png new file mode 100755 index 0000000..5907806 Binary files /dev/null and b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.bundle/SpinningWaitCursor@3x.png differ diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.h b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.h new file mode 100644 index 0000000..fadfcc4 --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXIndicatorView.h @@ -0,0 +1,33 @@ +// +// AXIndicatorView.h +// AXIndicatorView +// +// Created by devedbox on 2016/10/7. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#ifndef AXIndicatorView_h +#define AXIndicatorView_h + + +#endif /* AXIndicatorView_h */ + +#import "AXActivityIndicatorView.h" +#import "AXBreachedAnnulusIndicatorView.h" diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXSpinningWaitCursor.h b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXSpinningWaitCursor.h new file mode 100644 index 0000000..456c010 --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXSpinningWaitCursor.h @@ -0,0 +1,34 @@ +// +// AXSpinningWaitCursor.h +// AXIndicatorView +// +// Created by devedbox on 2017/5/14. +// Copyright © 2017年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import + +IB_DESIGNABLE +@interface AXSpinningWaitCursor : UIView +/// Animating. +@property(assign, nonatomic, getter=isAnimating) IBInspectable BOOL animating; +/// Duration. Default 1.0. +@property(assign, nonatomic) IBInspectable NSTimeInterval duration; +@end diff --git a/Pods/AXIndicatorView/AXIndicatorView/Classes/AXSpinningWaitCursor.m b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXSpinningWaitCursor.m new file mode 100644 index 0000000..4883427 --- /dev/null +++ b/Pods/AXIndicatorView/AXIndicatorView/Classes/AXSpinningWaitCursor.m @@ -0,0 +1,125 @@ +// +// AXSpinningWaitCursor.m +// AXIndicatorView +// +// Created by devedbox on 2017/5/14. +// Copyright © 2017年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXSpinningWaitCursor.h" + +@interface AXSpinningWaitCursor () +/// Image view. +@property(strong, nonatomic) UIImageView *imageView; +@end + +@implementation AXSpinningWaitCursor +#pragma mark - Initializer +- (instancetype)init { + if (self = [super init]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + if (self = [super initWithCoder:aDecoder]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)awakeFromNib { + [super awakeFromNib]; + + [self initializer]; +} + +- (void)initializer { + _duration = 1.0; + [self addSubview:self.imageView]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_didBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil]; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; +} + +#pragma mark - Override. +- (void)layoutSubviews { + [super layoutSubviews]; + + [_imageView setFrame:self.bounds]; +} + +#pragma mark - Getters. +- (UIImageView *)imageView { + if (_imageView) return _imageView; + UIImage *image; +#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0 + image = [UIImage imageNamed:@"AXIndicatorView.bundle/SpinningWaitCursor"]; +#else + image = [UIImage imageNamed:@"AXIndicatorView.bundle/SpinningWaitCursor" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil]; +#endif + _imageView = [[UIImageView alloc] initWithImage:image]; + _imageView.contentMode = UIViewContentModeCenter; + return _imageView; +} + +#pragma mark - Setters. +- (void)setAnimating:(BOOL)animating { + _animating = animating; + + if (_animating) { + [self _addAnimation]; + } else { + [self.imageView.layer removeAnimationForKey:@"rotate"]; + } +} + +- (void)setDuration:(NSTimeInterval)duration { + _duration = duration; + + if (_animating) { + [self.imageView.layer removeAnimationForKey:@"rotate"]; + [self _addAnimation]; + } +} + +- (void)_didBecomeActive:(id)arg { + if (_animating) [self setAnimating:_animating]; +} + +- (void)_addAnimation { + CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; + rotate.toValue = @(M_PI*2); + rotate.duration = _duration; + rotate.repeatCount = CGFLOAT_MAX; + rotate.removedOnCompletion = NO; + [self.imageView.layer addAnimation:rotate forKey:@"rotate"]; +} +@end diff --git a/Pods/AXIndicatorView/LICENSE b/Pods/AXIndicatorView/LICENSE new file mode 100644 index 0000000..653404a --- /dev/null +++ b/Pods/AXIndicatorView/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 ax + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Pods/AXIndicatorView/README.md b/Pods/AXIndicatorView/README.md new file mode 100644 index 0000000..05bf5cf --- /dev/null +++ b/Pods/AXIndicatorView/README.md @@ -0,0 +1 @@ +# AXIndicatorView \ No newline at end of file diff --git a/Pods/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXPopNavigationController.h b/Pods/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXPopNavigationController.h new file mode 100644 index 0000000..2a98a94 --- /dev/null +++ b/Pods/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXPopNavigationController.h @@ -0,0 +1,64 @@ +// +// UINavigationController+Injection.h +// AXNavigationBackItemInjection +// +// Created by devedbox on 16/8/3. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import +NS_ASSUME_NONNULL_BEGIN +/// Handler to tell navigation to pop item or not. +/// +/// @discusstion handler has higher priority than protocol. If you have both implemented. Then the system will choose the handler instead of protocol. +/// +/// @param navigationBar navigation bar to layout item. +/// @param item item to pop. +/// +/// @return a Boolean value to decide pop item or not. +/// +typedef BOOL(^AXNavigationItemPopHandler)(UINavigationBar *navigationBar, UINavigationItem *navigationItem); +/// Protocol include the decision method of poping item. +/// +/// @discusstion Confirming the protocol is optional but implementing the method in the protocol is required. +/// +@protocol AXNavigationBackItemProtocol +@optional +/// Decision method to tell navigation to pop item or not. +/// +/// @discusstion handler has higher priority than protocol. If you have both implemented. Then the system will choose the handler instead of protocol. +/// +/// @param navigationBar navigation bar to layout item. +/// @param item item to pop. +/// +/// @return a Boolean value to decide pop item or not. +/// +- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item; +@end +/// Injection of pop item key methods. +/// +@interface UINavigationController (Injection) +/// Navigation item pop handler. +/// +/// @discusstion handler has higher priority than protocol. If you have both implemented. Then the system will choose the handler instead of protocol. +/// +@property(copy, nonatomic) AXNavigationItemPopHandler popHandler; +@end +NS_ASSUME_NONNULL_END \ No newline at end of file diff --git a/Pods/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXPopNavigationController.m b/Pods/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXPopNavigationController.m new file mode 100644 index 0000000..f7f3976 --- /dev/null +++ b/Pods/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXNavigationBackItemInjection/AXPopNavigationController.m @@ -0,0 +1,134 @@ +// +// UINavigationController+Injection.m +// AXNavigationBackItemInjection +// +// Created by devedbox on 16/8/3. +// Copyright © 2016年 devedbox. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXPopNavigationController.h" +#import + +@interface UIGestureRecognizer (Injection) +@end + +@implementation UIGestureRecognizer (Injection) ++ (void)load { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Inject "-navigationBar:shouldPopItem:" + Method originalMethod = class_getInstanceMethod(self, NSSelectorFromString(@"_shouldBegin")); + Method swizzledMethod = class_getInstanceMethod(self, @selector(ax_gestureShouldBegin)); + method_exchangeImplementations(originalMethod, swizzledMethod); + }); +} + +- (BOOL)ax_gestureShouldBegin { + BOOL shouldBegin = [self ax_gestureShouldBegin]; + + if (![self isMemberOfClass:NSClassFromString(@"UIScreenEdgePanGestureRecognizer")]) return shouldBegin; + + UIResponder *nextViewController = self.view; + while (![nextViewController isKindOfClass:UIViewController.class]) { + nextViewController = nextViewController.nextResponder; + } + + if ([nextViewController isKindOfClass:UINavigationController.class]) { + UINavigationController *navigationController = (UINavigationController *)nextViewController; + + if (navigationController.popHandler) { + return navigationController.popHandler(navigationController.navigationBar, navigationController.topViewController.navigationItem); + } else { + if ([navigationController.topViewController respondsToSelector:@selector(navigationBar:shouldPopItem:)]) { + + return [(id)navigationController.topViewController navigationBar:navigationController.navigationBar shouldPopItem:navigationController.topViewController.navigationItem]; + } + } + } + + return shouldBegin; +} +@end + +@implementation UINavigationController (Injection) + ++ (void)load { + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // Inject "-navigationBar:shouldPopItem:" + Method originalMethod = class_getInstanceMethod(self, @selector(navigationBar:shouldPopItem:)); + Method swizzledMethod = class_getInstanceMethod(self, @selector(ax_navigationBar:shouldPopItem:)); + method_exchangeImplementations(originalMethod, swizzledMethod); + }); +} + +- (BOOL)ax_navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item { + // Should pop. It appears called the pop view controller methods. We should pop items directly. + BOOL shouldPopItemAfterPopViewController = [[self valueForKey:@"_isTransitioning"] boolValue]; + + if (shouldPopItemAfterPopViewController) { + return [self ax_navigationBar:navigationBar shouldPopItem:item]; + } + + if (self.popHandler) { + BOOL shouldPopItemAfterPopViewController = self.popHandler(navigationBar, item); + + if (shouldPopItemAfterPopViewController) { + return [self ax_navigationBar:navigationBar shouldPopItem:item]; + } + + // Make sure the back indicator view alpha set to 1.0. + [UIView animateWithDuration:0.25 animations:^{ + [[self.navigationBar subviews] lastObject].alpha = 1; + }]; + + return shouldPopItemAfterPopViewController; + } else { + UIViewController *viewController = [self topViewController]; + + if ([viewController respondsToSelector:@selector(navigationBar:shouldPopItem:)]) { + + BOOL shouldPopItemAfterPopViewController = [(id)viewController navigationBar:navigationBar shouldPopItem:item]; + + if (shouldPopItemAfterPopViewController) { + return [self ax_navigationBar:navigationBar shouldPopItem:item]; + } + + // Make sure the back indicator view alpha set to 1.0. + [UIView animateWithDuration:0.25 animations:^{ + [[self.navigationBar subviews] lastObject].alpha = 1; + }]; + + return shouldPopItemAfterPopViewController; + } + } + + return [self ax_navigationBar:navigationBar shouldPopItem:item]; +} + +#pragma mark - Getters&Setters +- (AXNavigationItemPopHandler)popHandler { + return objc_getAssociatedObject(self, _cmd); +} + +- (void)setPopHandler:(AXNavigationItemPopHandler)popHandler { + objc_setAssociatedObject(self, @selector(popHandler), [popHandler copy], OBJC_ASSOCIATION_COPY_NONATOMIC); +} +@end diff --git a/Pods/AXNavigationBackItemInjection/LICENSE b/Pods/AXNavigationBackItemInjection/LICENSE new file mode 100644 index 0000000..737a4da --- /dev/null +++ b/Pods/AXNavigationBackItemInjection/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 ax + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Pods/AXNavigationBackItemInjection/README.md b/Pods/AXNavigationBackItemInjection/README.md new file mode 100644 index 0000000..b15ab64 --- /dev/null +++ b/Pods/AXNavigationBackItemInjection/README.md @@ -0,0 +1,7 @@ +# AXNavigationBackItemInjection[![Build Status](https://travis-ci.org/devedbox/AXNavigationBackItemInjection.svg?branch=master)](https://travis-ci.org/devedbox/AXNavigationBackItemInjection)[![Version](https://img.shields.io/cocoapods/v/AXNavigationBackItemInjection.svg?style=flat)](http://cocoapods.org/pods/AXNavigationBackItemInjection)[![License](https://img.shields.io/cocoapods/l/AXNavigationBackItemInjection.svg?style=flat)](http://cocoapods.org/pods/AXNavigationBackItemInjection)[![Platform](https://img.shields.io/cocoapods/p/AXNavigationBackItemInjection.svg?style=flat)](http://cocoapods.org/pods/AXNavigationBackItemInjection) +Custom implementation of back navigation item actions. + + +Like this: + +[![sample](http://ww1.sinaimg.cn/large/d2297bd2gw1f6gmhv4jxvg20ac0ijq8c.gif)](http://ww1.sinaimg.cn/large/d2297bd2gw1f6gmhv4jxvg20ac0ijq8c.gif) \ No newline at end of file diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_error@2x.png b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_error@2x.png new file mode 100644 index 0000000..c41a95d Binary files /dev/null and b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_error@2x.png differ diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_error@3x.png b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_error@3x.png new file mode 100644 index 0000000..5b79ce5 Binary files /dev/null and b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_error@3x.png differ diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_success@2x.png b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_success@2x.png new file mode 100644 index 0000000..e056774 Binary files /dev/null and b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_success@2x.png differ diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_success@3x.png b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_success@3x.png new file mode 100644 index 0000000..e575ef6 Binary files /dev/null and b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.bundle/ax_hud_success@3x.png differ diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.h b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.h new file mode 100644 index 0000000..b27995b --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.h @@ -0,0 +1,186 @@ +// +// AXPracticalHUD.h +// AXSwift2OC +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// + +#import "AXPracticalHUDContentView.h" + +@protocol AXPracticalHUDAnimator; + +extern id _Nullable AXPracticalHUDFadeAnimator(void) NS_SWIFT_NAME(PracticalHUDFadeAnimator()); +extern id _Nullable AXPracticalHUDFlipUpAnimator(void) NS_SWIFT_NAME(PracticalHUDFlipUpAnimator()); +extern id _Nullable AXPracticalHUDZoomAnimator(void) NS_SWIFT_NAME(PracticalHUDZoomAnimator()); +extern id _Nullable AXPracticalHUDDropDownAnimator(void) NS_SWIFT_NAME(PracticalHUDDropDownAnimator()); + +/// Mode of hud view +typedef NS_ENUM(NSInteger, AXPracticalHUDMode) { + /// Progress is shown using an UIActivityIndicatorView. This is the default. + AXPracticalHUDModeNormal, + /// Progress is shown using a round, pie-chart like, progress view. + AXPracticalHUDModeProgress, + /// Progress is shown using a horizontal progress bar + AXPracticalHUDModeProgressBar, + /// Progress is shown using a horizontal colorful progress bar + AXPracticalHUDModeColourfulProgressBar, + /// Progress is shown using a ring-shaped progress view. + AXPracticalHUDModeProgressRing, + /// Shows a custom view + AXPracticalHUDModeCustomView, + /// Shows only labels + AXPracticalHUDModeText, + /// Progress is shown using an breach annular indicator. + AXPracticalHUDModeBreachedRing +} NS_SWIFT_NAME(PracticalHUDMode); +/// Position of hud view. +typedef NS_ENUM(NSInteger, AXPracticalHUDPosition) { + /// Top position. + AXPracticalHUDPositionTop, + /// Center position. + AXPracticalHUDPositionCenter, + /// Bottom position + AXPracticalHUDPositionBottom +} NS_SWIFT_NAME(PracticalHUDPosition); +/// Completion block when task finished. +typedef void(^AXPracticalHUDCompletionBlock)(void); +/// HUD delegate +@protocol AXPracticalHUDDelegate; + +NS_SWIFT_NAME(PracticalHUD) @interface AXPracticalHUD : UIView +/// Delegate of HUD view, +@property(assign, nonatomic, nullable) iddelegate; +#pragma mark - Boolean +/// Restore the hud view when hud hided if YES, setting the properties of hud view to the initial state. Default is NO. +@property(assign, nonatomic, getter=isRestoreEnabled) BOOL restoreEnabled; +/// Lock the background to avoid the touch events if YES. Default is NO. +@property(assign, nonatomic, getter=shouldLockBackground) BOOL lockBackground; +/// Using dim background if YES. Default is NO. +@property(assign, nonatomic, getter=shouldDimBackground) BOOL dimBackground; +/// Remove the hud from super view if hud is hidden. Default is YES. +@property(assign, nonatomic, getter=shouldRemoveFromSuperViewOnHide) BOOL removeFromSuperViewOnHide; +/// Using the square content view if YES. Default is NO. +@property(assign, nonatomic, getter=isSquare) BOOL square; +#pragma mark - Frame. +/// Total size of hud container view. Read only. +@property(readonly, nonatomic) CGSize size; +/// Margin of content views. Default is 15.0f. +@property(assign, nonatomic) CGFloat margin; +/// Offset of cotent view. Default is zero. +@property(assign, nonatomic) CGPoint offsets; +/// Minimum size of container view. Default is CGSizeZero. +@property(assign, nonatomic) CGSize minimumSize; +/// The insets of views in content view bounds. Default is {15.0f, 15.0f, 15.0f, 15.0f} +@property(assign, nonatomic) UIEdgeInsets contentInsets; +#pragma mark - Time interval. +/// Grace time showing hud view. Default is 0.0f. +@property(assign, nonatomic) NSTimeInterval grace; +/// Minimum showing time interval of hud view. Default is 0.5f. +@property(assign, nonatomic) NSTimeInterval threshold; +#pragma mark - Mode and ENUM. +/// Mode of the hud view.. +@property(assign, nonatomic) AXPracticalHUDMode mode; +/// Animator to show or hide the hud view. Default using the fade animator. +@property(strong, nonatomic, nonnull) id animator; +/// Position of the hud view. +@property(assign, nonatomic) AXPracticalHUDPosition position; +/// Completion block when hud view has hidden. +@property(copy, nonatomic, nullable) AXPracticalHUDCompletionBlock completion; +#pragma mark - Tasks. +/// Is tasks progressing. +@property(readonly, nonatomic, getter=isProgressing) BOOL progressing; +#pragma mark - Progress. +/// Progress of the progerss indicator. +@property(assign, nonatomic) CGFloat progress; +#pragma mark - Custom view. +/// Custom view. Readwrite. +@property(strong, nonatomic, nullable) UIView *customView; +#pragma mark - Content view +/// Content view. +@property(readonly, strong, nonatomic, nonnull) AXPracticalHUDContentView *contentView; +#pragma mark - Label +/// Title label. +@property(readonly, strong, nonatomic, nonnull) UILabel *label; +#pragma mark - Detail label. +/// Detail label. +@property(readonly, strong, nonatomic, nonnull) UILabel *detailLabel; +#pragma mark - Initializer +- (nullable instancetype)initWithView:(nullable UIView *)view; +- (nullable instancetype)initWithWindow:(nullable UIWindow *)window; +#pragma mark - Show & Hide. +- (void)show:(BOOL)animated; +- (void)hide:(BOOL)animated; + +- (void)show:(BOOL)animated executingBlock:(nullable dispatch_block_t)executing onQueue:(nullable dispatch_queue_t)queue completion:(nullable AXPracticalHUDCompletionBlock)completion; +- (void)show:(BOOL)animated executingBlockOnGQ:(nullable dispatch_block_t)executing completion:(nullable AXPracticalHUDCompletionBlock)completion; +- (void)show:(BOOL)animated executingMethod:(nullable SEL)method toTarget:(nullable id)target withObject:(nullable id)object; + +- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay completion:(nullable AXPracticalHUDCompletionBlock)completion; +@end + +@interface AXPracticalHUD(Shared) +#if UIKIT_DEFINE_AS_PROPERTIES +@property(class, readonly, nonatomic, nullable) AXPracticalHUD *sharedHUD NS_SWIFT_NAME(shared); +#else ++ (nullable instancetype)sharedHUD NS_SWIFT_NAME(shared()); +#endif + +- (void)showProgressInView:(nullable UIView *)view NS_SWIFT_NAME(showProgress(in:)); +- (void)showProgressBarInView:(nullable UIView *)view NS_SWIFT_NAME(showProgressBar(in:)); +- (void)showColorfulProgressBarInView:(nullable UIView *)view NS_SWIFT_NAME(showColorfulProgressBar(in:)); +- (void)showTextInView:(nullable UIView *)view NS_SWIFT_NAME(showText(in:)); +- (void)showNormalInView:(nullable UIView *)view NS_SWIFT_NAME(showNormal(in:)); +- (void)showErrorInView:(nullable UIView *)view NS_SWIFT_NAME(showError(in:)); +- (void)showSuccessInView:(nullable UIView *)view NS_SWIFT_NAME(showSuccess(in:)); + +- (void)showProgressInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showProgress(in:text:detail:configuration:)); +- (void)showProgressBarInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showProgressBar(in:text:detail:configuration:)); +- (void)showColorfulProgressBarInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showColorfulProgressBar(in:text:detail:configuration:)); +- (void)showTextInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showText(in:text:detail:configuration:)); +- (void)showNormalInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showNormal(in:text:detail:configuration:)); +- (void)showErrorInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showError(in:text:detail:configuration:)); +- (void)showSuccessInView:(nullable UIView *)view + text:(nullable NSString *)text + detail:(nullable NSString *)detail + configuration:(nullable void(^)(AXPracticalHUD * _Nullable HUD))configuration +NS_SWIFT_NAME(showSuccess(in:text:detail:configuration:)); +@end + +@interface AXPracticalHUD(Convenence) ++ (nullable instancetype)showHUDInView:(nullable UIView *)view animated:(BOOL)animated NS_SWIFT_NAME(showHud(in:animated:)); ++ (BOOL)hideHUDInView:(nullable UIView *)view animated:(BOOL)animated NS_SWIFT_NAME(hideHud(in:animated:)); ++ (NSInteger)hideAllHUDsInView:(nullable UIView *)view animated:(BOOL)animated NS_SWIFT_NAME(hideAllHuds(in:animated:)); ++ (nullable instancetype)HUDInView:(nullable UIView *)view NS_SWIFT_NAME(hud(in:)); ++ (nonnull NSArray *)HUDsInView:(nullable UIView *)view NS_SWIFT_NAME(huds(in:)); +@end + +NS_SWIFT_NAME(PracticalHUDDelegate) @protocol AXPracticalHUDDelegate +@optional +- (void)HUDWillShow:(nonnull AXPracticalHUD *)HUD; +- (void)HUDDidHidden:(nonnull AXPracticalHUD *)HUD; +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.m b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.m new file mode 100644 index 0000000..b96925f --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD.m @@ -0,0 +1,950 @@ +// +// AXPracticalHUD.m +// AXSwift2OC +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// + +#import "AXPracticalHUD.h" +#import "AXBarProgressView.h" +#import "AXCircleProgressView.h" +#import "AXGradientProgressView.h" +#import "AXPracticalHUDAnimator.h" +#import + +#ifndef kCFCoreFoundationVersionNumber_iOS_8_0 +#define kCFCoreFoundationVersionNumber_iOS_8_0 1140.1 +#endif +#ifndef EXECUTE_ON_MAIN_THREAD +#define EXECUTE_ON_MAIN_THREAD(block) \ +if ([NSThread isMainThread]) {\ + block();\ +} else {\ + dispatch_async(dispatch_get_main_queue(), block);\ +} +#endif + +#ifndef kAXPracticalHUDPadding +#define kAXPracticalHUDPadding 4.0f +#endif +#ifndef kAXPracticalHUDMaxMovement +#define kAXPracticalHUDMaxMovement 14.0f +#endif +#ifndef kAXPracticalHUDFontSize +#define kAXPracticalHUDFontSize 14.0f +#endif +#ifndef kAXPracticalHUDDetailFontSize +#define kAXPracticalHUDDetailFontSize 12.0f +#endif +#ifndef kAXPracticalHUDDefaultMargin +#define kAXPracticalHUDDefaultMargin 15.0f +#endif + +@interface AXPracticalHUD() +{ + /// Title label. + UILabel *_label; + /// Detail text label. + UILabel *_detailLabel; + /// Content view of HUD. + AXPracticalHUDContentView *_contentView; + /// Indicate is animating or not of the HUD view. + BOOL _animated; + + BOOL _isFinished; + SEL _executedMethod; + id _executedTarget; + id _executedObject; + CGAffineTransform _rotationTransform; +} +/// Grace planned timer. +@property(strong, nonatomic) NSTimer *graceTimer; +/// Min show planned timer. +@property(strong, nonatomic) NSTimer *minShowTimer; +/// Date of show's starting. +@property(strong, nonatomic) NSDate *showStarted; +/// Frame of content field. +@property(readonly, nonatomic) CGRect contentFrame; +/// Indocator view. +@property(strong, nonatomic) UIView *indicator; +// Motions: +@property(strong, nonatomic) UIInterpolatingMotionEffect *xMotionEffect; +@property(strong, nonatomic) UIInterpolatingMotionEffect *yMotionEffect; +/// Is the hud is animating. +@property(assign, nonatomic) BOOL forbidsLayoutSubviews; +@end + +@implementation AXPracticalHUD +#pragma mark - Life cycle +- (instancetype)init { + if (self = [super initWithFrame:CGRectZero]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithView:(UIView *)view { + return [self initWithFrame:view.bounds]; +} + +- (instancetype)initWithWindow:(UIWindow *)window { + return [self initWithView:window]; +} + +- (void)initializer { + _restoreEnabled = NO; + _lockBackground = NO; + _size = CGSizeZero; + _square = NO; + _margin = kAXPracticalHUDDefaultMargin; + _offsets = CGPointZero; + _minimumSize = CGSizeZero; + _grace = 0.0f; + _threshold = 0.5f; + _dimBackground = NO; + _contentInsets = UIEdgeInsetsMake(15.0f, 15.0f, 15.0f, 15.0f); + _progressing = NO; + + _mode = AXPracticalHUDModeNormal; + _position = AXPracticalHUDPositionCenter; + _progress = 0.0f; + _removeFromSuperViewOnHide = YES; + + _animated = NO; + _isFinished = NO; + _rotationTransform = CGAffineTransformIdentity; + + self.tintColor = [UIColor whiteColor]; + self.alpha = 0.0f; + self.opaque = NO; + self.contentMode = UIViewContentModeCenter; + self.backgroundColor = [UIColor clearColor]; + + self.autoresizingMask = + UIViewAutoresizingFlexibleTopMargin | + UIViewAutoresizingFlexibleBottomMargin | + UIViewAutoresizingFlexibleLeftMargin | + UIViewAutoresizingFlexibleRightMargin; + + [self addSubview:self.contentView]; + [_contentView addSubview:self.label]; + [_contentView addSubview:self.detailLabel]; + [self setupIndicators]; + + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(statusBarOrientationDidChange:) + name:UIApplicationDidChangeStatusBarOrientationNotification + object:nil]; +} + +#pragma mark - Override + +- (void)didMoveToSuperview { + [super didMoveToSuperview]; + + if (self.superview) { + // Layout subviews. + [self setNeedsLayout]; + [self layoutIfNeeded]; + + if ([_indicator isKindOfClass:[AXGradientProgressView class]] && + [_indicator respondsToSelector:@selector(beginAnimating)]) + { + [_indicator performSelector:@selector(beginAnimating)]; + } + + if (_position == AXPracticalHUDPositionCenter) { + _contentView.motionEffects = @[self.xMotionEffect, self.yMotionEffect]; + } else { + [_contentView removeMotionEffect:_xMotionEffect]; + [_contentView removeMotionEffect:_yMotionEffect]; + } + [self updateForCurrentOrientationAnimated:NO]; + } +} + +- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { + UIView *hitView = [super hitTest:point withEvent:event]; + if (_lockBackground) { + return hitView; + } else { + if (CGRectContainsPoint(self.contentFrame, point)) { + return hitView; + } else { + return nil; + } + } + return nil; +} + +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + + CGContextRef context = UIGraphicsGetCurrentContext(); + UIGraphicsPushContext(context); + + if (_dimBackground) { + //Gradient colours + size_t gradLocNum = 2; + CGFloat gradLocs[2] = {0.0, 1.0}; + CGFloat gradColors[8] = {0.0, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0, 0.3}; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocs, gradLocNum); + //Gradient center + CGPoint gradCenter = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2); + //Gradient radius + CGFloat gradRadius = MIN(self.bounds.size.width, self.bounds.size.height); + //Gradient draw + CGContextDrawRadialGradient (context, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation); + + CGColorSpaceRelease(colorSpace); + CGGradientRelease(gradient); + } + + UIGraphicsPopContext(); +} + +- (void)layoutSubviews { + [super layoutSubviews]; + + if (_forbidsLayoutSubviews) { + return; + } + + if (self.superview) { + self.frame = self.superview.bounds; + } + // Get bounds + CGRect bounds = self.bounds; + + CGFloat maxWidth = CGRectGetWidth(bounds) - _contentInsets.left - _contentInsets.right - 2 * _margin; + + CGRect rect_indicator = CGRectZero; + if (_indicator) { + rect_indicator = _indicator.frame; + } + + CGSize size = [_label.text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading + attributes:@{NSFontAttributeName : _label.font} + context:nil].size; + CGRect rect_label = CGRectMake(0, 0, ceil(size.width), ceil(size.height)); + + size = [_detailLabel.text boundingRectWithSize:CGSizeMake(maxWidth, CGFLOAT_MAX) + options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading + attributes:@{NSFontAttributeName : _detailLabel.font} + context:nil].size; + CGRect rect_detail = CGRectMake(0, 0, ceil(size.width), ceil(size.height)); + + CGFloat height_content = rect_indicator.size.height + rect_label.size.height + rect_detail.size.height; + height_content += _contentInsets.top + _contentInsets.bottom; + if (rect_label.size.height > 0) { + height_content += kAXPracticalHUDPadding; + } + if (rect_detail.size.height > 0) { + height_content += kAXPracticalHUDPadding; + } + + CGFloat width_content = 0.0; + if (_position == AXPracticalHUDPositionTop || _position == AXPracticalHUDPositionBottom) { + width_content = maxWidth + _contentInsets.left + _contentInsets.right; + } else { + width_content = MIN(maxWidth, MAX(rect_indicator.size.width, MAX(rect_label.size.width, rect_detail.size.width))) + _contentInsets.left + _contentInsets.right; + } + + CGSize size_content = CGSizeMake(width_content, height_content); + + CGFloat height_diff = 0.0; + + if (_square) { + CGFloat maxValue = MAX(width_content, height_content); + height_diff = (maxValue-height_content)*.5; + if (maxValue <= (bounds.size.width - 2 * _margin)) { + size_content.width = maxValue; + } + if (maxValue <= (bounds.size.height - 2 * _margin)) { + size_content.height = maxValue; + } + } + + if (size_content.width < _minimumSize.width) { + size_content.width = _minimumSize.width; + } + if (size_content.height < _minimumSize.height) { + height_diff = (_minimumSize.height - size_content.height)*.5; + size_content.height = _minimumSize.height; + } + + _size = size_content; + + rect_indicator.origin.y = _contentInsets.top + height_diff; + rect_indicator.origin.x = round(_size.width - rect_indicator.size.width) / 2; + _indicator.frame = rect_indicator; + + rect_label.origin.y = rect_label.size.height > 0.0 ? CGRectGetMaxY(rect_indicator) + kAXPracticalHUDPadding : CGRectGetMaxY(rect_indicator); + rect_label.origin.x = round((_size.width - rect_label.size.width) / 2) + _contentInsets.left - _contentInsets.right; + _label.frame = rect_label; + + rect_detail.origin.y = rect_detail.size.height > 0.0 ? CGRectGetMaxY(rect_label) + kAXPracticalHUDPadding : CGRectGetMaxY(rect_label); + rect_detail.origin.x = round((_size.width - rect_detail.size.width) / 2) + _contentInsets.left - _contentInsets.right; + _detailLabel.frame = rect_detail; + + // Set the frame by applying the transform of the contview. + _contentView.frame = self.contentFrame; +} + +#pragma mark - Public +- (void)show:(BOOL)animated { + [self show:animated executingBlock:nil onQueue:nil completion:nil]; +} + +- (void)hide:(BOOL)animated { + [self hide:animated afterDelay:0.0 completion:nil]; +} + +- (void)show:(BOOL)animated executingBlockOnGQ:(dispatch_block_t)executing completion:(AXPracticalHUDCompletionBlock)completion +{ + [self show:animated executingBlock:executing onQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) completion:completion]; +} + +- (void)show:(BOOL)animated executingBlock:(dispatch_block_t)executing onQueue:(dispatch_queue_t)queue completion:(AXPracticalHUDCompletionBlock)completion +{ + _animated = animated; + _completion = [completion copy]; + + if (executing) { + _progressing = YES; + dispatch_async(queue, ^{ + executing(); + dispatch_async(dispatch_get_main_queue(), ^{ + [self clear]; + }); + }); + } + + // If the grace time is set postpone the HUD display + if (_grace > 0.0) { + /* + NSTimer *newGraceTimer = [NSTimer timerWithTimeInterval:_grace target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO]; + [[NSRunLoop currentRunLoop] addTimer:newGraceTimer forMode:NSRunLoopCommonModes]; + _graceTimer = newGraceTimer; + */ + [self performSelector:animated?@selector(_showingByAnimated):@selector(_showingWithoutAnimated) withObject:nil afterDelay:_grace]; + } else { + // ... otherwise show the HUD imediately + [self showingAnimated:animated]; + } +} + +- (void)show:(BOOL)animated executingMethod:(SEL)method toTarget:(id)target withObject:(id)object +{ + _executedMethod = method; + _executedTarget = target; + _executedObject = object; + // Launch execution in new thread + _progressing = YES; + [NSThread detachNewThreadSelector:@selector(executing) toTarget:self withObject:nil]; + // Show HUD view + [self show:YES]; +} + +- (void)hide:(BOOL)animated afterDelay:(NSTimeInterval)delay completion:(void (^)(void))completion +{ + _animated = animated; + _completion = [completion copy]; + + NSTimeInterval timeInterval = delay; + + // If the minShow time is set, calculate how long the hud was shown, + // and pospone the hiding operation if necessary + if (_threshold > 0.0 && _showStarted) { + NSTimeInterval interv = [[NSDate date] timeIntervalSinceDate:_showStarted]; + if (interv < _threshold) { + /* + _minShowTimer = [NSTimer scheduledTimerWithTimeInterval:_threshold - interv target:self selector:@selector(handleMinShowTimer:) userInfo:nil repeats:NO]; + */ + timeInterval = MAX(_threshold - interv, delay); + } + } + + // ... otherwise hide the HUD after the delay. + [self performSelector:animated?@selector(_hidingByAnimated):@selector(_hidingWithoutAnimated) withObject:nil afterDelay:timeInterval]; +} + +#pragma mark - Setters + +- (void)setMode:(AXPracticalHUDMode)mode { + _mode = mode; + [self performSelectorOnMainThread:@selector(setupIndicators) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsLayout) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setPosition:(AXPracticalHUDPosition)position { + _position = position; + if (_position == AXPracticalHUDPositionCenter) { + _contentView.motionEffects = @[self.xMotionEffect, self.yMotionEffect]; + } else { + [_contentView removeMotionEffect:_xMotionEffect]; + [_contentView removeMotionEffect:_yMotionEffect]; + } + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsLayout) withObject:nil waitUntilDone:YES]; +} + +- (void)setProgress:(CGFloat)progress { + _progress = progress; + if ([_indicator isKindOfClass:[AXBarProgressView class]] || + [_indicator isKindOfClass:[AXCircleProgressView class]] || + [_indicator isKindOfClass:[AXGradientProgressView class]]) + { + dispatch_async(dispatch_get_main_queue(), ^{ + [_indicator setValue:@(_progress) forKey:@"progress"]; + }); + } +} + +- (void)setCustomView:(UIView *)customView { + _customView = customView; + [self performSelectorOnMainThread:@selector(setupIndicators) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsLayout) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setTintColor:(UIColor *)tintColor { + [super setTintColor:tintColor]; + + [self performSelectorOnMainThread:@selector(setupIndicators) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsLayout) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} +#pragma mark - Getters +- (CGRect)contentFrame { + CGSize size = _size; + switch (_position) { + case AXPracticalHUDPositionTop: { + CGPoint origin = CGPointMake(round((self.bounds.size.width - size.width) / 2) + _offsets.x, 0 + _offsets.y); + return CGRectMake(origin.x, origin.y, size.width, size.height); + } + case AXPracticalHUDPositionCenter: { + CGPoint origin = CGPointMake(round((self.bounds.size.width - size.width) / 2) + _offsets.x, round((self.bounds.size.height - size.height) / 2) + _offsets.y); + return CGRectMake(origin.x, origin.y, size.width, size.height); + } + case AXPracticalHUDPositionBottom: { + CGPoint origin; + if (self.superview) { + origin = CGPointMake(round((self.bounds.size.width - size.width) / 2) + _offsets.x, self.superview.bounds.size.height - size.height + _offsets.y); + } else { + origin = CGPointMake(round((self.bounds.size.width - size.width) / 2) + _offsets.x, round((self.bounds.size.height - size.height) / 2) + _offsets.y); + } + return CGRectMake(origin.x, origin.y, size.width, size.height); + } + default: + return CGRectZero; + } +} + +- (UILabel *)label { + if (_label) return _label; + _label = [[UILabel alloc] initWithFrame:self.bounds]; + _label.adjustsFontSizeToFitWidth = NO; + _label.textAlignment = NSTextAlignmentCenter; + _label.opaque = NO; + _label.backgroundColor = [UIColor clearColor]; + _label.textColor = [UIColor whiteColor]; + _label.font = [UIFont boldSystemFontOfSize:kAXPracticalHUDFontSize]; + return _label; +} + +- (UILabel *)detailLabel { + if (_detailLabel) return _detailLabel; + _detailLabel = [[UILabel alloc] initWithFrame:self.bounds]; + _detailLabel.adjustsFontSizeToFitWidth = NO; + _detailLabel.textAlignment = NSTextAlignmentCenter; + _detailLabel.opaque = NO; + _detailLabel.backgroundColor = [UIColor clearColor]; + _detailLabel.numberOfLines = 0; + _detailLabel.textColor = [[UIColor whiteColor] colorWithAlphaComponent:0.75]; + _detailLabel.font = [UIFont boldSystemFontOfSize:kAXPracticalHUDDetailFontSize]; + return _detailLabel; +} + +- (UIInterpolatingMotionEffect *)xMotionEffect { + if (_xMotionEffect) return _xMotionEffect; + _xMotionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + _xMotionEffect.minimumRelativeValue = @(-kAXPracticalHUDMaxMovement); + _xMotionEffect.maximumRelativeValue = @(kAXPracticalHUDMaxMovement); + return _xMotionEffect; +} + +- (UIInterpolatingMotionEffect *)yMotionEffect { + if (_yMotionEffect) return _yMotionEffect; + _yMotionEffect = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis]; + _yMotionEffect.minimumRelativeValue = @(-kAXPracticalHUDMaxMovement); + _yMotionEffect.maximumRelativeValue = @(kAXPracticalHUDMaxMovement); + return _yMotionEffect; +} + +- (AXPracticalHUDContentView *)contentView { + if (_contentView) return _contentView; + _contentView = [[AXPracticalHUDContentView alloc] initWithFrame:CGRectZero]; + _contentView.layer.cornerRadius = 4.0; + _contentView.layer.masksToBounds = true; + return _contentView; +} + +#pragma mark - Private helper +- (void)showingAnimated:(BOOL)animated { + if (_delegate && [_delegate respondsToSelector:@selector(HUDWillShow:)]) { + [_delegate HUDWillShow:self]; + } + // Cancel any scheduled hideDelayed: calls + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) + withObject:nil + waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsLayout) + withObject:nil + waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(layoutIfNeeded) + withObject:nil + waitUntilDone:YES]; + + id animator = _animator?:AXPracticalHUDFadeAnimator(); + _showStarted = [NSDate date]; + [self setForbidsLayoutSubviews:!animator.allowsLayoutSubviewsDuringAnimation]; + // Animating + [animator hud:self animate:animated isHidden:NO]; + if (animated) { + [self performSelector:@selector(setForbidsLayoutSubviews:) + withObject:@(NO) + afterDelay:[animator durationForTransition:NO]]; + } else { + [self setForbidsLayoutSubviews:NO]; + } +} + +- (void)_showingByAnimated { + [self showingAnimated:YES]; +} + +- (void)_showingWithoutAnimated { + [self showingAnimated:NO]; +} + +- (void)hidingAnimated:(BOOL)animated { + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + id animator = _animator?:AXPracticalHUDFadeAnimator(); + [self setForbidsLayoutSubviews:YES]; + [animator hud:self + animate:animated + isHidden:YES]; + + if (animated) { + [self performSelector:@selector(setForbidsLayoutSubviews:) + withObject:@(NO) + afterDelay:[animator durationForTransition:YES]]; + [self performSelector:@selector(completed) + withObject:nil + afterDelay:[animator durationForTransition:YES]]; + } else { + [self setForbidsLayoutSubviews:NO]; + [self completed]; + } +} + +- (void)_hidingByAnimated { + [self hidingAnimated:YES]; +} + +- (void)_hidingWithoutAnimated { + [self hidingAnimated:NO]; +} + +- (void)setupIndicators { + switch (_mode) { + case AXPracticalHUDModeNormal: + if (![_indicator isKindOfClass:[AXActivityIndicatorView class]]) { + [_indicator removeFromSuperview]; + _indicator = [[AXActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 37, 37)]; + _indicator.backgroundColor = [UIColor clearColor]; + } + [(AXActivityIndicatorView *)_indicator setLineWidth:3]; + [(AXActivityIndicatorView *)_indicator setDrawingComponents:12]; + [(AXActivityIndicatorView *)_indicator setShouldGradientColorIndex:YES]; + [(AXActivityIndicatorView *)_indicator setTintColor:self.tintColor]; + [(AXActivityIndicatorView *)_indicator setAnimating:YES]; + [_contentView addSubview:_indicator]; + break; + case AXPracticalHUDModeBreachedRing: { + if (![_indicator isKindOfClass:[AXBreachedAnnulusIndicatorView class]]) { + [_indicator removeFromSuperview]; + _indicator = [[AXBreachedAnnulusIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 37, 37)]; + _indicator.backgroundColor = [UIColor clearColor]; + [_contentView addSubview:_indicator]; + } + [(AXBreachedAnnulusIndicatorView *)_indicator setTintColor:self.tintColor]; + [(AXBreachedAnnulusIndicatorView *)_indicator setAnimating:YES]; + } + break; + case AXPracticalHUDModeProgressBar: + [_indicator removeFromSuperview]; + _indicator = [[AXBarProgressView alloc] init]; + [_indicator setValue:self.tintColor forKey:@"lineColor"]; + [_indicator setValue:self.tintColor forKey:@"progressColor"]; + [_contentView addSubview:_indicator]; + break; + case AXPracticalHUDModeProgress: + case AXPracticalHUDModeProgressRing: + if (![_indicator isKindOfClass:[AXCircleProgressView class]]) { + [_indicator removeFromSuperview]; + _indicator = [[AXCircleProgressView alloc] init]; + [_indicator setValue:self.tintColor forKey:@"progressColor"]; + [_contentView addSubview:_indicator]; + } + if (_mode == AXPracticalHUDModeProgressRing) { + [_indicator setValue:@(YES) forKey:@"annularEnabled"]; + } + break; + case AXPracticalHUDModeCustomView: + [_indicator removeFromSuperview]; + _indicator = _customView; + if (_indicator) [_contentView addSubview:_indicator]; + break; + case AXPracticalHUDModeColourfulProgressBar: + [_indicator removeFromSuperview]; + _indicator = [[AXGradientProgressView alloc] init]; + [_indicator setValue:@(2.0) forKey:@"progressHeight"]; + [_contentView addSubview:_indicator]; + break; + default: + [_indicator removeFromSuperview]; + _indicator = nil; + break; + } +} + +- (void)completed { + [NSObject cancelPreviousPerformRequestsWithTarget:self]; + _isFinished = YES; + self.alpha = .0; + if ([_indicator isKindOfClass:[AXGradientProgressView class]] && [_indicator respondsToSelector:@selector(endAnimating)]) { + [_indicator performSelector:@selector(endAnimating)]; + } + if (_removeFromSuperViewOnHide) { + [self removeFromSuperview]; + } + if (_restoreEnabled) { + [self restore]; + } + self.transform = CGAffineTransformIdentity; + _contentView.transform = CGAffineTransformIdentity; + if (_completion) { + EXECUTE_ON_MAIN_THREAD(^{ + _completion(); + }); + } + if (_delegate && [_delegate respondsToSelector:@selector(HUDDidHidden:)]) { + [_delegate HUDDidHidden:self]; + } +} + +- (void)statusBarOrientationDidChange:(NSNotification *)aNotification { + +} + +- (void)handleGraceTimer:(NSTimer *)sender { + if (_progressing) { + [self showingAnimated:_animated]; + } +} + +- (void)handleMinShowTimer:(NSTimer *)sender { + [self hidingAnimated:_animated]; +} + +- (void)executing { + @autoreleasepool { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-performSelector-leaks" + // Start executing the requested task + [_executedTarget performSelector:_executedMethod withObject:_executedObject]; +#pragma clang diagnostic pop + // Task completed, update view in main thread (note: view operations should + // be done only in the main thread + [self performSelectorOnMainThread:@selector(clear) withObject:nil waitUntilDone:NO]; + } +} + +- (void)clear { + _progressing = NO; + _executedMethod = nil; + _executedObject = nil; + _executedTarget = nil; + + [self hide:YES]; +} + +- (void)restore { + self.label.text = nil; + self.detailLabel.text = nil; + [self initializer]; +} + +- (void)updateForCurrentOrientationAnimated:(BOOL)animated { + // Stay in sync with the superview in any case + if (self.superview) { + self.bounds = self.superview.bounds; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) + withObject:nil + waitUntilDone:YES]; + } + + // Not needed on iOS 8+, compile out when the deployment target allows, + // to avoid sharedApplication problems on extension targets +#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000 + // Only needed pre iOS 7 when added to a window + BOOL iOS8OrLater = kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0; + if (iOS8OrLater || ![self.superview isKindOfClass:[UIWindow class]]) return; + + UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation; + CGFloat radians = 0; + if (UIInterfaceOrientationIsLandscape(orientation)) { + if (orientation == UIInterfaceOrientationLandscapeLeft) { radians = -(CGFloat)M_PI_2; } + else { radians = (CGFloat)M_PI_2; } + // Window coordinates differ! + self.bounds = CGRectMake(0, 0, self.bounds.size.height, self.bounds.size.width); + } else { + if (orientation == UIInterfaceOrientationPortraitUpsideDown) { radians = (CGFloat)M_PI; } + else { radians = 0; } + } + _rotationTransform = CGAffineTransformMakeRotation(radians); + + if (animated) { + [UIView beginAnimations:nil context:nil]; + [UIView setAnimationDuration:0.3]; + } + [self setTransform:_rotationTransform]; + if (animated) { + [UIView commitAnimations]; + } +#endif +} +@end + +@implementation AXPracticalHUD(Shared) ++ (instancetype)sharedHUD { + static id _sharedInstance = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedInstance = [[self alloc] init]; + }); + return _sharedInstance; +} + +- (void)showProgressInView:(UIView *)view { + [self showProgressInView:view + text:nil + detail:nil + configuration:nil]; +} +- (void)showProgressBarInView:(UIView *)view { + [self showProgressInView:view + text:nil + detail:nil + configuration:nil]; +} +- (void)showColorfulProgressBarInView:(UIView *)view; { + [self showColorfulProgressBarInView:view + text:nil + detail:nil + configuration:nil]; +} +- (void)showTextInView:(UIView *)view { + [self showTextInView:view + text:nil + detail:nil + configuration:nil]; +} +- (void)showNormalInView:(UIView *)view { + [self showNormalInView:view + text:nil + detail:nil + configuration:nil]; +} +- (void)showErrorInView:(UIView *)view { + [self showErrorInView:view + text:nil + detail:nil + configuration:nil]; +} +- (void)showSuccessInView:(UIView *)view { + [self showSuccessInView:view + text:nil + detail:nil + configuration:nil]; +} + +- (void)showProgressInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + [self _showInView:view + animated:YES + mode:AXPracticalHUDModeProgress + text:text + detail:detail customView:nil configuration:configuration]; +} +- (void)showProgressBarInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + [self _showInView:view + animated:YES + mode:AXPracticalHUDModeProgressBar + text:text + detail:detail + customView:nil + configuration:configuration]; +} +- (void)showColorfulProgressBarInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + [self _showInView:view + animated:YES + mode:AXPracticalHUDModeColourfulProgressBar + text:text + detail:detail + customView:nil + configuration:configuration]; +} +- (void)showTextInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + [self _showInView:view + animated:YES + mode:AXPracticalHUDModeText + text:text + detail:detail + customView:nil + configuration:configuration]; +} +- (void)showNormalInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + [self _showInView:view + animated:YES + mode:AXPracticalHUDModeNormal + text:text + detail:detail + customView:nil + configuration:configuration]; +} +- (void)showErrorInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + UIImage *image; +#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0 + UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"AXPracticalHUD.bundle/ax_hud_error"]]; + image = [UIImage imageNamed:@"AXPracticalHUD.bundle/ax_hud_error"]; +#else + image = [UIImage imageNamed:@"AXPracticalHUD.bundle/ax_hud_error" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil]; +#endif + UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); + CGContextRef context = UIGraphicsGetCurrentContext(); + CGContextTranslateCTM(context, 0, image.size.height); + CGContextScaleCTM(context, 1.0, -1.0); + CGContextSetBlendMode(context, kCGBlendModeNormal); + CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height); + CGContextClipToMask(context, rect, image.CGImage); + [self.tintColor?:[UIColor whiteColor] setFill]; + CGContextFillRect(context, rect); + image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; + [imageView setFrame:CGRectMake(0, 0, 37, 37)]; + [self _showInView:view animated:YES mode:AXPracticalHUDModeCustomView text:text detail:detail customView:imageView configuration:configuration]; +} +- (void)showSuccessInView:(UIView *)view text:(NSString *)text detail:(NSString *)detail configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + UIImage *image; +#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0 + image = [UIImage imageNamed:@"AXPracticalHUD.bundle/ax_hud_success"]; +#else + image = [UIImage imageNamed:@"AXPracticalHUD.bundle/ax_hud_success" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil]; +#endif + UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale); + CGContextRef context = UIGraphicsGetCurrentContext(); + CGContextTranslateCTM(context, 0, image.size.height); + CGContextScaleCTM(context, 1.0, -1.0); + CGContextSetBlendMode(context, kCGBlendModeNormal); + CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height); + CGContextClipToMask(context, rect, image.CGImage); + [self.tintColor?:[UIColor whiteColor] setFill]; + CGContextFillRect(context, rect); + image = UIGraphicsGetImageFromCurrentImageContext(); + UIGraphicsEndImageContext(); + UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; + [imageView setFrame:CGRectMake(0, 0, 37, 37)]; + [self _showInView:view animated:YES mode:AXPracticalHUDModeCustomView text:text detail:detail customView:imageView configuration:configuration]; +} + +#pragma mark - Private +- (void)_showInView:(UIView *)view animated:(BOOL)animated mode:(AXPracticalHUDMode)mode text:(NSString *)text detail:(NSString *)detail customView:(UIView *)customView configuration:(void(^)(AXPracticalHUD *HUD))configuration +{ + self.mode = mode; + self.label.text = text; + self.customView = customView; + self.detailLabel.text = detail; + [view addSubview:self]; + if (configuration) { + configuration(self); + } + [self show:animated]; +} +@end + +@implementation AXPracticalHUD(Convenence) ++ (instancetype)showHUDInView:(UIView *)view animated:(BOOL)animated { + AXPracticalHUD *hud = [[AXPracticalHUD alloc] initWithView:view]; + hud.removeFromSuperViewOnHide = YES; + [view addSubview:hud]; + [hud show:YES]; + return hud; +} ++ (BOOL)hideHUDInView:(UIView *)view animated:(BOOL)animated { + AXPracticalHUD *hud = [self HUDInView:view]; + if (hud) { + hud.removeFromSuperViewOnHide = YES; + [hud hide:YES]; + return YES; + } + return NO; +} ++ (NSInteger)hideAllHUDsInView:(UIView *)view animated:(BOOL)animated { + NSArray *HUDs = [self HUDsInView:view]; + for (AXPracticalHUD *hud in HUDs) { + hud.removeFromSuperViewOnHide = YES; + [hud hide:animated]; + } + return HUDs.count; +} ++ (instancetype)HUDInView:(UIView *)view { + NSEnumerator *subviewEnum = [view.subviews reverseObjectEnumerator]; + for (UIView *hud in subviewEnum) { + if ([hud isKindOfClass:[AXPracticalHUD class]]) { + return (AXPracticalHUD *)hud; + } + } + return nil; +} ++ (NSArray *)HUDsInView:(UIView *)view { + NSMutableArray *HUDs = [NSMutableArray array]; + for (UIView *hud in view.subviews) { + if ([hud isKindOfClass:[AXPracticalHUD class]]) { + [HUDs addObject:hud]; + } + } + return HUDs; +} +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/Animators/AXPracticalHUDAnimator.h b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/Animators/AXPracticalHUDAnimator.h new file mode 100644 index 0000000..c5431d2 --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/Animators/AXPracticalHUDAnimator.h @@ -0,0 +1,29 @@ +// +// AXPracticalHUDAnimator.h +// AXPracticalHUD +// +// Created by devedbox on 2018/2/4. +// Copyright © 2018年 AiXing. All rights reserved. +// + +#import + +@class AXPracticalHUD; + +/// The abstract declaration of the animator of the hud to show or hide +/// on the attached view. Custom classes should conform this protocol to +/// offer the showing and hiding methods. +NS_SWIFT_NAME(PracticalHUDAnimator) @protocol AXPracticalHUDAnimator +@required +/// Should allow layouting subviews during animation. +@property(readonly, nonatomic) BOOL allowsLayoutSubviewsDuringAnimation; +/// The last time duration of the animation. +- (NSTimeInterval)durationForTransition:(BOOL)isHidden; +/// The hud will call this method to show or hide the hud view when the transition +/// begins. +/// +/// @param hud: The hud view to be transitioned. +/// @param animated: Wether to run this animator by animation. +/// @param isHidden: Wether the animator is used to begin hidding transition animation. +- (void)hud:(AXPracticalHUD *)hud animate:(BOOL)animated isHidden:(BOOL)isHidden; +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/Animators/AXPracticalHUDAnimator.m b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/Animators/AXPracticalHUDAnimator.m new file mode 100644 index 0000000..b28e519 --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/Animators/AXPracticalHUDAnimator.m @@ -0,0 +1,212 @@ +// +// AXPracticalHUDAnimator.m +// AXPracticalHUD +// +// Created by devedbox on 2018/2/4. +// Copyright © 2018年 AiXing. All rights reserved. +// + +#import "AXPracticalHUDAnimator.h" +#import "AXPracticalHUD.h" + +@interface AXPracticalHUD (Private_Hooks) +/// Get the content frame of the hud. +@property(readonly, nonatomic) CGRect contentFrame; +@end + +@interface _AXPracticalHUDFadeAnimator: NSObject +@end + +@interface _AXPracticalHUDFlipUpAnimator: NSObject +@end + +@interface _AXPracticalHUDZoomAnimator: NSObject +@end + +@interface _AXPracticalHUDDropDownAnimator: NSObject +@end + +id AXPracticalHUDFadeAnimator() { + return [_AXPracticalHUDFadeAnimator new]; +} +id AXPracticalHUDFlipUpAnimator() { + return [_AXPracticalHUDFlipUpAnimator new]; +} +id AXPracticalHUDZoomAnimator() { + return [_AXPracticalHUDZoomAnimator new]; +} +id AXPracticalHUDDropDownAnimator() { + return [_AXPracticalHUDDropDownAnimator new]; +} + +#pragma mark - Fade. + +@implementation _AXPracticalHUDFadeAnimator +- (BOOL)allowsLayoutSubviewsDuringAnimation { + return YES; +} + +- (NSTimeInterval)durationForTransition:(BOOL)isHidden { + return isHidden ? 0.25 : 0.4; +} + +- (void)hud:(AXPracticalHUD *)hud animate:(BOOL)animated isHidden:(BOOL)isHidden { + if (animated) { + [UIView animateWithDuration:0.25 delay:isHidden ? 0.0 : 0.15 options:7 animations:^{ + hud.alpha = isHidden ? 0.0 : 1.0; + } completion:nil]; + } else { + hud.alpha = isHidden ? 0.0 : 1.0; + } +} +@end + +#pragma mark - FlipUp. + +@implementation _AXPracticalHUDFlipUpAnimator +- (BOOL)allowsLayoutSubviewsDuringAnimation { + return NO; +} + +- (NSTimeInterval)durationForTransition:(BOOL)isHidden { + return isHidden ? 0.5 : 0.65; +} + +- (void)hud:(AXPracticalHUD *)hud animate:(BOOL)animated isHidden:(BOOL)isHidden { + if (animated) { + if (isHidden) { + CGRect rect = hud.contentFrame; + CGFloat translation = (hud.position == AXPracticalHUDPositionBottom || hud.position == AXPracticalHUDPositionCenter) ? hud.bounds.size.height : -rect.size.height; + rect.origin.y = translation; + [UIView animateWithDuration:0.5 + delay:0.0 + usingSpringWithDamping:1.0 + initialSpringVelocity:0.9 + options:7 + animations:^{ + hud.contentView.frame = rect; + hud.alpha = 0.0; + } completion:^(BOOL finished) { + if (finished) { + hud.contentView.frame = hud.contentFrame; + } + }]; + } else { + [UIView animateWithDuration:0.25 animations:^{ + hud.alpha = 1.0; + }]; + CGRect rect = hud.contentFrame; + + CGFloat translation = (hud.position == AXPracticalHUDPositionBottom || hud.position == AXPracticalHUDPositionCenter) ? hud.bounds.size.height : -rect.size.height; + rect.origin.y = translation; + hud.contentView.frame = rect; + [UIView animateWithDuration:0.5 + delay:0.15 + usingSpringWithDamping:1.0 + initialSpringVelocity:0.9 + options:7 + animations:^{ + hud.contentView.frame = hud.contentFrame; + } completion:nil]; + } + } else { + hud.alpha = isHidden ? 0.0 : 1.0; + } +} +@end + +#pragma mark - Zoom. + +@implementation _AXPracticalHUDZoomAnimator +- (BOOL)allowsLayoutSubviewsDuringAnimation { + return NO; +} + +- (NSTimeInterval)durationForTransition:(BOOL)isHidden { + return 0.35; +} + +- (void)hud:(AXPracticalHUD *)hud animate:(BOOL)animated isHidden:(BOOL)isHidden { + if (animated) { + if (isHidden) { + [UIView animateWithDuration:0.25 animations:^{ + hud.alpha = 0.0; + }]; + [UIView animateWithDuration:0.35 + delay:0.0 + usingSpringWithDamping:1.0 + initialSpringVelocity:1.0 + options:7 + animations:^{ + hud.contentView.transform = CGAffineTransformMakeScale(0.8, 0.8); + } completion:^(BOOL finished) { + if (finished) { + hud.contentView.transform = CGAffineTransformIdentity; + } + }]; + } else { + [UIView animateWithDuration:0.25 animations:^{ + hud.alpha = 1.0; + }]; + hud.contentView.transform = CGAffineTransformMakeScale(0.5, 0.5); + [UIView animateWithDuration:0.35 + delay:0.0 + usingSpringWithDamping:1.0 + initialSpringVelocity:0.9 + options:7 + animations:^{ + hud.contentView.transform = CGAffineTransformIdentity; + } completion:nil]; + } + } else { + hud.alpha = isHidden ? 0.0 : 1.0; + } +} +@end + +@implementation _AXPracticalHUDDropDownAnimator +- (BOOL)allowsLayoutSubviewsDuringAnimation { + return NO; +} + +- (NSTimeInterval)durationForTransition:(BOOL)isHidden { + return isHidden ? 0.35 : 0.5; +} + +- (void)hud:(AXPracticalHUD *)hud animate:(BOOL)animated isHidden:(BOOL)isHidden { + if (animated) { + if (isHidden) { + [UIView animateWithDuration:0.25 + delay:0.1 + usingSpringWithDamping:1.0 + initialSpringVelocity:0.9 + options:7 + animations:^{ + hud.contentView.transform = CGAffineTransformRotate(CGAffineTransformMakeTranslation(0, CGRectGetHeight(hud.frame)-CGRectGetMinY(hud.contentView.frame)), -M_PI/12); + } completion:^(BOOL finished) { + if (finished) { + hud.contentView.transform = CGAffineTransformIdentity; + } + }]; + [UIView animateWithDuration:0.25 delay:0.1 options:7 animations:^{ + hud.alpha = 0.0; + } completion:NULL]; + } else { + [UIView animateWithDuration:0.25 animations:^{ + hud.alpha = 1.0; + }]; + hud.contentView.transform = CGAffineTransformRotate(CGAffineTransformMakeTranslation(0, -CGRectGetMaxY(hud.contentView.frame)), M_PI/12); + [UIView animateWithDuration:0.4 + delay:0.1 + usingSpringWithDamping:1.0 + initialSpringVelocity:0.9 + options:7 + animations:^{ + hud.contentView.transform = CGAffineTransformIdentity; + } completion:NULL]; + } + } else { + hud.alpha = isHidden ? 0.0 : 1.0; + } +} +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ContentView/AXPracticalHUDContentView.h b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ContentView/AXPracticalHUDContentView.h new file mode 100644 index 0000000..ead94a0 --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ContentView/AXPracticalHUDContentView.h @@ -0,0 +1,47 @@ +// +// AXPracticalHUDContentView.h +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import + +typedef NS_ENUM(NSInteger, AXPracticalHUDTranslucentStyle) { + /// Light translucent style. + AXPracticalHUDTranslucentStyleLight, + /// Dark translucent style. + AXPracticalHUDTranslucentStyleDark +} NS_SWIFT_NAME(PracticalHUDTranslucentStyle); + +NS_SWIFT_NAME(PracticalHUDContentView) @interface AXPracticalHUDContentView : UIView +/// Color of the content view. Default is nil. +@property(strong, nonatomic) UIColor *color; +/// End color of the content view. Default is nil. +@property(strong, nonatomic) UIColor *endColor; +/// Translucent. Default is NO. +@property(assign, nonatomic, getter=isTranslucent) BOOL translucent; +/// Translucent style. Default is Dark. +@property(assign, nonatomic) AXPracticalHUDTranslucentStyle translucentStyle; +/// Opacity. Default is 0.8f. If color of the content view is nil, then background color of the content view will +/// be filled with gray color with opacity alpha. +@property(assign, nonatomic) CGFloat opacity; +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ContentView/AXPracticalHUDContentView.m b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ContentView/AXPracticalHUDContentView.m new file mode 100644 index 0000000..446e764 --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ContentView/AXPracticalHUDContentView.m @@ -0,0 +1,201 @@ +// +// AXPracticalHUDContentView.m +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXPracticalHUDContentView.h" + +#ifndef kCFCoreFoundationVersionNumber_iOS_8_0 +#define kCFCoreFoundationVersionNumber_iOS_8_0 1140.1 +#endif + +@interface AXPracticalHUDContentView() +/// Effects view for the content view. +@property(strong, nonatomic) UIView *effectView; +@end + +@implementation AXPracticalHUDContentView +#pragma mark - Life cycle +- (instancetype)init { + if (self = [super init]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)initializer { + self.backgroundColor = [UIColor clearColor]; + _translucent = NO; + _translucentStyle = AXPracticalHUDTranslucentStyleDark; + _opacity = 0.8f; +} + +#pragma mark - Override +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + + CGContextRef context = UIGraphicsGetCurrentContext(); + UIGraphicsPushContext(context); + + if (_translucent) { + CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); + } else if (_endColor && _color) { + // Gradient color + size_t locationCount = 2; + CGFloat gradLocations[2] = {0.0, 1.0}; + CGFloat r1 = 0.0; + CGFloat r2 = 0.0; + CGFloat g1 = 0.0; + CGFloat g2 = 0.0; + CGFloat b1 = 0.0; + CGFloat b2 = 0.0; + CGFloat a1 = 0.75; + CGFloat a2 = 0.0; + [_color getRed:&r1 green:&g1 blue:&b1 alpha:&a1]; + [_endColor getRed:&r2 green:&g2 blue:&b2 alpha:&a2]; + CGFloat gradColors[8] = {r1, g1, b1, a1, r2, g2, b2, a2}; + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, locationCount); + CGContextDrawLinearGradient(context, gradient, CGPointMake(self.bounds.size.width / 2, self.bounds.size.height), CGPointMake(self.bounds.size.width / 2, 0), kCGGradientDrawsAfterEndLocation); + CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); + + CGColorSpaceRelease(colorSpace); + CGGradientRelease(gradient); + } else { + if (!_color) { + CGContextSetGrayFillColor(context, 0.0, _opacity); + } else { + CGContextSetFillColorWithColor(context, _color.CGColor); + } + // Set the cornor radius of the content view. + CGContextBeginPath(context); + CGRect rect = self.bounds; + CGContextMoveToPoint(context, CGRectGetMinX(rect) + 0.0, CGRectGetMinY(rect)); + CGContextAddArc(context, CGRectGetMaxX(rect) - 0.0, CGRectGetMinY(rect) + 0.0, 0.0, 3 * M_PI / 2, 0, 0); + CGContextAddArc(context, CGRectGetMaxX(rect) - 0.0, CGRectGetMaxY(rect) - 0.0, 0.0, 0, M_PI / 2, 0); + CGContextAddArc(context, CGRectGetMinX(rect) + 0.0, CGRectGetMaxY(rect) - 0.0, 0.0, M_PI / 2, M_PI, 0); + CGContextAddArc(context, CGRectGetMinX(rect) + 0.0, CGRectGetMinY(rect) + 0.0, 0.0, M_PI, 3 * M_PI / 2, 0); + CGContextClosePath(context); + CGContextFillPath(context); + } + + UIGraphicsPopContext(); +} + +- (void)layoutSubviews { + [super layoutSubviews]; + + _effectView.frame = self.bounds; +} +#pragma mark - Getters & Setters +- (UIView *)effectView { + if (_effectView) return _effectView; + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0) { + _effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]]; + _effectView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + } else { + _effectView = [[UIToolbar alloc] initWithFrame:CGRectZero]; + for (UIView *view in [_effectView subviews]) { + if ([view isKindOfClass:[UIImageView class]] && [[view subviews] count] == 0) { + [view setHidden:YES]; + } + } + ((UIToolbar *)_effectView).barStyle = UIBarStyleBlack; + _effectView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + } + return _effectView; +} + +- (void)setColor:(UIColor *)color { + _color = color; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setEndColor:(UIColor *)endColor { + _endColor = endColor; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setTranslucent:(BOOL)translucent { + _translucent = translucent; + if (_translucent) { + [self insertSubview:self.effectView atIndex:0]; + } else { + [_effectView removeFromSuperview]; + } + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; + [self performSelectorOnMainThread:@selector(setNeedsLayout) withObject:nil waitUntilDone:YES]; +} + +- (void)setTranslucentStyle:(AXPracticalHUDTranslucentStyle)translucentStyle { + _translucentStyle = translucentStyle; + if (!_translucent) return; + + if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iOS_8_0) { + if ([_effectView isKindOfClass:[UIVisualEffectView class]]) { + [_effectView removeFromSuperview]; + switch (translucentStyle) { + case AXPracticalHUDTranslucentStyleLight: + _effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]]; + _effectView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + break; + case AXPracticalHUDTranslucentStyleDark: + _effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]]; + _effectView.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; + break; + default: + break; + } + if (_translucent) { + [self insertSubview:_effectView atIndex:0]; + } + } + } else { + if ([_effectView isKindOfClass:[UIToolbar class]]) { + UIToolbar *effect = (UIToolbar *)_effectView; + switch (translucentStyle) { + case AXPracticalHUDTranslucentStyleLight: + effect.barStyle = UIBarStyleDefault; + break; + case AXPracticalHUDTranslucentStyleDark: + effect.barStyle = UIBarStyleBlack; + break; + default: + break; + } + } + } +} + +- (void)setOpacity:(CGFloat)opacity { + _opacity = opacity; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXBarProgressView.h b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXBarProgressView.h new file mode 100644 index 0000000..c02f2fa --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXBarProgressView.h @@ -0,0 +1,37 @@ +// +// AXBarProgressView.h +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import +/// Bar style progress view. +NS_SWIFT_NAME(BarProgressView) @interface AXBarProgressView : UIView +/// Progress value. Values between [0, 1]. +@property(assign, nonatomic) CGFloat progress; +/// Line color. Stroke color for the drawing. +@property(strong, nonatomic) UIColor *lineColor; +/// Progress color. Color for progress inticator. Default is white. +@property(strong, nonatomic) UIColor *progressColor; +/// Track color. Filling color for the drawing. +@property(strong, nonatomic) UIColor *trackColor; +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXBarProgressView.m b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXBarProgressView.m new file mode 100644 index 0000000..e7d33ac --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXBarProgressView.m @@ -0,0 +1,160 @@ +// +// AXBarProgressView.m +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXBarProgressView.h" + +@implementation AXBarProgressView +#pragma mark - Lift cycle +- (instancetype)init { + if (self = [super initWithFrame:CGRectMake(0, 0, 120, 12)]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)initializer { + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + + _progress = 0.0; + _progressColor = [UIColor whiteColor]; + _lineColor = [UIColor whiteColor]; + _trackColor = [UIColor clearColor]; +} +#pragma mark - Override +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + + CGContextRef context = UIGraphicsGetCurrentContext(); + + CGContextSetLineWidth(context, 2); + CGContextSetStrokeColorWithColor(context,_lineColor.CGColor); + CGContextSetFillColorWithColor(context, _trackColor.CGColor); + + // Draw background + CGFloat radius = (rect.size.height / 2) - 2; + CGContextMoveToPoint(context, 2, rect.size.height/2); + CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 2, 2); + CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); + CGContextAddLineToPoint(context, radius + 2, rect.size.height - 2); + CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); + CGContextFillPath(context); + + // Draw border + CGContextMoveToPoint(context, 2, rect.size.height/2); + CGContextAddArcToPoint(context, 2, 2, radius + 2, 2, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 2, 2); + CGContextAddArcToPoint(context, rect.size.width - 2, 2, rect.size.width - 2, rect.size.height / 2, radius); + CGContextAddArcToPoint(context, rect.size.width - 2, rect.size.height - 2, rect.size.width - radius - 2, rect.size.height - 2, radius); + CGContextAddLineToPoint(context, radius + 2, rect.size.height - 2); + CGContextAddArcToPoint(context, 2, rect.size.height - 2, 2, rect.size.height/2, radius); + CGContextStrokePath(context); + + CGContextSetFillColorWithColor(context, _progressColor.CGColor); + radius = radius - 2; + CGFloat amount = _progress * rect.size.width; + + // Progress in the middle area + if (amount >= radius + 4 && amount <= (rect.size.width - radius - 4)) { + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, amount, 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, amount, rect.size.height - 4); + CGContextAddLineToPoint(context, amount, radius + 4); + + CGContextFillPath(context); + } + + // Progress in the right arc + else if (amount > radius + 4) { + CGFloat x = amount - (rect.size.width - radius - 4); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, 4); + CGFloat angle = -acos(x/radius); + if isnan(angle) { + angle = 0.0; + } + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height / 2, radius, M_PI, angle, 0); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, rect.size.width - radius - 4, rect.size.height - 4); + angle = acos(x/radius); + if isnan(angle) { + angle = 0.0; + } + CGContextAddArc(context, rect.size.width - radius - 4, rect.size.height / 2, radius, -M_PI, angle, 1); + CGContextAddLineToPoint(context, amount, rect.size.height/2); + + CGContextFillPath(context); + } else if (amount < radius + 4 && amount > 0) {// Progress is in the left arc + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, 4, radius + 4, 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextMoveToPoint(context, 4, rect.size.height/2); + CGContextAddArcToPoint(context, 4, rect.size.height - 4, radius + 4, rect.size.height - 4, radius); + CGContextAddLineToPoint(context, radius + 4, rect.size.height/2); + + CGContextFillPath(context); + } +} +#pragma mark - Setters +- (void)setProgress:(CGFloat)progress { + _progress = progress; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setLineColor:(UIColor *)lineColor { + _lineColor = lineColor; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setProgressColor:(UIColor *)progressColor { + _progressColor = progressColor; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setTrackColor:(UIColor *)trackColor { + _trackColor = trackColor; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXCircleProgressView.h b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXCircleProgressView.h new file mode 100644 index 0000000..1e874bb --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXCircleProgressView.h @@ -0,0 +1,37 @@ +// +// AXCircleProgressView.h +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import +/// Circle style progress view. +NS_SWIFT_NAME(CircleProgressView) @interface AXCircleProgressView : UIView +/// Progress value. Between [0, 1]. +@property(assign, nonatomic) CGFloat progress; +/// Progress color. Color for the progress indicator. Default is white. +@property(strong, nonatomic) UIColor *progressColor; +/// Progress background color. Color for the background of the progress indicator. Default is 0.1@white. +@property(strong, nonatomic) UIColor *progressBgnColor; +/// Annular enabled. Pie style or hollow. Default is NO means pie. +@property(assign, nonatomic, getter=isAnnularEnabled) BOOL annularEnabled; +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXCircleProgressView.m b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXCircleProgressView.m new file mode 100644 index 0000000..40607fb --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXCircleProgressView.m @@ -0,0 +1,124 @@ +// +// AXCircleProgressView.m +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXCircleProgressView.h" + +@implementation AXCircleProgressView +#pragma mark - Life cycle +- (instancetype)init { + if (self = [super initWithFrame:CGRectMake(0, 0, 37, 37)]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)initializer { + self.backgroundColor = [UIColor clearColor]; + self.opaque = NO; + + _progress = 0.0; + _progressBgnColor = [UIColor colorWithWhite:1 alpha:.1]; + _progressColor = [UIColor whiteColor]; + _annularEnabled = NO; +} + +#pragma mark - Override +- (void)drawRect:(CGRect)rect { + [super drawRect:rect]; + // Get a rect + CGRect allRect = self.bounds; + CGRect circleRect = CGRectInset(allRect, 2.0, 2.0); + // Get current context + CGContextRef context = UIGraphicsGetCurrentContext(); + // Draw + if (_annularEnabled) { + // draw background + BOOL isPre_iOS_7_0 = kCFCoreFoundationVersionNumber <= kCFCoreFoundationVersionNumber_iOS_7_0; + CGFloat lineWidth = isPre_iOS_7_0 ? 5.0 : 2.0; + UIBezierPath *backgroundPath = [UIBezierPath bezierPath]; + backgroundPath.lineCapStyle = kCGLineCapButt; + CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2); + CGFloat radius = (self.bounds.size.width - lineWidth) / 2; + // 90degree + CGFloat startAngle = -(M_PI) / 2; + CGFloat endAngle = startAngle + (2.0 * M_PI); + [backgroundPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_progressBgnColor set]; + [backgroundPath stroke]; + // draw progress + UIBezierPath *progressPath = [UIBezierPath bezierPath]; + progressPath.lineCapStyle = isPre_iOS_7_0 ? kCGLineCapRound : kCGLineCapSquare; + progressPath.lineWidth = lineWidth; + endAngle = _progress * 2.0 * M_PI + startAngle; + [progressPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; + [_progressColor set]; + [progressPath stroke]; + } else { + // draw background + [_progressColor setStroke]; + [_progressBgnColor setFill]; + CGContextSetLineWidth(context, 2.0); + CGContextFillEllipseInRect(context, circleRect); + CGContextStrokeEllipseInRect(context, circleRect); + // draw progress + CGPoint center = CGPointMake(allRect.size.width / 2, allRect.size.height / 2); + CGFloat radius = (allRect.size.width - 4.0) / 2; + CGFloat startAngle = -(M_PI / 2); + CGFloat endAngle = _progress * 2.0 * M_PI + startAngle; + [_progressColor setFill]; + CGContextMoveToPoint(context, center.x, center.y); + CGContextAddArc(context, center.x, center.y, radius, startAngle, endAngle, 0); + CGContextClosePath(context); + CGContextFillPath(context); + } +} +#pragma mark - Setters +- (void)setProgress:(CGFloat)progress { + _progress = progress; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setProgressBgnColor:(UIColor *)progressBgnColor { + _progressBgnColor = progressBgnColor; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setProgressColor:(UIColor *)progressColor { + _progressColor = progressColor; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setAnnularEnabled:(BOOL)annularEnabled { + _annularEnabled = annularEnabled; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXGradientProgressView.h b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXGradientProgressView.h new file mode 100644 index 0000000..8f84995 --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXGradientProgressView.h @@ -0,0 +1,41 @@ +// +// AXGradientProgressView.h +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import +/// Gradient style progress view. +NS_SWIFT_NAME(GradientProgressView) @interface AXGradientProgressView : UIView +/// Progress value between [0, 1]. +@property(assign, nonatomic) CGFloat progress; +/// Height of the progress indicator aera. Default is 1.0. +@property(assign, nonatomic) CGFloat progressHeight; +/// Colors of the gradient. +@property(copy, nonatomic) NSMutableArray *colors; +/// Animation duration. Default is 0.08. +@property(assign, nonatomic) CGFloat duration; +/// Begin animation of the gradient progress view. +- (void)beginAnimating; +/// End animating. +- (void)endAnimating; +@end diff --git a/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXGradientProgressView.m b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXGradientProgressView.m new file mode 100644 index 0000000..752ab6d --- /dev/null +++ b/Pods/AXPracticalHUD/AXPracticalHUD/AXPracticalHUD/ProgressViews/AXGradientProgressView.m @@ -0,0 +1,158 @@ +// +// AXGradientProgressView.m +// AXPracticalHUD +// +// Created by ai on 9/7/15. +// Copyright © 2015 ai. All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +#import "AXGradientProgressView.h" + +@interface AXGradientProgressView() +@property(strong, nonatomic) CAGradientLayer *gradientLayer; +@property(strong, nonatomic) CADisplayLink *displayLink; +@end + +@implementation AXGradientProgressView +#pragma mark - Life cycle +- (instancetype)init { + if (self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 1.0)]) { + [self initializer]; + } + return self; +} + +- (instancetype)initWithFrame:(CGRect)frame { + if (self = [super initWithFrame:frame]) { + [self initializer]; + } + return self; +} + +- (void)initializer { + _progress = 0.0; + _progressHeight = 1.0; + _colors = [[[self class] defaultColors] mutableCopy]; + _duration = 0.08; + + [self.layer addSublayer:self.gradientLayer]; +} + +- (void)dealloc { + [_displayLink invalidate]; + _displayLink = nil; +} +#pragma mark - Override +- (void)didMoveToSuperview { + [super didMoveToSuperview]; + + if (self.superview) { + [self beginAnimating]; + } else { + [self endAnimating]; + } +} + +- (CGSize)sizeThatFits:(CGSize)size { + CGSize aSize = [super sizeThatFits:size]; + aSize.height = _progressHeight; + return aSize; +} + +- (void)layoutSubviews { + [super layoutSubviews]; + + [self sizeToFit]; +} + +- (void)layoutSublayersOfLayer:(CALayer *)layer { + [super layoutSublayersOfLayer:layer]; + + CGRect rect = _gradientLayer.frame; + rect.size.width = self.bounds.size.width * MIN(_progress, 1.0); + rect.size.height = self.bounds.size.height; + _gradientLayer.frame = rect; +} + +#pragma mark - Public +- (void)beginAnimating { + [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; +} + +- (void)endAnimating { + [_displayLink invalidate]; + _displayLink = nil; +} + +#pragma mark - Getters & Setters +- (CAGradientLayer *)gradientLayer { + if (_gradientLayer) return _gradientLayer; + _gradientLayer = [CAGradientLayer layer]; + _gradientLayer.startPoint = CGPointMake(0.0, 0); + _gradientLayer.endPoint = CGPointMake(1.0, 0); + _gradientLayer.colors = [_colors copy]; + _gradientLayer.type = kCAGradientLayerAxial; + return _gradientLayer; +} + +- (CADisplayLink *)displayLink { + if (_displayLink) return _displayLink; + _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)]; + if (@available(iOS 10.0, *)) { + self.displayLink.preferredFramesPerSecond = 60; + } else { + self.displayLink.frameInterval = 1; + } + return _displayLink; +} + +- (void)setColors:(NSMutableArray *)colors { + _colors = colors; + _gradientLayer.colors = _colors; +} + +- (void)setProgress:(CGFloat)progress { + _progress = progress; + [self performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES]; +} + +- (void)setProgressHeight:(CGFloat)progressHeight { + _progressHeight = progressHeight; +} +#pragma mark - Private helper +- (void)handleDisplayLink:(CADisplayLink *)sender { + NSMutableArray *colors = [_gradientLayer.colors mutableCopy]; + CGColorRef color = (__bridge CGColorRef)([colors lastObject]); + [colors removeLastObject]; + [colors insertObject:(__bridge id)(color) atIndex:0]; + _gradientLayer.colors = [colors copy]; +} + ++ (NSMutableArray *)defaultColors { + NSMutableArray *colors = [NSMutableArray array]; + NSInteger hue = 1; + while (hue <= 360) { + UIColor *color = [[UIColor alloc] initWithHue:1.0 * hue / 360.0 saturation:1.0 brightness:1.0 alpha:1.0]; + [colors addObject:(__bridge id)(color.CGColor)]; + hue += 5; + } + return colors; +} +@end diff --git a/Pods/AXPracticalHUD/LICENSE b/Pods/AXPracticalHUD/LICENSE new file mode 100644 index 0000000..4a62c57 --- /dev/null +++ b/Pods/AXPracticalHUD/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 xing Ai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/Pods/AXPracticalHUD/README.md b/Pods/AXPracticalHUD/README.md new file mode 100644 index 0000000..da24a06 --- /dev/null +++ b/Pods/AXPracticalHUD/README.md @@ -0,0 +1,5 @@ +# AXPracticalHUD + +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)! + +HUD view diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome-iPad.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome-iPad.png new file mode 100644 index 0000000..cd19edb Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome-iPad.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome-iPad@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome-iPad@2x.png new file mode 100644 index 0000000..5c8b081 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome-iPad@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome@2x.png new file mode 100644 index 0000000..565e0ce Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivityChrome@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari-iPad.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari-iPad.png new file mode 100644 index 0000000..31f2ca8 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari-iPad.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari-iPad@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari-iPad@2x.png new file mode 100644 index 0000000..856e4d0 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari-iPad@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari@2x.png new file mode 100644 index 0000000..b0dc8c7 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerActivitySafari@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerBack.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerBack.png new file mode 100644 index 0000000..195b4fd Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerBack.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerBack@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerBack@2x.png new file mode 100644 index 0000000..2ef9aca Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerBack@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerNext.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerNext.png new file mode 100644 index 0000000..453bc79 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerNext.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerNext@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerNext@2x.png new file mode 100644 index 0000000..5746bec Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/AXWebViewControllerNext@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/backItemImage@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/backItemImage@2x.png new file mode 100755 index 0000000..1990f09 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/backItemImage@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/backItemImage_hl@2x.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/backItemImage_hl@2x.png new file mode 100755 index 0000000..a2f7a8c Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/backItemImage_hl@2x.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/en.lproj/AXWebViewController.strings b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/en.lproj/AXWebViewController.strings new file mode 100644 index 0000000..4a9f786 --- /dev/null +++ b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/en.lproj/AXWebViewController.strings @@ -0,0 +1,24 @@ +/* + AXWebViewController.strings + AXWebViewController + + Created by devedbox on 16/8/14. + Copyright © 2016年 AiXing. All rights reserved. +*/ +"back" = "Back"; +"close" = "Close"; +"loading" = "Loading..."; +"load failed" = "Load failed"; +"load failed:" = "Load failed: "; +"web page" = "This page was generated by "; +"provided" = ""; +"browsing the web" = "Web browsing"; + +"messages" = "Messages from web page"; +"cancel" = "Cancel"; +"confirm" = "Confirm"; +"input" = "Input text content"; +"terminate" = "Web content process did terminate"; + +"OpenInChrome" = "Open in Chrome"; +"OpenInSafari" = "Open in Safari"; diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/404.html b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/404.html new file mode 100755 index 0000000..4383b88 --- /dev/null +++ b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/404.html @@ -0,0 +1,34 @@ + + + + + + +404 + + + + + + +
+ +
+

Not Found

+

点击重试

+ + diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/css/nosingle.css b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/css/nosingle.css new file mode 100755 index 0000000..aeda20e --- /dev/null +++ b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/css/nosingle.css @@ -0,0 +1,63 @@ +@charset "utf-8"; +/* CSS Document */ +*{ + margin:0px; + padding:0px; + font-family:"PingFang"; + } +body li{ + list-style-type:none; + } +body a{ + text-decoration:none; + } +img{ + border:0px; + } +a:focus{ + outline:none; + } +a{ + blr:expression(this.onFocus=this.blur()); + }/**链接a在获得焦点的同时失去焦点。如果用的是图片链接之类的,不会显示周边的**/ +/*****main*****/ +.img404{ + width:8rem; + overflow:hidden; + margin:5rem auto 1rem; + } +.img404 img{ + width:100%; + } +.detail404,.detail_neor{ + text-align:center; + font-size:12px; + color:#cecece; + } +.btn404,.detail_neor_btn{ + text-align:center; + color:#646464; + font-size:12px; + border:1px solid #cecece; + width:8rem; + margin:0.6rem auto; + padding:0.3rem 0 0.3rem; + border-radius:3px; + -webkit-border-radius:3px; + -moz-border-radius:3px; + } +.neterror{ + width:4rem; + overflow:hidden; + margin:6rem auto 1rem; + } +.neterror img{ + width:100%; + } + + + + + + + \ No newline at end of file diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/img/404.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/img/404.png new file mode 100755 index 0000000..30c2c9c Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/img/404.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/img/nosingle.png b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/img/nosingle.png new file mode 100755 index 0000000..751e122 Binary files /dev/null and b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/img/nosingle.png differ diff --git a/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/js/jquery-2.1.1.min.js b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/js/jquery-2.1.1.min.js new file mode 100755 index 0000000..181c65e --- /dev/null +++ b/Pods/AXWebViewController/AXWebViewController/AXWebViewController/AXWebViewController.bundle/html.bundle/js/jquery-2.1.1.min.js @@ -0,0 +1,5 @@ +/*! jQuery v2.1.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.1",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b) +},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("')}; +}).call(this, this); + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/pl.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/pl.lproj/BULanguage.strings new file mode 100644 index 0000000..09a488c --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/pl.lproj/BULanguage.strings @@ -0,0 +1,47 @@ +/* + BULanguage.strings + PAGAdSDK + + Created by ByteDance on 2022/11/15. + +*/ + +// String + +"Click" = "Click"; +"AD" = "Reklamy"; +"PlayConsumed" = "%.2fMB traffic will be consumed if you play it"; +"Evaluation" = "Evaluation"; +"Score" = "%@ reviews"; +"Select" = "Select"; +"Wan" = "";//英文逻辑不一样,为空就好 +"Back" = "Back"; +"Replay" = "Tap to replay"; +"Continue" = "Continue to play"; +"Skip" = "Skip"; +"Feedback" = "Feedback"; +"FeedbackStr1" = "Thanks for your feedback!"; +"FeedbackStr2" = "We'll continue to improve our service."; +"FeedbackStr3" = "You've submitted feedback!"; +"FeedbackStr4" = "Please don't submit again."; +"ViewNow" = "View now"; +"Download" = "Download Now"; +"LoadFailure" = "Failed to load, and click to try again"; +"GetRewardAfterWatching" = "Watch the entire video to claim your reward"; +"GiveUpReward" = "Leave"; +"ContinueWatching" = "Resume"; +"CanbeTurnedOffAfter" = "Skip after %ds"; +"CanbeSkipAfter" = "Pomiń po %d s"; +"Get" = "Get"; +"View" = "View"; +"ContinuePlaying" = "Keep on"; +"GetRewardAfterPlaying" = "Finish playing to get rewards!"; +"ViewDetail" = "View"; +"CommitScore" = "%@ reviews"; +"AdsClosed" = "Ads Closed"; +"PrivacyPolicy" = "Privacy Policy"; +"DisplayError" = "Błąd wyświetlania"; +"FeedbackExplaination" = "Opisz napotkany błąd wyświetlania i kliknij przycisk Prześlij. Również kreacja reklamowa zostanie odesłana do Pangle, aby rozwiązać problem."; +"Submit" = "Prześlij"; +"MutiNumAD" = "Reklama %d z %d"; +// Icon diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/pt.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/pt.lproj/BULanguage.strings new file mode 100644 index 0000000..3a0cdc3 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/pt.lproj/BULanguage.strings @@ -0,0 +1,47 @@ +/* + BULanguage.strings + BUAdSDK + + Created by wangyanlin on 2020/4/10. + Copyright © 2020 bytedance. All rights reserved. +*/ + +// String + +"Click" = "Clicar"; +"AD" = "Anúncios"; +"PlayConsumed" = "Ao executar este, você usará %.2f MB dos dados"; +"Evaluation" = "Avaliação"; +"Score" = "%@ críticas"; +"Select" = "Selecionar"; +"Back" = "Voltar"; +"Replay" = "Toque para repetir"; +"Continue" = "Continue para executar"; +"Skip" = "Ignorar"; +"Feedback" = "Comentários"; +"FeedbackStr1" = "Obrigado pelos seus comentários!"; +"FeedbackStr2" = "Continuaremos a melhorar o nosso serviço."; +"FeedbackStr3" = "Enviou comentários!"; +"FeedbackStr4" = "Não envie novamente."; +"ViewNow" = "Ver agora"; +"Download" = "Transferir agora"; +"LoadFailure" = "Falha ao carregar. Tente novamente."; +"GetRewardAfterWatching" = "Veja todo o vídeo para reclamar a sua recompensa"; +"GiveUpReward" = "Sair"; +"ContinueWatching" = "Retomar"; +"CanbeTurnedOffAfter" = "Pular depois de %ds"; +"CanbeSkipAfter" = "Pular depois de %ds"; +"Get" = "Fazer download"; +"View" = "Visualizar"; +"ContinuePlaying" = "Continuar executando"; +"GetRewardAfterPlaying" = "Finalizar a execução para solicitar as premiações"; +"Wan" = "10 mil"; +"ViewDetail" = "Visualizar"; +"CommitScore" = "%@ críticas"; +"AdsClosed" = "Anúncios fechados"; +"PrivacyPolicy" = "Política de Privacidade"; +"DisplayError" = "Erro de apresentação"; +"FeedbackExplaination" = "Introduza uma descrição do erro de apresentação e clique no botão Enviar. O criativo de anúncio também será remetido para a Pangle para ajudar a resolver o problema."; +"Submit" = "Enviar"; +"MutiNumAD" = "anúncio %d de %d"; +// Icon diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/ru.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/ru.lproj/BULanguage.strings new file mode 100644 index 0000000..bb5a8bc --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/ru.lproj/BULanguage.strings @@ -0,0 +1,46 @@ +/* + BULanguage.strings + BUAdSDK + + Created by wangyanlin on 2020/4/10. + Copyright © 2020 bytedance. All rights reserved. +*/ + +// String + +"Click" = "Нажмите"; +"AD" = "Реклама"; +"PlayConsumed" = "На воспроизведение будет потрачено %.2f МБ трафика"; +"Evaluation" = "Оценка"; +"Score" = "Отзывы: %@"; +"Select" = "Выбрать"; +"Back" = "Назад"; +"Replay" = "Нажмите, чтобы повторить"; +"Continue" = "Продолжить воспроизведение"; +"Skip" = "Пропустить"; +"Feedback" = "Отзыв"; +"FeedbackStr1" = "Спасибо за отзыв!"; +"FeedbackStr2" = "Мы будем и дальше улучшать наши услуги."; +"FeedbackStr3" = "Вы уже оставили отзыв!"; +"FeedbackStr4" = "Пожалуйста, не отправляйте его повторно."; +"ViewNow" = "Посмотреть"; +"Download" = "Загрузить"; +"LoadFailure" = "Ошибка загрузки. Попробуйте снова."; +"GetRewardAfterWatching" = "Посмотрите видео целиком, чтобы получить награду"; +"GiveUpReward" = "Покинуть"; +"ContinueWatching" = "Продолжить"; +"CanbeTurnedOffAfter" = "Можно пропустить через %d с"; +"CanbeSkipAfter" = "Пропустить через %d с."; +"Get" = "Скачать"; +"View" = "Вид"; +"ContinuePlaying" = "Продолжить просмотр"; +"GetRewardAfterPlaying" = "Завершите просмотр, чтобы получить награду"; +"Wan" = "10 тысяч"; +"ViewDetail" = "Вид"; +"CommitScore" = "Отзывы: %@"; +"AdsClosed" = "Объявления закрыты"; +"PrivacyPolicy" = "Политика конфиденциальности"; +"DisplayError" = "Ошибка отображения"; +"FeedbackExplaination" = "Введите описание ошибки отображения и нажмите кнопку «Отправить». Рекламный креатив также будет отправлен в Pangle в целях диагностики проблемы."; +"Submit" = "Отправить"; +"MutiNumAD" = "Реклама %d из %d"; diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/setup.txt b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/setup.txt new file mode 100644 index 0000000..ea75cb2 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/setup.txt @@ -0,0 +1 @@ +This text exists in 4300 and is the identifier in M ​​Access Rely library compatibility. Do not delete(请勿删除) diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/template.json b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/template.json new file mode 100644 index 0000000..d3f5a12 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/template.json @@ -0,0 +1 @@ + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/th.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/th.lproj/BULanguage.strings new file mode 100644 index 0000000..a7c8a5a --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/th.lproj/BULanguage.strings @@ -0,0 +1,46 @@ +/* + BULanguage.strings + BUAdSDK + + Created by wangyanlin on 2020/4/10. + Copyright © 2020 bytedance. All rights reserved. +*/ + +// String + +"Click" = "คลิก"; +"AD" = "โฆษณา"; +"PlayConsumed" = "การเล่นรายการนี้จะใช้อินเทอร์เน็ต %.2f MB"; +"Evaluation" = "การประเมินผล"; +"Score" = "%@ รีวิว"; +"Select" = "เลือก"; +"Back" = "ย้อนกลับ"; +"Replay" = "แตะเพื่อเล่นซ้ำ"; +"Continue" = "ดำเนินการต่อเพื่อเล่น"; +"Skip" = "ข้าม"; +"Feedback" = "คำติชม"; +"FeedbackStr1" = "ขอบคุณสำหรับคำติชม"; +"FeedbackStr2" = "เราจะปรับปรุงการให้บริการของเราต่อไป"; +"FeedbackStr3" = "คุณได้ส่งคำติชมมาแล้ว"; +"FeedbackStr4" = "คุณไม่จำเป็นต้องส่งอีกครั้ง"; +"ViewNow" = "ดูเลย"; +"Download" = "ดาวน์โหลดเลย"; +"LoadFailure" = "การโหลดล้มเหลว โปรดลองอีกครั้ง"; +"GetRewardAfterWatching" = "ดูวิดีโอให้จบเพื่อรับรางวัล"; +"GiveUpReward" = "ออก"; +"ContinueWatching" = "ดูต่อ"; +"CanbeTurnedOffAfter" = "ข้ามหลังจาก %d วิ"; +"CanbeSkipAfter" = "ข้ามหลังจาก %d วิ"; +"Get" = "ดาวน์โหลด"; +"View" = "ดู"; +"ContinuePlaying" = "เล่นต่อ"; +"GetRewardAfterPlaying" = "เล่นจนจบเพื่อรับรางวัล"; +"Wan" = "1 หมื่น"; +"ViewDetail" = "ดู"; +"CommitScore" = "%@ รีวิว"; +"AdsClosed" = "ปิดโฆษณา"; +"PrivacyPolicy" = "นโยบายความเป็นส่วนตัว"; +"DisplayError" = "ข้อผิดพลาดในการแสดงผล"; +"FeedbackExplaination" = "โปรดอธิบายข้อผิดพลาดในการแสดงผล และคลิกปุ่มส่ง โดยชิ้นงานโฆษณาจะถูกส่งกลับไปที่ Pangle เพื่อใช้ในการแก้ปัญหา"; +"Submit" = "ส่ง"; +"MutiNumAD" = "โฆษณา %d จาก %d"; diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/tr.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/tr.lproj/BULanguage.strings new file mode 100644 index 0000000..0b8f6ef --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/tr.lproj/BULanguage.strings @@ -0,0 +1,47 @@ +/* + BULanguage.strings + Pods + + Created by ByteDance on 2022/4/27. + +*/ + +// String + +"Click" = "Click"; +"AD" = "Reklamlar"; +"PlayConsumed" = "%.2fMB traffic will be consumed if you play it"; +"Evaluation" = "Evaluation"; +"Score" = "%@ inceleme"; +"Select" = "Seç"; +"Wan" = ""; +"Back" = "Geri"; +"Replay" = "Tekrar oynatmak için dokunun"; +"Continue" = "Continue to play"; +"Skip" = "Atla"; +"Feedback" = "Geri Bildirim"; +"FeedbackStr1" = "Geri bildiriminiz için teşekkürler!"; +"FeedbackStr2" = "Hizmetimizi iyileştirmeye devam edeceğiz."; +"FeedbackStr3" = "Geri bildirim gönderdiniz!"; +"FeedbackStr4" = "Lütfen tekrar göndermeyin."; +"ViewNow" = "Şimdi Görüntüle"; +"Download" = "Hemen İndir"; +"LoadFailure" = "Failed to load, and click to try again"; +"GetRewardAfterWatching" = "Ödülünüzü talep etmek için videonun tamamını izleyin"; +"GiveUpReward" = "Ayrıl"; +"ContinueWatching" = "Devam Et"; +"CanbeTurnedOffAfter" = "Skip after %ds"; +"CanbeSkipAfter" = "%d saniye sonra atla"; +"Get" = "Get"; +"View" = "View"; +"ContinuePlaying" = "Keep on"; +"GetRewardAfterPlaying" = "Finish playing to get rewards!"; +"ViewDetail" = "View"; +"CommitScore" = "%@ inceleme"; +"AdsClosed" = "Ads Closed"; +"PrivacyPolicy" = "Gizlilik Politikası"; +"DisplayError" = "Görüntü hatası"; +"FeedbackExplaination" = "Görüntü hatasının açıklamasını girin ve Gönder düğmesine tıklayın. Sorunun giderilmesine yardımcı olması için reklam kreatifi de Pangle'a geri gönderilecektir."; +"Submit" = "Gönder"; +"MutiNumAD" = "reklam %d / %d"; +// Icon diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/version.txt b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/version.txt new file mode 100644 index 0000000..61c0898 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/version.txt @@ -0,0 +1 @@ +6.0.0.4 diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/vi.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/vi.lproj/BULanguage.strings new file mode 100644 index 0000000..f3775cd --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/vi.lproj/BULanguage.strings @@ -0,0 +1,46 @@ +/* + BULanguage.strings + BUAdSDK + + Created by wangyanlin on 2020/4/10. + Copyright © 2020 bytedance. All rights reserved. +*/ + +// String + +"Click" = "Nhấp"; +"AD" = "Quảng cáo"; +"PlayConsumed" = "Bạn sẽ mất %.2f MB dữ liệu để phát mục này"; +"Evaluation" = "Đánh giá"; +"Score" = "%@ lượt đánh giá"; +"Select" = "Chọn"; +"Back" = "Quay lại"; +"Replay" = "Nhấn để phát lại"; +"Continue" = "Tiếp tục phát"; +"Skip" = "Bỏ qua"; +"Feedback" = "Phản hồi"; +"FeedbackStr1" = "Cảm ơn bạn đã phản hồi!"; +"FeedbackStr2" = "Chúng tôi sẽ không ngừng cải thiện dịch vụ."; +"FeedbackStr3" = "Bạn đã gửi phản hồi xong!"; +"FeedbackStr4" = "Vui lòng không gửi lại."; +"ViewNow" = "Xem ngay"; +"Download" = "Tải xuống ngay"; +"LoadFailure" = "Không tải được. Vui lòng thử lại."; +"GetRewardAfterWatching" = "Xem hết video để nhận phần thưởng"; +"GiveUpReward" = "Rời đi"; +"ContinueWatching" = "Tiếp tục"; +"CanbeTurnedOffAfter" = "Bỏ qua sau %d s"; +"CanbeSkipAfter" = "Bỏ qua sau %d giây"; +"Get" = "Tải"; +"View" = "Xem"; +"ContinuePlaying" = "Tiếp tục chơi"; +"GetRewardAfterPlaying" = "Chơi hết để giành phần thưởng"; +"Wan" = "10 nghìn"; +"ViewDetail" = "Xem"; +"CommitScore" = "%@ lượt đánh giá"; +"AdsClosed" = "Quảng cáo đã đóng"; +"PrivacyPolicy" = "Chính sách quyền riêng tư"; +"DisplayError" = "Lỗi hiển thị"; +"FeedbackExplaination" = "Nhập mô tả về lỗi hiển thị và nhấp vào nút Gửi. Mẫu quảng cáo cũng sẽ được gửi lại cho Pangle để hỗ trợ khắc phục sự cố."; +"Submit" = "Gửi"; +"MutiNumAD" = "quảng cáo %d/%d"; diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/zh-Hans.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/zh-Hans.lproj/BULanguage.strings new file mode 100644 index 0000000..0c2608e --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/zh-Hans.lproj/BULanguage.strings @@ -0,0 +1,47 @@ +/* + BULanguage.strings + BUAdSDK + + Created by 李盛 on 2019/1/7. + Copyright © 2019 bytedance. All rights reserved. +*/ + +// String + +"Click" = "点击"; +"AD" = "广告"; +"PlayConsumed" = "播放将消耗%.2fMB流量"; +"Evaluation" = "评价"; +"Score" = "%@个评分"; +"Select" = "选择"; +"Wan" = "万"; +"Back" = "返回"; +"Replay" = "点击重播"; +"Continue" = "继续播放"; +"Skip" = "跳过"; +"Feedback" = "反馈"; +"FeedbackStr1" = "感谢您的反馈!"; +"FeedbackStr2" = "我们将为您带来更优质的广告体验"; +"FeedbackStr3" = "您已提交过反馈!"; +"FeedbackStr4" = "请勿反复提交"; +"ViewNow" = "立即查看"; +"Download" = "立即下载"; +"LoadFailure" = "加载失败,点击重试"; +"GetRewardAfterWatching" = "观看完整视频才能获得奖励"; +"GiveUpReward" = "放弃奖励"; +"ContinueWatching" = "继续观看"; +"CanbeTurnedOffAfter" = "%ds后可关闭"; +"CanbeSkipAfter" = "广告在%ds后可跳过"; +"Get" = "立即下载"; +"View" = "立即查看"; +"ContinuePlaying" = "继续试玩"; +"GetRewardAfterPlaying" = "试玩后才可领取奖励"; +"ViewDetail" = "查看详情"; +"CommitScore" = "%@个评分"; +"AdsClosed" = "广告已关闭"; +"PrivacyPolicy" = "隐私政策"; +"DisplayError" = "显示异常"; +"FeedbackExplaination" = "请填写广告显示异常的描述,并点击提交按钮进行提交,同时我们会附带该广告素材信息一起回传以便于Pangle排查问题"; +"Submit" = "提交"; +"MutiNumAD" = "广告 %d/%d"; +// Icon diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.bundle/zh-Hant.lproj/BULanguage.strings b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/zh-Hant.lproj/BULanguage.strings new file mode 100644 index 0000000..33d220f --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.bundle/zh-Hant.lproj/BULanguage.strings @@ -0,0 +1,46 @@ +/* + BULanguage.strings + BUAdSDK + + Created by wangyanlin on 2020/4/10. + Copyright © 2020 bytedance. All rights reserved. +*/ + +// String + +"Click" = "點擊"; +"AD" = "廣告"; +"PlayConsumed" = "播放將消耗%.2fMB流量"; +"Evaluation" = "評估"; +"Score" = "%@個評分"; +"Select" = "選擇"; +"Back" = "返回"; +"Replay" = "點擊重播"; +"Continue" = "繼續播放"; +"Skip" = "跳過"; +"Feedback" = "迴響"; +"FeedbackStr1" = "感謝您的迴響!"; +"FeedbackStr2" = "我們將為您帶來更優質的廣告體驗"; +"FeedbackStr3" = "您已提交過迴響!"; +"FeedbackStr4" = "請勿反復提交"; +"ViewNow" = "立即查看"; +"Download" = "立即下載"; +"LoadFailure" = "加載失敗,點擊重試"; +"GetRewardAfterWatching" = "觀看完整視頻才能獲得獎勵"; +"GiveUpReward" = "放弃獎勵"; +"ContinueWatching" = "繼續觀看"; +"CanbeTurnedOffAfter" = "%ds後可關閉"; +"CanbeSkipAfter" = "廣告在%ds後可跳過"; +"Get" = "下載"; +"View" = "查看"; +"ContinuePlaying" = "繼續試玩"; +"GetRewardAfterPlaying" = "試玩後才可領取獎勵"; +"Wan" = "萬"; +"ViewDetail" = "查看詳情"; +"CommitScore" = "%@個評分"; +"AdsClosed" = "廣告已關閉"; +"PrivacyPolicy" = "隱私政策"; +"DisplayError" = "顯示錯誤"; +"FeedbackExplaination" = "輸入所顯示錯誤的描述,然後按下「提交」按鈕。系統也會將廣告創意傳送回Pangle以協助解決問題。"; +"Submit" = "提交"; +"MutiNumAD" = "第 %d 則廣告,共 %d 則"; diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/Info.plist b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/Info.plist new file mode 100644 index 0000000..5de733f --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/Info.plist @@ -0,0 +1,40 @@ + + + + + AvailableLibraries + + + LibraryIdentifier + ios-arm64 + LibraryPath + PAGAdSDK.framework + SupportedArchitectures + + arm64 + + SupportedPlatform + ios + + + LibraryIdentifier + ios-arm64_x86_64-simulator + LibraryPath + PAGAdSDK.framework + SupportedArchitectures + + arm64 + x86_64 + + SupportedPlatform + ios + SupportedPlatformVariant + simulator + + + CFBundlePackageType + XFWK + XCFrameworkFormatVersion + 1.0 + + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Headers b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Headers new file mode 120000 index 0000000..a177d2a --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Headers @@ -0,0 +1 @@ +Versions/Current/Headers \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Modules/module.modulemap b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Modules/module.modulemap new file mode 100644 index 0000000..c7d7a49 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module PAGAdSDK { + umbrella header "PAGAdSDK.h" + + export * + module * { export * } +} diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/PAGAdSDK b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/PAGAdSDK new file mode 120000 index 0000000..b2a845f --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/PAGAdSDK @@ -0,0 +1 @@ +Versions/Current/PAGAdSDK \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/PrivacyInfo.xcprivacy b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..56244f1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/PrivacyInfo.xcprivacy @@ -0,0 +1,127 @@ + + + + + NSPrivacyCollectedDataTypes + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeUserID + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeDeviceID + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeAdvertisingData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeCrashData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypePerformanceData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeCoarseLocation + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeOtherDataTypes + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryDiskSpace + NSPrivacyAccessedAPITypeReasons + + 7D9E.1 + E174.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Resources b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Resources new file mode 120000 index 0000000..953ee36 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Resources @@ -0,0 +1 @@ +Versions/Current/Resources \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdClientBiddingProtocol.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdClientBiddingProtocol.h new file mode 100644 index 0000000..66fb4fb --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdClientBiddingProtocol.h @@ -0,0 +1,24 @@ +// +// PAGAdClientBiddingProtocol.h +// Pods +// +// Created by bytedance on 2021/9/14. +// + +#import + +@protocol PAGAdClientBiddingProtocol + +@optional + +/// invoke this method when the bidding succeeds (strongly recommended) 当竞价成功调用此方法(强烈推荐) +/// @param auctionBidToWin the seccond place bidder's price 竞价方第二名的价格 +- (void)win:(nullable NSNumber*)auctionBidToWin; + +/// invoke this method when the bidding fails (strongly recommended) 当竞价失败调用此方法(强烈推荐) +/// @param auctionPrice auction price 竞价 +/// @param lossReason Reasons for failed bidding 失败的原因 +/// @param winBidder Who won the bid 谁赢了竞价 +- (void)loss:(nullable NSNumber*)auctionPrice lossReason:(nullable NSString*)lossReason winBidder:(nullable NSString*)winBidder; + +@end diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdDelegate.h new file mode 100644 index 0000000..d3e0612 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdDelegate.h @@ -0,0 +1,32 @@ +// +// PAGADDelegate.h +// PAGAdSDK +// +// Created by bytedance on 2022/4/7. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGAdProtocol; + +@protocol PAGAdDelegate + +@optional + +/// This method is called when the ad has been shown +- (void)adDidShow:(id)ad; + +/// This method is called when the add has been clicked +- (void)adDidClick:(id)ad; + +///This method is called when the ad has been dismissed. +- (void)adDidDismiss:(id)ad; + +///This method is called when the ad has been show fail +- (void)adDidShowFail:(id)ad error:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdProtocol.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdProtocol.h new file mode 100644 index 0000000..8666dae --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdProtocol.h @@ -0,0 +1,19 @@ +// +// PAGAdProtocol.h +// PangleSDK +// +// Created by bytedance on 2022/4/7. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGAdProtocol + +/// return extra info +- (nullable NSDictionary *)getMediaExtraInfo; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdPublicDefine.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdPublicDefine.h new file mode 100644 index 0000000..ec23206 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdPublicDefine.h @@ -0,0 +1,18 @@ +// +// PAGAdPublicDefine.h +// Pods +// +// Created by bytedance on 2022/5/16. +// + +#ifndef PAGAdPublicDefine_h +#define PAGAdPublicDefine_h + +FOUNDATION_EXPORT NSString * const PAGAdSDKErrorDomain; + +typedef NS_ENUM(NSUInteger, PAGAdErrorCode) { + PAGAdErrorCodeSlotIdNil = 1, + PAGAdErrorCodeRequestNil = 2, +}; + +#endif /* PAGAdPublicDefine_h */ diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdSDK.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdSDK.h new file mode 100644 index 0000000..acd94ec --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdSDK.h @@ -0,0 +1,40 @@ +// +// PAGAdSDK.h +// PAGAdSDK +// +// Copyright © 2017年 bytedance. All rights reserved. +// + +#import +// In this header, you should import all the public headers of your framework using statements like #import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdSize.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdSize.h new file mode 100644 index 0000000..3c97830 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAdSize.h @@ -0,0 +1,19 @@ +// +// PAGAdSize.h +// PangleAPI +// +// Created by bytedance on 2022/2/25. +// + +#import + +struct PAGAdSize { + CGSize size; +}; + +typedef struct PAGAdSize PAGBannerAdSize; + +CG_EXTERN PAGBannerAdSize const kPAGBannerSize320x50; +CG_EXTERN PAGBannerAdSize const kPAGBannerSize300x250; +/// Only for iPad banner ad +CG_EXTERN PAGBannerAdSize const kPAGBannerSize728x90; diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAppOpenRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAppOpenRequest.h new file mode 100644 index 0000000..a815284 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGAppOpenRequest.h @@ -0,0 +1,22 @@ +// +// PAGAppOpenRequest.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/26. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGAppOpenRequest : PAGRequest + + +/// If the ad data is not successfully loaded within the timeout period, +/// a timeout error from the invoked completion handler will be non-nil. +/// default is 3.5s +@property (nonatomic, assign) NSTimeInterval timeout; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAd.h new file mode 100644 index 0000000..99626a4 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAd.h @@ -0,0 +1,47 @@ +// +// PAGBannerAd.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" +#import "PAGBannerAdDelegate.h" +#import "PAGBannerRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGBannerAd; + +/// Callback for loading ad results. +/// @param bannerAd Ad instance after successfully loaded which will be non-nil on success. +/// @param error Loading error which will be non-nil on fail. +typedef void (^PAGBannerADLoadCompletionHandler)(PAGBannerAd * _Nullable bannerAd, + NSError * _Nullable error); + +@interface PAGBannerAd : NSObject + +/// Ad event delegate. +@property (nonatomic, weak, nullable) id delegate; +/// View of the banner ad. +@property (nonatomic, strong, readonly) UIView *bannerView; +/// View controller the banner ad will be presented on. +@property (nonatomic, weak, readwrite) UIViewController *rootViewController; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load banner ad +/// @param slotID Required. The unique identifier of banner ad. +/// @param request Required. An instance of a banner ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGBannerRequest *)request + completionHandler:(PAGBannerADLoadCompletionHandler)completionHandler; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAdDelegate.h new file mode 100644 index 0000000..9675163 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAdDelegate.h @@ -0,0 +1,18 @@ +// +// PAGBannerADDelegate.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGBannerAd; + +@protocol PAGBannerAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerRequest.h new file mode 100644 index 0000000..42bbbe1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGBannerRequest.h @@ -0,0 +1,20 @@ +// +// PAGBannerRequest.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGRequest.h" +#import "PAGAdSize.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGBannerRequest : PAGRequest + ++(instancetype)request UNAVAILABLE_ATTRIBUTE; ++ (instancetype)requestWithBannerSize:(PAGBannerAdSize)bannerSize; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGConfig.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGConfig.h new file mode 100644 index 0000000..977ea95 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGConfig.h @@ -0,0 +1,78 @@ +// +// PAGConfig.h +// PAGAdSDK +// +// Created by bytedance on 2022/5/9. +// + +#import + +typedef NS_ENUM(NSInteger, PAGAdSDKThemeStatus) { + PAGAdSDKThemeStatus_Normal = 0, //Light mode + PAGAdSDKThemeStatus_Night = 1, //Dark mode +}; + +typedef NS_ENUM(NSInteger, PAGChildDirectedType) { + PAGChildDirectedTypeDefault = -1,//default + PAGChildDirectedTypeNonChild = 0,// user is not a child + PAGChildDirectedTypeChild = 1,// user is a child +}; + +typedef NS_ENUM(NSInteger, PAGDoNotSellType) { + PAGDoNotSellTypeDefault = -1,//default + PAGDoNotSellTypeSell = 0,//“sale” of personal information is permitted + PAGDoNotSellTypeNotSell = 1,//user has opted out of “sale” of personal information +}; + +typedef NS_ENUM(NSInteger, PAGGDPRConsentType) { + PAGGDPRConsentTypeDefault = -1,//default + PAGGDPRConsentTypeNoConsent = 0,//user did not consent + PAGGDPRConsentTypeConsent = 1,//user provided consent +}; + +NS_ASSUME_NONNULL_BEGIN + +///Pangle SDK configuration class +@interface PAGConfig : NSObject + +///appId the unique identifier of the App +///@warning required +@property (nonatomic, copy) NSString *appID; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; +/// Initialization method of PAGConfig ++ (instancetype)shareConfig; + +@end + +@interface PAGConfig (Settings) + +///Set the COPPA of the user, COPPA is the short of Children's Online Privacy Protection Rule, the interface only works in the United States. +@property (nonatomic, assign) PAGChildDirectedType childDirected; + +///Custom set the GDPR of the user,GDPR is the short of General Data Protection Regulation,the interface only works in The European. +@property (nonatomic, assign) PAGGDPRConsentType GDPRConsent; + +/// Custom set the CCPA of the user,CCPA is the short of General Data Protection Regulation,the interface only works in USA. +@property (nonatomic, assign) PAGDoNotSellType doNotSell; + +@property (nonatomic, assign) PAGAdSDKThemeStatus themeStatus; + +/// Custom set the debugLog to print debug Log. +/// debugLog NO: close debug log, YES: open debug log. +@property (nonatomic, assign) BOOL debugLog; + +/// App logo image. If set, it will be displayed in the App open ad. +@property (nonatomic, strong, nullable) UIImage *appLogoImage; + +/// additional user information. +@property (nonatomic, copy) NSString *userDataString; + +///Whether to allow SDK to modify the category and options of AVAudioSession when playing audio, default is NO. +///The category set by the SDK is AVAudioSessionCategoryAmbient, and the options are AVAudioSessionCategoryOptionDuckOthers +@property (nonatomic, assign) BOOL allowModifyAudioSessionSetting; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGInterstitialRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGInterstitialRequest.h new file mode 100644 index 0000000..8c29af1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGInterstitialRequest.h @@ -0,0 +1,16 @@ +// +// PAGInterstitialRequest.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGInterstitialRequest : PAGRequest + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAd.h new file mode 100644 index 0000000..563fa4b --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAd.h @@ -0,0 +1,48 @@ +// +// PAGLAppOpenAd.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/26. +// +#import +#import "PAGLAppOpenAdDelegate.h" +#import "PAGAppOpenRequest.h" +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLAppOpenAd; + +/// Callback for loading ad results. +/// @param appOpenAd Ad instance after successfully loaded. +/// @param error Loading error. +typedef void (^PAGAppOpenADLoadCompletionHandler)(PAGLAppOpenAd * _Nullable appOpenAd, + NSError * _Nullable error); + +@interface PAGLAppOpenAd : NSObject + +/// Ad event delegate. +@property (nonatomic, weak, nullable) id delegate; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load open ad +/// @param slotID Required. The unique identifier of open ad. +/// @param request Required. An instance of an open ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGAppOpenRequest *)request + completionHandler:(PAGAppOpenADLoadCompletionHandler)completionHandler; + + +/// Present the open ad +/// @param rootViewController View controller the open ad will be presented on. +/// @warning This method must be called on the main thread. +- (void)presentFromRootViewController:(UIViewController *)rootViewController; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAdDelegate.h new file mode 100644 index 0000000..5b86b62 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAdDelegate.h @@ -0,0 +1,18 @@ +// +// PAGLAppOpenAdDelegate.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/26. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLAppOpenAd; + +@protocol PAGLAppOpenAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLImage.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLImage.h new file mode 100644 index 0000000..2d6bf3f --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLImage.h @@ -0,0 +1,24 @@ +// +// PAGLImage.h +// PAGAdSDK +// +// Created by Willie on 2022/5/5. +// + +NS_ASSUME_NONNULL_BEGIN + +/// A class that encapsulates image information +@interface PAGLImage : NSObject + +/// image address URL +@property (nonatomic, copy, readonly) NSString *imageURL; + +/// image width +@property (nonatomic, assign, readonly) CGFloat width; + +/// image height +@property (nonatomic, assign, readonly) CGFloat height; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAd.h new file mode 100644 index 0000000..d51bf59 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAd.h @@ -0,0 +1,49 @@ +// +// PAGLInterstitialAd.h +// PangleAPI +// +// Created by bytedance on 2022/2/25. +// + +#import +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" +#import "PAGLInterstitialAdDelegate.h" +#import "PAGInterstitialRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLInterstitialAd; + +/// Callback for loading interstitial results. +/// @param interstitialAd Ad instance after successfully loaded which will be non-nil on success. +/// @param error Loading error which will be non-nil on fail. +typedef void (^PAGInterstitialAdLoadCompletionHandler)(PAGLInterstitialAd * _Nullable interstitialAd, + NSError * _Nullable error); + +@interface PAGLInterstitialAd : NSObject + +/// Ad event delegate. +@property(nonatomic, weak, nullable) id delegate; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load interstitial ad +/// @param slotID Required. The unique identifier of interstitial ad. +/// @param request Required. An instance of an interstitial ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGInterstitialRequest *)request + completionHandler:(PAGInterstitialAdLoadCompletionHandler)completionHandler; + + +/// Present the interstitial ad +/// @param rootViewController View controller the interstitial ad will be presented on. +/// @warning This method must be called on the main thread. +- (void)presentFromRootViewController:(UIViewController *)rootViewController; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAdDelegate.h new file mode 100644 index 0000000..5e87f7d --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAdDelegate.h @@ -0,0 +1,18 @@ +// +// PAGLInterstitialAdDelegate.h +// PangleAPI +// +// Created by bytedance on 2022/2/25. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLInterstitialAd; + +@protocol PAGLInterstitialAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLMaterialMeta.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLMaterialMeta.h new file mode 100644 index 0000000..27506b2 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLMaterialMeta.h @@ -0,0 +1,38 @@ +// +// PAGLMaterialMeta.h +// PAGAdSDK +// +// Created by Willie on 2022/5/5. +// + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLImage; + +/// media type of ad +typedef NS_ENUM(NSUInteger, PAGLNativeMediaType) { + PAGLNativeMediaTypeImage = 1, // image ad + PAGLNativeMediaTypeVideo = 2, // video ad +}; + +/// A class that encapsulates advertising information +@interface PAGLMaterialMeta : NSObject + +/// ad logo icon. +@property (nonatomic, strong, readonly) PAGLImage *icon; + +/// ad headline. +@property (nonatomic, copy, readonly) NSString *AdTitle; + +/// ad description. +@property (nonatomic, copy, readonly) NSString *AdDescription; + +/// text displayed on the creative button. +@property (nonatomic, copy, readonly) NSString *buttonText; + +/// media type of ad +@property (nonatomic, assign, readonly) PAGLNativeMediaType mediaType; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAd.h new file mode 100644 index 0000000..9c9166c --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAd.h @@ -0,0 +1,61 @@ +// +// PAGLNativeAd.h +// PAGAdSDK +// +// Created by Willie on 2022/3/1. +// + +#import + +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLNativeAd, PAGLMaterialMeta, PAGNativeRequest; +@protocol PAGLNativeAdDelegate; + +typedef void (^PAGNativeADLoadCompletionHandler)(PAGLNativeAd * _Nullable nativeAd, + NSError * _Nullable error); + +/// Abstract ad slot containing ad data loading, response callbacks. +@interface PAGLNativeAd : NSObject + +/// Ad material. +@property (nonatomic, strong, readonly) PAGLMaterialMeta *data; + +/// The delegate for receiving state change messages. +/// The delegate is not limited to viewcontroller. +/// The delegate can be set to any object which conforming to . +@property (nonatomic, weak, nullable) id delegate; + +/// required. +/// Root view controller for handling ad actions. +/// Action method includes is 'presentViewController'. +@property (nonatomic, weak) UIViewController *rootViewController; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + +/// Actively request nativeAd datas. +/// @param slotID required. The unique identifier of a native ad. +/// @param request required. PAGNativeRequest instance. +/// @param completionHandler required. Callback when ad is loaded. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGNativeRequest *)request + completionHandler:(PAGNativeADLoadCompletionHandler)completionHandler; + +/// Register clickable views in native ads view. +/// Interaction types can be configured on TikTok Audience Network. +/// Interaction types include view video ad details page, open the webpage using a browser, open the webpage within the app, etc. +/// @param containerView required. Container view of the native ad. +/// @param clickableViews optional. Array of views that are clickable. +- (void)registerContainer:(__kindof UIView *)containerView + withClickableViews:(NSArray<__kindof UIView *> *_Nullable)clickableViews; + +/// Unregister ad view from the native ad. +- (void)unregisterView; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdDelegate.h new file mode 100644 index 0000000..251360e --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdDelegate.h @@ -0,0 +1,16 @@ +// +// PAGLNativeAdDelegate.h +// PAGAdSDK +// +// Created by Willie on 2022/3/1. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGLNativeAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdRelatedView.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdRelatedView.h new file mode 100644 index 0000000..fbd3966 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdRelatedView.h @@ -0,0 +1,35 @@ +// +// PAGLNativeAdRelatedView.h +// PAGAdSDK +// +// Created by Willie on 2022/4/6. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class PAGMediaView, PAGLNativeAd; + +/// A class that encapsulates a fixed ad style +@interface PAGLNativeAdRelatedView : NSObject + +/// Need to actively add to the view in order to deal with the feedback and improve the accuracy of ad. +@property (nonatomic, strong, readonly) UIButton *dislikeButton; + +/// Ad logo + Promotion label.Need to actively add to the view. +@property (nonatomic, strong, readonly) UIImageView *logoADImageView; + +/// dsp logo.Need to actively add to the view. +@property (nonatomic, strong, readonly) UIImageView *adChoicesView; + +/// A view used to display a video or image, which can be added directly to the ad view. +@property (nonatomic, strong, readonly) PAGMediaView *mediaView; + +/// Refresh the data every time you get new datas in order to show ad perfectly. +/// @param nativeAd PAGLNativeAd instance. +- (void)refreshWithNativeAd:(PAGLNativeAd *)nativeAd; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGMAdNetworkExtras.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGMAdNetworkExtras.h new file mode 100644 index 0000000..54bd21d --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGMAdNetworkExtras.h @@ -0,0 +1,12 @@ +// +// PAGMNetworkExtras.h +// PAGAdSDK +// +// Created by bytedance on 2022/11/8. +// + +#import + +@protocol PAGMAdNetworkExtras + +@end diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGMediaView.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGMediaView.h new file mode 100644 index 0000000..1650d00 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGMediaView.h @@ -0,0 +1,15 @@ +// +// PAGMediaView.h +// PAGAdSDK +// +// Created by Willie on 2022/4/7. +// + +NS_ASSUME_NONNULL_BEGIN + +/// A view that wraps a fixed ad style to display an image or video +@interface PAGMediaView : UIView + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGNativeRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGNativeRequest.h new file mode 100644 index 0000000..49fe087 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGNativeRequest.h @@ -0,0 +1,16 @@ +// +// PAGNativeRequest.h +// PAGAdSDK +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGNativeRequest : PAGRequest + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRequest.h new file mode 100644 index 0000000..bae3fc6 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRequest.h @@ -0,0 +1,28 @@ +// +// PAGRequest.h +// PAGAdSDK +// +// Created by bytedance on 2022/3/22. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGMAdNetworkExtras; +@interface PAGRequest : NSObject + +/// Ad string that represents an ad response. The SDK will render this ad and ignore all other +/// targeting information set on this request. +@property (nonatomic, copy) NSString *adString; + +/// extra info +@property (nonatomic, copy, nullable) NSDictionary *extraInfo; + ++ (instancetype)request; + +- (void)registerAdNetworkExtras:(id)extras; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardModel.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardModel.h new file mode 100644 index 0000000..3c78409 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardModel.h @@ -0,0 +1,23 @@ +// +// PAGRewardedModel.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGRewardModel : NSObject + +//奖励名称 +@property (nonatomic, copy, readonly) NSString *rewardName; +//奖励钱数 +@property (nonatomic, assign, readonly) NSInteger rewardAmount; + +- (instancetype)initWithRewardName:(NSString *)rewardName rewardAmount:(NSInteger)rewardAmount; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAd.h new file mode 100644 index 0000000..941f3b1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAd.h @@ -0,0 +1,49 @@ +// +// PAGRewardedAd.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" +#import "PAGRewardedAdDelegate.h" +#import "PAGRewardedRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGRewardedAd; +/// Callback for loading ad results. +/// @param rewardedAd Ad instance after successfully loaded which will be non-nil on success. +/// @param error Loading error which will be non-nil on fail. +typedef void (^PAGRewardedAdLoadCompletionHandler)(PAGRewardedAd * _Nullable rewardedAd, + NSError * _Nullable error); + +@interface PAGRewardedAd : NSObject + +/// Ad event delegate. +@property (nonatomic, weak, nullable) id delegate; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load rewarded ad +/// @param slotID Required. The unique identifier of rewarded ad. +/// @param request Required. An instance of a rewarded ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGRewardedRequest *)request + completionHandler:(PAGRewardedAdLoadCompletionHandler)completionHandler; + + +/// Present the rewarded ad +/// @param rootViewController View controller the rewarded ad will be presented on. +/// @warning This method must be called on the main thread. +- (void)presentFromRootViewController:(UIViewController *)rootViewController; + +@end + +NS_ASSUME_NONNULL_END + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAdDelegate.h new file mode 100644 index 0000000..b71f2f0 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAdDelegate.h @@ -0,0 +1,32 @@ +// +// PAGRewardedAdDelegate.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGRewardedAd; +@class PAGRewardModel; + +@protocol PAGRewardedAdDelegate + +@optional + +/// Tells the delegate that the user has earned the reward. +/// @param rewardedAd rewarded ad instance +/// @param rewardModel user's reward info +- (void)rewardedAd:(PAGRewardedAd *)rewardedAd userDidEarnReward:(PAGRewardModel *)rewardModel; + + +/// Tells the delegate that the user failed to earn the reward. +/// @param rewardedAd rewarded ad instance +/// @param error failed reson +- (void)rewardedAd:(PAGRewardedAd *)rewardedAd userEarnRewardFailWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedRequest.h new file mode 100644 index 0000000..bd32306 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedRequest.h @@ -0,0 +1,16 @@ +// +// PAGRewardedRequest.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGRewardedRequest : PAGRequest + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGSdk.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGSdk.h new file mode 100644 index 0000000..2e61d47 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/Headers/PAGSdk.h @@ -0,0 +1,51 @@ +// +// PAGSdk.h +// PAGAdSDK +// +// Created by bytedance on 2022/5/9. +// + +#import +#import "PAGConfig.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, PAGSDKInitializationState) { + PAGSDKInitializationStateNotReady = 0, + PAGSDKInitializationStateReady = 1 +}; + +typedef void (^PAGAdsCompletionHandler)(BOOL success, NSError * __nullable error); + +@interface PAGSdk : NSObject + +/// Pangle SDK version +@property (nonatomic, copy, readonly, class) NSString *SDKVersion; + +/// The SDK initialization state +@property (nonatomic, assign, readonly, class) PAGSDKInitializationState initializationState; + +/// Starts the Pangle SDK +/// @warning Call this method as early as possible to reduce ad request fail. +/// @param config SDK configuration +/// @param completionHandler Callback for starting the Pangle SDK ++ (void)startWithConfig:(PAGConfig *)config completionHandler:(nullable PAGAdsCompletionHandler)completionHandler; + +/// Get bidding token +/// @param slotID the unique identifier of ad. +/// @note This method recommend called on the sub thread. ++ (NSString *)getBiddingToken:(nullable NSString *)slotID; + +/// Get bidding token asynchronously +/// @param slotID the unique identifier of ad. +/// @param completion Callback to return the bidding token. ++ (void)getBiddingToken:(nullable NSString *)slotID completion:(void (^)(NSString * biddingToken))completion; + +/// Set a ad revenue info obtained from mediation. +/// You can get sample code from the Pangle platform to learn how to use this method. +/// @param adRevenue Assemble a dictionary of ad revenue info. ++ (void)setAdRevenue:(NSDictionary *)adRevenue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/PAGAdSDK b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/PAGAdSDK new file mode 100644 index 0000000..2820013 Binary files /dev/null and b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/A/PAGAdSDK differ diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/Current b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/Current new file mode 120000 index 0000000..8c7e5a6 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64/PAGAdSDK.framework/Versions/Current @@ -0,0 +1 @@ +A \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Headers b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Headers new file mode 120000 index 0000000..a177d2a --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Headers @@ -0,0 +1 @@ +Versions/Current/Headers \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Modules/module.modulemap b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Modules/module.modulemap new file mode 100644 index 0000000..c7d7a49 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Modules/module.modulemap @@ -0,0 +1,6 @@ +framework module PAGAdSDK { + umbrella header "PAGAdSDK.h" + + export * + module * { export * } +} diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/PAGAdSDK b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/PAGAdSDK new file mode 120000 index 0000000..b2a845f --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/PAGAdSDK @@ -0,0 +1 @@ +Versions/Current/PAGAdSDK \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/PrivacyInfo.xcprivacy b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..56244f1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/PrivacyInfo.xcprivacy @@ -0,0 +1,127 @@ + + + + + NSPrivacyCollectedDataTypes + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeUserID + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeDeviceID + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeAdvertisingData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeCrashData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypePerformanceData + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeCoarseLocation + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeAnalytics + NSPrivacyCollectedDataTypePurposeAppFunctionality + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyCollectedDataType + NSPrivacyCollectedDataTypeOtherDataTypes + NSPrivacyCollectedDataTypeLinked + + NSPrivacyCollectedDataTypeTracking + + NSPrivacyCollectedDataTypePurposes + + NSPrivacyCollectedDataTypePurposeThirdPartyAdvertising + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryFileTimestamp + NSPrivacyAccessedAPITypeReasons + + C617.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryDiskSpace + NSPrivacyAccessedAPITypeReasons + + 7D9E.1 + E174.1 + + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Resources b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Resources new file mode 120000 index 0000000..953ee36 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Resources @@ -0,0 +1 @@ +Versions/Current/Resources \ No newline at end of file diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdClientBiddingProtocol.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdClientBiddingProtocol.h new file mode 100644 index 0000000..66fb4fb --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdClientBiddingProtocol.h @@ -0,0 +1,24 @@ +// +// PAGAdClientBiddingProtocol.h +// Pods +// +// Created by bytedance on 2021/9/14. +// + +#import + +@protocol PAGAdClientBiddingProtocol + +@optional + +/// invoke this method when the bidding succeeds (strongly recommended) 当竞价成功调用此方法(强烈推荐) +/// @param auctionBidToWin the seccond place bidder's price 竞价方第二名的价格 +- (void)win:(nullable NSNumber*)auctionBidToWin; + +/// invoke this method when the bidding fails (strongly recommended) 当竞价失败调用此方法(强烈推荐) +/// @param auctionPrice auction price 竞价 +/// @param lossReason Reasons for failed bidding 失败的原因 +/// @param winBidder Who won the bid 谁赢了竞价 +- (void)loss:(nullable NSNumber*)auctionPrice lossReason:(nullable NSString*)lossReason winBidder:(nullable NSString*)winBidder; + +@end diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdDelegate.h new file mode 100644 index 0000000..d3e0612 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdDelegate.h @@ -0,0 +1,32 @@ +// +// PAGADDelegate.h +// PAGAdSDK +// +// Created by bytedance on 2022/4/7. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGAdProtocol; + +@protocol PAGAdDelegate + +@optional + +/// This method is called when the ad has been shown +- (void)adDidShow:(id)ad; + +/// This method is called when the add has been clicked +- (void)adDidClick:(id)ad; + +///This method is called when the ad has been dismissed. +- (void)adDidDismiss:(id)ad; + +///This method is called when the ad has been show fail +- (void)adDidShowFail:(id)ad error:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdProtocol.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdProtocol.h new file mode 100644 index 0000000..8666dae --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdProtocol.h @@ -0,0 +1,19 @@ +// +// PAGAdProtocol.h +// PangleSDK +// +// Created by bytedance on 2022/4/7. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGAdProtocol + +/// return extra info +- (nullable NSDictionary *)getMediaExtraInfo; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdPublicDefine.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdPublicDefine.h new file mode 100644 index 0000000..ec23206 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdPublicDefine.h @@ -0,0 +1,18 @@ +// +// PAGAdPublicDefine.h +// Pods +// +// Created by bytedance on 2022/5/16. +// + +#ifndef PAGAdPublicDefine_h +#define PAGAdPublicDefine_h + +FOUNDATION_EXPORT NSString * const PAGAdSDKErrorDomain; + +typedef NS_ENUM(NSUInteger, PAGAdErrorCode) { + PAGAdErrorCodeSlotIdNil = 1, + PAGAdErrorCodeRequestNil = 2, +}; + +#endif /* PAGAdPublicDefine_h */ diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdSDK.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdSDK.h new file mode 100644 index 0000000..acd94ec --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdSDK.h @@ -0,0 +1,40 @@ +// +// PAGAdSDK.h +// PAGAdSDK +// +// Copyright © 2017年 bytedance. All rights reserved. +// + +#import +// In this header, you should import all the public headers of your framework using statements like #import + +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import +#import diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdSize.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdSize.h new file mode 100644 index 0000000..3c97830 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAdSize.h @@ -0,0 +1,19 @@ +// +// PAGAdSize.h +// PangleAPI +// +// Created by bytedance on 2022/2/25. +// + +#import + +struct PAGAdSize { + CGSize size; +}; + +typedef struct PAGAdSize PAGBannerAdSize; + +CG_EXTERN PAGBannerAdSize const kPAGBannerSize320x50; +CG_EXTERN PAGBannerAdSize const kPAGBannerSize300x250; +/// Only for iPad banner ad +CG_EXTERN PAGBannerAdSize const kPAGBannerSize728x90; diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAppOpenRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAppOpenRequest.h new file mode 100644 index 0000000..a815284 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGAppOpenRequest.h @@ -0,0 +1,22 @@ +// +// PAGAppOpenRequest.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/26. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGAppOpenRequest : PAGRequest + + +/// If the ad data is not successfully loaded within the timeout period, +/// a timeout error from the invoked completion handler will be non-nil. +/// default is 3.5s +@property (nonatomic, assign) NSTimeInterval timeout; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAd.h new file mode 100644 index 0000000..99626a4 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAd.h @@ -0,0 +1,47 @@ +// +// PAGBannerAd.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" +#import "PAGBannerAdDelegate.h" +#import "PAGBannerRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGBannerAd; + +/// Callback for loading ad results. +/// @param bannerAd Ad instance after successfully loaded which will be non-nil on success. +/// @param error Loading error which will be non-nil on fail. +typedef void (^PAGBannerADLoadCompletionHandler)(PAGBannerAd * _Nullable bannerAd, + NSError * _Nullable error); + +@interface PAGBannerAd : NSObject + +/// Ad event delegate. +@property (nonatomic, weak, nullable) id delegate; +/// View of the banner ad. +@property (nonatomic, strong, readonly) UIView *bannerView; +/// View controller the banner ad will be presented on. +@property (nonatomic, weak, readwrite) UIViewController *rootViewController; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load banner ad +/// @param slotID Required. The unique identifier of banner ad. +/// @param request Required. An instance of a banner ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGBannerRequest *)request + completionHandler:(PAGBannerADLoadCompletionHandler)completionHandler; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAdDelegate.h new file mode 100644 index 0000000..9675163 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerAdDelegate.h @@ -0,0 +1,18 @@ +// +// PAGBannerADDelegate.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGBannerAd; + +@protocol PAGBannerAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerRequest.h new file mode 100644 index 0000000..42bbbe1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGBannerRequest.h @@ -0,0 +1,20 @@ +// +// PAGBannerRequest.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGRequest.h" +#import "PAGAdSize.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGBannerRequest : PAGRequest + ++(instancetype)request UNAVAILABLE_ATTRIBUTE; ++ (instancetype)requestWithBannerSize:(PAGBannerAdSize)bannerSize; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGConfig.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGConfig.h new file mode 100644 index 0000000..977ea95 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGConfig.h @@ -0,0 +1,78 @@ +// +// PAGConfig.h +// PAGAdSDK +// +// Created by bytedance on 2022/5/9. +// + +#import + +typedef NS_ENUM(NSInteger, PAGAdSDKThemeStatus) { + PAGAdSDKThemeStatus_Normal = 0, //Light mode + PAGAdSDKThemeStatus_Night = 1, //Dark mode +}; + +typedef NS_ENUM(NSInteger, PAGChildDirectedType) { + PAGChildDirectedTypeDefault = -1,//default + PAGChildDirectedTypeNonChild = 0,// user is not a child + PAGChildDirectedTypeChild = 1,// user is a child +}; + +typedef NS_ENUM(NSInteger, PAGDoNotSellType) { + PAGDoNotSellTypeDefault = -1,//default + PAGDoNotSellTypeSell = 0,//“sale” of personal information is permitted + PAGDoNotSellTypeNotSell = 1,//user has opted out of “sale” of personal information +}; + +typedef NS_ENUM(NSInteger, PAGGDPRConsentType) { + PAGGDPRConsentTypeDefault = -1,//default + PAGGDPRConsentTypeNoConsent = 0,//user did not consent + PAGGDPRConsentTypeConsent = 1,//user provided consent +}; + +NS_ASSUME_NONNULL_BEGIN + +///Pangle SDK configuration class +@interface PAGConfig : NSObject + +///appId the unique identifier of the App +///@warning required +@property (nonatomic, copy) NSString *appID; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; +/// Initialization method of PAGConfig ++ (instancetype)shareConfig; + +@end + +@interface PAGConfig (Settings) + +///Set the COPPA of the user, COPPA is the short of Children's Online Privacy Protection Rule, the interface only works in the United States. +@property (nonatomic, assign) PAGChildDirectedType childDirected; + +///Custom set the GDPR of the user,GDPR is the short of General Data Protection Regulation,the interface only works in The European. +@property (nonatomic, assign) PAGGDPRConsentType GDPRConsent; + +/// Custom set the CCPA of the user,CCPA is the short of General Data Protection Regulation,the interface only works in USA. +@property (nonatomic, assign) PAGDoNotSellType doNotSell; + +@property (nonatomic, assign) PAGAdSDKThemeStatus themeStatus; + +/// Custom set the debugLog to print debug Log. +/// debugLog NO: close debug log, YES: open debug log. +@property (nonatomic, assign) BOOL debugLog; + +/// App logo image. If set, it will be displayed in the App open ad. +@property (nonatomic, strong, nullable) UIImage *appLogoImage; + +/// additional user information. +@property (nonatomic, copy) NSString *userDataString; + +///Whether to allow SDK to modify the category and options of AVAudioSession when playing audio, default is NO. +///The category set by the SDK is AVAudioSessionCategoryAmbient, and the options are AVAudioSessionCategoryOptionDuckOthers +@property (nonatomic, assign) BOOL allowModifyAudioSessionSetting; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGInterstitialRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGInterstitialRequest.h new file mode 100644 index 0000000..8c29af1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGInterstitialRequest.h @@ -0,0 +1,16 @@ +// +// PAGInterstitialRequest.h +// PangleAPI +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGInterstitialRequest : PAGRequest + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAd.h new file mode 100644 index 0000000..563fa4b --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAd.h @@ -0,0 +1,48 @@ +// +// PAGLAppOpenAd.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/26. +// +#import +#import "PAGLAppOpenAdDelegate.h" +#import "PAGAppOpenRequest.h" +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLAppOpenAd; + +/// Callback for loading ad results. +/// @param appOpenAd Ad instance after successfully loaded. +/// @param error Loading error. +typedef void (^PAGAppOpenADLoadCompletionHandler)(PAGLAppOpenAd * _Nullable appOpenAd, + NSError * _Nullable error); + +@interface PAGLAppOpenAd : NSObject + +/// Ad event delegate. +@property (nonatomic, weak, nullable) id delegate; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load open ad +/// @param slotID Required. The unique identifier of open ad. +/// @param request Required. An instance of an open ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGAppOpenRequest *)request + completionHandler:(PAGAppOpenADLoadCompletionHandler)completionHandler; + + +/// Present the open ad +/// @param rootViewController View controller the open ad will be presented on. +/// @warning This method must be called on the main thread. +- (void)presentFromRootViewController:(UIViewController *)rootViewController; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAdDelegate.h new file mode 100644 index 0000000..5b86b62 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLAppOpenAdDelegate.h @@ -0,0 +1,18 @@ +// +// PAGLAppOpenAdDelegate.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/26. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLAppOpenAd; + +@protocol PAGLAppOpenAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLImage.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLImage.h new file mode 100644 index 0000000..2d6bf3f --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLImage.h @@ -0,0 +1,24 @@ +// +// PAGLImage.h +// PAGAdSDK +// +// Created by Willie on 2022/5/5. +// + +NS_ASSUME_NONNULL_BEGIN + +/// A class that encapsulates image information +@interface PAGLImage : NSObject + +/// image address URL +@property (nonatomic, copy, readonly) NSString *imageURL; + +/// image width +@property (nonatomic, assign, readonly) CGFloat width; + +/// image height +@property (nonatomic, assign, readonly) CGFloat height; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAd.h new file mode 100644 index 0000000..d51bf59 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAd.h @@ -0,0 +1,49 @@ +// +// PAGLInterstitialAd.h +// PangleAPI +// +// Created by bytedance on 2022/2/25. +// + +#import +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" +#import "PAGLInterstitialAdDelegate.h" +#import "PAGInterstitialRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLInterstitialAd; + +/// Callback for loading interstitial results. +/// @param interstitialAd Ad instance after successfully loaded which will be non-nil on success. +/// @param error Loading error which will be non-nil on fail. +typedef void (^PAGInterstitialAdLoadCompletionHandler)(PAGLInterstitialAd * _Nullable interstitialAd, + NSError * _Nullable error); + +@interface PAGLInterstitialAd : NSObject + +/// Ad event delegate. +@property(nonatomic, weak, nullable) id delegate; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load interstitial ad +/// @param slotID Required. The unique identifier of interstitial ad. +/// @param request Required. An instance of an interstitial ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGInterstitialRequest *)request + completionHandler:(PAGInterstitialAdLoadCompletionHandler)completionHandler; + + +/// Present the interstitial ad +/// @param rootViewController View controller the interstitial ad will be presented on. +/// @warning This method must be called on the main thread. +- (void)presentFromRootViewController:(UIViewController *)rootViewController; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAdDelegate.h new file mode 100644 index 0000000..5e87f7d --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLInterstitialAdDelegate.h @@ -0,0 +1,18 @@ +// +// PAGLInterstitialAdDelegate.h +// PangleAPI +// +// Created by bytedance on 2022/2/25. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLInterstitialAd; + +@protocol PAGLInterstitialAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLMaterialMeta.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLMaterialMeta.h new file mode 100644 index 0000000..27506b2 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLMaterialMeta.h @@ -0,0 +1,38 @@ +// +// PAGLMaterialMeta.h +// PAGAdSDK +// +// Created by Willie on 2022/5/5. +// + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLImage; + +/// media type of ad +typedef NS_ENUM(NSUInteger, PAGLNativeMediaType) { + PAGLNativeMediaTypeImage = 1, // image ad + PAGLNativeMediaTypeVideo = 2, // video ad +}; + +/// A class that encapsulates advertising information +@interface PAGLMaterialMeta : NSObject + +/// ad logo icon. +@property (nonatomic, strong, readonly) PAGLImage *icon; + +/// ad headline. +@property (nonatomic, copy, readonly) NSString *AdTitle; + +/// ad description. +@property (nonatomic, copy, readonly) NSString *AdDescription; + +/// text displayed on the creative button. +@property (nonatomic, copy, readonly) NSString *buttonText; + +/// media type of ad +@property (nonatomic, assign, readonly) PAGLNativeMediaType mediaType; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAd.h new file mode 100644 index 0000000..9c9166c --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAd.h @@ -0,0 +1,61 @@ +// +// PAGLNativeAd.h +// PAGAdSDK +// +// Created by Willie on 2022/3/1. +// + +#import + +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGLNativeAd, PAGLMaterialMeta, PAGNativeRequest; +@protocol PAGLNativeAdDelegate; + +typedef void (^PAGNativeADLoadCompletionHandler)(PAGLNativeAd * _Nullable nativeAd, + NSError * _Nullable error); + +/// Abstract ad slot containing ad data loading, response callbacks. +@interface PAGLNativeAd : NSObject + +/// Ad material. +@property (nonatomic, strong, readonly) PAGLMaterialMeta *data; + +/// The delegate for receiving state change messages. +/// The delegate is not limited to viewcontroller. +/// The delegate can be set to any object which conforming to . +@property (nonatomic, weak, nullable) id delegate; + +/// required. +/// Root view controller for handling ad actions. +/// Action method includes is 'presentViewController'. +@property (nonatomic, weak) UIViewController *rootViewController; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + +/// Actively request nativeAd datas. +/// @param slotID required. The unique identifier of a native ad. +/// @param request required. PAGNativeRequest instance. +/// @param completionHandler required. Callback when ad is loaded. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGNativeRequest *)request + completionHandler:(PAGNativeADLoadCompletionHandler)completionHandler; + +/// Register clickable views in native ads view. +/// Interaction types can be configured on TikTok Audience Network. +/// Interaction types include view video ad details page, open the webpage using a browser, open the webpage within the app, etc. +/// @param containerView required. Container view of the native ad. +/// @param clickableViews optional. Array of views that are clickable. +- (void)registerContainer:(__kindof UIView *)containerView + withClickableViews:(NSArray<__kindof UIView *> *_Nullable)clickableViews; + +/// Unregister ad view from the native ad. +- (void)unregisterView; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdDelegate.h new file mode 100644 index 0000000..251360e --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdDelegate.h @@ -0,0 +1,16 @@ +// +// PAGLNativeAdDelegate.h +// PAGAdSDK +// +// Created by Willie on 2022/3/1. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGLNativeAdDelegate + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdRelatedView.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdRelatedView.h new file mode 100644 index 0000000..fbd3966 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGLNativeAdRelatedView.h @@ -0,0 +1,35 @@ +// +// PAGLNativeAdRelatedView.h +// PAGAdSDK +// +// Created by Willie on 2022/4/6. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class PAGMediaView, PAGLNativeAd; + +/// A class that encapsulates a fixed ad style +@interface PAGLNativeAdRelatedView : NSObject + +/// Need to actively add to the view in order to deal with the feedback and improve the accuracy of ad. +@property (nonatomic, strong, readonly) UIButton *dislikeButton; + +/// Ad logo + Promotion label.Need to actively add to the view. +@property (nonatomic, strong, readonly) UIImageView *logoADImageView; + +/// dsp logo.Need to actively add to the view. +@property (nonatomic, strong, readonly) UIImageView *adChoicesView; + +/// A view used to display a video or image, which can be added directly to the ad view. +@property (nonatomic, strong, readonly) PAGMediaView *mediaView; + +/// Refresh the data every time you get new datas in order to show ad perfectly. +/// @param nativeAd PAGLNativeAd instance. +- (void)refreshWithNativeAd:(PAGLNativeAd *)nativeAd; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGMAdNetworkExtras.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGMAdNetworkExtras.h new file mode 100644 index 0000000..54bd21d --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGMAdNetworkExtras.h @@ -0,0 +1,12 @@ +// +// PAGMNetworkExtras.h +// PAGAdSDK +// +// Created by bytedance on 2022/11/8. +// + +#import + +@protocol PAGMAdNetworkExtras + +@end diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGMediaView.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGMediaView.h new file mode 100644 index 0000000..1650d00 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGMediaView.h @@ -0,0 +1,15 @@ +// +// PAGMediaView.h +// PAGAdSDK +// +// Created by Willie on 2022/4/7. +// + +NS_ASSUME_NONNULL_BEGIN + +/// A view that wraps a fixed ad style to display an image or video +@interface PAGMediaView : UIView + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGNativeRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGNativeRequest.h new file mode 100644 index 0000000..49fe087 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGNativeRequest.h @@ -0,0 +1,16 @@ +// +// PAGNativeRequest.h +// PAGAdSDK +// +// Created by bytedance on 2022/3/23. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGNativeRequest : PAGRequest + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRequest.h new file mode 100644 index 0000000..bae3fc6 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRequest.h @@ -0,0 +1,28 @@ +// +// PAGRequest.h +// PAGAdSDK +// +// Created by bytedance on 2022/3/22. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol PAGMAdNetworkExtras; +@interface PAGRequest : NSObject + +/// Ad string that represents an ad response. The SDK will render this ad and ignore all other +/// targeting information set on this request. +@property (nonatomic, copy) NSString *adString; + +/// extra info +@property (nonatomic, copy, nullable) NSDictionary *extraInfo; + ++ (instancetype)request; + +- (void)registerAdNetworkExtras:(id)extras; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardModel.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardModel.h new file mode 100644 index 0000000..3c78409 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardModel.h @@ -0,0 +1,23 @@ +// +// PAGRewardedModel.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGRewardModel : NSObject + +//奖励名称 +@property (nonatomic, copy, readonly) NSString *rewardName; +//奖励钱数 +@property (nonatomic, assign, readonly) NSInteger rewardAmount; + +- (instancetype)initWithRewardName:(NSString *)rewardName rewardAmount:(NSInteger)rewardAmount; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAd.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAd.h new file mode 100644 index 0000000..941f3b1 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAd.h @@ -0,0 +1,49 @@ +// +// PAGRewardedAd.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import +#import "PAGAdProtocol.h" +#import "PAGAdClientBiddingProtocol.h" +#import "PAGRewardedAdDelegate.h" +#import "PAGRewardedRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGRewardedAd; +/// Callback for loading ad results. +/// @param rewardedAd Ad instance after successfully loaded which will be non-nil on success. +/// @param error Loading error which will be non-nil on fail. +typedef void (^PAGRewardedAdLoadCompletionHandler)(PAGRewardedAd * _Nullable rewardedAd, + NSError * _Nullable error); + +@interface PAGRewardedAd : NSObject + +/// Ad event delegate. +@property (nonatomic, weak, nullable) id delegate; + ++ (instancetype)new UNAVAILABLE_ATTRIBUTE; +- (instancetype)init UNAVAILABLE_ATTRIBUTE; + + +/// Load rewarded ad +/// @param slotID Required. The unique identifier of rewarded ad. +/// @param request Required. An instance of a rewarded ad request. +/// @param completionHandler Handler which will be called when the request completes. ++ (void)loadAdWithSlotID:(NSString *)slotID + request:(PAGRewardedRequest *)request + completionHandler:(PAGRewardedAdLoadCompletionHandler)completionHandler; + + +/// Present the rewarded ad +/// @param rootViewController View controller the rewarded ad will be presented on. +/// @warning This method must be called on the main thread. +- (void)presentFromRootViewController:(UIViewController *)rootViewController; + +@end + +NS_ASSUME_NONNULL_END + diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAdDelegate.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAdDelegate.h new file mode 100644 index 0000000..b71f2f0 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedAdDelegate.h @@ -0,0 +1,32 @@ +// +// PAGRewardedAdDelegate.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import "PAGAdDelegate.h" + +NS_ASSUME_NONNULL_BEGIN + +@class PAGRewardedAd; +@class PAGRewardModel; + +@protocol PAGRewardedAdDelegate + +@optional + +/// Tells the delegate that the user has earned the reward. +/// @param rewardedAd rewarded ad instance +/// @param rewardModel user's reward info +- (void)rewardedAd:(PAGRewardedAd *)rewardedAd userDidEarnReward:(PAGRewardModel *)rewardModel; + + +/// Tells the delegate that the user failed to earn the reward. +/// @param rewardedAd rewarded ad instance +/// @param error failed reson +- (void)rewardedAd:(PAGRewardedAd *)rewardedAd userEarnRewardFailWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedRequest.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedRequest.h new file mode 100644 index 0000000..bd32306 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGRewardedRequest.h @@ -0,0 +1,16 @@ +// +// PAGRewardedRequest.h +// PAGAdSDK-PAGAdSDK +// +// Created by ByteDance on 2022/4/27. +// + +#import "PAGRequest.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface PAGRewardedRequest : PAGRequest + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGSdk.h b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGSdk.h new file mode 100644 index 0000000..2e61d47 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/Headers/PAGSdk.h @@ -0,0 +1,51 @@ +// +// PAGSdk.h +// PAGAdSDK +// +// Created by bytedance on 2022/5/9. +// + +#import +#import "PAGConfig.h" + +NS_ASSUME_NONNULL_BEGIN + +typedef NS_ENUM(NSInteger, PAGSDKInitializationState) { + PAGSDKInitializationStateNotReady = 0, + PAGSDKInitializationStateReady = 1 +}; + +typedef void (^PAGAdsCompletionHandler)(BOOL success, NSError * __nullable error); + +@interface PAGSdk : NSObject + +/// Pangle SDK version +@property (nonatomic, copy, readonly, class) NSString *SDKVersion; + +/// The SDK initialization state +@property (nonatomic, assign, readonly, class) PAGSDKInitializationState initializationState; + +/// Starts the Pangle SDK +/// @warning Call this method as early as possible to reduce ad request fail. +/// @param config SDK configuration +/// @param completionHandler Callback for starting the Pangle SDK ++ (void)startWithConfig:(PAGConfig *)config completionHandler:(nullable PAGAdsCompletionHandler)completionHandler; + +/// Get bidding token +/// @param slotID the unique identifier of ad. +/// @note This method recommend called on the sub thread. ++ (NSString *)getBiddingToken:(nullable NSString *)slotID; + +/// Get bidding token asynchronously +/// @param slotID the unique identifier of ad. +/// @param completion Callback to return the bidding token. ++ (void)getBiddingToken:(nullable NSString *)slotID completion:(void (^)(NSString * biddingToken))completion; + +/// Set a ad revenue info obtained from mediation. +/// You can get sample code from the Pangle platform to learn how to use this method. +/// @param adRevenue Assemble a dictionary of ad revenue info. ++ (void)setAdRevenue:(NSDictionary *)adRevenue; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/PAGAdSDK b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/PAGAdSDK new file mode 100644 index 0000000..2a1fbc9 Binary files /dev/null and b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/A/PAGAdSDK differ diff --git a/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/Current b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/Current new file mode 120000 index 0000000..8c7e5a6 --- /dev/null +++ b/Pods/Ads-Global/SDK/PAGAdSDK.xcframework/ios-arm64_x86_64-simulator/PAGAdSDK.framework/Versions/Current @@ -0,0 +1 @@ +A \ No newline at end of file diff --git a/Pods/AppAuth/LICENSE b/Pods/AppAuth/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/Pods/AppAuth/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Pods/AppAuth/README.md b/Pods/AppAuth/README.md new file mode 100644 index 0000000..53085b3 --- /dev/null +++ b/Pods/AppAuth/README.md @@ -0,0 +1,718 @@ +![AppAuth for iOS and macOS](https://rawgit.com/openid/AppAuth-iOS/master/appauth_lockup.svg) +[![tests](https://github.com/openid/AppAuth-iOS/actions/workflows/tests.yml/badge.svg?event=push)](https://github.com/openid/AppAuth-iOS/actions/workflows/tests.yml) +[![codecov](https://codecov.io/gh/openid/AppAuth-iOS/branch/master/graph/badge.svg)](https://codecov.io/gh/openid/AppAuth-iOS) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-brightgreen.svg?style=flat)](https://github.com/Carthage/Carthage) +[![SwiftPM compatible](https://img.shields.io/badge/SwiftPM-compatible-brightgreen.svg?style=flat)](https://swift.org/package-manager) +[![Pod Version](https://img.shields.io/cocoapods/v/AppAuth.svg?style=flat)](https://cocoapods.org/pods/AppAuth) +[![Pod License](https://img.shields.io/cocoapods/l/AppAuth.svg?style=flat)](https://github.com/openid/AppAuth-iOS/blob/master/LICENSE) +[![Pod Platform](https://img.shields.io/cocoapods/p/AppAuth.svg?style=flat)](https://cocoapods.org/pods/AppAuth) +[![Catalyst compatible](https://img.shields.io/badge/Catalyst-compatible-brightgreen.svg?style=flat)](https://developer.apple.com/documentation/xcode/creating_a_mac_version_of_your_ipad_app) + +AppAuth for iOS and macOS, and tvOS is a client SDK for communicating with +[OAuth 2.0](https://tools.ietf.org/html/rfc6749) and +[OpenID Connect](http://openid.net/specs/openid-connect-core-1_0.html) providers. +It strives to +directly map the requests and responses of those specifications, while following +the idiomatic style of the implementation language. In addition to mapping the +raw protocol flows, convenience methods are available to assist with common +tasks like performing an action with fresh tokens. + +It follows the best practices set out in +[RFC 8252 - OAuth 2.0 for Native Apps](https://tools.ietf.org/html/rfc8252) +including using `SFAuthenticationSession` and `SFSafariViewController` on iOS +for the auth request. `UIWebView` and `WKWebView` are explicitly *not* +supported due to the security and usability reasons explained in +[Section 8.12 of RFC 8252](https://tools.ietf.org/html/rfc8252#section-8.12). + +It also supports the [PKCE](https://tools.ietf.org/html/rfc7636) extension to +OAuth, which was created to secure authorization codes in public clients when +custom URI scheme redirects are used. The library is friendly to other +extensions (standard or otherwise), with the ability to handle additional params +in all protocol requests and responses. + +For tvOS, AppAuth implements [OAuth 2.0 Device Authorization Grant +](https://tools.ietf.org/html/rfc8628) to allow for tvOS sign-ins through a secondary device. + +## Specification + +### iOS + +#### Supported Versions + +AppAuth supports iOS 7 and above. + +iOS 9+ uses the in-app browser tab pattern +(via `SFSafariViewController`), and falls back to the system browser (mobile +Safari) on earlier versions. + +#### Authorization Server Requirements + +Both Custom URI Schemes (all supported versions of iOS) and Universal Links +(iOS 9+) can be used with the library. + +In general, AppAuth can work with any authorization server that supports +native apps, as documented in [RFC 8252](https://tools.ietf.org/html/rfc8252), +either through custom URI scheme redirects, or universal links. +Authorization servers that assume all clients are web-based, or require clients to maintain +confidentiality of the client secrets may not work well. + +### macOS + +#### Supported Versions + +AppAuth supports macOS (OS X) 10.9 and above. + +#### Authorization Server Requirements + +AppAuth for macOS supports both custom schemes; a loopback HTTP redirects +via a small embedded server. + +In general, AppAuth can work with any authorization server that supports +native apps, as documented in [RFC 8252](https://tools.ietf.org/html/rfc8252); +either through custom URI schemes, or loopback HTTP redirects. +Authorization servers that assume all clients are web-based, or require clients to maintain +confidentiality of the client secrets may not work well. + +### tvOS + +#### Supported Versions + +AppAuth supports tvOS 9.0 and above. Please note that while it is possible to run the standard AppAuth library on tvOS, the documentation below describes implementing [OAuth 2.0 Device Authorization Grant](https://tools.ietf.org/html/rfc8628) (AppAuthTV). + +#### Authorization Server Requirements + +AppAuthTV is designed for servers that support the device authorization flow as documented in [RFC 8628](https://tools.ietf.org/html/rfc8628). + +## Try + +Want to try out AppAuth? Just run: + + pod try AppAuth + +Follow the instructions in [Examples/README.md](Examples/README.md) to configure +with your own OAuth client (you need to update three configuration points with your +client info to try the demo). + +## Setup + +AppAuth supports four options for dependency management. + +### CocoaPods + +With [CocoaPods](https://guides.cocoapods.org/using/getting-started.html), +add the following line to your `Podfile`: + + pod 'AppAuth' + +Then, run `pod install`. + +**tvOS:** Use the `TV` subspec: + + pod 'AppAuth/TV' + + +### Swift Package Manager + +With [Swift Package Manager](https://swift.org/package-manager), +add the following `dependency` to your `Package.swift`: + +```swift +dependencies: [ + .package(url: "https://github.com/openid/AppAuth-iOS.git", .upToNextMajor(from: "1.3.0")) +] +``` + +**tvOS:** Use the `AppAuthTV` target. + +### Carthage + +With [Carthage](https://github.com/Carthage/Carthage), add the following +line to your `Cartfile`: + + github "openid/AppAuth-iOS" "master" + +Then, run `carthage bootstrap`. + +**tvOS:** Use the `AppAuthTV` framework. + +### Static Library + +You can also use AppAuth as a static library. This requires linking the library +and your project, and including the headers. Here is a suggested configuration: + +1. Create an Xcode Workspace. +2. Add `AppAuth.xcodeproj` to your Workspace. +3. Include libAppAuth as a linked library for your target (in the "General -> +Linked Framework and Libraries" section of your target). +4. Add `AppAuth-iOS/Source` to your search paths of your target ("Build Settings -> +"Header Search Paths"). + +*Note: There is no static library for AppAuthTV.* + +## Auth Flow + +AppAuth supports both manual interaction with the authorization server +where you need to perform your own token exchanges, as well as convenience +methods that perform some of this logic for you. This example uses the +convenience method, which returns either an `OIDAuthState` object, or an error. + +`OIDAuthState` is a class that keeps track of the authorization and token +requests and responses, and provides a convenience method to call an API with +fresh tokens. This is the only object that you need to serialize to retain the +authorization state of the session. + +### Configuration + +You can configure AppAuth by specifying the endpoints directly: + +Objective-C +```objc +NSURL *authorizationEndpoint = + [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/v2/auth"]; +NSURL *tokenEndpoint = + [NSURL URLWithString:@"https://www.googleapis.com/oauth2/v4/token"]; + +OIDServiceConfiguration *configuration = + [[OIDServiceConfiguration alloc] + initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint]; + +// perform the auth request... +``` + +Swift +```swift +let authorizationEndpoint = URL(string: "https://accounts.google.com/o/oauth2/v2/auth")! +let tokenEndpoint = URL(string: "https://www.googleapis.com/oauth2/v4/token")! +let configuration = OIDServiceConfiguration(authorizationEndpoint: authorizationEndpoint, + tokenEndpoint: tokenEndpoint) + +// perform the auth request... +``` + +**tvOS** + +Objective-C +```objc +NSURL *deviceAuthorizationEndpoint = + [NSURL URLWithString:@"https://oauth2.googleapis.com/device/code"]; +NSURL *tokenEndpoint = + [NSURL URLWithString:@"https://www.googleapis.com/oauth2/v4/token"]; + +OIDTVServiceConfiguration *configuration = + [[OIDTVServiceConfiguration alloc] + initWithDeviceAuthorizationEndpoint:deviceAuthorizationEndpoint + tokenEndpoint:tokenEndpoint]; + +// perform the auth request... +``` + + +Or through discovery: + +Objective-C +```objc +NSURL *issuer = [NSURL URLWithString:@"https://accounts.google.com"]; + +[OIDAuthorizationService discoverServiceConfigurationForIssuer:issuer + completion:^(OIDServiceConfiguration *_Nullable configuration, + NSError *_Nullable error) { + + if (!configuration) { + NSLog(@"Error retrieving discovery document: %@", + [error localizedDescription]); + return; + } + + // perform the auth request... +}]; +``` + +Swift +```swift +let issuer = URL(string: "https://accounts.google.com")! + +// discovers endpoints +OIDAuthorizationService.discoverConfiguration(forIssuer: issuer) { configuration, error in + guard let config = configuration else { + print("Error retrieving discovery document: \(error?.localizedDescription ?? "Unknown error")") + return + } + + // perform the auth request... +} +``` + +**tvOS** + +Objective-C +```objc +NSURL *issuer = [NSURL URLWithString:@"https://accounts.google.com"]; + +[OIDTVAuthorizationService discoverServiceConfigurationForIssuer:issuer + completion:^(OIDTVServiceConfiguration *_Nullable configuration, + NSError *_Nullable error) { + + if (!configuration) { + NSLog(@"Error retrieving discovery document: %@", + [error localizedDescription]); + return; + } + + // perform the auth request... +}]; +``` + +### Authorizing – iOS + +First, you need to have a property in your `UIApplicationDelegate` +implementation to hold the session, in order to continue the authorization flow +from the redirect. In this example, the implementation of this delegate is +a class named `AppDelegate`, if your app's application delegate has a different +name, please update the class name in samples below accordingly. + +Objective-C +```objc +@interface AppDelegate : UIResponder +// property of the app's AppDelegate +@property(nonatomic, strong, nullable) id currentAuthorizationFlow; +@end +``` + +Swift +```swift +class AppDelegate: UIResponder, UIApplicationDelegate { + // property of the app's AppDelegate + var currentAuthorizationFlow: OIDExternalUserAgentSession? +} +``` + + +And your main class, a property to store the auth state: + +Objective-C +```objc +// property of the containing class +@property(nonatomic, strong, nullable) OIDAuthState *authState; +``` +Swift +```swift +// property of the containing class +private var authState: OIDAuthState? +``` + + +Then, initiate the authorization request. By using the +`authStateByPresentingAuthorizationRequest` convenience method, the token +exchange will be performed automatically, and everything will be protected with +PKCE (if the server supports it). AppAuth also lets you perform these +requests manually. See the `authNoCodeExchange` method in the included Example +app for a demonstration: + +Objective-C +```objc +// builds authentication request +OIDAuthorizationRequest *request = + [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + scopes:@[OIDScopeOpenID, + OIDScopeProfile] + redirectURL:kRedirectURI + responseType:OIDResponseTypeCode + additionalParameters:nil]; + +// performs authentication request +AppDelegate *appDelegate = + (AppDelegate *)[UIApplication sharedApplication].delegate; +appDelegate.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + presentingViewController:self + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + if (authState) { + NSLog(@"Got authorization tokens. Access token: %@", + authState.lastTokenResponse.accessToken); + [self setAuthState:authState]; + } else { + NSLog(@"Authorization error: %@", [error localizedDescription]); + [self setAuthState:nil]; + } +}]; +``` + +Swift +```swift +// builds authentication request +let request = OIDAuthorizationRequest(configuration: configuration, + clientId: clientID, + clientSecret: clientSecret, + scopes: [OIDScopeOpenID, OIDScopeProfile], + redirectURL: redirectURI, + responseType: OIDResponseTypeCode, + additionalParameters: nil) + +// performs authentication request +print("Initiating authorization request with scope: \(request.scope ?? "nil")") + +let appDelegate = UIApplication.shared.delegate as! AppDelegate + +appDelegate.currentAuthorizationFlow = + OIDAuthState.authState(byPresenting: request, presenting: self) { authState, error in + if let authState = authState { + self.setAuthState(authState) + print("Got authorization tokens. Access token: " + + "\(authState.lastTokenResponse?.accessToken ?? "nil")") + } else { + print("Authorization error: \(error?.localizedDescription ?? "Unknown error")") + self.setAuthState(nil) + } +} +``` + +*Handling the Redirect* + +The authorization response URL is returned to the app via the iOS openURL +app delegate method, so you need to pipe this through to the current +authorization session (created in the previous session): + +Objective-C +```objc +- (BOOL)application:(UIApplication *)app + openURL:(NSURL *)url + options:(NSDictionary *)options { + // Sends the URL to the current authorization flow (if any) which will + // process it if it relates to an authorization response. + if ([_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:url]) { + _currentAuthorizationFlow = nil; + return YES; + } + + // Your additional URL handling (if any) goes here. + + return NO; +} +``` + +Swift +```swift +func application(_ app: UIApplication, + open url: URL, + options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { + // Sends the URL to the current authorization flow (if any) which will + // process it if it relates to an authorization response. + if let authorizationFlow = self.currentAuthorizationFlow, + authorizationFlow.resumeExternalUserAgentFlow(with: url) { + self.currentAuthorizationFlow = nil + return true + } + + // Your additional URL handling (if any) + + return false +} +``` + +### Authorizing – MacOS + +On macOS, the most popular way to get the authorization response redirect is to +start a local HTTP server on the loopback interface (limited to incoming +requests from the user's machine only). When the authorization is complete, the +user is redirected to that local server, and the authorization response can be +processed by the app. AppAuth takes care of managing the local HTTP server +lifecycle for you. + +> #### :bulb: Alternative: Custom URI Schemes +> Custom URI schemes are also supported on macOS, but some browsers display +> an interstitial, which reduces the usability. For an example on using custom +> URI schemes with macOS, See `Example-Mac`. + +To receive the authorization response using a local HTTP server, first you need +to have an instance variable in your main class to retain the HTTP redirect +handler: + +Objective-C +```objc +OIDRedirectHTTPHandler *_redirectHTTPHandler; +``` + +Then, as the port used by the local HTTP server varies, you need to start it +before building the authorization request, in order to get the exact redirect +URI to use: + +Objective-C +```objc +static NSString *const kSuccessURLString = + @"http://openid.github.io/AppAuth-iOS/redirect/"; +NSURL *successURL = [NSURL URLWithString:kSuccessURLString]; + +// Starts a loopback HTTP redirect listener to receive the code. This needs to be started first, +// as the exact redirect URI (including port) must be passed in the authorization request. +_redirectHTTPHandler = [[OIDRedirectHTTPHandler alloc] initWithSuccessURL:successURL]; +NSURL *redirectURI = [_redirectHTTPHandler startHTTPListener:nil]; +``` + +Then, initiate the authorization request. By using the +`authStateByPresentingAuthorizationRequest` convenience method, the token +exchange will be performed automatically, and everything will be protected with +PKCE (if the server supports it). By assigning the return value to the +`OIDRedirectHTTPHandler`'s `currentAuthorizationFlow`, the authorization will +continue automatically once the user makes their choice: + +```objc +// builds authentication request +OIDAuthorizationRequest *request = + [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + clientSecret:kClientSecret + scopes:@[ OIDScopeOpenID ] + redirectURL:redirectURI + responseType:OIDResponseTypeCode + additionalParameters:nil]; +// performs authentication request +__weak __typeof(self) weakSelf = self; +_redirectHTTPHandler.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + // Brings this app to the foreground. + [[NSRunningApplication currentApplication] + activateWithOptions:(NSApplicationActivateAllWindows | + NSApplicationActivateIgnoringOtherApps)]; + + // Processes the authorization response. + if (authState) { + NSLog(@"Got authorization tokens. Access token: %@", + authState.lastTokenResponse.accessToken); + } else { + NSLog(@"Authorization error: %@", error.localizedDescription); + } + [weakSelf setAuthState:authState]; +}]; +``` + + +### Authorizing – tvOS + +Ensure that your main class is a delegate of `OIDAuthStateChangeDelegate`, `OIDAuthStateErrorDelegate`, implement the corresponding methods, and include the following property and instance variable: + +Objective-C +```objc +// property of the containing class +@property(nonatomic, strong, nullable) OIDAuthState *authState; + +// instance variable of the containing class +OIDTVAuthorizationCancelBlock _cancelBlock; +``` + +Then, build and perform the authorization request. + +Objective-C +```objc +// builds authentication request +__weak __typeof(self) weakSelf = self; + +OIDTVAuthorizationRequest *request = + [[OIDTVAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + clientSecret:kClientSecret + scopes:@[ OIDScopeOpenID, OIDScopeProfile ] + additionalParameters:nil + additionalHeaders:nil]; + +// performs authentication request +OIDTVAuthorizationInitialization initBlock = + ^(OIDTVAuthorizationResponse *_Nullable response, NSError *_Nullable error) { + if (response) { + // process authorization response + NSLog(@"Got authorization response: %@", response); + } else { + // handle initialization error + NSLog(@"Error: %@", error); + } + }; + +OIDTVAuthorizationCompletion completionBlock = + ^(OIDAuthState *_Nullable authState, NSError *_Nullable error) { + weakSelf.signInView.hidden = YES; + if (authState) { + NSLog(@"Token response: %@", authState.lastTokenResponse); + [weakSelf setAuthState:authState]; + } else { + NSLog(@"Error: %@", error); + [weakSelf setAuthState:nil]; + } + }; + +_cancelBlock = [OIDTVAuthorizationService authorizeTVRequest:request + initialization:initBlock + completion:completionBlock]; +``` + +### Making API Calls + +AppAuth gives you the raw token information, if you need it. However, we +recommend that users of the `OIDAuthState` convenience wrapper use the provided +`performActionWithFreshTokens:` method to perform their API calls to avoid +needing to worry about token freshness: + +Objective-C +```objc +[_authState performActionWithFreshTokens:^(NSString *_Nonnull accessToken, + NSString *_Nonnull idToken, + NSError *_Nullable error) { + if (error) { + NSLog(@"Error fetching fresh tokens: %@", [error localizedDescription]); + return; + } + + // perform your API request using the tokens +}]; +``` + +Swift +```swift +let userinfoEndpoint = URL(string:"https://openidconnect.googleapis.com/v1/userinfo")! +self.authState?.performAction() { (accessToken, idToken, error) in + + if error != nil { + print("Error fetching fresh tokens: \(error?.localizedDescription ?? "Unknown error")") + return + } + guard let accessToken = accessToken else { + return + } + + // Add Bearer token to request + var urlRequest = URLRequest(url: userinfoEndpoint) + urlRequest.allHTTPHeaderFields = ["Authorization": "Bearer \(accessToken)"] + + // Perform request... +} +``` + +### Custom User-Agents (iOS and macOS) + +Each OAuth flow involves presenting an external user-agent to the user, that +allows them to interact with the OAuth authorization server. Typical examples +of a user-agent are the user's browser, or an in-app browser tab incarnation +like `ASWebAuthenticationSession` on iOS. + +AppAuth ships with several implementations of an external user-agent out of the +box, including defaults for iOS and macOS suitable for most cases. The default +user-agents typically share persistent cookies with the system default browser, +to improve the chance that the user doesn't need to sign-in all over again. + +It is possible to change the user-agent that AppAuth uses, and even write your +own - all without needing to fork the library. + +All implementations of the external user-agent, be they included or created by +you need to conform to the +[`OIDExternalUserAgent`](http://openid.github.io/AppAuth-iOS/docs/latest/protocol_o_i_d_external_user_agent-p.html) +protocol. + +Instances of the `OIDExternalUserAgent`are passed into +[`OIDAuthState.authStateByPresentingAuthorizationRequest:externalUserAgent:callback`](http://openid.github.io/AppAuth-iOS/docs/latest/interface_o_i_d_auth_state.html#ac762fe2bf95c116f0b437419be211fa1) +and/or +[`OIDAuthorizationService.presentAuthorizationRequest:externalUserAgent:callback:`](http://openid.github.io/AppAuth-iOS/docs/latest/interface_o_i_d_authorization_service.html#ae551f8e6887366a46e49b09b37389b8f) +rather than using the platform-specific convenience methods (which use the +default user-agents for their respective platforms), like +[`OIDAuthState.authStateByPresentingAuthorizationRequest:presentingViewController:callback:`](http://openid.github.io/AppAuth-iOS/docs/latest/category_o_i_d_auth_state_07_i_o_s_08.html#ae32fd0732cd3192cd5219f2655a4c85c). + +Popular use-cases for writing your own user-agent implementation include needing +to style the user-agent in ways not supported by AppAuth, and implementing a +fully custom flow with your own business logic. You can take one of the existing +implementations as a starting point to copy, rename, and customize to your +needs. + +#### Custom Browser User-Agent + +AppAuth for iOS includes a few extra user-agent implementations which you can +try, or use as a reference for your own implementation. One of them, +[`OIDExternalUserAgentIOSCustomBrowser`](http://openid.github.io/AppAuth-iOS/docs/latest/interface_o_i_d_external_user_agent_i_o_s_custom_browser.html) +enables you to use a different browser for authentication, like Chrome for iOS +or Firefox for iOS. + +Here's how to configure AppAuth to use a custom browser using the +`OIDExternalUserAgentIOSCustomBrowser` user agent: + +First, add the following array to your +[Info.plist](https://github.com/openid/AppAuth-iOS/blob/135f99d2cb4e9d18d310ac2588b905e612461561/Examples/Example-iOS_ObjC/Source/Info.plist#L34) +(in XCode, right click -> Open As -> Source Code) + +``` + LSApplicationQueriesSchemes + + googlechromes + opera-https + firefox + +``` + +This is required so that AppAuth can test for the browser and open the app store +if it's not installed (the default behavior of this user-agent). You only need +to include the URL scheme of the actual browser you intend to use. + +Objective-C +```objc +// performs authentication request +AppDelegate *appDelegate = + (AppDelegate *)[UIApplication sharedApplication].delegate; +id userAgent = + [OIDExternalUserAgentIOSCustomBrowser CustomBrowserChrome]; +appDelegate.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + externalUserAgent:userAgent + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + if (authState) { + NSLog(@"Got authorization tokens. Access token: %@", + authState.lastTokenResponse.accessToken); + [self setAuthState:authState]; + } else { + NSLog(@"Authorization error: %@", [error localizedDescription]); + [self setAuthState:nil]; + } +}]; +``` + +Swift +``` +guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { + self.logMessage("Error accessing AppDelegate") + return + } +let userAgent = OIDExternalUserAgentIOSCustomBrowser.customBrowserChrome() +appDelegate.currentAuthorizationFlow = OIDAuthState.authState(byPresenting: request, externalUserAgent: userAgent) { authState, error in + if let authState = authState { + self.setAuthState(authState) + self.logMessage("Got authorization tokens. Access token: \(authState.lastTokenResponse?.accessToken ?? "DEFAULT_TOKEN")") + } else { + self.logMessage("Authorization error: \(error?.localizedDescription ?? "DEFAULT_ERROR")") + self.setAuthState(nil) + } +} +``` + +That's it! With those two changes (which you can try on the included sample), +AppAuth will use Chrome iOS for the authorization request (and open Chrome in +the App Store if it's not installed). + +⚠️**Note: the `OIDExternalUserAgentIOSCustomBrowser` user-agent is not intended for consumer apps**. It is designed for +advanced enterprise use-cases where the app developers have greater control over +the operating environment and have special requirements that require a custom +browser like Chrome. + +You don't need to stop with the included external user agents either! Since the +[`OIDExternalUserAgent`](http://openid.github.io/AppAuth-iOS/docs/latest/protocol_o_i_d_external_user_agent-p.html) +protocol is part of AppAuth's public API, you can implement your own versions of +it. In the above example, +`userAgent = [OIDExternalUserAgentIOSCustomBrowser CustomBrowserChrome]` would +be replaced with an instantiation of your user-agent implementation. + +## API Documentation + +Browse the [API documentation](http://openid.github.io/AppAuth-iOS/docs/latest/annotated.html). + +## Included Samples + +Sample apps that explore core AppAuth features are available for iOS, macOS and tvOS; follow the instructions in [Examples/README.md](Examples/README.md) to get started. diff --git a/Pods/AppAuth/Sources/AppAuth.h b/Pods/AppAuth/Sources/AppAuth.h new file mode 100644 index 0000000..19abc55 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth.h @@ -0,0 +1,92 @@ +/*! @file AppAuth.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthState.h" +#import "OIDAuthStateChangeDelegate.h" +#import "OIDAuthStateErrorDelegate.h" +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationService.h" +#import "OIDError.h" +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgent.h" +#import "OIDExternalUserAgentRequest.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDGrantTypes.h" +#import "OIDIDToken.h" +#import "OIDRegistrationRequest.h" +#import "OIDRegistrationResponse.h" +#import "OIDResponseTypes.h" +#import "OIDScopes.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDTokenUtilities.h" +#import "OIDURLSessionProvider.h" +#import "OIDEndSessionRequest.h" +#import "OIDEndSessionResponse.h" + +#if TARGET_OS_TV +#elif TARGET_OS_WATCH +#elif TARGET_OS_IOS || TARGET_OS_MACCATALYST +#import "OIDAuthState+IOS.h" +#import "OIDAuthorizationService+IOS.h" +#import "OIDExternalUserAgentIOS.h" +#import "OIDExternalUserAgentIOSCustomBrowser.h" +#import "OIDExternalUserAgentCatalyst.h" +#elif TARGET_OS_OSX +#import "OIDAuthState+Mac.h" +#import "OIDAuthorizationService+Mac.h" +#import "OIDExternalUserAgentMac.h" +#import "OIDRedirectHTTPHandler.h" +#else +#error "Platform Undefined" +#endif + +/*! @mainpage AppAuth for iOS and macOS + + @section introduction Introduction + + AppAuth for iOS and macOS is a client SDK for communicating with [OAuth 2.0] + (https://tools.ietf.org/html/rfc6749) and [OpenID Connect] + (http://openid.net/specs/openid-connect-core-1_0.html) providers. It strives to + directly map the requests and responses of those specifications, while following + the idiomatic style of the implementation language. In addition to mapping the + raw protocol flows, convenience methods are available to assist with common + tasks like performing an action with fresh tokens. + + It follows the best practices set out in + [RFC 8252 - OAuth 2.0 for Native Apps](https://tools.ietf.org/html/rfc8252) + including using `SFAuthenticationSession` and `SFSafariViewController` on iOS + for the auth request. Web view and `WKWebView` are explicitly *not* + supported due to the security and usability reasons explained in + [Section 8.12 of RFC 8252](https://tools.ietf.org/html/rfc8252#section-8.12). + + It also supports the [PKCE](https://tools.ietf.org/html/rfc7636) extension to + OAuth which was created to secure authorization codes in public clients when + custom URI scheme redirects are used. The library is friendly to other + extensions (standard or otherwise) with the ability to handle additional params + in all protocol requests and responses. + + Homepage: http://openid.github.io/AppAuth-iOS/
+ API Documentation: http://openid.github.io/AppAuth-iOS/docs/latest
+ Git Repository: https://github.com/openid/AppAuth-iOS
+ + */ diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthState+IOS.h b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthState+IOS.h new file mode 100644 index 0000000..1a1ee63 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthState+IOS.h @@ -0,0 +1,84 @@ +/*! @file OIDAuthState+IOS.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import + +#import "OIDAuthState.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief iOS specific convenience methods for @c OIDAuthState. + */ +@interface OIDAuthState (IOS) + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + and performing the authorization code exchange in the case of code flow requests. For + the hybrid flow, the caller should validate the id_token and c_hash, then perform the token + request (@c OIDAuthorizationService.performTokenRequest:callback:) + and update the OIDAuthState with the results (@c + OIDAuthState.updateWithTokenResponse:error:). + @param authorizationRequest The authorization request to present. + @param presentingViewController The view controller to use for presenting the authentication UI. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthStateAuthorizationCallback)callback; + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + (optionally using an emphemeral browser session that shares no cookies or data with the + normal browser session) and performing the authorization code exchange in the case of code + flow requests. For the hybrid flow, the caller should validate the id_token and c_hash, then + perform the token request (@c OIDAuthorizationService.performTokenRequest:callback:) + and update the OIDAuthState with the results (@c + OIDAuthState.updateWithTokenResponse:error:). + @param authorizationRequest The authorization request to present. + @param presentingViewController The view controller to use for presenting the authentication UI. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingViewController:(UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthStateAuthorizationCallback)callback + API_AVAILABLE(ios(13)); + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + callback:(OIDAuthStateAuthorizationCallback)callback API_AVAILABLE(ios(11)) API_UNAVAILABLE(macCatalyst) + __deprecated_msg("This method will not work on iOS 13. Use " + "authStateByPresentingAuthorizationRequest:presentingViewController:callback:"); + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthState+IOS.m b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthState+IOS.m new file mode 100644 index 0000000..c474a77 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthState+IOS.m @@ -0,0 +1,78 @@ +/*! @file OIDAuthState+IOS.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import "OIDAuthState+IOS.h" +#import "OIDExternalUserAgentIOS.h" +#import "OIDExternalUserAgentCatalyst.h" + +@implementation OIDAuthState (IOS) + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthStateAuthorizationCallback)callback { + id externalUserAgent; +#if TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentCatalyst alloc] + initWithPresentingViewController:presentingViewController]; +#else // TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:presentingViewController]; +#endif // TARGET_OS_MACCATALYST + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:callback]; +} + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingViewController:(UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthStateAuthorizationCallback)callback { + id externalUserAgent; +#if TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentCatalyst alloc] + initWithPresentingViewController:presentingViewController + prefersEphemeralSession:prefersEphemeralSession]; +#else // TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentIOS alloc] + initWithPresentingViewController:presentingViewController + prefersEphemeralSession:prefersEphemeralSession]; +#endif // TARGET_OS_MACCATALYST + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:callback]; +} + +#if !TARGET_OS_MACCATALYST ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + callback:(OIDAuthStateAuthorizationCallback)callback { + OIDExternalUserAgentIOS *externalUserAgent = [[OIDExternalUserAgentIOS alloc] init]; + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:callback]; +} +#endif // !TARGET_OS_MACCATALYST + +@end + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthorizationService+IOS.h b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthorizationService+IOS.h new file mode 100644 index 0000000..c7c685d --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthorizationService+IOS.h @@ -0,0 +1,67 @@ +/*! @file OIDAuthorizationService+IOS.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import + +#import "OIDAuthorizationService.h" +#import "OIDExternalUserAgentSession.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides iOS specific authorization request handling. + */ +@interface OIDAuthorizationService (IOS) + +/*! @brief Perform an authorization flow, presenting an appropriate browser for the user to + authenticate. + @param request The authorization request. + @param presentingViewController The view controller from which to present authentication UI. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthorizationCallback)callback; + +/*! @brief Perform an authorization flow using the @c ASWebAuthenticationSession optionally using an + emphemeral browser session that shares no cookies or data with the normal browser session. + @param request The authorization request. + @param presentingViewController The view controller from which to present authentication UI. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingViewController:(UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthorizationCallback)callback API_AVAILABLE(ios(13)); + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthorizationService+IOS.m b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthorizationService+IOS.m new file mode 100644 index 0000000..4ca07c5 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDAuthorizationService+IOS.m @@ -0,0 +1,64 @@ +/*! @file OIDAuthorizationService+IOS.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import "OIDAuthorizationService+IOS.h" +#import "OIDExternalUserAgentIOS.h" +#import "OIDExternalUserAgentCatalyst.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation OIDAuthorizationService (IOS) + ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthorizationCallback)callback { + id externalUserAgent; +#if TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentCatalyst alloc] + initWithPresentingViewController:presentingViewController]; +#else // TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:presentingViewController]; +#endif // TARGET_OS_MACCATALYST + return [self presentAuthorizationRequest:request externalUserAgent:externalUserAgent callback:callback]; +} + ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingViewController:(UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthorizationCallback)callback { + id externalUserAgent; +#if TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentCatalyst alloc] + initWithPresentingViewController:presentingViewController + prefersEphemeralSession:prefersEphemeralSession]; +#else // TARGET_OS_MACCATALYST + externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:presentingViewController + prefersEphemeralSession:prefersEphemeralSession]; +#endif // TARGET_OS_MACCATALYST + return [self presentAuthorizationRequest:request externalUserAgent:externalUserAgent callback:callback]; +} + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentCatalyst.h b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentCatalyst.h new file mode 100644 index 0000000..910d0bb --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentCatalyst.h @@ -0,0 +1,61 @@ +/*! @file OIDExternalUserAgentCatalyst.h + @brief AppAuth iOS SDK + @copyright + Copyright 2019 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import + +#import "OIDExternalUserAgent.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief A Catalyst specific external user-agent that uses `ASWebAuthenticationSession` to + present the request. +*/ +API_AVAILABLE(macCatalyst(13)) API_UNAVAILABLE(ios) +@interface OIDExternalUserAgentCatalyst : NSObject + +/*! @internal + @brief Unavailable. Please use @c initWithPresentingViewController: + */ +- (nonnull instancetype)init NS_UNAVAILABLE; + +/*! @brief The designated initializer. + @param presentingViewController The view controller from which to present the + \SFSafariViewController. + */ +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController + NS_DESIGNATED_INITIALIZER; + +/*! @brief Create an external user-agent which optionally uses a private authentication session. + @param presentingViewController The view controller from which to present the browser. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + */ +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession; + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentCatalyst.m b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentCatalyst.m new file mode 100644 index 0000000..d6771b3 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentCatalyst.m @@ -0,0 +1,157 @@ +/*! @file OIDExternalUserAgentCatalyst.m + @brief AppAuth iOS SDK + @copyright + Copyright 2019 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import "OIDExternalUserAgentCatalyst.h" + +#import +#import + +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDExternalUserAgentRequest.h" + +#if TARGET_OS_MACCATALYST + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDExternalUserAgentCatalyst () +@end + +@implementation OIDExternalUserAgentCatalyst { + UIViewController *_presentingViewController; + BOOL _prefersEphemeralSession; + + BOOL _externalUserAgentFlowInProgress; + __weak id _session; + ASWebAuthenticationSession *_webAuthenticationVC; +} + +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController { + self = [super init]; + if (self) { + _presentingViewController = presentingViewController; + } + return self; +} + +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession { + self = [self initWithPresentingViewController:presentingViewController]; + if (self) { + _prefersEphemeralSession = prefersEphemeralSession; + } + return self; +} + +- (BOOL)presentExternalUserAgentRequest:(id)request + session:(id)session { + if (_externalUserAgentFlowInProgress) { + // TODO: Handle errors as authorization is already in progress. + return NO; + } + + _externalUserAgentFlowInProgress = YES; + _session = session; + BOOL openedUserAgent = NO; + NSURL *requestURL = [request externalUserAgentRequestURL]; + + __weak OIDExternalUserAgentCatalyst *weakSelf = self; + NSString *redirectScheme = request.redirectScheme; + ASWebAuthenticationSession *authenticationVC = + [[ASWebAuthenticationSession alloc] initWithURL:requestURL + callbackURLScheme:redirectScheme + completionHandler:^(NSURL * _Nullable callbackURL, + NSError * _Nullable error) { + __strong OIDExternalUserAgentCatalyst *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + strongSelf->_webAuthenticationVC = nil; + if (callbackURL) { + [strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL]; + } else { + NSError *safariError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:error + description:nil]; + [strongSelf->_session failExternalUserAgentFlowWithError:safariError]; + } + }]; + + authenticationVC.presentationContextProvider = self; + authenticationVC.prefersEphemeralWebBrowserSession = _prefersEphemeralSession; + _webAuthenticationVC = authenticationVC; + openedUserAgent = [authenticationVC start]; + + if (!openedUserAgent) { + [self cleanUp]; + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError + underlyingError:nil + description:@"Unable to open ASWebAuthenticationSession view controller."]; + [session failExternalUserAgentFlowWithError:safariError]; + } + return openedUserAgent; +} + +- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion { + if (!_externalUserAgentFlowInProgress) { + // Ignore this call if there is no authorization flow in progress. + if (completion) completion(); + return; + } + + ASWebAuthenticationSession *webAuthenticationVC = _webAuthenticationVC; + + [self cleanUp]; + + if (webAuthenticationVC) { + // dismiss the ASWebAuthenticationSession + [webAuthenticationVC cancel]; + if (completion) completion(); + } else { + if (completion) completion(); + } +} + +- (void)cleanUp { + // The weak reference to |_session| is set to nil to avoid accidentally using + // it while not in an authorization flow. + _webAuthenticationVC = nil; + _session = nil; + _externalUserAgentFlowInProgress = NO; +} + +#pragma mark - ASWebAuthenticationPresentationContextProviding + +- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session { + return _presentingViewController.view.window; +} + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_MACCATALYST + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOS.h b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOS.h new file mode 100644 index 0000000..12abc20 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOS.h @@ -0,0 +1,69 @@ +/*! @file OIDExternalUserAgentIOS.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import + +#import "OIDExternalUserAgent.h" + +@class SFSafariViewController; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief An iOS specific external user-agent that uses the best possible user-agent available + depending on the version of iOS to present the request. + */ +API_UNAVAILABLE(macCatalyst) +@interface OIDExternalUserAgentIOS : NSObject + +- (null_unspecified instancetype)init API_AVAILABLE(ios(11)) + __deprecated_msg("This method will not work on iOS 13, use " + "initWithPresentingViewController:presentingViewController"); + +/*! @brief The designated initializer. + @param presentingViewController The view controller from which to present the authentication UI. + @discussion The specific authentication UI used depends on the iOS version and accessibility + options. iOS 8 uses the system browser, iOS 9-10 use @c SFSafariViewController, iOS 11 uses + @c SFAuthenticationSession + (unless Guided Access is on which does not work) or uses @c SFSafariViewController, and iOS + 12+ uses @c ASWebAuthenticationSession (unless Guided Access is on). + */ +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController + NS_DESIGNATED_INITIALIZER; + +/*! @brief Create an external user-agent which optionally uses a private authentication session. + @param presentingViewController The view controller from which to present the browser. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + @discussion Authentication is performed with @c ASWebAuthenticationSession (unless Guided Access + is on), setting the ephemerality based on the argument. + */ +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession + API_AVAILABLE(ios(13)); + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOS.m b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOS.m new file mode 100644 index 0000000..4a8cda0 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOS.m @@ -0,0 +1,268 @@ +/*! @file OIDExternalUserAgentIOS.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import "OIDExternalUserAgentIOS.h" + +#import +#import + +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDExternalUserAgentRequest.h" + +#if !TARGET_OS_MACCATALYST + +NS_ASSUME_NONNULL_BEGIN + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 +@interface OIDExternalUserAgentIOS () +@end +#else +@interface OIDExternalUserAgentIOS () +@end +#endif + +@implementation OIDExternalUserAgentIOS { + UIViewController *_presentingViewController; + BOOL _prefersEphemeralSession; + + BOOL _externalUserAgentFlowInProgress; + __weak id _session; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + __weak SFSafariViewController *_safariVC; + SFAuthenticationSession *_authenticationVC; + ASWebAuthenticationSession *_webAuthenticationVC; +#pragma clang diagnostic pop +} + +- (null_unspecified instancetype)init { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnonnull" + return [self initWithPresentingViewController:nil]; +#pragma clang diagnostic pop +} + +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController { + self = [super init]; + if (self) { +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + NSAssert(presentingViewController != nil, + @"presentingViewController cannot be nil on iOS 13"); +#endif // __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + + _presentingViewController = presentingViewController; + } + return self; +} + +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController + prefersEphemeralSession:(BOOL)prefersEphemeralSession { + self = [self initWithPresentingViewController:presentingViewController]; + if (self) { + _prefersEphemeralSession = prefersEphemeralSession; + } + return self; +} + +- (BOOL)presentExternalUserAgentRequest:(id)request + session:(id)session { + if (_externalUserAgentFlowInProgress) { + // TODO: Handle errors as authorization is already in progress. + return NO; + } + + _externalUserAgentFlowInProgress = YES; + _session = session; + BOOL openedUserAgent = NO; + NSURL *requestURL = [request externalUserAgentRequestURL]; + + // iOS 12 and later, use ASWebAuthenticationSession + if (@available(iOS 12.0, *)) { + // ASWebAuthenticationSession doesn't work with guided access (rdar://40809553) + if (!UIAccessibilityIsGuidedAccessEnabled()) { + __weak OIDExternalUserAgentIOS *weakSelf = self; + NSString *redirectScheme = request.redirectScheme; + ASWebAuthenticationSession *authenticationVC = + [[ASWebAuthenticationSession alloc] initWithURL:requestURL + callbackURLScheme:redirectScheme + completionHandler:^(NSURL * _Nullable callbackURL, + NSError * _Nullable error) { + __strong OIDExternalUserAgentIOS *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + strongSelf->_webAuthenticationVC = nil; + if (callbackURL) { + [strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL]; + } else { + NSError *safariError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:error + description:nil]; + [strongSelf->_session failExternalUserAgentFlowWithError:safariError]; + } + }]; +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + if (@available(iOS 13.0, *)) { + authenticationVC.presentationContextProvider = self; + authenticationVC.prefersEphemeralWebBrowserSession = _prefersEphemeralSession; + } +#endif + _webAuthenticationVC = authenticationVC; + openedUserAgent = [authenticationVC start]; + } + } + // iOS 11, use SFAuthenticationSession + if (@available(iOS 11.0, *)) { + // SFAuthenticationSession doesn't work with guided access (rdar://40809553) + if (!openedUserAgent && !UIAccessibilityIsGuidedAccessEnabled()) { + __weak OIDExternalUserAgentIOS *weakSelf = self; + NSString *redirectScheme = request.redirectScheme; + SFAuthenticationSession *authenticationVC = + [[SFAuthenticationSession alloc] initWithURL:requestURL + callbackURLScheme:redirectScheme + completionHandler:^(NSURL * _Nullable callbackURL, + NSError * _Nullable error) { + __strong OIDExternalUserAgentIOS *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + strongSelf->_authenticationVC = nil; + if (callbackURL) { + [strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL]; + } else { + NSError *safariError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:error + description:@"User cancelled."]; + [strongSelf->_session failExternalUserAgentFlowWithError:safariError]; + } + }]; + _authenticationVC = authenticationVC; + openedUserAgent = [authenticationVC start]; + } + } + // iOS 9 and 10, use SFSafariViewController + if (@available(iOS 9.0, *)) { + if (!openedUserAgent && _presentingViewController) { + SFSafariViewController *safariVC = + [[SFSafariViewController alloc] initWithURL:requestURL]; + safariVC.delegate = self; + _safariVC = safariVC; + [_presentingViewController presentViewController:safariVC animated:YES completion:nil]; + openedUserAgent = YES; + } + } + // iOS 8 and earlier, use mobile Safari + if (!openedUserAgent){ + openedUserAgent = [[UIApplication sharedApplication] openURL:requestURL]; + } + + if (!openedUserAgent) { + [self cleanUp]; + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError + underlyingError:nil + description:@"Unable to open Safari."]; + [session failExternalUserAgentFlowWithError:safariError]; + } + return openedUserAgent; +} + +- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion { + if (!_externalUserAgentFlowInProgress) { + // Ignore this call if there is no authorization flow in progress. + if (completion) completion(); + return; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + SFSafariViewController *safariVC = _safariVC; + SFAuthenticationSession *authenticationVC = _authenticationVC; + ASWebAuthenticationSession *webAuthenticationVC = _webAuthenticationVC; +#pragma clang diagnostic pop + + [self cleanUp]; + + if (webAuthenticationVC) { + // dismiss the ASWebAuthenticationSession + [webAuthenticationVC cancel]; + if (completion) completion(); + } else if (authenticationVC) { + // dismiss the SFAuthenticationSession + [authenticationVC cancel]; + if (completion) completion(); + } else if (safariVC) { + // dismiss the SFSafariViewController + [safariVC dismissViewControllerAnimated:YES completion:completion]; + } else { + if (completion) completion(); + } +} + +- (void)cleanUp { + // The weak references to |_safariVC| and |_session| are set to nil to avoid accidentally using + // them while not in an authorization flow. + _safariVC = nil; + _authenticationVC = nil; + _webAuthenticationVC = nil; + _session = nil; + _externalUserAgentFlowInProgress = NO; +} + +#pragma mark - SFSafariViewControllerDelegate + +- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller NS_AVAILABLE_IOS(9.0) { + if (controller != _safariVC) { + // Ignore this call if the safari view controller do not match. + return; + } + if (!_externalUserAgentFlowInProgress) { + // Ignore this call if there is no authorization flow in progress. + return; + } + id session = _session; + [self cleanUp]; + NSError *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:nil + description:@"No external user agent flow in progress."]; + [session failExternalUserAgentFlowWithError:error]; +} + +#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 +#pragma mark - ASWebAuthenticationPresentationContextProviding + +- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session API_AVAILABLE(ios(13.0)){ + return _presentingViewController.view.window; +} +#endif // __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 + +@end + +NS_ASSUME_NONNULL_END + +#endif // !TARGET_OS_MACCATALYST + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOSCustomBrowser.h b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOSCustomBrowser.h new file mode 100644 index 0000000..2032e8c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOSCustomBrowser.h @@ -0,0 +1,113 @@ +/*! @file OIDExternalUserAgentIOSCustomBrowser.h + @brief AppAuth iOS SDK + @copyright + Copyright 2018 Google LLC + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import + +#import "OIDExternalUserAgent.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief A block that transforms a regular http/https URL into one that will open in an + alternative browser. + @param requestURL the http/https request URL to be transformed. + @return transformed URL. + */ +typedef NSURL *_Nullable (^OIDCustomBrowserURLTransformation)(NSURL *_Nullable requestURL); + +/*! @brief An implementation of the OIDExternalUserAgent protocol for iOS that uses + a custom browser (i.e. not Safari) for external requests. It is suitable for browsers that + offer a custom url scheme that simply replaces the "https" scheme. It is not designed + for browsers that require other modifications to the URL. If the browser is not installed + the user will be prompted to install it. + */ +API_UNAVAILABLE(macCatalyst) +@interface OIDExternalUserAgentIOSCustomBrowser : NSObject + +/*! @brief URL transformation block for the browser. + */ +@property(nonatomic, readonly) OIDCustomBrowserURLTransformation URLTransformation; + +/*! @brief URL Scheme used to test for whether the browser is installed. + */ +@property(nonatomic, readonly, nullable) NSString *canOpenURLScheme; + +/*! @brief URL of the browser's App Store listing. + */ +@property(nonatomic, readonly, nullable) NSURL *appStoreURL; + +/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Chrome. + */ ++ (instancetype)CustomBrowserChrome; + +/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Firefox. + */ ++ (instancetype)CustomBrowserFirefox; + +/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Opera. + */ ++ (instancetype)CustomBrowserOpera; + +/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Safari. + */ ++ (instancetype)CustomBrowserSafari; + +/*! @brief Creates a @c OIDCustomBrowserURLTransformation using the scheme substitution method used + iOS browsers like Chrome and Firefox. + */ ++ (OIDCustomBrowserURLTransformation) + URLTransformationSchemeSubstitutionHTTPS:(NSString *)browserSchemeHTTPS + HTTP:(nullable NSString *)browserSchemeHTTP; + +/*! @brief Creates a @c OIDCustomBrowserURLTransformation with the URL prefix method used by + iOS browsers like Firefox. + */ ++ (OIDCustomBrowserURLTransformation) URLTransformationSchemeConcatPrefix:(NSString*)URLprefix; + +/*! @internal + @brief Unavailable. Please use @c initWithURLTransformation:canOpenURLScheme:appStoreURL: + */ +- (nonnull instancetype)init NS_UNAVAILABLE; + +/*! @brief OIDExternalUserAgent for a custom browser. @c presentExternalUserAgentRequest:session method + will return NO if the browser isn't installed. + */ +- (nullable instancetype)initWithURLTransformation:(OIDCustomBrowserURLTransformation)URLTransformation; + +/*! @brief The designated initializer. + @param URLTransformation the transformation block to translate the URL into one that will open + in the desired custom browser. + @param canOpenURLScheme any scheme supported by the browser used to check if the browser is + installed. + @param appStoreURL URL of the browser in the app store. When this and @c canOpenURLScheme + are non-nil, @c presentExternalUserAgentRequest:session will redirect the user to the app store + if the browser is not installed. + */ +- (nullable instancetype)initWithURLTransformation:(OIDCustomBrowserURLTransformation)URLTransformation + canOpenURLScheme:(nullable NSString *)canOpenURLScheme + appStoreURL:(nullable NSURL *)appStoreURL + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOSCustomBrowser.m b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOSCustomBrowser.m new file mode 100644 index 0000000..be5dc82 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/iOS/OIDExternalUserAgentIOSCustomBrowser.m @@ -0,0 +1,171 @@ +/*! @file OIDExternalUserAgentIOSCustomBrowser.m + @brief AppAuth iOS SDK + @copyright + Copyright 2018 Google LLC + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_IOS || TARGET_OS_MACCATALYST + +#import "OIDExternalUserAgentIOSCustomBrowser.h" + +#import + +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationService.h" +#import "OIDErrorUtilities.h" +#import "OIDURLQueryComponent.h" + +#if !TARGET_OS_MACCATALYST + +NS_ASSUME_NONNULL_BEGIN + +@implementation OIDExternalUserAgentIOSCustomBrowser + ++ (instancetype)CustomBrowserChrome { + // Chrome iOS documentation: https://developer.chrome.com/multidevice/ios/links + OIDCustomBrowserURLTransformation transform = [[self class] URLTransformationSchemeSubstitutionHTTPS:@"googlechromes" HTTP:@"googlechrome"]; + NSURL *appStoreURL = + [NSURL URLWithString:@"https://itunes.apple.com/us/app/chrome/id535886823"]; + return [[[self class] alloc] initWithURLTransformation:transform + canOpenURLScheme:@"googlechromes" + appStoreURL:appStoreURL]; +} + ++ (instancetype)CustomBrowserFirefox { + // Firefox iOS documentation: https://github.com/mozilla-mobile/firefox-ios-open-in-client + OIDCustomBrowserURLTransformation transform = + [[self class] URLTransformationSchemeConcatPrefix:@"firefox://open-url?url="]; + NSURL *appStoreURL = + [NSURL URLWithString:@"https://itunes.apple.com/us/app/firefox-web-browser/id989804926"]; + return [[[self class] alloc] initWithURLTransformation:transform + canOpenURLScheme:@"firefox" + appStoreURL:appStoreURL]; +} + ++ (instancetype)CustomBrowserOpera { + OIDCustomBrowserURLTransformation transform = + [[self class] URLTransformationSchemeSubstitutionHTTPS:@"opera-https" HTTP:@"opera-http"]; + NSURL *appStoreURL = + [NSURL URLWithString:@"https://itunes.apple.com/us/app/opera-mini-web-browser/id363729560"]; + return [[[self class] alloc] initWithURLTransformation:transform + canOpenURLScheme:@"opera-https" + appStoreURL:appStoreURL]; +} + ++ (instancetype)CustomBrowserSafari { + OIDCustomBrowserURLTransformation transformNOP = ^NSURL *(NSURL *requestURL) { + return requestURL; + }; + OIDExternalUserAgentIOSCustomBrowser *transform = + [[[self class] alloc] initWithURLTransformation:transformNOP]; + return transform; +} + ++ (OIDCustomBrowserURLTransformation) + URLTransformationSchemeSubstitutionHTTPS:(NSString *)browserSchemeHTTPS + HTTP:(nullable NSString *)browserSchemeHTTP { + OIDCustomBrowserURLTransformation transform = ^NSURL *(NSURL *requestURL) { + // Replace the URL Scheme with the Chrome equivalent. + NSString *newScheme = nil; + if ([requestURL.scheme isEqualToString:@"https"]) { + newScheme = browserSchemeHTTPS; + } else if ([requestURL.scheme isEqualToString:@"http"]) { + if (!browserSchemeHTTP) { + NSAssert(false, @"No HTTP scheme registered for browser"); + return nil; + } + newScheme = browserSchemeHTTP; + } + + // Replaces the URI scheme with the custom scheme + NSURLComponents *components = [NSURLComponents componentsWithURL:requestURL + resolvingAgainstBaseURL:YES]; + components.scheme = newScheme; + return components.URL; + }; + return transform; +} + ++ (OIDCustomBrowserURLTransformation)URLTransformationSchemeConcatPrefix:(NSString *)URLprefix { + OIDCustomBrowserURLTransformation transform = ^NSURL *(NSURL *requestURL) { + NSString *requestURLString = [requestURL absoluteString]; + NSMutableCharacterSet *allowedParamCharacters = + [OIDURLQueryComponent URLParamValueAllowedCharacters]; + NSString *encodedUrl = [requestURLString stringByAddingPercentEncodingWithAllowedCharacters:allowedParamCharacters]; + NSString *newURL = [NSString stringWithFormat:@"%@%@", URLprefix, encodedUrl]; + return [NSURL URLWithString:newURL]; + }; + return transform; +} + +- (nullable instancetype)initWithURLTransformation: + (OIDCustomBrowserURLTransformation)URLTransformation { + return [self initWithURLTransformation:URLTransformation canOpenURLScheme:nil appStoreURL:nil]; +} + +- (nullable instancetype) + initWithURLTransformation:(OIDCustomBrowserURLTransformation)URLTransformation + canOpenURLScheme:(nullable NSString *)canOpenURLScheme + appStoreURL:(nullable NSURL *)appStoreURL { + self = [super init]; + if (self) { + _URLTransformation = URLTransformation; + _canOpenURLScheme = canOpenURLScheme; + _appStoreURL = appStoreURL; + } + return self; +} + +- (BOOL)presentExternalUserAgentRequest:(nonnull id)request + session:(nonnull id)session { + // If the app store URL is set, checks if the app is installed and if not opens the app store. + if (_appStoreURL && _canOpenURLScheme) { + // Verifies existence of LSApplicationQueriesSchemes Info.plist key. + NSArray __unused* canOpenURLs = + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"LSApplicationQueriesSchemes"]; + NSAssert(canOpenURLs, @"plist missing LSApplicationQueriesSchemes key"); + NSAssert1([canOpenURLs containsObject:_canOpenURLScheme], + @"plist missing LSApplicationQueriesSchemes entry for '%@'", _canOpenURLScheme); + + // Opens AppStore if app isn't installed + NSString *testURLString = [NSString stringWithFormat:@"%@://example.com", _canOpenURLScheme]; + NSURL *testURL = [NSURL URLWithString:testURLString]; + if (![[UIApplication sharedApplication] canOpenURL:testURL]) { + [[UIApplication sharedApplication] openURL:_appStoreURL]; + return NO; + } + } + + // Transforms the request URL and opens it. + NSURL *requestURL = [request externalUserAgentRequestURL]; + requestURL = _URLTransformation(requestURL); + BOOL openedInBrowser = [[UIApplication sharedApplication] openURL:requestURL]; + return openedInBrowser; +} + +- (void)dismissExternalUserAgentAnimated:(BOOL)animated + completion:(nonnull void (^)(void))completion { + completion(); +} + +@end + +NS_ASSUME_NONNULL_END + +#endif // !TARGET_OS_MACCATALYST + +#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/LoopbackHTTPServer/OIDLoopbackHTTPServer.h b/Pods/AppAuth/Sources/AppAuth/macOS/LoopbackHTTPServer/OIDLoopbackHTTPServer.h new file mode 100644 index 0000000..ed2ac87 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/LoopbackHTTPServer/OIDLoopbackHTTPServer.h @@ -0,0 +1,192 @@ +/*! @file OIDLoopbackHTTPServer.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth Authors. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +// Based on the MiniSOAP Sample +// https://developer.apple.com/library/mac/samplecode/MiniSOAP/Introduction/Intro.html +// Modified to limit connections to the loopback interface only. + +#import + +#if TARGET_OS_OSX + +#import +#import + +@class HTTPConnection, HTTPServerRequest, TCPServer; + +extern NSString * const TCPServerErrorDomain; + +typedef enum { + kTCPServerCouldNotBindToIPv4Address = 1, + kTCPServerCouldNotBindToIPv6Address = 2, + kTCPServerNoSocketsAvailable = 3, +} TCPServerErrorCode; + +@protocol TCPServerDelegate + +- (void)TCPServer:(TCPServer *)server + didReceiveConnectionFromAddress:(NSData *)addr + inputStream:(NSInputStream *)istr + outputStream:(NSOutputStream *)ostr; + +@end + +@interface TCPServer : NSObject { +@private + __weak id delegate; + NSString *domain; + NSString *name; + NSString *type; + uint16_t port; + CFSocketRef ipv4socket; + CFSocketRef ipv6socket; + NSNetService *netService; +} + +- (id)delegate; +- (void)setDelegate:(id)value; + +- (NSString *)domain; +- (void)setDomain:(NSString *)value; + +- (NSString *)name; +- (void)setName:(NSString *)value; + +- (NSString *)type; +- (void)setType:(NSString *)value; + +- (uint16_t)port; +- (void)setPort:(uint16_t)value; + +- (BOOL)start:(NSError **)error; +- (BOOL)stop; + +- (BOOL)hasIPv4Socket; +- (BOOL)hasIPv6Socket; + +// called when a new connection comes in; by default, informs the delegate +- (void)handleNewConnectionFromAddress:(NSData *)addr + inputStream:(NSInputStream *)istr + outputStream:(NSOutputStream *)ostr; + +@end + +@interface HTTPServer : TCPServer { +@private + Class connClass; + NSURL *docRoot; + // Currently active connections spawned from the HTTPServer. + NSMutableArray *connections; +} + +- (Class)connectionClass; +// used to configure the subclass of HTTPConnection to create when +// a new connection comes in; by default, this is HTTPConnection +- (void)setConnectionClass:(Class)value; + +@end + +@interface HTTPServer (HTTPServerDelegateMethods) +// If the delegate implements this method, this is called +// by an HTTPServer when a new connection comes in. If the +// delegate wishes to refuse the connection, then it should +// invalidate the connection object from within this method. +- (void)HTTPServer:(HTTPServer *)serv didMakeNewConnection:(HTTPConnection *)conn; +@end + + +// This class represents each incoming client connection. +@interface HTTPConnection : NSObject { +@private + __weak id delegate; + NSData *peerAddress; + __weak HTTPServer *server; + NSMutableArray *requests; + NSInputStream *istream; + NSOutputStream *ostream; + NSMutableData *ibuffer; + NSMutableData *obuffer; + BOOL isValid; + BOOL firstResponseDone; +} + +- (id)initWithPeerAddress:(NSData *)addr + inputStream:(NSInputStream *)istr + outputStream:(NSOutputStream *)ostr + forServer:(HTTPServer *)serv; + +- (id)delegate; +- (void)setDelegate:(id)value; + +- (NSData *)peerAddress; + +- (HTTPServer *)server; + +// get the next request that needs to be responded to +- (HTTPServerRequest *)nextRequest; + +- (BOOL)isValid; +// shut down the connection +- (void)invalidate; + +// perform the default handling action: GET and HEAD requests for files +// in the local file system (relative to the documentRoot of the server) +- (void)performDefaultRequestHandling:(HTTPServerRequest *)sreq; + +@end + +@interface HTTPConnection (HTTPConnectionDelegateMethods) +// The "didReceiveRequest:" tells the delegate when a new request comes in. +- (void)HTTPConnection:(HTTPConnection *)conn didReceiveRequest:(HTTPServerRequest *)mess; +- (void)HTTPConnection:(HTTPConnection *)conn didSendResponse:(HTTPServerRequest *)mess; +@end + + +// As NSURLRequest and NSURLResponse are not entirely suitable for use from +// the point of view of an HTTP server, we use CFHTTPMessageRef to encapsulate +// requests and responses. This class packages the (future) response with a +// request and other info for convenience. +@interface HTTPServerRequest : NSObject { +@private + HTTPConnection *connection; + CFHTTPMessageRef request; + CFHTTPMessageRef response; + NSInputStream *responseStream; +} + +- (id)initWithRequest:(CFHTTPMessageRef)req connection:(HTTPConnection *)conn; + +- (HTTPConnection *)connection; + +- (CFHTTPMessageRef)request; + +// The response may include a body. As soon as the response is set, +// the response may be written out to the network. +- (CFHTTPMessageRef)response; +- (void)setResponse:(CFHTTPMessageRef)value; + +- (NSInputStream *)responseBodyStream; +// If there is to be a response body stream (when, say, a big +// file is to be returned, rather than reading the whole thing +// into memory), then it must be set on the request BEFORE the +// response [headers] itself. +- (void)setResponseBodyStream:(NSInputStream *)value; + +@end + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/LoopbackHTTPServer/OIDLoopbackHTTPServer.m b/Pods/AppAuth/Sources/AppAuth/macOS/LoopbackHTTPServer/OIDLoopbackHTTPServer.m new file mode 100644 index 0000000..dca381c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/LoopbackHTTPServer/OIDLoopbackHTTPServer.m @@ -0,0 +1,618 @@ +/*! @file OIDLoopbackHTTPServer.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth Authors. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import "OIDLoopbackHTTPServer.h" +#include +#include +#include + +// We'll ignore the pointer arithmetic warnings for now. +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wpointer-arith" + +@implementation HTTPServer + +- (id)init { + self = [super init]; + connClass = [HTTPConnection self]; + connections = [[NSMutableArray alloc] init]; + return self; +} + +- (Class)connectionClass { + return connClass; +} + +- (void)setConnectionClass:(Class)value { + connClass = value; +} + +// Removes the connection from the list of active connections. +- (void)removeConnection:(HTTPConnection *)connection { + [connections removeObject:connection]; +} + +// Converts the TCPServer delegate notification into the HTTPServer delegate method. +- (void)handleNewConnectionFromAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr { + HTTPConnection *connection = [[connClass alloc] initWithPeerAddress:addr inputStream:istr outputStream:ostr forServer:self]; + // Adds connection to the active connection list to retain it. + [connections addObject:connection]; + [connection setDelegate:[self delegate]]; + if ([self delegate] && [[self delegate] respondsToSelector:@selector(HTTPServer:didMakeNewConnection:)]) { + [[self delegate] HTTPServer:self didMakeNewConnection:connection]; + } +} + +@end + + +@implementation HTTPConnection + +- (id)init { + return nil; +} + +- (id)initWithPeerAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr forServer:(HTTPServer *)serv { + peerAddress = [addr copy]; + server = serv; + istream = istr; + ostream = ostr; + [istream setDelegate:self]; + [ostream setDelegate:self]; + [istream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(id)kCFRunLoopCommonModes]; + [ostream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:(id)kCFRunLoopCommonModes]; + [istream open]; + [ostream open]; + isValid = YES; + return self; +} + +- (void)dealloc { + [self invalidate]; +} + +- (id)delegate { + return delegate; +} + +- (void)setDelegate:(id)value { + delegate = value; +} + +- (NSData *)peerAddress { + return peerAddress; +} + +- (HTTPServer *)server { + return server; +} + +- (HTTPServerRequest *)nextRequest { + for (HTTPServerRequest *request in requests) { + if (![request response]) { + return request; + } + } + return nil; +} + +- (BOOL)isValid { + return isValid; +} + +- (void)invalidate { + if (isValid) { + isValid = NO; + [server removeConnection:self]; + [istream setDelegate:nil]; + [ostream setDelegate:nil]; + [istream close]; + [ostream close]; + istream = nil; + ostream = nil; + ibuffer = nil; + obuffer = nil; + requests = nil; + } +} + +// YES return means that a complete request was parsed, and the caller +// should call again as the buffered bytes may have another complete +// request available. +- (BOOL)processIncomingBytes { + CFHTTPMessageRef working = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, TRUE); + CFHTTPMessageAppendBytes(working, [ibuffer bytes], [ibuffer length]); + + // This "try and possibly succeed" approach is potentially expensive + // (lots of bytes being copied around), but the only API available for + // the server to use, short of doing the parsing itself. + + // HTTPConnection does not handle the chunked transfer encoding + // described in the HTTP spec. And if there is no Content-Length + // header, then the request is the remainder of the stream bytes. + + if (CFHTTPMessageIsHeaderComplete(working)) { + NSString *contentLengthValue = (__bridge_transfer NSString *)CFHTTPMessageCopyHeaderFieldValue(working, (CFStringRef)@"Content-Length"); + + unsigned contentLength = contentLengthValue ? [contentLengthValue intValue] : 0; + NSData *body = (__bridge_transfer NSData *)CFHTTPMessageCopyBody(working); + NSUInteger bodyLength = [body length]; + if (contentLength <= bodyLength) { + NSData *newBody = [NSData dataWithBytes:[body bytes] length:contentLength]; + [ibuffer setLength:0]; + [ibuffer appendBytes:([body bytes] + contentLength) length:(bodyLength - contentLength)]; + CFHTTPMessageSetBody(working, (__bridge CFDataRef)newBody); + } else { + CFRelease(working); + return NO; + } + } else { + return NO; + } + + HTTPServerRequest *request = [[HTTPServerRequest alloc] initWithRequest:working connection:self]; + if (!requests) { + requests = [[NSMutableArray alloc] init]; + } + [requests addObject:request]; + if (delegate && [delegate respondsToSelector:@selector(HTTPConnection:didReceiveRequest:)]) { + // Schedules the delegate to be executed later on the main thread. Cannot call the delegate + // directly as this method is called in a loop in order to process multiple messages, and + // the delegate may choose to stop and dealloc the listener – so we need queue the messages + // and process them separately. + id myDelegate = delegate; + dispatch_async(dispatch_get_main_queue(), ^() { + [myDelegate HTTPConnection:self didReceiveRequest:request]; + }); + } else { + [self performDefaultRequestHandling:request]; + } + + CFRelease(working); + return YES; +} + +- (void)processOutgoingBytes { + // The HTTP headers, then the body if any, then the response stream get + // written out, in that order. The Content-Length: header is assumed to + // be properly set in the response. Outgoing responses are processed in + // the order the requests were received (required by HTTP). + + // Write as many bytes as possible, from buffered bytes, response + // headers and body, and response stream. + + if (![ostream hasSpaceAvailable]) { + return; + } + + NSUInteger olen = [obuffer length]; + if (0 < olen) { + NSInteger writ = [ostream write:[obuffer bytes] maxLength:olen]; + // buffer any unwritten bytes for later writing + if (writ < olen) { + memmove([obuffer mutableBytes], [obuffer mutableBytes] + writ, olen - writ); + [obuffer setLength:olen - writ]; + return; + } + [obuffer setLength:0]; + } + + NSUInteger cnt = requests ? [requests count] : 0; + HTTPServerRequest *req = (0 < cnt) ? [requests objectAtIndex:0] : nil; + + CFHTTPMessageRef cfresp = req ? [req response] : NULL; + if (!cfresp) return; + + if (!obuffer) { + obuffer = [[NSMutableData alloc] init]; + } + + if (!firstResponseDone) { + firstResponseDone = YES; + NSData *serialized = (__bridge_transfer NSData *)CFHTTPMessageCopySerializedMessage(cfresp); + NSUInteger olen = [serialized length]; + if (0 < olen) { + NSInteger writ = [ostream write:[serialized bytes] maxLength:olen]; + if (writ < olen) { + // buffer any unwritten bytes for later writing + [obuffer setLength:(olen - writ)]; + memmove([obuffer mutableBytes], [serialized bytes] + writ, olen - writ); + return; + } + } + } + + NSInputStream *respStream = [req responseBodyStream]; + if (respStream) { + if ([respStream streamStatus] == NSStreamStatusNotOpen) { + [respStream open]; + } + // read some bytes from the stream into our local buffer + [obuffer setLength:16 * 1024]; + NSInteger read = [respStream read:[obuffer mutableBytes] maxLength:[obuffer length]]; + [obuffer setLength:read]; + } + + if (0 == [obuffer length]) { + // When we get to this point with an empty buffer, then the + // processing of the response is done. If the input stream + // is closed or at EOF, then no more requests are coming in. + if (delegate && [delegate respondsToSelector:@selector(HTTPConnection:didSendResponse:)]) { + [delegate HTTPConnection:self didSendResponse:req]; + } + [requests removeObjectAtIndex:0]; + firstResponseDone = NO; + if ([istream streamStatus] == NSStreamStatusAtEnd && [requests count] == 0) { + [self invalidate]; + } + return; + } + + olen = [obuffer length]; + if (0 < olen) { + NSInteger writ = [ostream write:[obuffer bytes] maxLength:olen]; + // buffer any unwritten bytes for later writing + if (writ < olen) { + memmove([obuffer mutableBytes], [obuffer mutableBytes] + writ, olen - writ); + } + [obuffer setLength:olen - writ]; + } +} + +- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)streamEvent { + switch(streamEvent) { + case NSStreamEventHasBytesAvailable:; + uint8_t buf[16 * 1024]; + uint8_t *buffer = NULL; + NSUInteger len = 0; + if (![istream getBuffer:&buffer length:&len]) { + NSInteger amount = [istream read:buf maxLength:sizeof(buf)]; + buffer = buf; + len = amount; + } + if (0 < len) { + if (!ibuffer) { + ibuffer = [[NSMutableData alloc] init]; + } + [ibuffer appendBytes:buffer length:len]; + } + do {} while ([self processIncomingBytes]); + break; + case NSStreamEventHasSpaceAvailable:; + [self processOutgoingBytes]; + break; + case NSStreamEventEndEncountered:; + [self processIncomingBytes]; + if (stream == ostream) { + // When the output stream is closed, no more writing will succeed and + // will abandon the processing of any pending requests and further + // incoming bytes. + [self invalidate]; + } + break; + case NSStreamEventErrorOccurred:; + NSLog(@"HTTPServer stream error: %@", [stream streamError]); + break; + default: + break; + } +} + +- (void)performDefaultRequestHandling:(HTTPServerRequest *)mess { + CFHTTPMessageRef request = [mess request]; + + NSString *vers = (__bridge_transfer id)CFHTTPMessageCopyVersion(request); + if (!vers || ![vers isEqual:(id)kCFHTTPVersion1_1]) { + CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 505, NULL, (__bridge CFStringRef)vers); // Version Not Supported + [mess setResponse:response]; + CFRelease(response); + return; + } + + // 500s all requests when no delegate set to handle them. + CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 500, NULL, kCFHTTPVersion1_1); // Bad Request + [mess setResponse:response]; + CFRelease(response); +} + +@end + + +@implementation HTTPServerRequest + +- (id)init { + return nil; +} + +- (id)initWithRequest:(CFHTTPMessageRef)req connection:(HTTPConnection *)conn { + connection = conn; + request = (CFHTTPMessageRef)CFRetain(req); + return self; +} + +- (void)dealloc { + if (request) CFRelease(request); + if (response) CFRelease(response); +} + +- (HTTPConnection *)connection { + return connection; +} + +- (CFHTTPMessageRef)request { + return request; +} + +- (CFHTTPMessageRef)response { + return response; +} + +- (void)setResponse:(CFHTTPMessageRef)value { + if (value != response) { + if (response) CFRelease(response); + response = (CFHTTPMessageRef)CFRetain(value); + if (response) { + // check to see if the response can now be sent out + [connection processOutgoingBytes]; + } + } +} + +- (NSInputStream *)responseBodyStream { + return responseStream; +} + +- (void)setResponseBodyStream:(NSInputStream *)value { + if (value != responseStream) { + responseStream = value; + } +} + +@end + +NSString * const TCPServerErrorDomain = @"TCPServerErrorDomain"; + +@implementation TCPServer + +- (id)init { + return self; +} + +- (void)dealloc { + [self stop]; +} + +- (id)delegate { + return delegate; +} + +- (void)setDelegate:(id)value { + delegate = value; +} + +- (NSString *)domain { + return domain; +} + +- (void)setDomain:(NSString *)value { + if (domain != value) { + domain = [value copy]; + } +} + +- (NSString *)name { + return name; +} + +- (void)setName:(NSString *)value { + if (name != value) { + name = [value copy]; + } +} + +- (NSString *)type { + return type; +} + +- (void)setType:(NSString *)value { + if (type != value) { + type = [value copy]; + } +} + +- (uint16_t)port { + return port; +} + +- (void)setPort:(uint16_t)value { + port = value; +} + +- (void)handleNewConnectionFromAddress:(NSData *)addr inputStream:(NSInputStream *)istr outputStream:(NSOutputStream *)ostr { + // if the delegate implements the delegate method, call it + if (delegate && [(NSObject*)delegate respondsToSelector:@selector(TCPServer:didReceiveConnectionFromAddress:inputStream:outputStream:)]) { + [delegate TCPServer:self didReceiveConnectionFromAddress:addr inputStream:istr outputStream:ostr]; + } +} + +// This function is called by CFSocket when a new connection comes in. +// We gather some data here, and convert the function call to a method +// invocation on TCPServer. +static void TCPServerAcceptCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { + TCPServer *server = (__bridge TCPServer *)info; + if (kCFSocketAcceptCallBack == type) { + // for an AcceptCallBack, the data parameter is a pointer to a CFSocketNativeHandle + CFSocketNativeHandle nativeSocketHandle = *(CFSocketNativeHandle *)data; + uint8_t name[SOCK_MAXADDRLEN]; + socklen_t namelen = sizeof(name); + NSData *peer = nil; + if (0 == getpeername(nativeSocketHandle, (struct sockaddr *)name, &namelen)) { + peer = [NSData dataWithBytes:name length:namelen]; + } + CFReadStreamRef readStream = NULL; + CFWriteStreamRef writeStream = NULL; + CFStreamCreatePairWithSocket(kCFAllocatorDefault, nativeSocketHandle, &readStream, &writeStream); + if (readStream && writeStream) { + CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); + CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue); + [server handleNewConnectionFromAddress:peer inputStream:(__bridge NSInputStream *)readStream outputStream:(__bridge NSOutputStream *)writeStream]; + } else { + // on any failure, need to destroy the CFSocketNativeHandle + // since we are not going to use it any more + close(nativeSocketHandle); + } + if (readStream) CFRelease(readStream); + if (writeStream) CFRelease(writeStream); + } +} + +- (BOOL)start:(NSError **)error { + CFSocketContext socketCtxt = {0, (__bridge void *)(self), NULL, NULL, NULL}; + ipv4socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&TCPServerAcceptCallBack, &socketCtxt); + ipv6socket = CFSocketCreate(kCFAllocatorDefault, PF_INET6, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, (CFSocketCallBack)&TCPServerAcceptCallBack, &socketCtxt); + + if (NULL == ipv4socket || NULL == ipv6socket) { + if (error) *error = [[NSError alloc] initWithDomain:TCPServerErrorDomain code:kTCPServerNoSocketsAvailable userInfo:nil]; + if (ipv4socket) CFRelease(ipv4socket); + if (ipv6socket) CFRelease(ipv6socket); + ipv4socket = NULL; + ipv6socket = NULL; + return NO; + } + + int yes = 1; + setsockopt(CFSocketGetNative(ipv4socket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); + setsockopt(CFSocketGetNative(ipv6socket), SOL_SOCKET, SO_REUSEADDR, (void *)&yes, sizeof(yes)); + + // set up the IPv4 endpoint; if port is 0, this will cause the kernel to choose a port for us + struct sockaddr_in addr4; + memset(&addr4, 0, sizeof(addr4)); + addr4.sin_len = sizeof(addr4); + addr4.sin_family = AF_INET; + addr4.sin_port = htons(port); + addr4.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + NSData *address4 = [NSData dataWithBytes:&addr4 length:sizeof(addr4)]; + + if (kCFSocketSuccess == CFSocketSetAddress(ipv4socket, (CFDataRef)address4)) { + if (0 == port) { + // now that the binding was successful, we get the port number + // -- we will need it for the v6 endpoint and for the NSNetService + NSData *addr = (__bridge_transfer NSData *)CFSocketCopyAddress(ipv4socket); + memcpy(&addr4, [addr bytes], [addr length]); + port = ntohs(addr4.sin_port); + } + } else { + if (ipv4socket) CFRelease(ipv4socket); + ipv4socket = NULL; + } + + // set up the IPv6 endpoint + struct sockaddr_in6 addr6; + memset(&addr6, 0, sizeof(addr6)); + addr6.sin6_len = sizeof(addr6); + addr6.sin6_family = AF_INET6; + addr6.sin6_port = htons(port); + memcpy(&(addr6.sin6_addr), &in6addr_loopback, sizeof(addr6.sin6_addr)); + NSData *address6 = [NSData dataWithBytes:&addr6 length:sizeof(addr6)]; + + if (kCFSocketSuccess == CFSocketSetAddress(ipv6socket, (CFDataRef)address6)) { + if (0 == port) { + // In this case the IPv4 socket failed to bind but the IPv6 socket succeeded + // Get the port number of the IPv6 socket + NSData *addr = (__bridge_transfer NSData *)CFSocketCopyAddress(ipv6socket); + memcpy(&addr6, [addr bytes], [addr length]); + port = ntohs(addr6.sin6_port); + } + } else { + if (ipv6socket) CFRelease(ipv6socket); + ipv6socket = NULL; + } + + if (!ipv4socket && !ipv6socket) { + // Couldn't bind an IPv4 or IPv6 socket, return an error + if (error) *error = [[NSError alloc] initWithDomain:TCPServerErrorDomain code:kTCPServerCouldNotBindToIPv4Address userInfo:nil]; + return NO; + } + + // set up the run loop sources for the sockets + CFRunLoopRef cfrl = CFRunLoopGetCurrent(); + + if (ipv4socket) { + CFRunLoopSourceRef source4 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, ipv4socket, 0); + CFRunLoopAddSource(cfrl, source4, kCFRunLoopCommonModes); + CFRelease(source4); + } + + if (ipv6socket) { + CFRunLoopSourceRef source6 = CFSocketCreateRunLoopSource(kCFAllocatorDefault, ipv6socket, 0); + CFRunLoopAddSource(cfrl, source6, kCFRunLoopCommonModes); + CFRelease(source6); + } + + // we can only publish the service if we have a type to publish with + if (nil != type) { + NSString *publishingDomain = domain ? domain : @""; + NSString *publishingName = nil; + if (nil != name) { + publishingName = name; + } else { + NSString * thisHostName = [[NSProcessInfo processInfo] hostName]; + if ([thisHostName hasSuffix:@".local"]) { + publishingName = [thisHostName substringToIndex:([thisHostName length] - 6)]; + } + } + netService = [[NSNetService alloc] initWithDomain:publishingDomain type:type name:publishingName port:port]; + [netService publish]; + } + + return YES; +} + +- (BOOL)stop { + [netService stop]; + netService = nil; + if (ipv4socket) { + CFSocketInvalidate(ipv4socket); + CFRelease(ipv4socket); + ipv4socket = NULL; + } + if (ipv6socket) { + CFSocketInvalidate(ipv6socket); + CFRelease(ipv6socket); + ipv6socket = NULL; + } + return YES; +} + +- (BOOL)hasIPv4Socket { + return ipv4socket != nil; +} + +- (BOOL)hasIPv6Socket { + return ipv6socket != nil; +} + +@end + +#pragma GCC diagnostic pop + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthState+Mac.h b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthState+Mac.h new file mode 100644 index 0000000..71e56f2 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthState+Mac.h @@ -0,0 +1,92 @@ +/*! @file OIDAuthState+Mac.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import +#import "OIDAuthState.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief macOS specific convenience methods for @c OIDAuthState. + */ +@interface OIDAuthState (Mac) + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + and performing the authorization code exchange in the case of code flow requests. For + the hybrid flow, the caller should validate the id_token and c_hash, then perform the token + request (@c OIDAuthorizationService.performTokenRequest:callback:) + and update the OIDAuthState with the results (@c + OIDAuthState.updateWithTokenResponse:error:). + @param authorizationRequest The authorization request to present. + @param presentingWindow The window to present the authentication flow. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + @discussion This method adopts @c ASWebAuthenticationSession for macOS 10.15 and above or the + default browser otherwise. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingWindow:(NSWindow *)presentingWindow + callback:(OIDAuthStateAuthorizationCallback)callback; + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + (optionally using an emphemeral browser session that shares no cookies or data with the + normal browser session) and performing the authorization code exchange in the case of code + flow requests. For the hybrid flow, the caller should validate the id_token and c_hash, then + perform the token request (@c OIDAuthorizationService.performTokenRequest:callback:) + and update the OIDAuthState with the results using + @c OIDAuthState.updateWithTokenResponse:error:. + @param authorizationRequest The authorization request to present. + @param presentingWindow The window to present the @c ASWebAuthenticationSession UI. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingWindow:(NSWindow *)presentingWindow + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthStateAuthorizationCallback)callback + API_AVAILABLE(macos(10.15)); + +/*! @param authorizationRequest The authorization request to present. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + @discussion This method uses the default browser to present the authentication flow. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + callback:(OIDAuthStateAuthorizationCallback)callback + __deprecated_msg("For macOS 10.15 and above please use " + "authStateByPresentingAuthorizationRequest:presentingWindow:callback:"); + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthState+Mac.m b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthState+Mac.m new file mode 100644 index 0000000..f2894da --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthState+Mac.m @@ -0,0 +1,62 @@ +/*! @file OIDAuthState+Mac.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import "OIDAuthState+Mac.h" + +#import "OIDExternalUserAgentMac.h" + +@implementation OIDAuthState (Mac) + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingWindow:(NSWindow *)presentingWindow + callback:(OIDAuthStateAuthorizationCallback)callback { + OIDExternalUserAgentMac *externalUserAgent = [[OIDExternalUserAgentMac alloc] initWithPresentingWindow:presentingWindow]; + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:callback]; +} ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingWindow:(NSWindow *)presentingWindow + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthStateAuthorizationCallback)callback { + OIDExternalUserAgentMac *externalUserAgent = + [[OIDExternalUserAgentMac alloc] initWithPresentingWindow:presentingWindow + prefersEphemeralSession:prefersEphemeralSession]; + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:callback]; +} + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + callback:(OIDAuthStateAuthorizationCallback)callback { + OIDExternalUserAgentMac *externalUserAgent = [[OIDExternalUserAgentMac alloc] init]; + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:callback]; +} + +@end + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthorizationService+Mac.h b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthorizationService+Mac.h new file mode 100644 index 0000000..0a34faf --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthorizationService+Mac.h @@ -0,0 +1,78 @@ +/*! @file OIDAuthorizationService+Mac.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import +#import "OIDAuthorizationService.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides macOS specific authorization request handling. + */ +@interface OIDAuthorizationService (Mac) + +/*! @brief Perform an authorization flow. + @param request The authorization request. + @param presentingWindow The window to present the authentication flow. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + @discussion This method adopts @c ASWebAuthenticationSession for macOS 10.15 and above or the + default browser otherwise. + */ ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingWindow:(NSWindow *)presentingWindow + callback:(OIDAuthorizationCallback)callback; + +/*! @brief Perform an authorization flow using the @c ASWebAuthenticationSession optionally using an + emphemeral browser session that shares no cookies or data with the normal browser session. + @param request The authorization request. + @param presentingWindow The window to present the authentication flow. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingWindow:(NSWindow *)presentingWindow + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthorizationCallback)callback + API_AVAILABLE(macos(10.15)); + +/*! @brief Perform an authorization flow using the default browser. + @param request The authorization request. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id)presentAuthorizationRequest:(OIDAuthorizationRequest *)request + callback:(OIDAuthorizationCallback)callback + __deprecated_msg("For macOS 10.15 and above please use presentAuthorizationRequest:presentingWindow:callback:"); + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthorizationService+Mac.m b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthorizationService+Mac.m new file mode 100644 index 0000000..4d3d9a0 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDAuthorizationService+Mac.m @@ -0,0 +1,64 @@ +/*! @file OIDAuthorizationService+Mac.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import "OIDAuthorizationService+Mac.h" + +#import "OIDExternalUserAgentMac.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation OIDAuthorizationService (Mac) + ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingWindow:(NSWindow *)presentingWindow + callback:(OIDAuthorizationCallback)callback { + OIDExternalUserAgentMac *externalUserAgent = [[OIDExternalUserAgentMac alloc] initWithPresentingWindow:presentingWindow]; + return [self presentAuthorizationRequest:request + externalUserAgent:externalUserAgent + callback:callback]; +} + ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingWindow:(NSWindow *)presentingWindow + prefersEphemeralSession:(BOOL)prefersEphemeralSession + callback:(OIDAuthorizationCallback)callback { + OIDExternalUserAgentMac *externalUserAgent = + [[OIDExternalUserAgentMac alloc] initWithPresentingWindow:presentingWindow + prefersEphemeralSession:prefersEphemeralSession]; + return [self presentAuthorizationRequest:request + externalUserAgent:externalUserAgent + callback:callback]; +} + ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + callback:(OIDAuthorizationCallback)callback { + OIDExternalUserAgentMac *externalUserAgent = [[OIDExternalUserAgentMac alloc] init]; + return [self presentAuthorizationRequest:request + externalUserAgent:externalUserAgent + callback:callback]; +} + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDExternalUserAgentMac.h b/Pods/AppAuth/Sources/AppAuth/macOS/OIDExternalUserAgentMac.h new file mode 100644 index 0000000..360c44a --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDExternalUserAgentMac.h @@ -0,0 +1,54 @@ +/*! @file OIDExternalUserAgentMac.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import +#import "OIDExternalUserAgent.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief A Mac-specific external user-agent UI Coordinator that uses the default browser to + present an external user-agent request. + */ +@interface OIDExternalUserAgentMac : NSObject + +/*! @brief The designated initializer. + @param presentingWindow The window from which to present the @c ASWebAuthenticationSession on + macOS 10.15 and above. Older macOS versions use the system browser. + */ +- (instancetype)initWithPresentingWindow:(NSWindow *)presentingWindow NS_DESIGNATED_INITIALIZER; + +/*! @brief Create an external user-agent which optionally uses a private authentication session. + @param presentingWindow The window from which to present the @c ASWebAuthenticationSession. + @param prefersEphemeralSession Whether the caller prefers to use a private authentication + session. See @c ASWebAuthenticationSession.prefersEphemeralWebBrowserSession for more. + */ +- (nullable instancetype)initWithPresentingWindow:(NSWindow *)presentingWindow + prefersEphemeralSession:(BOOL)prefersEphemeralSession + API_AVAILABLE(macos(10.15)); + +- (instancetype)init __deprecated_msg("Use initWithPresentingWindow for macOS 10.15 and above."); + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDExternalUserAgentMac.m b/Pods/AppAuth/Sources/AppAuth/macOS/OIDExternalUserAgentMac.m new file mode 100644 index 0000000..d1e08f9 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDExternalUserAgentMac.m @@ -0,0 +1,170 @@ +/*! @file OIDExternalUserAgentMac.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import "OIDExternalUserAgentMac.h" + +#import + +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDExternalUserAgentRequest.h" +#import + + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDExternalUserAgentMac () +@end + +@implementation OIDExternalUserAgentMac { + BOOL _externalUserAgentFlowInProgress; + __weak id _session; + BOOL _prefersEphemeralSession; + + NSWindow *_presentingWindow; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + ASWebAuthenticationSession *_webAuthenticationSession; +#pragma clang diagnostic pop +} + +- (instancetype)initWithPresentingWindow:(NSWindow *)presentingWindow { + self = [super init]; + if (self) { + _presentingWindow = presentingWindow; + } + return self; +} + +- (nullable instancetype)initWithPresentingWindow:(NSWindow *)presentingWindow + prefersEphemeralSession:(BOOL)prefersEphemeralSession { + self = [self initWithPresentingWindow:presentingWindow]; + if (self) { + _prefersEphemeralSession = prefersEphemeralSession; + } + return self; +} + +- (instancetype)init { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wnonnull" + return [self initWithPresentingWindow:nil]; +#pragma clang diagnostic pop +} + +- (BOOL)presentExternalUserAgentRequest:(id)request + session:(id)session { + if (_externalUserAgentFlowInProgress) { + // TODO: Handle errors as authorization is already in progress. + return NO; + } + + _externalUserAgentFlowInProgress = YES; + _session = session; + NSURL *requestURL = [request externalUserAgentRequestURL]; + + if (@available(macOS 10.15, *)) { + if (_presentingWindow) { + __weak OIDExternalUserAgentMac *weakSelf = self; + NSString *redirectScheme = request.redirectScheme; + ASWebAuthenticationSession *authenticationSession = + [[ASWebAuthenticationSession alloc] initWithURL:requestURL + callbackURLScheme:redirectScheme + completionHandler:^(NSURL * _Nullable callbackURL, + NSError * _Nullable error) { + __strong OIDExternalUserAgentMac *strongSelf = weakSelf; + if (!strongSelf) { + return; + } + strongSelf->_webAuthenticationSession = nil; + if (callbackURL) { + [strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL]; + } else { + NSError *safariError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:error + description:nil]; + [strongSelf->_session failExternalUserAgentFlowWithError:safariError]; + } + }]; + + authenticationSession.presentationContextProvider = self; + + _webAuthenticationSession = authenticationSession; + _webAuthenticationSession.prefersEphemeralWebBrowserSession = _prefersEphemeralSession; + return [authenticationSession start]; + } + } + + BOOL openedBrowser = [[NSWorkspace sharedWorkspace] openURL:requestURL]; + if (!openedBrowser) { + [self cleanUp]; + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeBrowserOpenError + underlyingError:nil + description:@"Unable to open the browser."]; + [session failExternalUserAgentFlowWithError:safariError]; + } + return openedBrowser; +} + +- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion { + if (!_externalUserAgentFlowInProgress) { + // Ignore this call if there is no authorization flow in progress. + if (completion) completion(); + return; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wpartial-availability" + ASWebAuthenticationSession *webAuthenticationSession = _webAuthenticationSession; +#pragma clang diagnostic pop + + // Ideally the browser tab with the URL should be closed here, but the AppAuth library does not + // control the browser. + [self cleanUp]; + if (webAuthenticationSession) { + // dismiss the ASWebAuthenticationSession + [webAuthenticationSession cancel]; + if (completion) completion(); + } else if (completion) { + completion(); + } +} + +- (void)cleanUp { + _session = nil; + _externalUserAgentFlowInProgress = NO; + _webAuthenticationSession = nil; +} + +#pragma mark - ASWebAuthenticationPresentationContextProviding + +- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session + API_AVAILABLE(macosx(10.15)) { + return _presentingWindow; +} + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDRedirectHTTPHandler.h b/Pods/AppAuth/Sources/AppAuth/macOS/OIDRedirectHTTPHandler.h new file mode 100644 index 0000000..831eb0b --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDRedirectHTTPHandler.h @@ -0,0 +1,90 @@ +/*! @file OIDRedirectHTTPHandler.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import + +NS_ASSUME_NONNULL_BEGIN + +@protocol OIDExternalUserAgentSession; + +/*! @brief Start a HTTP server on the loopback interface (i.e. @c 127.0.0.1) to receive the OAuth + response redirects on macOS. + */ +@interface OIDRedirectHTTPHandler : NSObject + +/*! @brief The external user-agent request flow session which receives the return URL from the + browser. + @discussion The loopback HTTP server will try sending incoming request URLs to the OAuth + redirect handler to continue the flow. This should be set while an external user-agent + request flow is in progress. + */ +@property(nonatomic, strong, nullable) id currentAuthorizationFlow; + +/*! @brief Creates an a loopback HTTP redirect URI handler with the given success URL. + @param successURL The URL that the user is redirected to after the external user-agent request flow completes + either with a result of success or error. The contents of this page should instruct the user + to return to the app. + @discussion Once you have initiated the external user-agent request, be sure to set + @c currentAuthorizationFlow on this object so that any responses received by this listener will + be routed accordingly. + */ +- (instancetype)initWithSuccessURL:(nullable NSURL *)successURL; + +/*! @brief Starts listening on the loopback interface on a specified port, and returns a URL + with the base address. Use the returned redirect URI to build a @c OIDExternalUserAgentRequest, + and once you initiate the request, set the resulting @c OIDExternalUserAgentSession to + @c currentAuthorizationFlow so the response can be handled. + @param returnError The error if an error occurred while starting the local HTTP server. + @param port The manually specified port, or 0 for a random available port. + @return The URL containing the address of the server with the specified port, or nil if there was an error. + @discussion Each instance of @c OIDRedirectHTTPHandler can only listen for a single response. + Calling this more than once will result in the previous listener being cancelled (equivalent + of @c cancelHTTPListener being called). + */ +- (NSURL *)startHTTPListener:(NSError **)returnError withPort:(uint16_t)port; + +/*! @brief Starts listening on the loopback interface on a random available port, and returns a URL + with the base address. Use the returned redirect URI to build a @c OIDExternalUserAgentRequest, + and once you initiate the request, set the resulting @c OIDExternalUserAgentSession to + @c currentAuthorizationFlow so the response can be handled. + @param returnError The error if an error occurred while starting the local HTTP server. + @return The URL containing the address of the server with the randomly assigned available port. + @discussion Each instance of @c OIDRedirectHTTPHandler can only listen for a single response. + Calling this more than once will result in the previous listener being cancelled (equivalent + of @c cancelHTTPListener being called). + */ +- (NSURL *)startHTTPListener:(NSError **)returnError; + +/*! @brief Stops listening the loopback interface and sends an cancellation error (in the domain + ::OIDGeneralErrorDomain, with the code ::OIDErrorCodeProgramCanceledAuthorizationFlow) to + the @c currentAuthorizationFlow. Has no effect if called when no requests are pending. + @discussion The HTTP listener is stopped automatically on receiving a valid response (regardless + of whether the request succeeded or not), this method should not be called except when + abandoning the external user-agent request. + */ +- (void)cancelHTTPListener; + +@end + +NS_ASSUME_NONNULL_END + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuth/macOS/OIDRedirectHTTPHandler.m b/Pods/AppAuth/Sources/AppAuth/macOS/OIDRedirectHTTPHandler.m new file mode 100644 index 0000000..3d0d765 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuth/macOS/OIDRedirectHTTPHandler.m @@ -0,0 +1,177 @@ +/*! @file OIDRedirectHTTPHandler.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#if TARGET_OS_OSX + +#import "OIDRedirectHTTPHandler.h" + +#import "OIDAuthorizationService.h" +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDLoopbackHTTPServer.h" + +/*! @brief Page that is returned following a completed authorization. Show your own page instead by + supplying a URL in @c initWithSuccessURL that the user will be redirected to. + */ +static NSString *const kHTMLAuthorizationComplete = + @"Authorization complete.
Return to the app."; + +/*! @brief Error warning that the @c currentAuthorizationFlow is not set on this object (likely a + developer error, unless the user stumbled upon the loopback server before the authorization + had started completely). + @description An object conforming to @c OIDExternalUserAgentSession is returned when the + authorization is presented with + @c OIDAuthorizationService::presentAuthorizationRequest:callback:. It should be set to + @c currentAuthorization when using a loopback redirect. + */ +static NSString *const kHTMLErrorMissingCurrentAuthorizationFlow = + @"AppAuth Error: No currentAuthorizationFlow is set on the " + "OIDRedirectHTTPHandler. Cannot process redirect."; + +/*! @brief Error warning that the URL does not represent a valid redirect. This should be rare, may + happen if the user stumbles upon the loopback server randomly. + */ +static NSString *const kHTMLErrorRedirectNotValid = + @"AppAuth Error: Not a valid redirect."; + +@implementation OIDRedirectHTTPHandler { + HTTPServer *_httpServ; + NSURL *_successURL; +} + +- (instancetype)init { + return [self initWithSuccessURL:nil]; +} + +- (instancetype)initWithSuccessURL:(nullable NSURL *)successURL { + self = [super init]; + if (self) { + _successURL = [successURL copy]; + } + return self; +} + +- (NSURL *)startHTTPListener:(NSError **)returnError withPort:(uint16_t)port { + // Cancels any pending requests. + [self cancelHTTPListener]; + + // Starts a HTTP server on the loopback interface. + // By not specifying a port, a random available one will be assigned. + _httpServ = [[HTTPServer alloc] init]; + [_httpServ setPort:port]; + [_httpServ setDelegate:self]; + NSError *error = nil; + if (![_httpServ start:&error]) { + if (returnError) { + *returnError = error; + } + return nil; + } else if ([_httpServ hasIPv4Socket]) { + // Prefer the IPv4 loopback address + NSString *serverURL = [NSString stringWithFormat:@"http://127.0.0.1:%d/", [_httpServ port]]; + return [NSURL URLWithString:serverURL]; + } else if ([_httpServ hasIPv6Socket]) { + // Use the IPv6 loopback address if IPv4 isn't available + NSString *serverURL = [NSString stringWithFormat:@"http://[::1]:%d/", [_httpServ port]]; + return [NSURL URLWithString:serverURL]; + } + + return nil; +} + +- (NSURL *)startHTTPListener:(NSError **)returnError { + // A port of 0 requests a random available port + return [self startHTTPListener:returnError withPort:0]; +} + +- (void)cancelHTTPListener { + [self stopHTTPListener]; + + // Cancels the pending authorization flow (if any) with error. + NSError *cancelledError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeProgramCanceledAuthorizationFlow + underlyingError:nil + description:@"The HTTP listener was cancelled programmatically."]; + [_currentAuthorizationFlow failExternalUserAgentFlowWithError:cancelledError]; + _currentAuthorizationFlow = nil; +} + +/*! @brief Stops listening on the loopback interface without modifying the state of the + @c currentAuthorizationFlow. Should be called when the authorization flow completes or is + cancelled. + */ +- (void)stopHTTPListener { + _httpServ.delegate = nil; + [_httpServ stop]; + _httpServ = nil; +} + +- (void)HTTPConnection:(HTTPConnection *)conn didReceiveRequest:(HTTPServerRequest *)mess { + // Sends URL to AppAuth. + CFURLRef url = CFHTTPMessageCopyRequestURL(mess.request); + BOOL handled = [_currentAuthorizationFlow resumeExternalUserAgentFlowWithURL:(__bridge NSURL *)url]; + + // Stops listening to further requests after the first valid authorization response. + if (handled) { + _currentAuthorizationFlow = nil; + [self stopHTTPListener]; + } + + // Responds to browser request. + NSString *bodyText = kHTMLAuthorizationComplete; + NSInteger httpResponseCode = (_successURL) ? 302 : 200; + // Returns an error page if a URL other than the expected redirect is requested. + if (!handled) { + if (_currentAuthorizationFlow) { + bodyText = kHTMLErrorRedirectNotValid; + httpResponseCode = 404; + } else { + bodyText = kHTMLErrorMissingCurrentAuthorizationFlow; + httpResponseCode = 400; + } + } + NSData *data = [bodyText dataUsingEncoding:NSUTF8StringEncoding]; + + CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, + httpResponseCode, + NULL, + kCFHTTPVersion1_1); + if (httpResponseCode == 302) { + CFHTTPMessageSetHeaderFieldValue(response, + (__bridge CFStringRef)@"Location", + (__bridge CFStringRef)_successURL.absoluteString); + } + CFHTTPMessageSetHeaderFieldValue(response, + (__bridge CFStringRef)@"Content-Length", + (__bridge CFStringRef)[NSString stringWithFormat:@"%lu", + (unsigned long)data.length]); + CFHTTPMessageSetBody(response, (__bridge CFDataRef)data); + + [mess setResponse:response]; + CFRelease(response); +} + +- (void)dealloc { + [self cancelHTTPListener]; +} + +@end + +#endif // TARGET_OS_OSX diff --git a/Pods/AppAuth/Sources/AppAuthCore.h b/Pods/AppAuth/Sources/AppAuthCore.h new file mode 100644 index 0000000..c30af46 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore.h @@ -0,0 +1,44 @@ +/*! @file AppAuthCore.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthState.h" +#import "OIDAuthStateChangeDelegate.h" +#import "OIDAuthStateErrorDelegate.h" +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationService.h" +#import "OIDError.h" +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgent.h" +#import "OIDExternalUserAgentRequest.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDGrantTypes.h" +#import "OIDIDToken.h" +#import "OIDRegistrationRequest.h" +#import "OIDRegistrationResponse.h" +#import "OIDResponseTypes.h" +#import "OIDScopes.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDTokenUtilities.h" +#import "OIDURLSessionProvider.h" +#import "OIDEndSessionRequest.h" +#import "OIDEndSessionResponse.h" diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthState.h b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthState.h new file mode 100644 index 0000000..46c78a8 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthState.h @@ -0,0 +1,303 @@ +/*! @file OIDAuthState.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +#import + +@class OIDAuthorizationRequest; +@class OIDAuthorizationResponse; +@class OIDAuthState; +@class OIDRegistrationResponse; +@class OIDTokenResponse; +@class OIDTokenRequest; +@protocol OIDAuthStateChangeDelegate; +@protocol OIDAuthStateErrorDelegate; +@protocol OIDExternalUserAgent; +@protocol OIDExternalUserAgentSession; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a block used to call an action with a fresh access token. + @param accessToken A valid access token if available. + @param idToken A valid ID token if available. + @param error The error if an error occurred. + */ +typedef void (^OIDAuthStateAction)(NSString *_Nullable accessToken, + NSString *_Nullable idToken, + NSError *_Nullable error); + +/*! @brief The method called when the @c + OIDAuthState.authStateByPresentingAuthorizationRequest:presentingViewController:callback: + method has completed or failed. + @param authState The auth state, if the authorization request succeeded. + @param error The error if an error occurred. + */ +typedef void (^OIDAuthStateAuthorizationCallback)(OIDAuthState *_Nullable authState, + NSError *_Nullable error); + +/*! @brief The exception thrown when a developer tries to create a refresh request from an + authorization request with no authorization code. + */ +static NSString *const kRefreshTokenRequestException = + @"Attempted to create a token refresh request from a token response with no refresh token."; + +/*! @brief A convenience class that retains the auth state between @c OIDAuthorizationResponse%s + and @c OIDTokenResponse%s. + */ +@interface OIDAuthState : NSObject + +/*! @brief The most recent refresh token received from the server. + @discussion Rather than using this property directly, you should call + @c OIDAuthState.performActionWithFreshTokens:. + @remarks refresh_token + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/*! @brief The scope of the current authorization grant. + @discussion This represents the latest scope returned by the server and may be a subset of the + scope that was initially granted. + @remarks scope + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief The most recent authorization response used to update the authorization state. For the + implicit flow, this will contain the latest access token. + */ +@property(nonatomic, readonly) OIDAuthorizationResponse *lastAuthorizationResponse; + +/*! @brief The most recent token response used to update this authorization state. This will + contain the latest access token. + */ +@property(nonatomic, readonly, nullable) OIDTokenResponse *lastTokenResponse; + +/*! @brief The most recent registration response used to update this authorization state. This will + contain the latest client credentials. + */ +@property(nonatomic, readonly, nullable) OIDRegistrationResponse *lastRegistrationResponse; + +/*! @brief The authorization error that invalidated this @c OIDAuthState. + @discussion The authorization error encountered by @c OIDAuthState or set by the user via + @c OIDAuthState.updateWithAuthorizationError: that invalidated this @c OIDAuthState. + Authorization errors from @c OIDAuthState will always have a domain of + @c ::OIDOAuthAuthorizationErrorDomain or @c ::OIDOAuthTokenErrorDomain. Note: that after + unarchiving the @c OIDAuthState object, the \NSError_userInfo property of this error will + be nil. + */ +@property(nonatomic, readonly, nullable) NSError *authorizationError; + +/*! @brief Returns YES if the authorization state is not known to be invalid. + @discussion Returns YES if no OAuth errors have been received, and the last call resulted in a + successful access token or id token. This does not mean that the access is fresh - just + that it was valid the last time it was used. Note that network and other transient errors + do not invalidate the authorized state. If NO, you should authenticate the user again, + using a fresh authorization request. Invalid @c OIDAuthState objects may still be useful in + that case, to hint at the previously authorized user and streamline the re-authentication + experience. + */ +@property(nonatomic, readonly) BOOL isAuthorized; + +/*! @brief The @c OIDAuthStateChangeDelegate delegate. + @discussion Use the delegate to observe state changes (and update storage) as well as error + states. + */ +@property(nonatomic, weak, nullable) id stateChangeDelegate; + +/*! @brief The @c OIDAuthStateErrorDelegate delegate. + @discussion Use the delegate to observe state changes (and update storage) as well as error + states. + */ +@property(nonatomic, weak, nullable) id errorDelegate; + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + and performing the authorization code exchange in the case of code flow requests. For + the hybrid flow, the caller should validate the id_token and c_hash, then perform the token + request (@c OIDAuthorizationService.performTokenRequest:callback:) + and update the OIDAuthState with the results (@c + OIDAuthState.updateWithTokenResponse:error:). + @param authorizationRequest The authorization request to present. + @param externalUserAgent A external user agent that can present an external user-agent request. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + externalUserAgent:(id)externalUserAgent + callback:(OIDAuthStateAuthorizationCallback)callback; + +/*! @internal + @brief Unavailable. Please use @c initWithAuthorizationResponse:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Creates an auth state from an authorization response. + @param authorizationResponse The authorization response. + */ +- (instancetype)initWithAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse; + +/*! @brief Creates an auth state from an authorization and token response. + @param authorizationResponse The authorization response. + @param tokenResponse The token response. + */ +- (instancetype)initWithAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse + tokenResponse:(nullable OIDTokenResponse *)tokenResponse; + +/*! @brief Creates an auth state from an registration response. + @param registrationResponse The registration response. + */ +- (instancetype)initWithRegistrationResponse:(OIDRegistrationResponse *)registrationResponse; + +/*! @brief Creates an auth state from an authorization, token and registration response. + @param authorizationResponse The authorization response. + @param tokenResponse The token response. + @param registrationResponse The registration response. + */ +- (instancetype)initWithAuthorizationResponse: + (nullable OIDAuthorizationResponse *)authorizationResponse + tokenResponse:(nullable OIDTokenResponse *)tokenResponse + registrationResponse:(nullable OIDRegistrationResponse *)registrationResponse + NS_DESIGNATED_INITIALIZER; + +/*! @brief Updates the authorization state based on a new authorization response. + @param authorizationResponse The new authorization response to update the state with. + @param error Any error encountered when performing the authorization request. Errors in the + domain @c ::OIDOAuthAuthorizationErrorDomain are reflected in the auth state, other errors + are assumed to be transient, and ignored. + @discussion Typically called with the response from an incremental authorization request, + or if using the implicit flow. Will clear the @c #lastTokenResponse property. + */ +- (void)updateWithAuthorizationResponse:(nullable OIDAuthorizationResponse *)authorizationResponse + error:(nullable NSError *)error; + +/*! @brief Updates the authorization state based on a new token response. + @param tokenResponse The new token response to update the state from. + @param error Any error encountered when performing the authorization request. Errors in the + domain @c ::OIDOAuthTokenErrorDomain are reflected in the auth state, other errors + are assumed to be transient, and ignored. + @discussion Typically called with the response from an authorization code exchange, or a token + refresh. + */ +- (void)updateWithTokenResponse:(nullable OIDTokenResponse *)tokenResponse + error:(nullable NSError *)error; + +/*! @brief Updates the authorization state based on a new registration response. + @param registrationResponse The new registration response to update the state with. + @discussion Typically called with the response from a successful client registration + request. Will reset the auth state. + */ +- (void)updateWithRegistrationResponse:(nullable OIDRegistrationResponse *)registrationResponse; + +/*! @brief Updates the authorization state based on an authorization error. + @param authorizationError The authorization error. + @discussion Call this method if you receive an authorization error during an API call to + invalidate the authentication state of this @c OIDAuthState. Don't call with errors + unrelated to authorization, such as transient network errors. + The OIDAuthStateErrorDelegate.authState:didEncounterAuthorizationError: method of + @c #errorDelegate will be called with the error. + You may optionally use the convenience method + OIDErrorUtilities.resourceServerAuthorizationErrorWithCode:errorResponse:underlyingError: + to create \NSError objects for use here. + The latest error received is stored in @c #authorizationError. Note: that after unarchiving + this object, the \NSError_userInfo property of this error will be nil. + */ +- (void)updateWithAuthorizationError:(NSError *)authorizationError; + +/*! @brief Calls the block with a valid access token (refreshing it first, if needed), or if a + refresh was needed and failed, with the error that caused it to fail. + @param action The block to execute with a fresh token. This block will be executed on the main + thread. + */ +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action; + +/*! @brief Calls the block with a valid access token (refreshing it first, if needed), or if a + refresh was needed and failed, with the error that caused it to fail. + @param action The block to execute with a fresh token. This block will be executed on the main + thread. + @param additionalParameters Additional parameters for the token request if token is + refreshed. + */ +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action + additionalRefreshParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Calls the block with a valid access token (refreshing it first, if needed), or if a + refresh was needed and failed, with the error that caused it to fail. + @param action The block to execute with a fresh token. This block will be executed on the main + thread. + @param additionalParameters Additional parameters for the token request if token is + refreshed. + @param dispatchQueue The dispatchQueue on which to dispatch the action block. + */ +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action + additionalRefreshParameters: + (nullable NSDictionary *)additionalParameters + dispatchQueue:(dispatch_queue_t)dispatchQueue; + +/*! @brief Forces a token refresh the next time @c OIDAuthState.performActionWithFreshTokens: is + called, even if the current tokens are considered valid. + */ +- (void)setNeedsTokenRefresh; + +/*! @brief Creates a token request suitable for refreshing an access token. + @return A @c OIDTokenRequest suitable for using a refresh token to obtain a new access token. + @discussion After performing the refresh, call @c OIDAuthState.updateWithTokenResponse:error: + to update the authorization state based on the response. Rather than doing the token refresh + yourself, you should use @c OIDAuthState.performActionWithFreshTokens:. + @see https://tools.ietf.org/html/rfc6749#section-1.5 + */ +- (nullable OIDTokenRequest *)tokenRefreshRequest; + +/*! @brief Creates a token request suitable for refreshing an access token. + @param additionalParameters Additional parameters for the token request. + @return A @c OIDTokenRequest suitable for using a refresh token to obtain a new access token. + @discussion After performing the refresh, call @c OIDAuthState.updateWithTokenResponse:error: + to update the authorization state based on the response. Rather than doing the token refresh + yourself, you should use @c OIDAuthState.performActionWithFreshTokens:. + @see https://tools.ietf.org/html/rfc6749#section-1.5 + */ +- (nullable OIDTokenRequest *)tokenRefreshRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Creates a token request suitable for refreshing an access token. + @param additionalParameters Additional parameters for the token request. + @param additionalHeaders Additional headers for the token request. + @return A @c OIDTokenRequest suitable for using a refresh token to obtain a new access token. + @discussion After performing the refresh, call @c OIDAuthState.updateWithTokenResponse:error: + to update the authorization state based on the response. Rather than doing the token refresh + yourself, you should use @c OIDAuthState.performActionWithFreshTokens:. + @see https://tools.ietf.org/html/rfc6749#section-1.5 + */ +- (nullable OIDTokenRequest *)tokenRefreshRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders; + +/*! @brief Creates a token request suitable for refreshing an access token. + @param additionalHeaders Additional parameters for the token request. + @return A @c OIDTokenRequest suitable for using a refresh token to obtain a new access token. + @discussion After performing the refresh, call @c OIDAuthState.updateWithTokenResponse:error: + to update the authorization state based on the response. Rather than doing the token refresh + yourself, you should use @c OIDAuthState.performActionWithFreshTokens:. + @see https://tools.ietf.org/html/rfc6749#section-1.5 + */ +- (nullable OIDTokenRequest *)tokenRefreshRequestWithAdditionalHeaders: + (nullable NSDictionary *)additionalHeaders; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthState.m b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthState.m new file mode 100644 index 0000000..cb5a22a --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthState.m @@ -0,0 +1,605 @@ +/*! @file OIDAuthState.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthState.h" + +#import "OIDAuthStateChangeDelegate.h" +#import "OIDAuthStateErrorDelegate.h" +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationService.h" +#import "OIDDefines.h" +#import "OIDError.h" +#import "OIDErrorUtilities.h" +#import "OIDRegistrationResponse.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDTokenUtilities.h" + +/*! @brief Key used to encode the @c refreshToken property for @c NSSecureCoding. + */ +static NSString *const kRefreshTokenKey = @"refreshToken"; + +/*! @brief Key used to encode the @c needsTokenRefresh property for @c NSSecureCoding. + */ +static NSString *const kNeedsTokenRefreshKey = @"needsTokenRefresh"; + +/*! @brief Key used to encode the @c scope property for @c NSSecureCoding. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c lastAuthorizationResponse property for @c NSSecureCoding. + */ +static NSString *const kLastAuthorizationResponseKey = @"lastAuthorizationResponse"; + +/*! @brief Key used to encode the @c lastTokenResponse property for @c NSSecureCoding. + */ +static NSString *const kLastTokenResponseKey = @"lastTokenResponse"; + +/*! @brief Key used to encode the @c lastOAuthError property for @c NSSecureCoding. + */ +static NSString *const kAuthorizationErrorKey = @"authorizationError"; + +/*! @brief Number of seconds the access token is refreshed before it actually expires. + */ +static const NSUInteger kExpiryTimeTolerance = 60; + +/*! @brief Object to hold OIDAuthState pending actions. + */ +@interface OIDAuthStatePendingAction : NSObject +@property(nonatomic, readonly, nullable) OIDAuthStateAction action; +@property(nonatomic, readonly, nullable) dispatch_queue_t dispatchQueue; +@end +@implementation OIDAuthStatePendingAction +- (id)initWithAction:(OIDAuthStateAction)action andDispatchQueue:(dispatch_queue_t)dispatchQueue { + self = [super init]; + if (self) { + _action = action; + _dispatchQueue = dispatchQueue; + } + return self; +} +@end + +@interface OIDAuthState () + +/*! @brief The access token generated by the authorization server. + @discussion Rather than using this property directly, you should call + @c OIDAuthState.withFreshTokenPerformAction:. + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/*! @brief The approximate expiration date & time of the access token. + @discussion Rather than using this property directly, you should call + @c OIDAuthState.withFreshTokenPerformAction:. + */ +@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate; + +/*! @brief ID Token value associated with the authenticated session. + @discussion Rather than using this property directly, you should call + OIDAuthState.withFreshTokenPerformAction:. + */ +@property(nonatomic, readonly, nullable) NSString *idToken; + +/*! @brief Private method, called when the internal state changes. + */ +- (void)didChangeState; + +@end + + +@implementation OIDAuthState { + /*! @brief Array of pending actions (use @c _pendingActionsSyncObject to synchronize access). + */ + NSMutableArray *_pendingActions; + + /*! @brief Object for synchronizing access to @c pendingActions. + */ + id _pendingActionsSyncObject; + + /*! @brief If YES, tokens will be refreshed on the next API call regardless of expiry. + */ + BOOL _needsTokenRefresh; +} + +#pragma mark - Convenience initializers + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + externalUserAgent:(id)externalUserAgent + callback:(OIDAuthStateAuthorizationCallback)callback { + // presents the authorization request + id authFlowSession = [OIDAuthorizationService + presentAuthorizationRequest:authorizationRequest + externalUserAgent:externalUserAgent + callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse, + NSError *_Nullable authorizationError) { + // inspects response and processes further if needed (e.g. authorization + // code exchange) + if (authorizationResponse) { + if ([authorizationRequest.responseType + isEqualToString:OIDResponseTypeCode]) { + // if the request is for the code flow (NB. not hybrid), assumes the + // code is intended for this client, and performs the authorization + // code exchange + OIDTokenRequest *tokenExchangeRequest = + [authorizationResponse tokenExchangeRequest]; + [OIDAuthorizationService performTokenRequest:tokenExchangeRequest + originalAuthorizationResponse:authorizationResponse + callback:^(OIDTokenResponse *_Nullable tokenResponse, + NSError *_Nullable tokenError) { + OIDAuthState *authState; + if (tokenResponse) { + authState = [[OIDAuthState alloc] + initWithAuthorizationResponse: + authorizationResponse + tokenResponse:tokenResponse]; + } + callback(authState, tokenError); + }]; + } else { + // hybrid flow (code id_token). Two possible cases: + // 1. The code is not for this client, ie. will be sent to a + // webservice that performs the id token verification and token + // exchange + // 2. The code is for this client and, for security reasons, the + // application developer must verify the id_token signature and + // c_hash before calling the token endpoint + OIDAuthState *authState = [[OIDAuthState alloc] + initWithAuthorizationResponse:authorizationResponse]; + callback(authState, authorizationError); + } + } else { + callback(nil, authorizationError); + } + }]; + return authFlowSession; +} + +#pragma mark - Initializers + +- (nonnull instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithAuthorizationResponse:tokenResponse:)) + +/*! @brief Creates an auth state from an authorization response. + @param authorizationResponse The authorization response. + */ +- (instancetype)initWithAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse { + return [self initWithAuthorizationResponse:authorizationResponse tokenResponse:nil]; +} + + +/*! @brief Designated initializer. + @param authorizationResponse The authorization response. + @discussion Creates an auth state from an authorization response and token response. + */ +- (instancetype)initWithAuthorizationResponse:(OIDAuthorizationResponse *)authorizationResponse + tokenResponse:(nullable OIDTokenResponse *)tokenResponse { + return [self initWithAuthorizationResponse:authorizationResponse + tokenResponse:tokenResponse + registrationResponse:nil]; +} + +/*! @brief Creates an auth state from an registration response. + @param registrationResponse The registration response. + */ +- (instancetype)initWithRegistrationResponse:(OIDRegistrationResponse *)registrationResponse { + return [self initWithAuthorizationResponse:nil + tokenResponse:nil + registrationResponse:registrationResponse]; +} + +- (instancetype)initWithAuthorizationResponse: + (nullable OIDAuthorizationResponse *)authorizationResponse + tokenResponse:(nullable OIDTokenResponse *)tokenResponse + registrationResponse:(nullable OIDRegistrationResponse *)registrationResponse { + self = [super init]; + if (self) { + _pendingActionsSyncObject = [[NSObject alloc] init]; + + if (registrationResponse) { + [self updateWithRegistrationResponse:registrationResponse]; + } + + if (authorizationResponse) { + [self updateWithAuthorizationResponse:authorizationResponse error:nil]; + } + + if (tokenResponse) { + [self updateWithTokenResponse:tokenResponse error:nil]; + } + } + return self; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, isAuthorized: %@, refreshToken: \"%@\", " + "scope: \"%@\", accessToken: \"%@\", " + "accessTokenExpirationDate: %@, idToken: \"%@\", " + "lastAuthorizationResponse: %@, lastTokenResponse: %@, " + "lastRegistrationResponse: %@, authorizationError: %@>", + NSStringFromClass([self class]), + (void *)self, + (self.isAuthorized) ? @"YES" : @"NO", + [OIDTokenUtilities redact:_refreshToken], + _scope, + [OIDTokenUtilities redact:self.accessToken], + self.accessTokenExpirationDate, + [OIDTokenUtilities redact:self.idToken], + _lastAuthorizationResponse, + _lastTokenResponse, + _lastRegistrationResponse, + _authorizationError]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + _lastAuthorizationResponse = [aDecoder decodeObjectOfClass:[OIDAuthorizationResponse class] + forKey:kLastAuthorizationResponseKey]; + _lastTokenResponse = [aDecoder decodeObjectOfClass:[OIDTokenResponse class] + forKey:kLastTokenResponseKey]; + self = [self initWithAuthorizationResponse:_lastAuthorizationResponse + tokenResponse:_lastTokenResponse]; + if (self) { + _authorizationError = + [aDecoder decodeObjectOfClass:[NSError class] forKey:kAuthorizationErrorKey]; + _scope = [aDecoder decodeObjectOfClass:[NSString class] forKey:kScopeKey]; + _refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey]; + _needsTokenRefresh = [aDecoder decodeBoolForKey:kNeedsTokenRefreshKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_lastAuthorizationResponse forKey:kLastAuthorizationResponseKey]; + [aCoder encodeObject:_lastTokenResponse forKey:kLastTokenResponseKey]; + if (_authorizationError) { + NSError *codingSafeAuthorizationError = [NSError errorWithDomain:_authorizationError.domain + code:_authorizationError.code + userInfo:nil]; + [aCoder encodeObject:codingSafeAuthorizationError forKey:kAuthorizationErrorKey]; + } + [aCoder encodeObject:_scope forKey:kScopeKey]; + [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey]; + [aCoder encodeBool:_needsTokenRefresh forKey:kNeedsTokenRefreshKey]; +} + +#pragma mark - Private convenience getters + +- (NSString *)accessToken { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.accessToken + : _lastAuthorizationResponse.accessToken; +} + +- (NSString *)tokenType { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.tokenType + : _lastAuthorizationResponse.tokenType; +} + +- (NSDate *)accessTokenExpirationDate { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.accessTokenExpirationDate + : _lastAuthorizationResponse.accessTokenExpirationDate; +} + +- (NSString *)idToken { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.idToken + : _lastAuthorizationResponse.idToken; +} + +#pragma mark - Getters + +- (BOOL)isAuthorized { + return !self.authorizationError && (self.accessToken || self.idToken || self.refreshToken); +} + +#pragma mark - Updating the state + +- (void)updateWithRegistrationResponse:(OIDRegistrationResponse *)registrationResponse { + _lastRegistrationResponse = registrationResponse; + _refreshToken = nil; + _scope = nil; + _lastAuthorizationResponse = nil; + _lastTokenResponse = nil; + _authorizationError = nil; + [self didChangeState]; +} + +- (void)updateWithAuthorizationResponse:(nullable OIDAuthorizationResponse *)authorizationResponse + error:(nullable NSError *)error { + // If the error is an OAuth authorization error, updates the state. Other errors are ignored. + if (error.domain == OIDOAuthAuthorizationErrorDomain) { + [self updateWithAuthorizationError:error]; + return; + } + if (!authorizationResponse) { + return; + } + + _lastAuthorizationResponse = authorizationResponse; + + // clears the last token response and refresh token as these now relate to an old authorization + // that is no longer relevant + _lastTokenResponse = nil; + _refreshToken = nil; + _authorizationError = nil; + + // if the response's scope is nil, it means that it equals that of the request + // see: https://tools.ietf.org/html/rfc6749#section-5.1 + _scope = (authorizationResponse.scope) ? authorizationResponse.scope + : authorizationResponse.request.scope; + + [self didChangeState]; +} + +- (void)updateWithTokenResponse:(nullable OIDTokenResponse *)tokenResponse + error:(nullable NSError *)error { + if (_authorizationError) { + // Calling updateWithTokenResponse while in an error state probably means the developer obtained + // a new token and did the exchange without also calling updateWithAuthorizationResponse. + // Attempts to handle gracefully, but warns the developer that this is unexpected. + NSLog(@"OIDAuthState:updateWithTokenResponse should not be called in an error state [%@] call" + "updateWithAuthorizationResponse with the result of the fresh authorization response" + "first", + _authorizationError); + + _authorizationError = nil; + } + + // If the error is an OAuth authorization error, updates the state. Other errors are ignored. + if (error.domain == OIDOAuthTokenErrorDomain) { + [self updateWithAuthorizationError:error]; + return; + } + if (!tokenResponse) { + return; + } + + _lastTokenResponse = tokenResponse; + + // updates the scope and refresh token if they are present on the TokenResponse. + // according to the spec, these may be changed by the server, including when refreshing the + // access token. See: https://tools.ietf.org/html/rfc6749#section-5.1 and + // https://tools.ietf.org/html/rfc6749#section-6 + if (tokenResponse.scope) { + _scope = tokenResponse.scope; + } + if (tokenResponse.refreshToken) { + _refreshToken = tokenResponse.refreshToken; + } + + [self didChangeState]; +} + +- (void)updateWithAuthorizationError:(NSError *)oauthError { + _authorizationError = oauthError; + + [self didChangeState]; + + [_errorDelegate authState:self didEncounterAuthorizationError:oauthError]; +} + +#pragma mark - OAuth Requests + +- (OIDTokenRequest *)tokenRefreshRequest { + return [self tokenRefreshRequestWithAdditionalParameters:nil]; +} + +- (OIDTokenRequest *)tokenRefreshRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters { + + if (!_refreshToken) { + [OIDErrorUtilities raiseException:kRefreshTokenRequestException]; + } + return [[OIDTokenRequest alloc] + initWithConfiguration:_lastAuthorizationResponse.request.configuration + grantType:OIDGrantTypeRefreshToken + authorizationCode:nil + redirectURL:nil + clientID:_lastAuthorizationResponse.request.clientID + clientSecret:_lastAuthorizationResponse.request.clientSecret + scope:nil + refreshToken:_refreshToken + codeVerifier:nil + additionalParameters:additionalParameters + additionalHeaders:nil]; +} + +- (OIDTokenRequest *)tokenRefreshRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters + additionalHeaders: + (NSDictionary *)additionalHeaders { + + if (!_refreshToken) { + [OIDErrorUtilities raiseException:kRefreshTokenRequestException]; + } + return [[OIDTokenRequest alloc] + initWithConfiguration:_lastAuthorizationResponse.request.configuration + grantType:OIDGrantTypeRefreshToken + authorizationCode:nil + redirectURL:nil + clientID:_lastAuthorizationResponse.request.clientID + clientSecret:_lastAuthorizationResponse.request.clientSecret + scope:nil + refreshToken:_refreshToken + codeVerifier:nil + additionalParameters:additionalParameters + additionalHeaders:additionalHeaders]; +} + +- (OIDTokenRequest *)tokenRefreshRequestWithAdditionalHeaders: + (NSDictionary *)additionalHeaders { + + if (!_refreshToken) { + [OIDErrorUtilities raiseException:kRefreshTokenRequestException]; + } + return [[OIDTokenRequest alloc] + initWithConfiguration:_lastAuthorizationResponse.request.configuration + grantType:OIDGrantTypeRefreshToken + authorizationCode:nil + redirectURL:nil + clientID:_lastAuthorizationResponse.request.clientID + clientSecret:_lastAuthorizationResponse.request.clientSecret + scope:nil + refreshToken:_refreshToken + codeVerifier:nil + additionalParameters:nil + additionalHeaders:additionalHeaders]; +} + +#pragma mark - Stateful Actions + +- (void)didChangeState { + [_stateChangeDelegate didChangeState:self]; +} + +- (void)setNeedsTokenRefresh { + _needsTokenRefresh = YES; +} + +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action { + [self performActionWithFreshTokens:action additionalRefreshParameters:nil]; +} + +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action + additionalRefreshParameters: + (nullable NSDictionary *)additionalParameters { + [self performActionWithFreshTokens:action + additionalRefreshParameters:additionalParameters + dispatchQueue:dispatch_get_main_queue()]; +} + +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action + additionalRefreshParameters: + (nullable NSDictionary *)additionalParameters + dispatchQueue:(dispatch_queue_t)dispatchQueue { + + if ([self isTokenFresh]) { + // access token is valid within tolerance levels, perform action + dispatch_async(dispatchQueue, ^{ + action(self.accessToken, self.idToken, nil); + }); + return; + } + + if (!_refreshToken) { + // no refresh token available and token has expired + NSError *tokenRefreshError = [ + OIDErrorUtilities errorWithCode:OIDErrorCodeTokenRefreshError + underlyingError:nil + description:@"Unable to refresh expired token without a refresh token."]; + dispatch_async(dispatchQueue, ^{ + action(nil, nil, tokenRefreshError); + }); + return; + } + + // access token is expired, first refresh the token, then perform action + NSAssert(_pendingActionsSyncObject, @"_pendingActionsSyncObject cannot be nil", @""); + OIDAuthStatePendingAction* pendingAction = + [[OIDAuthStatePendingAction alloc] initWithAction:action andDispatchQueue:dispatchQueue]; + @synchronized(_pendingActionsSyncObject) { + // if a token is already in the process of being refreshed, adds to pending actions + if (_pendingActions) { + [_pendingActions addObject:pendingAction]; + return; + } + + // creates a list of pending actions, starting with this one + _pendingActions = [NSMutableArray arrayWithObject:pendingAction]; + } + + // refresh the tokens + OIDTokenRequest *tokenRefreshRequest = + [self tokenRefreshRequestWithAdditionalParameters:additionalParameters]; + [OIDAuthorizationService performTokenRequest:tokenRefreshRequest + originalAuthorizationResponse:_lastAuthorizationResponse + callback:^(OIDTokenResponse *_Nullable response, + NSError *_Nullable error) { + // update OIDAuthState based on response + if (response) { + self->_needsTokenRefresh = NO; + [self updateWithTokenResponse:response error:nil]; + } else { + if (error.domain == OIDOAuthTokenErrorDomain) { + self->_needsTokenRefresh = NO; + [self updateWithAuthorizationError:error]; + } else { + if ([self->_errorDelegate respondsToSelector: + @selector(authState:didEncounterTransientError:)]) { + [self->_errorDelegate authState:self didEncounterTransientError:error]; + } + } + } + + // nil the pending queue and process everything that was queued up + NSArray *actionsToProcess; + @synchronized(self->_pendingActionsSyncObject) { + actionsToProcess = self->_pendingActions; + self->_pendingActions = nil; + } + for (OIDAuthStatePendingAction* actionToProcess in actionsToProcess) { + dispatch_async(actionToProcess.dispatchQueue, ^{ + actionToProcess.action(self.accessToken, self.idToken, error); + }); + } + }]; +} + +#pragma mark - + +/*! @fn isTokenFresh + @brief Determines whether a token refresh request must be made to refresh the tokens. + */ +- (BOOL)isTokenFresh { + if (_needsTokenRefresh) { + // forced refresh + return NO; + } + + if (!self.accessTokenExpirationDate) { + // if there is no expiration time but we have an access token, it is assumed to never expire + return !!self.accessToken; + } + + // has the token expired? + BOOL tokenFresh = [self.accessTokenExpirationDate timeIntervalSinceNow] > kExpiryTimeTolerance; + return tokenFresh; +} + +@end + + diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthStateChangeDelegate.h b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthStateChangeDelegate.h new file mode 100644 index 0000000..2570df1 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthStateChangeDelegate.h @@ -0,0 +1,39 @@ +/*! @file OIDAuthStateChangeDelegate.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthState; + +NS_ASSUME_NONNULL_BEGIN + +/*! @protocol OIDAuthStateChangeDelegate + @brief Delegate of the OIDAuthState used to monitor various changes in state. + */ +@protocol OIDAuthStateChangeDelegate + +/*! @brief Called when the authorization state changes and any backing storage needs to be updated. + @param state The @c OIDAuthState that changed. + @discussion If you are storing the authorization state, you should update the storage when the + state changes. + */ +- (void)didChangeState:(OIDAuthState *)state; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthStateErrorDelegate.h b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthStateErrorDelegate.h new file mode 100644 index 0000000..91a9b1c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthStateErrorDelegate.h @@ -0,0 +1,62 @@ +/*! @file OIDAuthStateErrorDelegate.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthState; + +NS_ASSUME_NONNULL_BEGIN + +/*! @protocol OIDAuthStateErrorDelegate + @brief Delegate of the OIDAuthState used to monitor errors. + */ +@protocol OIDAuthStateErrorDelegate + +/*! @brief Called when an authentication occurs, which indicates the auth session is invalid. + @param state The @c OIDAuthState on which the error occurred. + @param error The authorization error. + @discussion This is a hard error (not a transient network issue) that indicates a problem with + the authorization. You should stop using the @c OIDAuthState when such an error is + encountered. If the \NSError_code is @c ::OIDErrorCodeOAuthInvalidGrant then + the session may be recoverable with user interaction (i.e. re-authentication). In all cases + you should consider the user unauthorized, and remove locally cached resources that require + that authorization. @c OIDAuthState will call this method automatically if it encounters + an OAuth error (that is, an HTTP 400 response with a valid OAuth error response) during + authorization or token refresh (such as performed automatically when using + @c OIDAuthState.performActionWithFreshTokens:). You can signal authorization errors with + @c OIDAuthState.updateWithAuthorizationError:. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +- (void)authState:(OIDAuthState *)state didEncounterAuthorizationError:(NSError *)error; + +@optional + +/*! @brief Called when a network or other transient error occurs. + @param state The @c OIDAuthState on which the error occurred. + @param error The transient error. + @discussion This is a soft error, typically network related. The @c OIDAuthState is likely + still valid, and should not be discarded. Retry the request using an incremental backoff + strategy. This is only called when using the @c OIDAuthState convenience methods such as + @c OIDAuthState.performActionWithFreshTokens:. If you are refreshing the tokens yourself + outside of @c OIDAuthState class, it will never be called. + */ +- (void)authState:(OIDAuthState *)state didEncounterTransientError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationRequest.h b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationRequest.h new file mode 100644 index 0000000..c3a0cc0 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationRequest.h @@ -0,0 +1,273 @@ +/*! @file OIDAuthorizationRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +// These files only declare string constants useful for constructing a @c OIDAuthorizationRequest, +// so they are imported here for convenience. +#import "OIDExternalUserAgentRequest.h" +#import "OIDResponseTypes.h" +#import "OIDScopes.h" + +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The @c code_challenge_method value for the S256 code challenge. + @see https://tools.ietf.org/html/rfc7636#section-4.3 + */ +extern NSString *const OIDOAuthorizationRequestCodeChallengeMethodS256; + + +/*! @brief Represents an authorization request. + @see https://tools.ietf.org/html/rfc6749#section-4 + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + */ +@interface OIDAuthorizationRequest : + NSObject + +/*! @brief The service's configuration. + @remarks This configuration specifies how to connect to a particular OAuth provider. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @brief The expected response type. + @remarks response_type + @discussion Generally 'code' if pure OAuth, otherwise a space-delimited list of of response + types including 'code', 'token', and 'id_token' for OpenID Connect. + @see https://tools.ietf.org/html/rfc6749#section-3.1.1 + @see http://openid.net/specs/openid-connect-core-1_0.html#rfc.section.3 + */ +@property(nonatomic, readonly) NSString *responseType; + +/*! @brief The client identifier. + @remarks client_id + @see https://tools.ietf.org/html/rfc6749#section-2.2 + */ +@property(nonatomic, readonly) NSString *clientID; + +/*! @brief The client secret. + @remarks client_secret + @discussion The client secret is used to prove that identity of the client when exchaning an + authorization code for an access token. + The client secret is not passed in the authorizationRequestURL. It is only used when + exchanging the authorization code for an access token. + @see https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +@property(nonatomic, readonly, nullable) NSString *clientSecret; + +/*! @brief The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief The client's redirect URI. + @remarks redirect_uri + @see https://tools.ietf.org/html/rfc6749#section-3.1.2 + */ +@property(nonatomic, readonly, nullable) NSURL *redirectURL; + +/*! @brief An opaque value used by the client to maintain state between the request and callback. + @remarks state + @discussion If this value is not explicitly set, this library will automatically add state and + perform appropriate validation of the state in the authorization response. It is recommended + that the default implementation of this parameter be used wherever possible. Typically used + to prevent CSRF attacks, as recommended in RFC6819 Section 5.3.5. + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + @see https://tools.ietf.org/html/rfc6819#section-5.3.5 + */ +@property(nonatomic, readonly, nullable) NSString *state; + +/*! @brief String value used to associate a Client session with an ID Token, and to mitigate replay + attacks. The value is passed through unmodified from the Authentication Request to the ID + Token. Sufficient entropy MUST be present in the nonce values used to prevent attackers from + guessing values. + @remarks nonce + @discussion If this value is not explicitly set, this library will automatically add nonce and + perform appropriate validation of the nonce in the ID Token. + @see https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest + */ +@property(nonatomic, readonly, nullable) NSString *nonce; + +/*! @brief The PKCE code verifier. + @remarks code_verifier + @discussion The code verifier itself is not included in the authorization request that is sent + on the wire, but needs to be in the token exchange request. + @c OIDAuthorizationResponse.tokenExchangeRequest will create a @c OIDTokenRequest that + includes this parameter automatically. + @see https://tools.ietf.org/html/rfc7636#section-4.1 + */ +@property(nonatomic, readonly, nullable) NSString *codeVerifier; + +/*! @brief The PKCE code challenge, derived from #codeVerifier. + @remarks code_challenge + @see https://tools.ietf.org/html/rfc7636#section-4.2 + */ +@property(nonatomic, readonly, nullable) NSString *codeChallenge; + +/*! @brief The method used to compute the @c #codeChallenge + @remarks code_challenge_method + @see https://tools.ietf.org/html/rfc7636#section-4.3 + */ +@property(nonatomic, readonly, nullable) NSString *codeChallengeMethod; + +/*! @brief The client's additional authorization parameters. + @see https://tools.ietf.org/html/rfc6749#section-3.1 + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalParameters; + +/*! @internal + @brief Unavailable. Please use + @c initWithConfiguration:clientId:scopes:redirectURL:responseType:additionalParameters:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Creates an authorization request with opinionated defaults (a secure @c state, and + PKCE with S256 as the @c code_challenge_method). + @param configuration The service's configuration. + @param clientID The client identifier. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param additionalParameters The client's additional authorization parameters. + @remarks This convenience initializer generates a state parameter and PKCE challenges + automatically. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Creates an authorization request with custom nonce, a secure @c state, + and PKCE with S256 as the @c code_challenge_method. + @param configuration The service's configuration. + @param clientID The client identifier. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param nonce String value used to associate a Client session with an ID Token. Can be set to nil + if not using OpenID Connect, although pure OAuth servers should ignore params they don't + understand anyway. + @param additionalParameters The client's additional authorization parameters. + @remarks This convenience initializer generates a state parameter and PKCE challenges + automatically. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + nonce:(nullable NSString *)nonce + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Creates an authorization request with opinionated defaults (a secure @c state, @c nonce, + and PKCE with S256 as the @c code_challenge_method). + @param configuration The service's configuration. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param additionalParameters The client's additional authorization parameters. + @remarks This convenience initializer generates a state parameter and PKCE challenges + automatically. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param clientID The client identifier. + @param scope A scope string per the OAuth2 spec (a space-delimited set of scopes). + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param state An opaque value used by the client to maintain state between the request and + callback. + @param nonce String value used to associate a Client session with an ID Token. Can be set to nil + if not using OpenID Connect, although pure OAuth servers should ignore params they don't + understand anyway. + @param codeVerifier The PKCE code verifier. See @c OIDAuthorizationRequest.generateCodeVerifier. + @param codeChallenge The PKCE code challenge, calculated from the code verifier such as with + @c OIDAuthorizationRequest.codeChallengeS256ForVerifier:. + @param codeChallengeMethod The PKCE code challenge method. + ::OIDOAuthorizationRequestCodeChallengeMethodS256 when + @c OIDAuthorizationRequest.codeChallengeS256ForVerifier: is used to create the code + challenge. + @param additionalParameters The client's additional authorization parameters. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + redirectURL:(nullable NSURL *)redirectURL + responseType:(NSString *)responseType + state:(nullable NSString *)state + nonce:(nullable NSString *)nonce + codeVerifier:(nullable NSString *)codeVerifier + codeChallenge:(nullable NSString *)codeChallenge + codeChallengeMethod:(nullable NSString *)codeChallengeMethod + additionalParameters:(nullable NSDictionary *)additionalParameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Constructs the request URI by adding the request parameters to the query component of the + authorization endpoint URI using the "application/x-www-form-urlencoded" format. + @return A URL representing the authorization request. + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + */ +- (NSURL *)authorizationRequestURL; + +/*! @brief Generates an OAuth state param using a random source. + @return The generated state. + @see https://tools.ietf.org/html/rfc6819#section-5.3.5 + */ ++ (nullable NSString *)generateState; + +/*! @brief Constructs a PKCE-compliant code verifier. + @return The generated code verifier. + @see https://tools.ietf.org/html/rfc7636#section-4.1 + */ ++ (nullable NSString *)generateCodeVerifier; + +/*! @brief Creates a PKCE S256 codeChallenge from the codeVerifier. + @param codeVerifier The code verifier from which the code challenge will be derived. + @return The generated code challenge. + @details Generate a secure code verifier to pass into this method with + @c OIDAuthorizationRequest.generateCodeVerifier. The matching @c #codeChallengeMethod for + @c #codeChallenge%s created by this method is + ::OIDOAuthorizationRequestCodeChallengeMethodS256. + @see https://tools.ietf.org/html/rfc7636#section-4.1 + */ ++ (nullable NSString *)codeChallengeS256ForVerifier:(nullable NSString *)codeVerifier; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationRequest.m b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationRequest.m new file mode 100644 index 0000000..1be1fdf --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationRequest.m @@ -0,0 +1,377 @@ +/*! @file OIDAuthorizationRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationRequest.h" + +#import "OIDDefines.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDTokenUtilities.h" +#import "OIDURLQueryComponent.h" + +/*! @brief The key for the @c configuration property for @c NSSecureCoding + */ +static NSString *const kConfigurationKey = @"configuration"; + +/*! @brief Key used to encode the @c responseType property for @c NSSecureCoding, and on the URL + request. + */ +static NSString *const kResponseTypeKey = @"response_type"; + +/*! @brief Key used to encode the @c clientID property for @c NSSecureCoding, and on the URL + request. + */ +static NSString *const kClientIDKey = @"client_id"; + +/*! @brief Key used to encode the @c clientSecret property for @c NSSecureCoding. + */ +static NSString *const kClientSecretKey = @"client_secret"; + +/*! @brief Key used to encode the @c scope property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c redirectURL property for @c NSSecureCoding, and on the URL + request. + */ +static NSString *const kRedirectURLKey = @"redirect_uri"; + +/*! @brief Key used to encode the @c state property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kStateKey = @"state"; + +/*! @brief Key used to encode the @c nonce property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kNonceKey = @"nonce"; + +/*! @brief Key used to encode the @c codeVerifier property for @c NSSecureCoding. + */ +static NSString *const kCodeVerifierKey = @"code_verifier"; + +/*! @brief Key used to send the @c codeChallenge on the URL request. + */ +static NSString *const kCodeChallengeKey = @"code_challenge"; + +/*! @brief Key used to send the @c codeChallengeMethod on the URL request. + */ +static NSString *const kCodeChallengeMethodKey = @"code_challenge_method"; + +/*! @brief Key used to encode the @c additionalParameters property for + @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Number of random bytes generated for the @ state. + */ +static NSUInteger const kStateSizeBytes = 32; + +/*! @brief Number of random bytes generated for the @ codeVerifier. + */ +static NSUInteger const kCodeVerifierBytes = 32; + +/*! @brief Assertion text for unsupported response types. + */ +static NSString *const OIDOAuthUnsupportedResponseTypeMessage = + @"The response_type \"%@\" isn't supported. AppAuth only supports the \"code\" or \"code id_token\" response_type."; + +/*! @brief Code challenge request method. + */ +NSString *const OIDOAuthorizationRequestCodeChallengeMethodS256 = @"S256"; + +@implementation OIDAuthorizationRequest + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER( + @selector(initWithConfiguration: + clientId: + scopes: + redirectURL: + responseType: + additionalParameters:) + ) + +/*! @brief Check if the response type is one AppAuth supports + @remarks AppAuth only supports the `code` and `code id_token` response types. + @see https://github.com/openid/AppAuth-iOS/issues/98 + @see https://github.com/openid/AppAuth-iOS/issues/292 + */ ++ (BOOL)isSupportedResponseType:(NSString *)responseType +{ + NSString *codeIdToken = [@[OIDResponseTypeCode, OIDResponseTypeIDToken] + componentsJoinedByString:@" "]; + NSString *idTokenCode = [@[OIDResponseTypeIDToken, OIDResponseTypeCode] + componentsJoinedByString:@" "]; + + return [responseType isEqualToString:OIDResponseTypeCode] + || [responseType isEqualToString:codeIdToken] + || [responseType isEqualToString:idTokenCode]; +} + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + state:(nullable NSString *)state + nonce:(nullable NSString *)nonce + codeVerifier:(nullable NSString *)codeVerifier + codeChallenge:(nullable NSString *)codeChallenge + codeChallengeMethod:(nullable NSString *)codeChallengeMethod + additionalParameters:(nullable NSDictionary *)additionalParameters +{ + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _clientID = [clientID copy]; + _clientSecret = [clientSecret copy]; + _scope = [scope copy]; + _redirectURL = [redirectURL copy]; + _responseType = [responseType copy]; + if (![[self class] isSupportedResponseType:_responseType]) { + NSAssert(NO, OIDOAuthUnsupportedResponseTypeMessage, _responseType); + return nil; + } + _state = [state copy]; + _nonce = [nonce copy]; + _codeVerifier = [codeVerifier copy]; + _codeChallenge = [codeChallenge copy]; + _codeChallengeMethod = [codeChallengeMethod copy]; + + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + } + return self; +} + +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(NSString *)clientSecret + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters { + + // generates PKCE code verifier and challenge + NSString *codeVerifier = [[self class] generateCodeVerifier]; + NSString *codeChallenge = [[self class] codeChallengeS256ForVerifier:codeVerifier]; + + return [self initWithConfiguration:configuration + clientId:clientID + clientSecret:clientSecret + scope:[OIDScopeUtilities scopesWithArray:scopes] + redirectURL:redirectURL + responseType:responseType + state:[[self class] generateState] + nonce:[[self class] generateState] + codeVerifier:codeVerifier + codeChallenge:codeChallenge + codeChallengeMethod:OIDOAuthorizationRequestCodeChallengeMethodS256 + additionalParameters:additionalParameters]; +} + +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + clientId:clientID + clientSecret:nil + scopes:scopes + redirectURL:redirectURL + responseType:responseType + additionalParameters:additionalParameters]; +} + +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + nonce:(nullable NSString *)nonce + additionalParameters:(nullable NSDictionary *)additionalParameters { + // generates PKCE code verifier and challenge + NSString *codeVerifier = [[self class] generateCodeVerifier]; + NSString *codeChallenge = [[self class] codeChallengeS256ForVerifier:codeVerifier]; + + return [self initWithConfiguration:configuration + clientId:clientID + clientSecret:nil + scope:[OIDScopeUtilities scopesWithArray:scopes] + redirectURL:redirectURL + responseType:responseType + state:[[self class] generateState] + nonce:nonce + codeVerifier:codeVerifier + codeChallenge:codeChallenge + codeChallengeMethod:OIDOAuthorizationRequestCodeChallengeMethodS256 + additionalParameters:additionalParameters]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDServiceConfiguration *configuration = + [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] + forKey:kConfigurationKey]; + NSString *responseType = [aDecoder decodeObjectOfClass:[NSString class] forKey:kResponseTypeKey]; + NSString *clientID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientIDKey]; + NSString *clientSecret = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientSecretKey]; + NSString *scope = [aDecoder decodeObjectOfClass:[NSString class] forKey:kScopeKey]; + NSURL *redirectURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kRedirectURLKey]; + NSString *state = [aDecoder decodeObjectOfClass:[NSString class] forKey:kStateKey]; + NSString *nonce = [aDecoder decodeObjectOfClass:[NSString class] forKey:kNonceKey]; + NSString *codeVerifier = [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeVerifierKey]; + NSString *codeChallenge = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeChallengeKey]; + NSString *codeChallengeMethod = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeChallengeMethodKey]; + NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class] + ]]; + NSDictionary *additionalParameters = + [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses + forKey:kAdditionalParametersKey]; + + self = [self initWithConfiguration:configuration + clientId:clientID + clientSecret:clientSecret + scope:scope + redirectURL:redirectURL + responseType:responseType + state:state + nonce:nonce + codeVerifier:codeVerifier + codeChallenge:codeChallenge + codeChallengeMethod:codeChallengeMethod + additionalParameters:additionalParameters]; + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_configuration forKey:kConfigurationKey]; + [aCoder encodeObject:_responseType forKey:kResponseTypeKey]; + [aCoder encodeObject:_clientID forKey:kClientIDKey]; + [aCoder encodeObject:_clientSecret forKey:kClientSecretKey]; + [aCoder encodeObject:_scope forKey:kScopeKey]; + [aCoder encodeObject:_redirectURL forKey:kRedirectURLKey]; + [aCoder encodeObject:_state forKey:kStateKey]; + [aCoder encodeObject:_nonce forKey:kNonceKey]; + [aCoder encodeObject:_codeVerifier forKey:kCodeVerifierKey]; + [aCoder encodeObject:_codeChallenge forKey:kCodeChallengeKey]; + [aCoder encodeObject:_codeChallengeMethod forKey:kCodeChallengeMethodKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, request: %@>", + NSStringFromClass([self class]), + (void *)self, + self.authorizationRequestURL]; +} + +#pragma mark - State and PKCE verifier/challenge generation Methods + ++ (nullable NSString *)generateCodeVerifier { + return [OIDTokenUtilities randomURLSafeStringWithSize:kCodeVerifierBytes]; +} + ++ (nullable NSString *)generateState { + return [OIDTokenUtilities randomURLSafeStringWithSize:kStateSizeBytes]; +} + ++ (nullable NSString *)codeChallengeS256ForVerifier:(NSString *)codeVerifier { + if (!codeVerifier) { + return nil; + } + // generates the code_challenge per spec https://tools.ietf.org/html/rfc7636#section-4.2 + // code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) + // NB. the ASCII conversion on the code_verifier entropy was done at time of generation. + NSData *sha256Verifier = [OIDTokenUtilities sha256:codeVerifier]; + return [OIDTokenUtilities encodeBase64urlNoPadding:sha256Verifier]; +} + +#pragma mark - + +- (NSURL *)authorizationRequestURL { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + // Required parameters. + [query addParameter:kResponseTypeKey value:_responseType]; + [query addParameter:kClientIDKey value:_clientID]; + + // Add any additional parameters the client has specified. + [query addParameters:_additionalParameters]; + + // Add optional parameters, as applicable. + if (_redirectURL) { + [query addParameter:kRedirectURLKey value:_redirectURL.absoluteString]; + } + if (_scope) { + [query addParameter:kScopeKey value:_scope]; + } + if (_state) { + [query addParameter:kStateKey value:_state]; + } + if (_nonce) { + [query addParameter:kNonceKey value:_nonce]; + } + if (_codeChallenge) { + [query addParameter:kCodeChallengeKey value:_codeChallenge]; + } + if (_codeChallengeMethod) { + [query addParameter:kCodeChallengeMethodKey value:_codeChallengeMethod]; + } + + // Construct the URL: + return [query URLByReplacingQueryInURL:_configuration.authorizationEndpoint]; +} + +#pragma mark - OIDExternalUserAgentRequest + +- (NSURL *)externalUserAgentRequestURL { + return [self authorizationRequestURL]; +} + +- (NSString *)redirectScheme { + return [[self redirectURL] scheme]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationResponse.h b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationResponse.h new file mode 100644 index 0000000..a9af186 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationResponse.h @@ -0,0 +1,141 @@ +/*! @file OIDAuthorizationResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorizationRequest; +@class OIDTokenRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the response to an authorization request. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2 + @see https://tools.ietf.org/html/rfc6749#section-5.1 + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@interface OIDAuthorizationResponse : NSObject + +/*! @brief The request which was serviced. + */ +@property(nonatomic, readonly) OIDAuthorizationRequest *request; + +/*! @brief The authorization code generated by the authorization server. + @discussion Set when the response_type requested includes 'code'. + @remarks code + */ +@property(nonatomic, readonly, nullable) NSString *authorizationCode; + +/*! @brief REQUIRED if the "state" parameter was present in the client authorization request. The + exact value received from the client. + @remarks state + */ +@property(nonatomic, readonly, nullable) NSString *state; + +/*! @brief The access token generated by the authorization server. + @discussion Set when the response_type requested includes 'token'. + @remarks access_token + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/*! @brief The approximate expiration date & time of the access token. + @discussion Set when the response_type requested includes 'token'. + @remarks expires_in + @seealso OIDAuthorizationResponse.accessToken + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate; + +/*! @brief Typically "Bearer" when present. Otherwise, another token_type value that the Client has + negotiated with the Authorization Server. + @discussion Set when the response_type requested includes 'token'. + @remarks token_type + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *tokenType; + +/*! @brief ID Token value associated with the authenticated session. + @discussion Set when the response_type requested includes 'id_token'. + @remarks id_token + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *idToken; + +/*! @brief The scope of the access token. OPTIONAL, if identical to the scopes requested, otherwise, + REQUIRED. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief Additional parameters returned from the authorization server. + */ +@property(nonatomic, readonly, nullable) + NSDictionary *> *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithRequest:parameters:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the Authorization Server. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (instancetype)initWithRequest:(OIDAuthorizationRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Creates a token request suitable for exchanging an authorization code for an access + token. + @return A @c OIDTokenRequest suitable for exchanging an authorization code for an access + token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (nullable OIDTokenRequest *)tokenExchangeRequest; + +/*! @brief Creates a token request suitable for exchanging an authorization code for an access + token. + @param additionalParameters Additional parameters for the token request. + @return A @c OIDTokenRequest suitable for exchanging an authorization code for an access + token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (nullable OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Creates a token request suitable for exchanging an authorization code for an access + token. + @param additionalParameters Additional parameters for the token request. + @param additionalHeaders Additional headers for the token request. + @return A @c OIDTokenRequest suitable for exchanging an authorization code for an access + token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (nullable OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationResponse.m b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationResponse.m new file mode 100644 index 0000000..957f81d --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationResponse.m @@ -0,0 +1,219 @@ +/*! @file OIDAuthorizationResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationResponse.h" + +#import "OIDAuthorizationRequest.h" +#import "OIDDefines.h" +#import "OIDError.h" +#import "OIDFieldMapping.h" +#import "OIDTokenRequest.h" +#import "OIDTokenUtilities.h" + +/*! @brief The key for the @c authorizationCode property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kAuthorizationCodeKey = @"code"; + +/*! @brief The key for the @c state property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kStateKey = @"state"; + +/*! @brief The key for the @c accessToken property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kAccessTokenKey = @"access_token"; + +/*! @brief The key for the @c accessTokenExpirationDate property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kExpiresInKey = @"expires_in"; + +/*! @brief The key for the @c tokenType property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kTokenTypeKey = @"token_type"; + +/*! @brief The key for the @c idToken property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kIDTokenKey = @"id_token"; + +/*! @brief The key for the @c scope property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +/*! @brief The exception thrown when a developer tries to create a token exchange request from an + authorization request with no authorization code. + */ +static NSString *const kTokenExchangeRequestException = + @"Attempted to create a token exchange request from an authorization response with no " + "authorization code."; + +@implementation OIDAuthorizationResponse + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[kStateKey] = + [[OIDFieldMapping alloc] initWithName:@"_state" type:[NSString class]]; + fieldMap[kAuthorizationCodeKey] = + [[OIDFieldMapping alloc] initWithName:@"_authorizationCode" type:[NSString class]]; + fieldMap[kAccessTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessToken" type:[NSString class]]; + fieldMap[kExpiresInKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessTokenExpirationDate" + type:[NSDate class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]]; + }]; + fieldMap[kTokenTypeKey] = + [[OIDFieldMapping alloc] initWithName:@"_tokenType" type:[NSString class]]; + fieldMap[kIDTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_idToken" type:[NSString class]]; + fieldMap[kScopeKey] = + [[OIDFieldMapping alloc] initWithName:@"_scope" type:[NSString class]]; + }); + return fieldMap; +} + +#pragma mark - Initializers + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:)) + +- (instancetype)initWithRequest:(OIDAuthorizationRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super init]; + if (self) { + _request = [request copy]; + NSDictionary *> *additionalParameters = + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:parameters + instance:self]; + _additionalParameters = additionalParameters; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDAuthorizationRequest *request = + [aDecoder decodeObjectOfClass:[OIDAuthorizationRequest class] forKey:kRequestKey]; + self = [self initWithRequest:request parameters:@{ }]; + if (self) { + [OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self]; + _additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes] + forKey:kAdditionalParametersKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_request forKey:kRequestKey]; + [OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, authorizationCode: %@, state: \"%@\", accessToken: " + "\"%@\", accessTokenExpirationDate: %@, tokenType: %@, " + "idToken: \"%@\", scope: \"%@\", additionalParameters: %@, " + "request: %@>", + NSStringFromClass([self class]), + (void *)self, + _authorizationCode, + _state, + [OIDTokenUtilities redact:_accessToken], + _accessTokenExpirationDate, + _tokenType, + [OIDTokenUtilities redact:_idToken], + _scope, + _additionalParameters, + _request]; +} + +#pragma mark - + +- (OIDTokenRequest *)tokenExchangeRequest { + return [self tokenExchangeRequestWithAdditionalParameters:nil additionalHeaders:nil]; +} + +- (OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters { + return [self tokenExchangeRequestWithAdditionalParameters:additionalParameters + additionalHeaders:nil]; +} + +- (OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters + additionalHeaders: + (NSDictionary *)additionalHeaders { + // TODO: add a unit test to confirm exception is thrown when expected and the request is created + // with the correct parameters. + if (!_authorizationCode) { + [NSException raise:kTokenExchangeRequestException + format:kTokenExchangeRequestException]; + } + return [[OIDTokenRequest alloc] initWithConfiguration:_request.configuration + grantType:OIDGrantTypeAuthorizationCode + authorizationCode:_authorizationCode + redirectURL:_request.redirectURL + clientID:_request.clientID + clientSecret:_request.clientSecret + scope:nil + refreshToken:nil + codeVerifier:_request.codeVerifier + additionalParameters:additionalParameters + additionalHeaders:additionalHeaders]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationService.h b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationService.h new file mode 100644 index 0000000..c8fee53 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationService.h @@ -0,0 +1,170 @@ +/*! @file OIDAuthorizationService.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorization; +@class OIDAuthorizationRequest; +@class OIDAuthorizationResponse; +@class OIDEndSessionRequest; +@class OIDEndSessionResponse; +@class OIDRegistrationRequest; +@class OIDRegistrationResponse; +@class OIDServiceConfiguration; +@class OIDTokenRequest; +@class OIDTokenResponse; +@protocol OIDExternalUserAgent; +@protocol OIDExternalUserAgentSession; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the type of block used as a callback for creating a service configuration from + a remote OpenID Connect Discovery document. + @param configuration The service configuration, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDDiscoveryCallback)(OIDServiceConfiguration *_Nullable configuration, + NSError *_Nullable error); + +/*! @brief Represents the type of block used as a callback for various methods of + @c OIDAuthorizationService. + @param authorizationResponse The authorization response, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDAuthorizationCallback)(OIDAuthorizationResponse *_Nullable authorizationResponse, + NSError *_Nullable error); + +/*! @brief Block used as a callback for the end-session request of @c OIDAuthorizationService. + @param endSessionResponse The end-session response, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDEndSessionCallback)(OIDEndSessionResponse *_Nullable endSessionResponse, + NSError *_Nullable error); + +/*! @brief Represents the type of block used as a callback for various methods of + @c OIDAuthorizationService. + @param tokenResponse The token response, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDTokenCallback)(OIDTokenResponse *_Nullable tokenResponse, + NSError *_Nullable error); + +/*! @brief Represents the type of dictionary used to specify additional querystring parameters + when making authorization or token endpoint requests. + */ +typedef NSDictionary *_Nullable OIDTokenEndpointParameters; + +/*! @brief Represents the type of block used as a callback for various methods of + @c OIDAuthorizationService. + @param registrationResponse The registration response, if available. + @param error The error if an error occurred. +*/ +typedef void (^OIDRegistrationCompletion)(OIDRegistrationResponse *_Nullable registrationResponse, + NSError *_Nullable error); + +/*! @brief Performs various OAuth and OpenID Connect related calls via the user agent or + \NSURLSession. + */ +@interface OIDAuthorizationService : NSObject + +/*! @brief The service's configuration. + @remarks Each authorization service is initialized with a configuration. This configuration + specifies how to connect to a particular OAuth provider. Clients should use separate + authorization service instances for each provider they wish to integrate with. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Convenience method for creating an authorization service configuration from an OpenID + Connect compliant issuer URL. + @param issuerURL The service provider's OpenID Connect issuer. + @param completion A block which will be invoked when the authorization service configuration has + been created, or when an error has occurred. + @see https://openid.net/specs/openid-connect-discovery-1_0.html + */ ++ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL + completion:(OIDDiscoveryCallback)completion; + + +/*! @brief Convenience method for creating an authorization service configuration from an OpenID + Connect compliant identity provider's discovery document. + @param discoveryURL The URL of the service provider's OpenID Connect discovery document. + @param completion A block which will be invoked when the authorization service configuration has + been created, or when an error has occurred. + @see https://openid.net/specs/openid-connect-discovery-1_0.html + */ ++ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL + completion:(OIDDiscoveryCallback)completion; + +/*! @brief Perform an authorization flow using a generic flow shim. + @param request The authorization request. + @param externalUserAgent Generic external user-agent that can present an authorization + request. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + */ ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + externalUserAgent:(id)externalUserAgent + callback:(OIDAuthorizationCallback)callback; + +/*! @brief Perform a logout request. + @param request The end-session logout request. + @param externalUserAgent Generic external user-agent that can present user-agent requests. + @param callback The method called when the request has completed or failed. + @return A @c OIDExternalUserAgentSession instance which will terminate when it + receives a @c OIDExternalUserAgentSession.cancel message, or after processing a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message. + @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout + */ ++ (id) + presentEndSessionRequest:(OIDEndSessionRequest *)request + externalUserAgent:(id)externalUserAgent + callback:(OIDEndSessionCallback)callback; + +/*! @brief Performs a token request. + @param request The token request. + @param callback The method called when the request has completed or failed. + */ ++ (void)performTokenRequest:(OIDTokenRequest *)request callback:(OIDTokenCallback)callback; + +/*! @brief Performs a token request. + @param request The token request. + @param authorizationResponse The original authorization response related to this token request. + @param callback The method called when the request has completed or failed. + */ ++ (void)performTokenRequest:(OIDTokenRequest *)request + originalAuthorizationResponse:(OIDAuthorizationResponse *_Nullable)authorizationResponse + callback:(OIDTokenCallback)callback; + +/*! @brief Performs a registration request. + @param request The registration request. + @param completion The method called when the request has completed or failed. + */ ++ (void)performRegistrationRequest:(OIDRegistrationRequest *)request + completion:(OIDRegistrationCompletion)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationService.m b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationService.m new file mode 100644 index 0000000..cc749a3 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDAuthorizationService.m @@ -0,0 +1,790 @@ +/*! @file OIDAuthorizationService.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationService.h" + +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDDefines.h" +#import "OIDEndSessionRequest.h" +#import "OIDEndSessionResponse.h" +#import "OIDErrorUtilities.h" +#import "OIDExternalUserAgent.h" +#import "OIDExternalUserAgentSession.h" +#import "OIDIDToken.h" +#import "OIDRegistrationRequest.h" +#import "OIDRegistrationResponse.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDURLQueryComponent.h" +#import "OIDURLSessionProvider.h" + +/*! @brief Path appended to an OpenID Connect issuer for discovery + @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig + */ +static NSString *const kOpenIDConfigurationWellKnownPath = @".well-known/openid-configuration"; + +/*! @brief Max allowable iat (Issued At) time skew + @see https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation + */ +static int const kOIDAuthorizationSessionIATMaxSkew = 600; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDAuthorizationSession : NSObject + +- (instancetype)init NS_UNAVAILABLE; + +- (instancetype)initWithRequest:(OIDAuthorizationRequest *)request + NS_DESIGNATED_INITIALIZER; + +@end + +@implementation OIDAuthorizationSession { + OIDAuthorizationRequest *_request; + id _externalUserAgent; + OIDAuthorizationCallback _pendingauthorizationFlowCallback; +} + +- (instancetype)initWithRequest:(OIDAuthorizationRequest *)request { + self = [super init]; + if (self) { + _request = [request copy]; + } + return self; +} + +- (void)presentAuthorizationWithExternalUserAgent:(id)externalUserAgent + callback:(OIDAuthorizationCallback)authorizationFlowCallback { + _externalUserAgent = externalUserAgent; + _pendingauthorizationFlowCallback = authorizationFlowCallback; + BOOL authorizationFlowStarted = + [_externalUserAgent presentExternalUserAgentRequest:_request session:self]; + if (!authorizationFlowStarted) { + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError + underlyingError:nil + description:@"Unable to open Safari."]; + [self didFinishWithResponse:nil error:safariError]; + } +} + +- (void)cancel { + [self cancelWithCompletion:nil]; +} + +- (void)cancelWithCompletion:(nullable void (^)(void))completion { + [_externalUserAgent dismissExternalUserAgentAnimated:YES completion:^{ + NSError *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:nil + description:@"Authorization flow was cancelled."]; + [self didFinishWithResponse:nil error:error]; + if (completion) completion(); + }]; +} + +/*! @brief Does the redirection URL equal another URL down to the path component? + @param URL The first redirect URI to compare. + @param redirectionURL The second redirect URI to compare. + @return YES if the URLs match down to the path level (query params are ignored). + */ ++ (BOOL)URL:(NSURL *)URL matchesRedirectionURL:(NSURL *)redirectionURL { + NSURL *standardizedURL = [URL standardizedURL]; + NSURL *standardizedRedirectURL = [redirectionURL standardizedURL]; + + return [standardizedURL.scheme caseInsensitiveCompare:standardizedRedirectURL.scheme] == NSOrderedSame + && OIDIsEqualIncludingNil(standardizedURL.user, standardizedRedirectURL.user) + && OIDIsEqualIncludingNil(standardizedURL.password, standardizedRedirectURL.password) + && OIDIsEqualIncludingNil(standardizedURL.host, standardizedRedirectURL.host) + && OIDIsEqualIncludingNil(standardizedURL.port, standardizedRedirectURL.port) + && OIDIsEqualIncludingNil(standardizedURL.path, standardizedRedirectURL.path); +} + +- (BOOL)shouldHandleURL:(NSURL *)URL { + return [[self class] URL:URL matchesRedirectionURL:_request.redirectURL]; +} + +- (BOOL)resumeExternalUserAgentFlowWithURL:(NSURL *)URL { + // rejects URLs that don't match redirect (these may be completely unrelated to the authorization) + if (![self shouldHandleURL:URL]) { + return NO; + } + + AppAuthRequestTrace(@"Authorization Response: %@", URL); + + // checks for an invalid state + if (!_pendingauthorizationFlowCallback) { + [NSException raise:OIDOAuthExceptionInvalidAuthorizationFlow + format:@"%@", OIDOAuthExceptionInvalidAuthorizationFlow, nil]; + } + + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] initWithURL:URL]; + + NSError *error; + OIDAuthorizationResponse *response = nil; + + // checks for an OAuth error response as per RFC6749 Section 4.1.2.1 + if (query.dictionaryValue[OIDOAuthErrorFieldError]) { + error = [OIDErrorUtilities OAuthErrorWithDomain:OIDOAuthAuthorizationErrorDomain + OAuthResponse:query.dictionaryValue + underlyingError:nil]; + } + + // no error, should be a valid OAuth 2.0 response + if (!error) { + response = [[OIDAuthorizationResponse alloc] initWithRequest:_request + parameters:query.dictionaryValue]; + + // verifies that the state in the response matches the state in the request, or both are nil + if (!OIDIsEqualIncludingNil(_request.state, response.state)) { + NSMutableDictionary *userInfo = [query.dictionaryValue mutableCopy]; + userInfo[NSLocalizedDescriptionKey] = + [NSString stringWithFormat:@"State mismatch, expecting %@ but got %@ in authorization " + "response %@", + _request.state, + response.state, + response]; + response = nil; + error = [NSError errorWithDomain:OIDOAuthAuthorizationErrorDomain + code:OIDErrorCodeOAuthAuthorizationClientError + userInfo:userInfo]; + } + } + + [_externalUserAgent dismissExternalUserAgentAnimated:YES completion:^{ + [self didFinishWithResponse:response error:error]; + }]; + + return YES; +} + +- (void)failExternalUserAgentFlowWithError:(NSError *)error { + [self didFinishWithResponse:nil error:error]; +} + +/*! @brief Invokes the pending callback and performs cleanup. + @param response The authorization response, if any to return to the callback. + @param error The error, if any, to return to the callback. + */ +- (void)didFinishWithResponse:(nullable OIDAuthorizationResponse *)response + error:(nullable NSError *)error { + OIDAuthorizationCallback callback = _pendingauthorizationFlowCallback; + _pendingauthorizationFlowCallback = nil; + _externalUserAgent = nil; + if (callback) { + callback(response, error); + } +} + +@end + +@interface OIDEndSessionImplementation : NSObject { + // private variables + OIDEndSessionRequest *_request; + id _externalUserAgent; + OIDEndSessionCallback _pendingEndSessionCallback; +} +- (instancetype)init NS_UNAVAILABLE; + +- (instancetype)initWithRequest:(OIDEndSessionRequest *)request + NS_DESIGNATED_INITIALIZER; +@end + + +@implementation OIDEndSessionImplementation + +- (instancetype)initWithRequest:(OIDEndSessionRequest *)request { + self = [super init]; + if (self) { + _request = [request copy]; + } + return self; +} + +- (void)presentAuthorizationWithExternalUserAgent:(id)externalUserAgent + callback:(OIDEndSessionCallback)authorizationFlowCallback { + _externalUserAgent = externalUserAgent; + _pendingEndSessionCallback = authorizationFlowCallback; + BOOL authorizationFlowStarted = + [_externalUserAgent presentExternalUserAgentRequest:_request session:self]; + if (!authorizationFlowStarted) { + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError + underlyingError:nil + description:@"Unable to open Safari."]; + [self didFinishWithResponse:nil error:safariError]; + } +} + +- (void)cancel { + [self cancelWithCompletion:nil]; +} + +- (void)cancelWithCompletion:(nullable void (^)(void))completion { + [_externalUserAgent dismissExternalUserAgentAnimated:YES completion:^{ + NSError *error = [OIDErrorUtilities + errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:nil + description:nil]; + [self didFinishWithResponse:nil error:error]; + if (completion) completion(); + }]; +} + +- (BOOL)shouldHandleURL:(NSURL *)URL { + // The logic of when to handle the URL is the same as for authorization requests: should match + // down to the path component. + return [[OIDAuthorizationSession class] URL:URL + matchesRedirectionURL:_request.postLogoutRedirectURL]; +} + +- (BOOL)resumeExternalUserAgentFlowWithURL:(NSURL *)URL { + // rejects URLs that don't match redirect (these may be completely unrelated to the authorization) + if (![self shouldHandleURL:URL]) { + return NO; + } + // checks for an invalid state + if (!_pendingEndSessionCallback) { + [NSException raise:OIDOAuthExceptionInvalidAuthorizationFlow + format:@"%@", OIDOAuthExceptionInvalidAuthorizationFlow, nil]; + } + + + NSError *error; + OIDEndSessionResponse *response = nil; + + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] initWithURL:URL]; + response = [[OIDEndSessionResponse alloc] initWithRequest:_request + parameters:query.dictionaryValue]; + + // verifies that the state in the response matches the state in the request, or both are nil + if (!OIDIsEqualIncludingNil(_request.state, response.state)) { + NSMutableDictionary *userInfo = [query.dictionaryValue mutableCopy]; + userInfo[NSLocalizedDescriptionKey] = + [NSString stringWithFormat:@"State mismatch, expecting %@ but got %@ in authorization " + "response %@", + _request.state, + response.state, + response]; + response = nil; + error = [NSError errorWithDomain:OIDOAuthAuthorizationErrorDomain + code:OIDErrorCodeOAuthAuthorizationClientError + userInfo:userInfo]; + } + + [_externalUserAgent dismissExternalUserAgentAnimated:YES completion:^{ + [self didFinishWithResponse:response error:error]; + }]; + + return YES; +} + +- (void)failExternalUserAgentFlowWithError:(NSError *)error { + [self didFinishWithResponse:nil error:error]; +} + +/*! @brief Invokes the pending callback and performs cleanup. + @param response The authorization response, if any to return to the callback. + @param error The error, if any, to return to the callback. + */ +- (void)didFinishWithResponse:(nullable OIDEndSessionResponse *)response + error:(nullable NSError *)error { + OIDEndSessionCallback callback = _pendingEndSessionCallback; + _pendingEndSessionCallback = nil; + _externalUserAgent = nil; + if (callback) { + callback(response, error); + } +} + +@end + +@implementation OIDAuthorizationService + ++ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL + completion:(OIDDiscoveryCallback)completion { + NSURL *fullDiscoveryURL = + [issuerURL URLByAppendingPathComponent:kOpenIDConfigurationWellKnownPath]; + + [[self class] discoverServiceConfigurationForDiscoveryURL:fullDiscoveryURL + completion:completion]; +} + ++ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL + completion:(OIDDiscoveryCallback)completion { + + NSURLSession *session = [OIDURLSessionProvider session]; + NSURLSessionDataTask *task = + [session dataTaskWithURL:discoveryURL + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + // If we got any sort of error, just report it. + if (error || !data) { + NSString *errorDescription = + [NSString stringWithFormat:@"Connection error fetching discovery document '%@': %@.", + discoveryURL, + error.localizedDescription]; + error = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + + NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response; + + // Check for non-200 status codes. + // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse + if (urlResponse.statusCode != 200) { + NSError *URLResponseError = [OIDErrorUtilities HTTPErrorWithHTTPResponse:urlResponse + data:data]; + NSString *errorDescription = + [NSString stringWithFormat:@"Non-200 HTTP response (%d) fetching discovery document " + "'%@'.", + (int)urlResponse.statusCode, + discoveryURL]; + error = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:URLResponseError + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + + // Construct an OIDServiceDiscovery with the received JSON. + OIDServiceDiscovery *discovery = + [[OIDServiceDiscovery alloc] initWithJSONData:data error:&error]; + if (error || !discovery) { + NSString *errorDescription = + [NSString stringWithFormat:@"JSON error parsing document at '%@': %@", + discoveryURL, + error.localizedDescription]; + error = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + + // Create our service configuration with the discovery document and return it. + OIDServiceConfiguration *configuration = + [[OIDServiceConfiguration alloc] initWithDiscoveryDocument:discovery]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(configuration, nil); + }); + }]; + [task resume]; +} + +#pragma mark - Authorization Endpoint + ++ (id) presentAuthorizationRequest:(OIDAuthorizationRequest *)request + externalUserAgent:(id)externalUserAgent + callback:(OIDAuthorizationCallback)callback { + + AppAuthRequestTrace(@"Authorization Request: %@", request); + + OIDAuthorizationSession *flowSession = [[OIDAuthorizationSession alloc] initWithRequest:request]; + [flowSession presentAuthorizationWithExternalUserAgent:externalUserAgent callback:callback]; + return flowSession; +} + ++ (id) + presentEndSessionRequest:(OIDEndSessionRequest *)request + externalUserAgent:(id)externalUserAgent + callback:(OIDEndSessionCallback)callback { + OIDEndSessionImplementation *flowSession = + [[OIDEndSessionImplementation alloc] initWithRequest:request]; + [flowSession presentAuthorizationWithExternalUserAgent:externalUserAgent callback:callback]; + return flowSession; +} + +#pragma mark - Token Endpoint + ++ (void)performTokenRequest:(OIDTokenRequest *)request callback:(OIDTokenCallback)callback { + [[self class] performTokenRequest:request + originalAuthorizationResponse:nil + callback:callback]; +} + ++ (void)performTokenRequest:(OIDTokenRequest *)request + originalAuthorizationResponse:(OIDAuthorizationResponse *_Nullable)authorizationResponse + callback:(OIDTokenCallback)callback { + + NSURLRequest *URLRequest = [request URLRequest]; + + AppAuthRequestTrace(@"Token Request: %@\nHeaders:%@\nHTTPBody: %@", + URLRequest.URL, + URLRequest.allHTTPHeaderFields, + [[NSString alloc] initWithData:URLRequest.HTTPBody + encoding:NSUTF8StringEncoding]); + + NSURLSession *session = [OIDURLSessionProvider session]; + [[session dataTaskWithRequest:URLRequest + completionHandler:^(NSData *_Nullable data, + NSURLResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + // A network error or server error occurred. + NSString *errorDescription = + [NSString stringWithFormat:@"Connection error making token request to '%@': %@.", + URLRequest.URL, + error.localizedDescription]; + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + NSHTTPURLResponse *HTTPURLResponse = (NSHTTPURLResponse *)response; + NSInteger statusCode = HTTPURLResponse.statusCode; + AppAuthRequestTrace(@"Token Response: HTTP Status %d\nHTTPBody: %@", + (int)statusCode, + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); + if (statusCode != 200) { + // A server error occurred. + NSError *serverError = + [OIDErrorUtilities HTTPErrorWithHTTPResponse:HTTPURLResponse data:data]; + + // HTTP 4xx may indicate an RFC6749 Section 5.2 error response, attempts to parse as such. + if (statusCode >= 400 && statusCode < 500) { + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonDeserializationError]; + + // If the HTTP 4xx response parses as JSON and has an 'error' key, it's an OAuth error. + // These errors are special as they indicate a problem with the authorization grant. + if (json[OIDOAuthErrorFieldError]) { + NSError *oauthError = + [OIDErrorUtilities OAuthErrorWithDomain:OIDOAuthTokenErrorDomain + OAuthResponse:json + underlyingError:serverError]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, oauthError); + }); + return; + } + } + + // Status code indicates this is an error, but not an RFC6749 Section 5.2 error. + NSString *errorDescription = + [NSString stringWithFormat:@"Non-200 HTTP response (%d) making token request to '%@'.", + (int)statusCode, + URLRequest.URL]; + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeServerError + underlyingError:serverError + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonDeserializationError]; + if (jsonDeserializationError) { + // A problem occurred deserializing the response/JSON. + NSString *errorDescription = + [NSString stringWithFormat:@"JSON error parsing token response: %@", + jsonDeserializationError.localizedDescription]; + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONDeserializationError + underlyingError:jsonDeserializationError + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + OIDTokenResponse *tokenResponse = + [[OIDTokenResponse alloc] initWithRequest:request parameters:json]; + if (!tokenResponse) { + // A problem occurred constructing the token response from the JSON. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeTokenResponseConstructionError + underlyingError:jsonDeserializationError + description:@"Token response invalid."]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + // If an ID Token is included in the response, validates the ID Token following the rules + // in OpenID Connect Core Section 3.1.3.7 for features that AppAuth directly supports + // (which excludes rules #1, #4, #5, #7, #8, #12, and #13). Regarding rule #6, ID Tokens + // received by this class are received via direct communication between the Client and the Token + // Endpoint, thus we are exercising the option to rely only on the TLS validation. AppAuth + // has a zero dependencies policy, and verifying the JWT signature would add a dependency. + // Users of the library are welcome to perform the JWT signature verification themselves should + // they wish. + if (tokenResponse.idToken) { + OIDIDToken *idToken = [[OIDIDToken alloc] initWithIDTokenString:tokenResponse.idToken]; + if (!idToken) { + NSError *invalidIDToken = + [OIDErrorUtilities errorWithCode:OIDErrorCodeIDTokenParsingError + underlyingError:nil + description:@"ID Token parsing failed"]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, invalidIDToken); + }); + return; + } + + // OpenID Connect Core Section 3.1.3.7. rule #1 + // Not supported: AppAuth does not support JWT encryption. + + // OpenID Connect Core Section 3.1.3.7. rule #2 + // Validates that the issuer in the ID Token matches that of the discovery document. + NSURL *issuer = tokenResponse.request.configuration.issuer; + if (issuer && ![idToken.issuer isEqual:issuer]) { + NSError *invalidIDToken = + [OIDErrorUtilities errorWithCode:OIDErrorCodeIDTokenFailedValidationError + underlyingError:nil + description:@"Issuer mismatch"]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, invalidIDToken); + }); + return; + } + + // OpenID Connect Core Section 3.1.3.7. rule #3 & Section 2 azp Claim + // Validates that the aud (audience) Claim contains the client ID, or that the azp + // (authorized party) Claim matches the client ID. + NSString *clientID = tokenResponse.request.clientID; + if (![idToken.audience containsObject:clientID] && + ![idToken.claims[@"azp"] isEqualToString:clientID]) { + NSError *invalidIDToken = + [OIDErrorUtilities errorWithCode:OIDErrorCodeIDTokenFailedValidationError + underlyingError:nil + description:@"Audience mismatch"]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, invalidIDToken); + }); + return; + } + + // OpenID Connect Core Section 3.1.3.7. rules #4 & #5 + // Not supported. + + // OpenID Connect Core Section 3.1.3.7. rule #6 + // As noted above, AppAuth only supports the code flow which results in direct communication + // of the ID Token from the Token Endpoint to the Client, and we are exercising the option to + // use TSL server validation instead of checking the token signature. Users may additionally + // check the token signature should they wish. + + // OpenID Connect Core Section 3.1.3.7. rules #7 & #8 + // Not applicable. See rule #6. + + // OpenID Connect Core Section 3.1.3.7. rule #9 + // Validates that the current time is before the expiry time. + NSTimeInterval expiresAtDifference = [idToken.expiresAt timeIntervalSinceNow]; + if (expiresAtDifference < 0) { + NSError *invalidIDToken = + [OIDErrorUtilities errorWithCode:OIDErrorCodeIDTokenFailedValidationError + underlyingError:nil + description:@"ID Token expired"]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, invalidIDToken); + }); + return; + } + + // OpenID Connect Core Section 3.1.3.7. rule #10 + // Validates that the issued at time is not more than +/- 10 minutes on the current time. + NSTimeInterval issuedAtDifference = [idToken.issuedAt timeIntervalSinceNow]; + if (fabs(issuedAtDifference) > kOIDAuthorizationSessionIATMaxSkew) { + NSString *message = + [NSString stringWithFormat:@"Issued at time is more than %d seconds before or after " + "the current time", + kOIDAuthorizationSessionIATMaxSkew]; + NSError *invalidIDToken = + [OIDErrorUtilities errorWithCode:OIDErrorCodeIDTokenFailedValidationError + underlyingError:nil + description:message]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, invalidIDToken); + }); + return; + } + + // Only relevant for the authorization_code response type + if ([tokenResponse.request.grantType isEqual:OIDGrantTypeAuthorizationCode]) { + // OpenID Connect Core Section 3.1.3.7. rule #11 + // Validates the nonce. + NSString *nonce = authorizationResponse.request.nonce; + if (nonce && ![idToken.nonce isEqual:nonce]) { + NSError *invalidIDToken = + [OIDErrorUtilities errorWithCode:OIDErrorCodeIDTokenFailedValidationError + underlyingError:nil + description:@"Nonce mismatch"]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, invalidIDToken); + }); + return; + } + } + + // OpenID Connect Core Section 3.1.3.7. rules #12 + // ACR is not directly supported by AppAuth. + + // OpenID Connect Core Section 3.1.3.7. rules #12 + // max_age is not directly supported by AppAuth. + } + + // Success + dispatch_async(dispatch_get_main_queue(), ^{ + callback(tokenResponse, nil); + }); + }] resume]; +} + + +#pragma mark - Registration Endpoint + ++ (void)performRegistrationRequest:(OIDRegistrationRequest *)request + completion:(OIDRegistrationCompletion)completion { + NSURLRequest *URLRequest = [request URLRequest]; + if (!URLRequest) { + // A problem occurred deserializing the response/JSON. + NSError *returnedError = [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONSerializationError + underlyingError:nil + description:@"The registration request could not " + "be serialized as JSON."]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, returnedError); + }); + return; + } + + NSURLSession *session = [OIDURLSessionProvider session]; + [[session dataTaskWithRequest:URLRequest + completionHandler:^(NSData *_Nullable data, + NSURLResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + // A network error or server error occurred. + NSString *errorDescription = + [NSString stringWithFormat:@"Connection error making registration request to '%@': %@.", + URLRequest.URL, + error.localizedDescription]; + NSError *returnedError = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, returnedError); + }); + return; + } + + NSHTTPURLResponse *HTTPURLResponse = (NSHTTPURLResponse *) response; + + if (HTTPURLResponse.statusCode != 201 && HTTPURLResponse.statusCode != 200) { + // A server error occurred. + NSError *serverError = [OIDErrorUtilities HTTPErrorWithHTTPResponse:HTTPURLResponse + data:data]; + + // HTTP 400 may indicate an OpenID Connect Dynamic Client Registration 1.0 Section 3.3 error + // response, checks for that + if (HTTPURLResponse.statusCode == 400) { + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonDeserializationError]; + + // if the HTTP 400 response parses as JSON and has an 'error' key, it's an OAuth error + // these errors are special as they indicate a problem with the authorization grant + if (json[OIDOAuthErrorFieldError]) { + NSError *oauthError = + [OIDErrorUtilities OAuthErrorWithDomain:OIDOAuthRegistrationErrorDomain + OAuthResponse:json + underlyingError:serverError]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, oauthError); + }); + return; + } + } + + // not an OAuth error, just a generic server error + NSString *errorDescription = + [NSString stringWithFormat:@"Non-200/201 HTTP response (%d) making registration request " + "to '%@'.", + (int)HTTPURLResponse.statusCode, + URLRequest.URL]; + NSError *returnedError = [OIDErrorUtilities errorWithCode:OIDErrorCodeServerError + underlyingError:serverError + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, returnedError); + }); + return; + } + + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonDeserializationError]; + if (jsonDeserializationError) { + // A problem occurred deserializing the response/JSON. + NSString *errorDescription = + [NSString stringWithFormat:@"JSON error parsing registration response: %@", + jsonDeserializationError.localizedDescription]; + NSError *returnedError = [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONDeserializationError + underlyingError:jsonDeserializationError + description:errorDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, returnedError); + }); + return; + } + + OIDRegistrationResponse *registrationResponse = + [[OIDRegistrationResponse alloc] initWithRequest:request + parameters:json]; + if (!registrationResponse) { + // A problem occurred constructing the registration response from the JSON. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeRegistrationResponseConstructionError + underlyingError:nil + description:@"Registration response invalid."]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, returnedError); + }); + return; + } + + // Success + dispatch_async(dispatch_get_main_queue(), ^{ + completion(registrationResponse, nil); + }); + }] resume]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDClientMetadataParameters.h b/Pods/AppAuth/Sources/AppAuthCore/OIDClientMetadataParameters.h new file mode 100644 index 0000000..39ea2d6 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDClientMetadataParameters.h @@ -0,0 +1,51 @@ +/*! @file OIDClientMetadataParameters.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Parameter name for the token endpoint authentication method. + */ +extern NSString *const OIDTokenEndpointAuthenticationMethodParam; + +/*! @brief Parameter name for the application type. + */ +extern NSString *const OIDApplicationTypeParam; + +/*! @brief Parameter name for the redirect URI values. + */ +extern NSString *const OIDRedirectURIsParam; + +/*! @brief Parameter name for the response type values. + */ +extern NSString *const OIDResponseTypesParam; + +/*! @brief Parameter name for the grant type values. + */ +extern NSString *const OIDGrantTypesParam; + +/*! @brief Parameter name for the subject type. + */ +extern NSString *const OIDSubjectTypeParam; + +/*! @brief Application type that indicates this client is a native (not a web) application. + */ +extern NSString *const OIDApplicationTypeNative; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDClientMetadataParameters.m b/Pods/AppAuth/Sources/AppAuthCore/OIDClientMetadataParameters.m new file mode 100644 index 0000000..79ad467 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDClientMetadataParameters.m @@ -0,0 +1,33 @@ +/*! @file OIDClientMetadataParameters.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDClientMetadataParameters.h" + +NSString *const OIDTokenEndpointAuthenticationMethodParam = @"token_endpoint_auth_method"; + +NSString *const OIDApplicationTypeParam = @"application_type"; + +NSString *const OIDRedirectURIsParam = @"redirect_uris"; + +NSString *const OIDResponseTypesParam = @"response_types"; + +NSString *const OIDGrantTypesParam = @"grant_types"; + +NSString *const OIDSubjectTypeParam = @"subject_type"; + +NSString *const OIDApplicationTypeNative = @"native"; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDDefines.h b/Pods/AppAuth/Sources/AppAuthCore/OIDDefines.h new file mode 100644 index 0000000..8ff4f19 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDDefines.h @@ -0,0 +1,51 @@ +/*! @file OIDDefines.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +/*! @def OIDIsEqualIncludingNil(x, y) + @brief Returns YES if x and y are equal by reference or value. + @discussion NOTE: parameters may be evaluated multiple times. Be careful if using this check + with expressions - especially if the expressions have side effects. + @param x An object. + @param y An object. + */ +#define OIDIsEqualIncludingNil(x, y) (((x) == (y)) || [(x) isEqual:(y)]) + +/*! @def OID_UNAVAILABLE_USE_INITIALIZER(designatedInitializer) + @brief Provides a template implementation for init-family methods which have been marked as + NS_UNAVILABLE. Stops the compiler from giving a warning when it's the super class' + designated initializer, and gives callers useful feedback telling them what the + new designated initializer is. + @remarks Takes a SEL as a parameter instead of a string so that we get compiler warnings if the + designated intializer's signature changes. + @param designatedInitializer A SEL referencing the designated initializer. + */ +#define OID_UNAVAILABLE_USE_INITIALIZER(designatedInitializer) { \ + NSString *reason = [NSString stringWithFormat:@"Called: %@\nDesignated Initializer:%@", \ + NSStringFromSelector(_cmd), \ + NSStringFromSelector(designatedInitializer)]; \ + @throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." \ + reason:reason \ + userInfo:nil]; \ +} + +#ifdef _APPAUTHTRACE +# define AppAuthRequestTrace(fmt, ...) NSLog(fmt, ##__VA_ARGS__); +#else // _APPAUTHTRACE +# define AppAuthRequestTrace(...) +#endif // _APPAUTHTRACE + diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionRequest.h b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionRequest.h new file mode 100644 index 0000000..4087e9f --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionRequest.h @@ -0,0 +1,107 @@ +/*! @file OIDEndSessionRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2017 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDExternalUserAgentRequest.h" + +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDEndSessionRequest : NSObject + + +/*! @brief The service's configuration. + @remarks This configuration specifies how to connect to a particular OAuth provider. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @brief The client's redirect URI. + @remarks post_logout_redirect_uri + @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout + */ +@property(nonatomic, readonly, nullable) NSURL *postLogoutRedirectURL; + +/*! @brief Previously issued ID Token passed to the end session endpoint as a hint about the End-User's current authenticated + session with the Client + @remarks id_token_hint + @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout + */ +@property(nonatomic, readonly, nullable) NSString *idTokenHint; + +/*! @brief An opaque value used by the client to maintain state between the request and callback. + @remarks state + @discussion If this value is not explicitly set, this library will automatically add state and + perform appropriate validation of the state in the authorization response. It is recommended + that the default implementation of this parameter be used wherever possible. Typically used + to prevent CSRF attacks, as recommended in RFC6819 Section 5.3.5. + @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout + */ +@property(nonatomic, readonly, nullable) NSString *state; + +/*! @brief The client's additional authorization parameters. + @see https://tools.ietf.org/html/rfc6749#section-3.1 + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalParameters; + +/*! @internal + @brief Unavailable. Please use @c initWithConfiguration:clientId:scopes:redirectURL:additionalParameters:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Creates an authorization request with opinionated defaults (a secure @c state). + @param configuration The service's configuration. + @param idTokenHint The previously issued ID Token + @param postLogoutRedirectURL The client's post-logout redirect URI. + callback. + @param additionalParameters The client's additional authorization parameters. +*/ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + idTokenHint:(NSString *)idTokenHint + postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param idTokenHint The previously issued ID Token + @param postLogoutRedirectURL The client's post-logout redirect URI. + @param state An opaque value used by the client to maintain state between the request and + callback. + @param additionalParameters The client's additional authorization parameters. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + idTokenHint:(NSString *)idTokenHint + postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL + state:(NSString *)state + additionalParameters:(nullable NSDictionary *)additionalParameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Constructs the request URI by adding the request parameters to the query component of the + authorization endpoint URI using the "application/x-www-form-urlencoded" format. + @return A URL representing the authorization request. + @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout + */ +- (NSURL *)endSessionRequestURL; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionRequest.m b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionRequest.m new file mode 100644 index 0000000..1e9eb0e --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionRequest.m @@ -0,0 +1,190 @@ +/*! @file OIDEndSessionRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2017 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDEndSessionRequest.h" + +#import "OIDDefines.h" +#import "OIDTokenUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDURLQueryComponent.h" + +/*! @brief The key for the @c configuration property for @c NSSecureCoding + */ +static NSString *const kConfigurationKey = @"configuration"; + +/*! @brief Key used to encode the @c state property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kStateKey = @"state"; + +/*! @brief Key used to encode the @c postLogoutRedirectURL property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kPostLogoutRedirectURLKey = @"post_logout_redirect_uri"; + +/*! @brief Key used to encode the @c idTokenHint property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kIdTokenHintKey = @"id_token_hint"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Number of random bytes generated for the @state. + */ +static NSUInteger const kStateSizeBytes = 32; + +/*! @brief Assertion text for missing end_session_endpoint. + */ +static NSString *const OIDMissingEndSessionEndpointMessage = +@"The service configuration is missing an end_session_endpoint."; + +@implementation OIDEndSessionRequest + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER( + @selector(initWithConfiguration: + idTokenHint: + postLogoutRedirectURL: + additionalParameters:) + ) + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + idTokenHint:(NSString *)idTokenHint + postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL + state:(NSString *)state + additionalParameters:(NSDictionary *)additionalParameters +{ + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _idTokenHint = [idTokenHint copy]; + _postLogoutRedirectURL = [postLogoutRedirectURL copy]; + _state = [state copy]; + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + } + return self; +} + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + idTokenHint:(NSString *)idTokenHint + postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL + additionalParameters:(NSDictionary *)additionalParameters +{ + return [self initWithConfiguration:configuration + idTokenHint:idTokenHint + postLogoutRedirectURL:postLogoutRedirectURL + state:[[self class] generateState] + additionalParameters:additionalParameters]; +} +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDServiceConfiguration *configuration = [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] forKey:kConfigurationKey]; + + NSString *idTokenHint = [aDecoder decodeObjectOfClass:[NSString class] forKey:kIdTokenHintKey]; + NSURL *postLogoutRedirectURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kPostLogoutRedirectURLKey]; + NSString *state = [aDecoder decodeObjectOfClass:[NSString class] forKey:kStateKey]; + NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class] + ]]; + NSDictionary *additionalParameters = [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses + forKey:kAdditionalParametersKey]; + + self = [self initWithConfiguration:configuration + idTokenHint:idTokenHint + postLogoutRedirectURL:postLogoutRedirectURL + state:state + additionalParameters:additionalParameters]; + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_configuration forKey:kConfigurationKey]; + [aCoder encodeObject:_idTokenHint forKey:kIdTokenHintKey]; + [aCoder encodeObject:_postLogoutRedirectURL forKey:kPostLogoutRedirectURLKey]; + [aCoder encodeObject:_state forKey:kStateKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, request: %@>", + NSStringFromClass([self class]), + (void *)self, + self.endSessionRequestURL]; +} + ++ (nullable NSString *)generateState { + return [OIDTokenUtilities randomURLSafeStringWithSize:kStateSizeBytes]; +} + +#pragma mark - OIDExternalUserAgentRequest + +- (NSURL*)externalUserAgentRequestURL { + return [self endSessionRequestURL]; +} + +- (NSString *)redirectScheme { + return [_postLogoutRedirectURL scheme]; +} + +#pragma mark - + +- (NSURL *)endSessionRequestURL { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + // Add any additional parameters the client has specified. + [query addParameters:_additionalParameters]; + + // Add optional parameters, as applicable. + if (_idTokenHint) { + [query addParameter:kIdTokenHintKey value:_idTokenHint]; + } + + if (_postLogoutRedirectURL) { + [query addParameter:kPostLogoutRedirectURLKey value:_postLogoutRedirectURL.absoluteString]; + } + + if (_state) { + [query addParameter:kStateKey value:_state]; + } + + NSAssert(_configuration.endSessionEndpoint, OIDMissingEndSessionEndpointMessage); + + // Construct the URL + return [query URLByReplacingQueryInURL:_configuration.endSessionEndpoint]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionResponse.h b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionResponse.h new file mode 100644 index 0000000..ab69b93 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionResponse.h @@ -0,0 +1,64 @@ +/*! @file OIDEndSessionResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2017 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDEndSessionRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the response to an End Session request. + @see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout + */ + +@interface OIDEndSessionResponse : NSObject + +/*! @brief The request which was serviced. + */ +@property(nonatomic, readonly) OIDEndSessionRequest *request; + +/*! @brief REQUIRED if the "state" parameter was present in the client end-session request. The + exact value received from the client. + @remarks state + */ +@property(nonatomic, readonly, nullable) NSString *state; + +/*! @brief Additional parameters returned from the end session endpoint. + */ +@property(nonatomic, readonly, nullable) + NSDictionary *> *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithParameters:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the End Session Endpoint. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (instancetype)initWithRequest:(OIDEndSessionRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionResponse.m b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionResponse.m new file mode 100644 index 0000000..bedf0cd --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDEndSessionResponse.m @@ -0,0 +1,118 @@ +/*! @file OIDEndSessionResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2017 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDEndSessionResponse.h" + +#import "OIDDefines.h" +#import "OIDEndSessionRequest.h" +#import "OIDFieldMapping.h" + +/*! @brief The key for the @c state property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kStateKey = @"state"; + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +/*! @brief Key used to encode the @c additionalParameters property for + @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +@implementation OIDEndSessionResponse + +#pragma mark - Initializers + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:)) + +- (instancetype)initWithRequest:(OIDEndSessionRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super init]; + if (self) { + _request = [request copy]; + NSDictionary *> *additionalParameters = + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:parameters + instance:self]; + _additionalParameters = additionalParameters; + } + return self; +} + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[kStateKey] = + [[OIDFieldMapping alloc] initWithName:@"_state" type:[NSString class]]; + }); + return fieldMap; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDEndSessionRequest *request = + [aDecoder decodeObjectOfClass:[OIDEndSessionRequest class] forKey:kRequestKey]; + self = [self initWithRequest:request parameters:@{ }]; + if (self) { + [OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self]; + _additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes] + forKey:kAdditionalParametersKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_request forKey:kRequestKey]; + [OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, state: \"%@\", " + "additionalParameters: %@, request: %@>", + NSStringFromClass([self class]), + (void *)self, + _state, + _additionalParameters, + _request]; +} +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDError.h b/Pods/AppAuth/Sources/AppAuthCore/OIDError.h new file mode 100644 index 0000000..5131f0a --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDError.h @@ -0,0 +1,393 @@ +/*! @file OIDError.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The error domain for all NSErrors returned from the AppAuth library. + */ +extern NSString *const OIDGeneralErrorDomain; + +/*! @brief The error domain for OAuth specific errors on the authorization endpoint. + @discussion This error domain is used when the server responds to an authorization request + with an explicit OAuth error, as defined by RFC6749 Section 4.1.2.1. If the authorization + response is invalid and not explicitly an error response, another error domain will be used. + The error response parameter dictionary is available in the + \NSError_userInfo dictionary using the @c ::OIDOAuthErrorResponseErrorKey key. + The \NSError_code will be one of the @c ::OIDErrorCodeOAuthAuthorization enum values. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ +extern NSString *const OIDOAuthAuthorizationErrorDomain; + +/*! @brief The error domain for OAuth specific errors on the token endpoint. + @discussion This error domain is used when the server responds with HTTP 400 and an OAuth error, + as defined RFC6749 Section 5.2. If an HTTP 400 response does not parse as an OAuth error + (i.e. no 'error' field is present or the JSON is invalid), another error domain will be + used. The entire OAuth error response dictionary is available in the \NSError_userInfo + dictionary using the @c ::OIDOAuthErrorResponseErrorKey key. Unlike transient network + errors, errors in this domain invalidate the authentication state, and either indicate a + client error or require user interaction (i.e. reauthentication) to resolve. + The \NSError_code will be one of the @c ::OIDErrorCodeOAuthToken enum values. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthTokenErrorDomain; + +/*! @brief The error domain for dynamic client registration errors. + @discussion This error domain is used when the server responds with HTTP 400 and an OAuth error, + as defined in OpenID Connect Dynamic Client Registration 1.0 Section 3.3. If an HTTP 400 + response does not parse as an OAuth error (i.e. no 'error' field is present or the JSON is + invalid), another error domain will be used. The entire OAuth error response dictionary is + available in the \NSError_userInfo dictionary using the @c ::OIDOAuthErrorResponseErrorKey + key. Unlike transient network errors, errors in this domain invalidate the authentication + state, and indicates a client error. + The \NSError_code will be one of the @c ::OIDErrorCodeOAuthToken enum values. + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError + */ +extern NSString *const OIDOAuthRegistrationErrorDomain; + +/*! @brief The error domain for authorization errors encountered out of band on the resource server. + */ +extern NSString *const OIDResourceServerAuthorizationErrorDomain; + +/*! @brief An error domain representing received HTTP errors. + */ +extern NSString *const OIDHTTPErrorDomain; + +/*! @brief An error key for the original OAuth error response (if any). + */ +extern NSString *const OIDOAuthErrorResponseErrorKey; + +/*! @brief The key of the 'error' response field in a RFC6749 Section 5.2 response. + @remark error + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthErrorFieldError; + +/*! @brief The key of the 'error_description' response field in a RFC6749 Section 5.2 response. + @remark error_description + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthErrorFieldErrorDescription; + +/*! @brief The key of the 'error_uri' response field in a RFC6749 Section 5.2 response. + @remark error_uri + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthErrorFieldErrorURI; + +/*! @brief The various error codes returned from the AppAuth library. + */ +typedef NS_ENUM(NSInteger, OIDErrorCode) { + /*! @brief Indicates a problem parsing an OpenID Connect Service Discovery document. + */ + OIDErrorCodeInvalidDiscoveryDocument = -2, + + /*! @brief Indicates the user manually canceled the OAuth authorization code flow. + */ + OIDErrorCodeUserCanceledAuthorizationFlow = -3, + + /*! @brief Indicates an OAuth authorization flow was programmatically cancelled. + */ + OIDErrorCodeProgramCanceledAuthorizationFlow = -4, + + /*! @brief Indicates a network error or server error occurred. + */ + OIDErrorCodeNetworkError = -5, + + /*! @brief Indicates a server error occurred. + */ + OIDErrorCodeServerError = -6, + + /*! @brief Indicates a problem occurred deserializing the response/JSON. + */ + OIDErrorCodeJSONDeserializationError = -7, + + /*! @brief Indicates a problem occurred constructing the token response from the JSON. + */ + OIDErrorCodeTokenResponseConstructionError = -8, + + /*! @brief @c UIApplication.openURL: returned NO when attempting to open the authorization + request in mobile Safari. + */ + OIDErrorCodeSafariOpenError = -9, + + /*! @brief @c NSWorkspace.openURL returned NO when attempting to open the authorization + request in the default browser. + */ + OIDErrorCodeBrowserOpenError = -10, + + /*! @brief Indicates a problem when trying to refresh the tokens. + */ + OIDErrorCodeTokenRefreshError = -11, + + /*! @brief Indicates a problem occurred constructing the registration response from the JSON. + */ + OIDErrorCodeRegistrationResponseConstructionError = -12, + + /*! @brief Indicates a problem occurred deserializing the response/JSON. + */ + OIDErrorCodeJSONSerializationError = -13, + + /*! @brief The ID Token did not parse. + */ + OIDErrorCodeIDTokenParsingError = -14, + + /*! @brief The ID Token did not pass validation (e.g. issuer, audience checks). + */ + OIDErrorCodeIDTokenFailedValidationError = -15, +}; + +/*! @brief Enum of all possible OAuth error codes as defined by RFC6749 + @discussion Used by @c ::OIDErrorCodeOAuthAuthorization and @c ::OIDErrorCodeOAuthToken + which define endpoint-specific subsets of OAuth codes. Those enum types are down-castable + to this one. + @see https://tools.ietf.org/html/rfc6749#section-11.4 + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuth) { + + /*! @remarks invalid_request + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidRequest = -2, + + /*! @remarks unauthorized_client + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthUnauthorizedClient = -3, + + /*! @remarks access_denied + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAccessDenied = -4, + + /*! @remarks unsupported_response_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthUnsupportedResponseType = -5, + + /*! @remarks invalid_scope + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidScope = -6, + + /*! @remarks server_error + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthServerError = -7, + + /*! @remarks temporarily_unavailable + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthTemporarilyUnavailable = -8, + + /*! @remarks invalid_client + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidClient = -9, + + /*! @remarks invalid_grant + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidGrant = -10, + + /*! @remarks unsupported_grant_type + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthUnsupportedGrantType = -11, + + /*! @remarks invalid_redirect_uri + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError + */ + OIDErrorCodeOAuthInvalidRedirectURI = -12, + + /*! @remarks invalid_client_metadata + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError + */ + OIDErrorCodeOAuthInvalidClientMetadata = -13, + + /*! @brief An authorization error occurring on the client rather than the server. For example, + due to a state mismatch or misconfiguration. Should be treated as an unrecoverable + authorization error. + */ + OIDErrorCodeOAuthClientError = -0xEFFF, + + /*! @brief An OAuth error not known to this library + @discussion Indicates an OAuth error as per RFC6749, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. Such errors are assumed to invalidate the + authentication state + */ + OIDErrorCodeOAuthOther = -0xF000, +}; + +/*! @brief The error codes for the @c ::OIDOAuthAuthorizationErrorDomain error domain + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuthAuthorization) { + /*! @remarks invalid_request + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationInvalidRequest = OIDErrorCodeOAuthInvalidRequest, + + /*! @remarks unauthorized_client + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationUnauthorizedClient = OIDErrorCodeOAuthUnauthorizedClient, + + /*! @remarks access_denied + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationAccessDenied = + OIDErrorCodeOAuthAccessDenied, + + /*! @remarks unsupported_response_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationUnsupportedResponseType = + OIDErrorCodeOAuthUnsupportedResponseType, + + /*! @brief Indicates a network error or server error occurred. + @remarks invalid_scope + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationAuthorizationInvalidScope = OIDErrorCodeOAuthInvalidScope, + + /*! @brief Indicates a server error occurred. + @remarks server_error + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationServerError = OIDErrorCodeOAuthServerError, + + /*! @remarks temporarily_unavailable + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationTemporarilyUnavailable = OIDErrorCodeOAuthTemporarilyUnavailable, + + /*! @brief An authorization error occurring on the client rather than the server. For example, + due to a state mismatch or client misconfiguration. Should be treated as an unrecoverable + authorization error. + */ + OIDErrorCodeOAuthAuthorizationClientError = OIDErrorCodeOAuthClientError, + + /*! @brief An authorization OAuth error not known to this library + @discussion this indicates an OAuth error as per RFC6749, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. We assume such errors are not transient. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationOther = OIDErrorCodeOAuthOther, +}; + + +/*! @brief The error codes for the @c ::OIDOAuthTokenErrorDomain error domain + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuthToken) { + /*! @remarks invalid_request + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidRequest = OIDErrorCodeOAuthInvalidRequest, + + /*! @remarks invalid_client + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidClient = OIDErrorCodeOAuthInvalidClient, + + /*! @remarks invalid_grant + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidGrant = OIDErrorCodeOAuthInvalidGrant, + + /*! @remarks unauthorized_client + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenUnauthorizedClient = OIDErrorCodeOAuthUnauthorizedClient, + + /*! @remarks unsupported_grant_type + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenUnsupportedGrantType = OIDErrorCodeOAuthUnsupportedGrantType, + + /*! @remarks invalid_scope + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidScope = OIDErrorCodeOAuthInvalidScope, + + /*! @brief An unrecoverable token error occurring on the client rather than the server. + */ + OIDErrorCodeOAuthTokenClientError = OIDErrorCodeOAuthClientError, + + /*! @brief A token endpoint OAuth error not known to this library + @discussion this indicates an OAuth error as per RFC6749, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. We assume such errors are not transient. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenOther = OIDErrorCodeOAuthOther, +}; + +/*! @brief The error codes for the @c ::OIDOAuthRegistrationErrorDomain error domain + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuthRegistration) { + /*! @remarks invalid_request + @see http://tools.ietf.org/html/rfc6750#section-3.1 + */ + OIDErrorCodeOAuthRegistrationInvalidRequest = OIDErrorCodeOAuthInvalidRequest, + + /*! @remarks invalid_redirect_uri + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError + */ + OIDErrorCodeOAuthRegistrationInvalidRedirectURI = OIDErrorCodeOAuthInvalidRedirectURI, + + /*! @remarks invalid_client_metadata + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationError + */ + OIDErrorCodeOAuthRegistrationInvalidClientMetadata = OIDErrorCodeOAuthInvalidClientMetadata, + + /*! @brief An unrecoverable token error occurring on the client rather than the server. + */ + OIDErrorCodeOAuthRegistrationClientError = OIDErrorCodeOAuthClientError, + + /*! @brief A registration endpoint OAuth error not known to this library + @discussion this indicates an OAuth error, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. We assume such errors are not transient. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthRegistrationOther = OIDErrorCodeOAuthOther, +}; + + +/*! @brief The exception text for the exception which occurs when a + @c OIDExternalUserAgentSession receives a message after it has already completed. + */ +extern NSString *const OIDOAuthExceptionInvalidAuthorizationFlow; + +/*! @brief The text for the exception which occurs when a Token Request is constructed + with a null redirectURL for a grant_type that requires a nonnull Redirect + */ +extern NSString *const OIDOAuthExceptionInvalidTokenRequestNullRedirectURL; + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDError.m b/Pods/AppAuth/Sources/AppAuthCore/OIDError.m new file mode 100644 index 0000000..87c8623 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDError.m @@ -0,0 +1,45 @@ +/*! @file OIDError.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDError.h" + +NSString *const OIDGeneralErrorDomain = @"org.openid.appauth.general"; + +NSString *const OIDOAuthTokenErrorDomain = @"org.openid.appauth.oauth_token"; + +NSString *const OIDOAuthAuthorizationErrorDomain = @"org.openid.appauth.oauth_authorization"; + +NSString *const OIDOAuthRegistrationErrorDomain = @"org.openid.appauth.oauth_registration"; + +NSString *const OIDResourceServerAuthorizationErrorDomain = @"org.openid.appauth.resourceserver"; + +NSString *const OIDHTTPErrorDomain = @"org.openid.appauth.remote-http"; + +NSString *const OIDOAuthExceptionInvalidAuthorizationFlow = @"An OAuth redirect was sent to a " + "OIDExternalUserAgentSession after it already completed."; + +NSString *const OIDOAuthExceptionInvalidTokenRequestNullRedirectURL = @"A OIDTokenRequest was " + "created with a grant_type that requires a redirectURL, but a null redirectURL was given"; + +NSString *const OIDOAuthErrorResponseErrorKey = @"OIDOAuthErrorResponseErrorKey"; + +NSString *const OIDOAuthErrorFieldError = @"error"; + +NSString *const OIDOAuthErrorFieldErrorDescription = @"error_description"; + +NSString *const OIDOAuthErrorFieldErrorURI = @"error_uri"; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDErrorUtilities.h b/Pods/AppAuth/Sources/AppAuthCore/OIDErrorUtilities.h new file mode 100644 index 0000000..3380f6f --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDErrorUtilities.h @@ -0,0 +1,107 @@ +/*! @file OIDErrorUtilities.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDError.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Convenience methods for creating standardized \NSError instances. + */ +@interface OIDErrorUtilities : NSObject + +/*! @brief Creates a standard \NSError from an @c ::OIDErrorCode and custom user info. + Automatically populates the localized error description. + @param code The error code. + @param underlyingError The underlying error which occurred, if applicable. + @param description A custom description, if applicable. + @return An \NSError representing the error code. + */ ++ (NSError *)errorWithCode:(OIDErrorCode)code + underlyingError:(nullable NSError *)underlyingError + description:(nullable NSString *)description; + +/*! @brief Creates a standard \NSError from an @c ::OIDErrorCode and custom user info. + Automatically populates the localized error description. + @param OAuthErrorDomain The OAuth error domain. Must be @c ::OIDOAuthAuthorizationErrorDomain or + @c ::OIDOAuthTokenErrorDomain. + @param errorResponse The dictionary from an OAuth error response (as per RFC6749 Section 5.2). + @param underlyingError The underlying error which occurred, if applicable. + @return An \NSError representing the OAuth error. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ ++ (NSError *)OAuthErrorWithDomain:(NSString *)OAuthErrorDomain + OAuthResponse:(NSDictionary *)errorResponse + underlyingError:(nullable NSError *)underlyingError; + +/*! @brief Creates a \NSError indicating that the resource server responded with an authorization + error. + @param code Your error code. + @param errorResponse The resource server error response, if any. + @param underlyingError The underlying error which occurred, if applicable. + @return An \NSError representing the authorization error from the resource server. + */ ++ (NSError *)resourceServerAuthorizationErrorWithCode:(NSInteger)code + errorResponse:(nullable NSDictionary *)errorResponse + underlyingError:(nullable NSError *)underlyingError; + + +/*! @brief Creates a standard \NSError from an \NSHTTPURLResponse. Automatically + populates the localized error description with the response data associated with the + \NSHTTPURLResponse, if available. + @param HTTPURLResponse The response which indicates an error occurred. + @param data The response data associated with the response which should be converted to an + @c NSString assuming a UTF-8 encoding, if available. + @return An \NSError representing the error. + */ ++ (NSError *)HTTPErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPURLResponse + data:(nullable NSData *)data; + +/*! @brief Raises an exception with the given name as both the name, and the message. + @param name The name of the exception. + */ ++ (void)raiseException:(NSString *)name; + +/*! @brief Raises an exception with the given name and message. + @param name The name of the exception. + @param message The message of the exception. + */ ++ (void)raiseException:(NSString *)name message:(NSString *)message; + +/*! @brief Converts an OAuth error code into an @c ::OIDErrorCodeOAuth error code. + @param errorCode The OAuth error code. + @discussion Returns @c ::OIDErrorCodeOAuthOther if the string is not in AppAuth's list. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ ++ (OIDErrorCodeOAuth)OAuthErrorCodeFromString:(NSString *)errorCode; + +/*! @brief Returns true if the given error domain is an OAuth error domain. + @param errorDomain The error domain to test. + @discussion An OAuth error domain is used for errors returned per RFC6749 sections 4.1.2.1 and + 5.2. Other errors, such as network errors can also occur but they will not have an OAuth + error domain. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ ++ (BOOL)isOAuthErrorDomain:(NSString*)errorDomain; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDErrorUtilities.m b/Pods/AppAuth/Sources/AppAuthCore/OIDErrorUtilities.m new file mode 100644 index 0000000..3b3c060 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDErrorUtilities.m @@ -0,0 +1,172 @@ +/*! @file OIDErrorUtilities.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDErrorUtilities.h" + +@implementation OIDErrorUtilities + ++ (NSError *)errorWithCode:(OIDErrorCode)code + underlyingError:(NSError *)underlyingError + description:(NSString *)description { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + if (description) { + userInfo[NSLocalizedDescriptionKey] = description; + } + // TODO: Populate localized description based on code. + NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain + code:code + userInfo:userInfo]; + return error; +} + ++ (BOOL)isOAuthErrorDomain:(NSString *)errorDomain { + return errorDomain == OIDOAuthRegistrationErrorDomain + || errorDomain == OIDOAuthAuthorizationErrorDomain + || errorDomain == OIDOAuthTokenErrorDomain; +} + ++ (NSError *)resourceServerAuthorizationErrorWithCode:(NSInteger)code + errorResponse:(nullable NSDictionary *)errorResponse + underlyingError:(nullable NSError *)underlyingError { + // builds the userInfo dictionary with the full OAuth response and other information + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (errorResponse) { + userInfo[OIDOAuthErrorResponseErrorKey] = errorResponse; + } + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + NSError *error = [NSError errorWithDomain:OIDResourceServerAuthorizationErrorDomain + code:code + userInfo:userInfo]; + return error; +} + ++ (NSError *)OAuthErrorWithDomain:(NSString *)oAuthErrorDomain + OAuthResponse:(NSDictionary *)errorResponse + underlyingError:(NSError *)underlyingError { + // not a valid OAuth error + if (![self isOAuthErrorDomain:oAuthErrorDomain] + || !errorResponse + || !errorResponse[OIDOAuthErrorFieldError] + || ![errorResponse[OIDOAuthErrorFieldError] isKindOfClass:[NSString class]]) { + return [[self class] errorWithCode:OIDErrorCodeNetworkError + underlyingError:underlyingError + description:underlyingError.localizedDescription]; + } + + // builds the userInfo dictionary with the full OAuth response and other information + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[OIDOAuthErrorResponseErrorKey] = errorResponse; + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + + NSString *oauthErrorCodeString = errorResponse[OIDOAuthErrorFieldError]; + NSString *oauthErrorMessage = nil; + if ([errorResponse[OIDOAuthErrorFieldErrorDescription] isKindOfClass:[NSString class]]) { + oauthErrorMessage = errorResponse[OIDOAuthErrorFieldErrorDescription]; + } else { + oauthErrorMessage = [errorResponse[OIDOAuthErrorFieldErrorDescription] description]; + } + NSString *oauthErrorURI = nil; + if ([errorResponse[OIDOAuthErrorFieldErrorURI] isKindOfClass:[NSString class]]) { + oauthErrorURI = errorResponse[OIDOAuthErrorFieldErrorURI]; + } else { + oauthErrorURI = [errorResponse[OIDOAuthErrorFieldErrorURI] description]; + } + + // builds the error description, using the information supplied by the server if possible + NSMutableString *description = [NSMutableString string]; + [description appendString:oauthErrorCodeString]; + if (oauthErrorMessage) { + [description appendString:@": "]; + [description appendString:oauthErrorMessage]; + } + if (oauthErrorURI) { + if ([description length] > 0) { + [description appendString:@" - "]; + } + [description appendString:oauthErrorURI]; + } + if ([description length] == 0) { + // backup description + [description appendFormat:@"OAuth error: %@ - https://tools.ietf.org/html/rfc6749#section-5.2", + oauthErrorCodeString]; + } + userInfo[NSLocalizedDescriptionKey] = description; + + // looks up the error code based on the "error" response param + OIDErrorCodeOAuth code = [[self class] OAuthErrorCodeFromString:oauthErrorCodeString]; + + NSError *error = [NSError errorWithDomain:oAuthErrorDomain + code:code + userInfo:userInfo]; + return error; +} + ++ (NSError *)HTTPErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPURLResponse + data:(nullable NSData *)data { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (data) { + NSString *serverResponse = + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (serverResponse) { + userInfo[NSLocalizedDescriptionKey] = serverResponse; + } + } + NSError *serverError = + [NSError errorWithDomain:OIDHTTPErrorDomain + code:HTTPURLResponse.statusCode + userInfo:userInfo]; + return serverError; +} + ++ (OIDErrorCodeOAuth)OAuthErrorCodeFromString:(NSString *)errorCode { + NSDictionary *errorCodes = @{ + @"invalid_request": @(OIDErrorCodeOAuthInvalidRequest), + @"unauthorized_client": @(OIDErrorCodeOAuthUnauthorizedClient), + @"access_denied": @(OIDErrorCodeOAuthAccessDenied), + @"unsupported_response_type": @(OIDErrorCodeOAuthUnsupportedResponseType), + @"invalid_scope": @(OIDErrorCodeOAuthInvalidScope), + @"server_error": @(OIDErrorCodeOAuthServerError), + @"temporarily_unavailable": @(OIDErrorCodeOAuthTemporarilyUnavailable), + @"invalid_client": @(OIDErrorCodeOAuthInvalidClient), + @"invalid_grant": @(OIDErrorCodeOAuthInvalidGrant), + @"unsupported_grant_type": @(OIDErrorCodeOAuthUnsupportedGrantType), + }; + NSNumber *code = errorCodes[errorCode]; + if (code) { + return [code integerValue]; + } else { + return OIDErrorCodeOAuthOther; + } +} + ++ (void)raiseException:(NSString *)name { + [[self class] raiseException:name message:name]; +} + ++ (void)raiseException:(NSString *)name message:(NSString *)message { + [NSException raise:name format:@"%@", message]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgent.h b/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgent.h new file mode 100644 index 0000000..c4eb0a9 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgent.h @@ -0,0 +1,53 @@ +/*! @file OIDExternalUserAgent.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@protocol OIDExternalUserAgentSession; +@protocol OIDExternalUserAgentRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @protocol OIDExternalUserAgent + @brief An external user-agent UI that presents displays the request to the user. Clients may + provide custom implementations of an external user-agent to customize the way the requests + are presented to the end user. + */ +@protocol OIDExternalUserAgent + +/*! @brief Presents the request in the external user-agent. + @param request The request to be presented in the external user-agent. + @param session The @c OIDExternalUserAgentSession instance that initiates presenting the UI. + Concrete implementations of a @c OIDExternalUserAgent may call + resumeExternalUserAgentFlowWithURL or failExternalUserAgentFlowWithError on session to either + resume or fail the request. + @return YES If the request UI was successfully presented to the user. + */ +- (BOOL)presentExternalUserAgentRequest:(id )request + session:(id)session; + +/*! @brief Dimisses the external user-agent and calls completion when the dismiss operation ends. + @param animated Whether or not the dismiss operation should be animated. + @remarks Has no effect if no UI is presented. + @param completion The block to be called when the dismiss operations ends + */ +- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgentRequest.h b/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgentRequest.h new file mode 100644 index 0000000..8ea40cb --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgentRequest.h @@ -0,0 +1,37 @@ +/*! @file OIDExternalUserAgent.h + @brief AppAuth iOS SDK + @copyright + Copyright 2017 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +/*! @protocol OIDExternalUserAgent + @brief An interface that any external user-agent request may implement to use the + @c OIDExternalUserAgent flow. + */ +@protocol OIDExternalUserAgentRequest + +/*! @brief Method to create and return the complete request URL instance. + @return A @c NSURL instance which contains the URL to be opened in an external UI (i.e. browser) + */ +- (NSURL*)externalUserAgentRequestURL; + +/*! @brief If this external user-agent request has a redirect URL, this should return its scheme. + Since some external requests have optional callbacks (such as the end session endpoint), the + return value of this method is nullable. + @return A @c NSString instance that contains the scheme of a callback url, or nil if there is + no callback url for this request. + */ +- (NSString*)redirectScheme; +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgentSession.h b/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgentSession.h new file mode 100644 index 0000000..3b886a6 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDExternalUserAgentSession.h @@ -0,0 +1,65 @@ +/*! @file OIDExternalUserAgentSession.h + @brief AppAuth iOS SDK + @copyright + Copyright 2017 The AppAuth Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents an in-flight external user-agent session. + */ +@protocol OIDExternalUserAgentSession + +/*! @brief Cancels the code flow session, invoking the request's callback with a cancelled error. + @remarks Has no effect if called more than once, or after a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message was received. + Will cause an error with code: @c ::OIDErrorCodeProgramCanceledAuthorizationFlow to be + passed to the @c callback block passed to + @c OIDAuthorizationService.presentAuthorizationRequest:presentingViewController:callback: + */ +- (void)cancel; + +/*! @brief Cancels the code flow session, invoking the request's callback with a cancelled error. + @remarks Has no effect if called more than once, or after a + @c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message was received. + Will cause an error with code: @c ::OIDErrorCodeProgramCanceledAuthorizationFlow to be + passed to the @c callback block passed to + @c OIDAuthorizationService.presentAuthorizationRequest:presentingViewController:callback: + @param completion The block to be called when the cancel operation ends + */ +- (void)cancelWithCompletion:(nullable void (^)(void))completion; + +/*! @brief Clients should call this method with the result of the external user-agent code flow if + it becomes available. + @param URL The redirect URL invoked by the server. + @discussion When the URL represented a valid response, implementations should clean up any + left-over UI state from the request, for example by closing the + \SFSafariViewController or loopback HTTP listener if those were used. The completion block + of the pending request should then be invoked. + @remarks Has no effect if called more than once, or after a @c cancel message was received. + @return YES if the passed URL matches the expected redirect URL and was consumed, NO otherwise. + */ +- (BOOL)resumeExternalUserAgentFlowWithURL:(NSURL *)URL; + +/*! @brief @c OIDExternalUserAgent or clients should call this method when the + external user-agent flow failed with a non-OAuth error. + @param error The error that is the reason for the failure of this external flow. + @remarks Has no effect if called more than once, or after a @c cancel message was received. + */ +- (void)failExternalUserAgentFlowWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDFieldMapping.h b/Pods/AppAuth/Sources/AppAuthCore/OIDFieldMapping.h new file mode 100644 index 0000000..f0a56fe --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDFieldMapping.h @@ -0,0 +1,126 @@ +/*! @file OIDFieldMapping.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a function which transforms incoming source values into instance variable + values. + */ +typedef _Nullable id(^OIDFieldMappingConversionFunction)(NSObject *_Nullable value); + +/*! @brief Describes the mapping of a key/value pair to an iVar with an optional conversion + function. + */ +@interface OIDFieldMapping : NSObject + +/*! @brief The name of the instance variable the field should be mapped to. + */ +@property(nonatomic, readonly) NSString *name; + +/*! @brief The type of the instance variable. + */ +@property(nonatomic, readonly) Class expectedType; + +/*! @brief An optional conversion function which specifies a transform from the incoming data to the + instance variable value. + */ +@property(nonatomic, readonly, nullable) OIDFieldMappingConversionFunction conversion; + +/*! @internal + @brief Unavailable. Please use initWithName:type:conversion:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief The designated initializer. + @param name The name of the instance variable the field should be mapped to. + @param type The type of the instance variable. + @param conversion An optional conversion function which specifies a transform from the incoming + data to the instance variable value. Used during the process performed by + @c OIDFieldMapping.remainingParametersWithMap:parameters:instance: but not during + encoding/decoding, since the encoded and decoded values should already be of the type + specified by the @c type parameter. + */ +- (instancetype)initWithName:(NSString *)name + type:(Class)type + conversion:(nullable OIDFieldMappingConversionFunction)conversion + NS_DESIGNATED_INITIALIZER; + +/*! @brief A convenience initializer. + @param name The name of the instance variable the field should be mapped to. + @param type The type of the instance variable. + */ +- (instancetype)initWithName:(NSString *)name + type:(Class)type; + +/*! @brief Performs a mapping of key/value pairs in an incoming parameters dictionary to instance + variables, returning a dictionary of parameter key/values which didn't map to instance + variables. + @param map A mapping of incoming keys to instance variables. + @param parameters Incoming key value pairs to map to an instance's variables. + @param instance The instance whose variables should be set based on the mapping. + @return A dictionary of parameter key/values which didn't map to instance variables. + */ ++ (NSDictionary *> *)remainingParametersWithMap: + (NSDictionary *)map + parameters:(NSDictionary *> *)parameters + instance:(id)instance; + +/*! @brief This helper method for @c NSCoding implementations performs a serialization of fields + defined in a field mapping. + @param aCoder An @c NSCoder instance to serialize instance variable values to. + @param map A mapping of keys to instance variables. + @param instance The instance whose variables should be serialized based on the mapping. + */ ++ (void)encodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance; + +/*! @brief This helper method for @c NSCoding implementations performs a deserialization of + fields defined in a field mapping. + @param aCoder An @c NSCoder instance from which to deserialize instance variable values from. + @param map A mapping of keys to instance variables. + @param instance The instance whose variables should be deserialized based on the mapping. + */ ++ (void)decodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance; + +/*! @brief Returns an @c NSSet of classes suitable for deserializing JSON content in an + @c NSSecureCoding context. + */ ++ (NSSet *)JSONTypes; + +/*! @brief Returns a function for converting an @c NSString to an @c NSURL. + */ ++ (OIDFieldMappingConversionFunction)URLConversion; + +/*! @brief Returns a function for converting an @c NSNumber number of seconds from now to an + @c NSDate. + */ ++ (OIDFieldMappingConversionFunction)dateSinceNowConversion; + +/*! @brief Returns a function for converting an @c NSNumber representing a unix time stamp to an + @c NSDate. + */ ++ (OIDFieldMappingConversionFunction)dateEpochConversion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDFieldMapping.m b/Pods/AppAuth/Sources/AppAuthCore/OIDFieldMapping.m new file mode 100644 index 0000000..f843656 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDFieldMapping.m @@ -0,0 +1,132 @@ +/*! @file OIDFieldMapping.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDFieldMapping.h" + +#import "OIDDefines.h" + +@implementation OIDFieldMapping + +- (nonnull instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithName:type:conversion:)) + +- (instancetype)initWithName:(NSString *)name + type:(Class)type { + return [self initWithName:name type:type conversion:nil]; +} + +- (instancetype)initWithName:(NSString *)name + type:(Class)type + conversion:(nullable OIDFieldMappingConversionFunction)conversion { + self = [super init]; + if (self) { + _name = [name copy]; + _expectedType = type; + _conversion = conversion; + } + return self; +} + ++ (NSDictionary *> *)remainingParametersWithMap: + (NSDictionary *)map + parameters:(NSDictionary *> *)parameters + instance:(id)instance { + NSMutableDictionary *additionalParameters = [NSMutableDictionary dictionary]; + for (NSString *key in parameters) { + NSObject *value = [parameters[key] copy]; + OIDFieldMapping *mapping = map[key]; + // If the field doesn't appear in the mapping, we add it to the additional parameters + // dictionary. + if (!mapping) { + additionalParameters[key] = value; + continue; + } + // If the field mapping specifies a conversion function, apply the conversion to the value. + if (mapping.conversion) { + value = mapping.conversion(value); + } + // Check the type of the value and make sure it matches the type we expected. If it doesn't we + // add the value to the additional parameters dictionary but don't assign the instance variable. + if (![value isKindOfClass:mapping.expectedType]) { + additionalParameters[key] = value; + continue; + } + // Assign the instance variable. + [instance setValue:value forKey:mapping.name]; + } + return additionalParameters; +} + ++ (void)encodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance { + for (NSString *key in map) { + id value = [instance valueForKey:map[key].name]; + [aCoder encodeObject:value forKey:key]; + } +} + ++ (void)decodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance { + for (NSString *key in map) { + OIDFieldMapping *mapping = map[key]; + id value = [aCoder decodeObjectOfClass:mapping.expectedType forKey:key]; + [instance setValue:value forKey:mapping.name]; + } +} + ++ (NSSet *)JSONTypes { + return [NSSet setWithArray:@[ + [NSDictionary class], + [NSArray class], + [NSString class], + [NSNumber class] + ]]; +} + ++ (OIDFieldMappingConversionFunction)URLConversion { + return ^id _Nullable(NSObject *_Nullable value) { + if ([value isKindOfClass:[NSString class]]) { + return [NSURL URLWithString:(NSString *)value]; + } + return value; + }; +} + ++ (OIDFieldMappingConversionFunction)dateSinceNowConversion { + return ^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]]; + }; +} + ++ (OIDFieldMappingConversionFunction)dateEpochConversion { + return ^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *) value; + return [NSDate dateWithTimeIntervalSince1970:[valueAsNumber longLongValue]]; + }; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDGrantTypes.h b/Pods/AppAuth/Sources/AppAuthCore/OIDGrantTypes.h new file mode 100644 index 0000000..6e65004 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDGrantTypes.h @@ -0,0 +1,40 @@ +/*! @file OIDGrantTypes.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +/*! @brief For exchanging an authorization code for an access token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +extern NSString *const OIDGrantTypeAuthorizationCode; + +/*! @brief For refreshing an access token with a refresh token. + @see https://tools.ietf.org/html/rfc6749#section-6 + */ +extern NSString *const OIDGrantTypeRefreshToken; + +/*! @brief For obtaining an access token with a username and password. + @see https://tools.ietf.org/html/rfc6749#section-4.3.2 + */ +extern NSString *const OIDGrantTypePassword; + +/*! @brief For obtaining an access token from the token endpoint using client credentials. + @see https://tools.ietf.org/html/rfc6749#section-3.2.1 + @see https://tools.ietf.org/html/rfc6749#section-4.4.2 + */ +extern NSString *const OIDGrantTypeClientCredentials; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDGrantTypes.m b/Pods/AppAuth/Sources/AppAuthCore/OIDGrantTypes.m new file mode 100644 index 0000000..2b19343 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDGrantTypes.m @@ -0,0 +1,27 @@ +/*! @file OIDGrantTypes.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDGrantTypes.h" + +NSString *const OIDGrantTypeAuthorizationCode = @"authorization_code"; + +NSString *const OIDGrantTypeRefreshToken = @"refresh_token"; + +NSString *const OIDGrantTypePassword = @"password"; + +NSString *const OIDGrantTypeClientCredentials = @"client_credentials"; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDIDToken.h b/Pods/AppAuth/Sources/AppAuthCore/OIDIDToken.h new file mode 100644 index 0000000..6fe84d7 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDIDToken.h @@ -0,0 +1,91 @@ +/*! @file OIDIDToken.h + @brief AppAuth iOS SDK + @copyright + Copyright 2017 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief A convenience class that parses an ID Token and extracts the claims _but does not_ + verify its signature. AppAuth only supports the OpenID Code flow, meaning ID Tokens + received by AppAuth are sent from the token endpoint on a TLS protected channel, + offering some assurances as to the origin of the token. You may wish to additionally + verify the ID Token signature using a JWT signature verification library of your + choosing. + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + @see https://tools.ietf.org/html/rfc7519 + @see https://jwt.io/ + */ +@interface OIDIDToken : NSObject + +/*! @internal + @brief Unavailable. Please use @c initWithAuthorizationResponse:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Parses the given ID Token string. + @param idToken The ID Token spring. + */ +- (nullable instancetype)initWithIDTokenString:(NSString *)idToken; + +/*! @brief The header JWT values. + */ +@property(nonatomic, readonly) NSDictionary *header; + +/*! @brief All ID Token claims. + */ +@property(nonatomic, readonly) NSDictionary *claims; + +/*! @brief Issuer Identifier for the Issuer of the response. + @remarks iss + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +@property(nonatomic, readonly) NSURL *issuer; + +/*! @brief Subject Identifier. + @remarks sub + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +@property(nonatomic, readonly) NSString *subject; + +/*! @brief Audience(s) that this ID Token is intended for. + @remarks aud + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +@property(nonatomic, readonly) NSArray *audience; + +/*! @brief Expiration time on or after which the ID Token MUST NOT be accepted for processing. + @remarks exp + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +@property(nonatomic, readonly) NSDate *expiresAt; + +/*! @brief Time at which the JWT was issued. + @remarks iat + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +@property(nonatomic, readonly) NSDate *issuedAt; + +/*! @brief String value used to associate a Client session with an ID Token, and to mitigate replay + attacks. + @remarks nonce + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + */ +@property(nonatomic, readonly, nullable) NSString *nonce; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDIDToken.m b/Pods/AppAuth/Sources/AppAuthCore/OIDIDToken.m new file mode 100644 index 0000000..57a7324 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDIDToken.m @@ -0,0 +1,149 @@ +/*! @file OIDIDToken.m + @brief AppAuth iOS SDK + @copyright + Copyright 2017 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDIDToken.h" + +/*! Field keys associated with an ID Token. */ +static NSString *const kIssKey = @"iss"; +static NSString *const kSubKey = @"sub"; +static NSString *const kAudKey = @"aud"; +static NSString *const kExpKey = @"exp"; +static NSString *const kIatKey = @"iat"; +static NSString *const kNonceKey = @"nonce"; + +#import "OIDFieldMapping.h" + +@implementation OIDIDToken + +- (instancetype)initWithIDTokenString:(NSString *)idToken { + self = [super init]; + NSArray *sections = [idToken componentsSeparatedByString:@"."]; + + // The header and claims sections are required. + if (sections.count <= 1) { + return nil; + } + + _header = [[self class] parseJWTSection:sections[0]]; + _claims = [[self class] parseJWTSection:sections[1]]; + if (!_header || !_claims) { + return nil; + } + + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:_claims + instance:self]; + + // Required fields. + if (!_issuer || !_audience || !_subject || !_expiresAt || !_issuedAt) { + return nil; + } + + return self; +} + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + + fieldMap[kIssKey] = + [[OIDFieldMapping alloc] initWithName:@"_issuer" + type:[NSURL class] + conversion:[OIDFieldMapping URLConversion]]; + fieldMap[kSubKey] = + [[OIDFieldMapping alloc] initWithName:@"_subject" type:[NSString class]]; + fieldMap[kAudKey] = + [[OIDFieldMapping alloc] initWithName:@"_audience" + type:[NSArray class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if ([value isKindOfClass:[NSArray class]]) { + return value; + } + if ([value isKindOfClass:[NSString class]]) { + return @[value]; + } + return nil; + }]; + fieldMap[kExpKey] = + [[OIDFieldMapping alloc] initWithName:@"_expiresAt" + type:[NSDate class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSince1970:valueAsNumber.longLongValue]; + }]; + fieldMap[kIatKey] = + [[OIDFieldMapping alloc] initWithName:@"_issuedAt" + type:[NSDate class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSince1970:valueAsNumber.longLongValue]; + }]; + fieldMap[kNonceKey] = + [[OIDFieldMapping alloc] initWithName:@"_nonce" type:[NSString class]]; + }); + return fieldMap; +} + ++ (NSDictionary *)parseJWTSection:(NSString *)sectionString { + NSData *decodedData = [[self class] base64urlNoPaddingDecode:sectionString]; + + // Parses JSON. + NSError *error; + id object = [NSJSONSerialization JSONObjectWithData:decodedData options:0 error:&error]; + if (error) { + NSLog(@"Error %@ parsing token payload %@", error, sectionString); + } + if ([object isKindOfClass:[NSDictionary class]]) { + return (NSDictionary *)object; + } + + return nil; +} + ++ (NSData *)base64urlNoPaddingDecode:(NSString *)base64urlNoPaddingString { + NSMutableString *body = [base64urlNoPaddingString mutableCopy]; + + // Converts base64url to base64. + NSRange range = NSMakeRange(0, base64urlNoPaddingString.length); + [body replaceOccurrencesOfString:@"-" withString:@"+" options:NSLiteralSearch range:range]; + [body replaceOccurrencesOfString:@"_" withString:@"/" options:NSLiteralSearch range:range]; + + // Converts base64 no padding to base64 with padding + while (body.length % 4 != 0) { + [body appendString:@"="]; + } + + // Decodes base64 string. + NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:body options:0]; + return decodedData; +} + +@end + + diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationRequest.h b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationRequest.h new file mode 100644 index 0000000..e509c60 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationRequest.h @@ -0,0 +1,141 @@ +/*! @file OIDRegistrationRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorizationResponse; +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a registration request. + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationRequest + */ +@interface OIDRegistrationRequest : NSObject + +/*! @brief The service's configuration. + @remarks This configuration specifies how to connect to a particular OAuth provider. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @brief The initial access token to access the Client Registration Endpoint + (if required by the OpenID Provider). + @remarks OAuth 2.0 Access Token optionally issued by an Authorization Server granting + access to its Client Registration Endpoint. This token (if required) is + provisioned out of band. + @see Section 3 of OpenID Connect Dynamic Client Registration 1.0 + https://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration + */ +@property(nonatomic, readonly) NSString *initialAccessToken; + +/*! @brief The application type to register, will always be 'native'. + @remarks application_type + @see https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata + */ +@property(nonatomic, readonly) NSString *applicationType; + +/*! @brief The client's redirect URI's. + @remarks redirect_uris + @see https://tools.ietf.org/html/rfc6749#section-3.1.2 + */ +@property(nonatomic, readonly) NSArray *redirectURIs; + +/*! @brief The response types to register for usage by this client. + @remarks response_types + @see http://openid.net/specs/openid-connect-core-1_0.html#Authentication + */ +@property(nonatomic, readonly, nullable) NSArray *responseTypes; + +/*! @brief The grant types to register for usage by this client. + @remarks grant_types + @see https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata + */ +@property(nonatomic, readonly, nullable) NSArray *grantTypes; + +/*! @brief The subject type to to request. + @remarks subject_type + @see http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes + */ +@property(nonatomic, readonly, nullable) NSString *subjectType; + +/*! @brief The client authentication method to use at the token endpoint. + @remarks token_endpoint_auth_method + @see http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication + */ +@property(nonatomic, readonly, nullable) NSString *tokenEndpointAuthenticationMethod; + +/*! @brief The client's additional token request parameters. + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithConfiguration + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Create a Client Registration Request to an OpenID Provider that supports open Dynamic + Registration. + @param configuration The service's configuration. + @param redirectURIs The redirect URIs to register for the client. + @param responseTypes The response types to register for the client. + @param grantTypes The grant types to register for the client. + @param subjectType The subject type to register for the client. + @param tokenEndpointAuthMethod The token endpoint authentication method to register for the + client. + @param additionalParameters The client's additional registration request parameters. + */ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + redirectURIs:(NSArray *)redirectURIs + responseTypes:(nullable NSArray *)responseTypes + grantTypes:(nullable NSArray *)grantTypes + subjectType:(nullable NSString *)subjectType + tokenEndpointAuthMethod:(nullable NSString *)tokenEndpointAuthMethod + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param redirectURIs The redirect URIs to register for the client. + @param responseTypes The response types to register for the client. + @param grantTypes The grant types to register for the client. + @param subjectType The subject type to register for the client. + @param tokenEndpointAuthMethod The token endpoint authentication method to register for the + client. + @param initialAccessToken The initial access token to access the Client Registration Endpoint + (if required by the OpenID Provider). + @param additionalParameters The client's additional registration request parameters. + @see https://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration + */ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + redirectURIs:(NSArray *)redirectURIs + responseTypes:(nullable NSArray *)responseTypes + grantTypes:(nullable NSArray *)grantTypes + subjectType:(nullable NSString *)subjectType + tokenEndpointAuthMethod:(nullable NSString *)tokenEndpointAuthMethod + initialAccessToken:(nullable NSString *)initialAccessToken + additionalParameters:(nullable NSDictionary *)additionalParameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Constructs an @c NSURLRequest representing the registration request. + @return An @c NSURLRequest representing the registration request. + */ +- (NSURLRequest *)URLRequest; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationRequest.m b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationRequest.m new file mode 100644 index 0000000..9efd18f --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationRequest.m @@ -0,0 +1,248 @@ +/*! @file OIDRegistrationRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDRegistrationRequest.h" + +#import "OIDClientMetadataParameters.h" +#import "OIDDefines.h" +#import "OIDServiceConfiguration.h" + +/*! @brief The key for the @c configuration property for @c NSSecureCoding + */ +static NSString *const kConfigurationKey = @"configuration"; + +/*! @brief The key for the @c initialAccessToken property for @c NSSecureCoding + */ +static NSString *const kInitialAccessToken = @"initial_access_token"; + +/*! @brief Key used to encode the @c redirectURIs property for @c NSSecureCoding + */ +static NSString *const kRedirectURIsKey = @"redirect_uris"; + +/*! @brief The key for the @c responseTypes property for @c NSSecureCoding. + */ +static NSString *const kResponseTypesKey = @"response_types"; + +/*! @brief Key used to encode the @c grantType property for @c NSSecureCoding + */ +static NSString *const kGrantTypesKey = @"grant_types"; + +/*! @brief Key used to encode the @c subjectType property for @c NSSecureCoding + */ +static NSString *const kSubjectTypeKey = @"subject_type"; + +/*! @brief Key used to encode the @c additionalParameters property for + @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +@implementation OIDRegistrationRequest + +#pragma mark - Initializers + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER( + @selector(initWithConfiguration: + redirectURIs: + responseTypes: + grantTypes: + subjectType: + tokenEndpointAuthMethod: + additionalParameters:) + ) + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + redirectURIs:(NSArray *)redirectURIs + responseTypes:(nullable NSArray *)responseTypes + grantTypes:(nullable NSArray *)grantTypes + subjectType:(nullable NSString *)subjectType + tokenEndpointAuthMethod:(nullable NSString *)tokenEndpointAuthenticationMethod + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + redirectURIs:redirectURIs + responseTypes:responseTypes + grantTypes:grantTypes + subjectType:subjectType + tokenEndpointAuthMethod:tokenEndpointAuthenticationMethod + initialAccessToken:nil + additionalParameters:additionalParameters]; +} + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + redirectURIs:(NSArray *)redirectURIs + responseTypes:(nullable NSArray *)responseTypes + grantTypes:(nullable NSArray *)grantTypes + subjectType:(nullable NSString *)subjectType + tokenEndpointAuthMethod:(nullable NSString *)tokenEndpointAuthenticationMethod + initialAccessToken:(nullable NSString *)initialAccessToken + additionalParameters:(nullable NSDictionary *)additionalParameters { + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _initialAccessToken = [initialAccessToken copy]; + _redirectURIs = [redirectURIs copy]; + _responseTypes = [responseTypes copy]; + _grantTypes = [grantTypes copy]; + _subjectType = [subjectType copy]; + _tokenEndpointAuthenticationMethod = [tokenEndpointAuthenticationMethod copy]; + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + + _applicationType = OIDApplicationTypeNative; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDServiceConfiguration *configuration = + [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] + forKey:kConfigurationKey]; + NSString *initialAccessToken = [aDecoder decodeObjectOfClass:[NSString class] + forKey:kInitialAccessToken]; + NSArray *redirectURIs = [aDecoder decodeObjectOfClass:[NSArray class] + forKey:kRedirectURIsKey]; + NSArray *responseTypes = [aDecoder decodeObjectOfClass:[NSArray class] + forKey:kResponseTypesKey]; + NSArray *grantTypes = [aDecoder decodeObjectOfClass:[NSArray class] + forKey:kGrantTypesKey]; + NSString *subjectType = [aDecoder decodeObjectOfClass:[NSString class] + forKey:kSubjectTypeKey]; + NSString *tokenEndpointAuthenticationMethod = + [aDecoder decodeObjectOfClass:[NSString class] + forKey:OIDTokenEndpointAuthenticationMethodParam]; + NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[ [NSDictionary class], + [NSString class] ]]; + NSDictionary *additionalParameters = + [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses + forKey:kAdditionalParametersKey]; + self = [self initWithConfiguration:configuration + redirectURIs:redirectURIs + responseTypes:responseTypes + grantTypes:grantTypes + subjectType:subjectType + tokenEndpointAuthMethod:tokenEndpointAuthenticationMethod + initialAccessToken:initialAccessToken + additionalParameters:additionalParameters]; + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_configuration forKey:kConfigurationKey]; + [aCoder encodeObject:_initialAccessToken forKey:kInitialAccessToken]; + [aCoder encodeObject:_redirectURIs forKey:kRedirectURIsKey]; + [aCoder encodeObject:_responseTypes forKey:kResponseTypesKey]; + [aCoder encodeObject:_grantTypes forKey:kGrantTypesKey]; + [aCoder encodeObject:_subjectType forKey:kSubjectTypeKey]; + [aCoder encodeObject:_tokenEndpointAuthenticationMethod + forKey:OIDTokenEndpointAuthenticationMethodParam]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + NSURLRequest *request = [self URLRequest]; + NSString *requestBody = [[NSString alloc] initWithData:request.HTTPBody + encoding:NSUTF8StringEncoding]; + return [NSString stringWithFormat:@"<%@: %p, request: >", + NSStringFromClass([self class]), + (void *)self, + request.URL, + requestBody]; +} + +- (NSURLRequest *)URLRequest { + static NSString *const kHTTPPost = @"POST"; + static NSString *const kBearer = @"Bearer"; + static NSString *const kHTTPContentTypeHeaderKey = @"Content-Type"; + static NSString *const kHTTPContentTypeHeaderValue = @"application/json"; + static NSString *const kHTTPAuthorizationHeaderKey = @"Authorization"; + + NSData *postBody = [self JSONString]; + if (!postBody) { + return nil; + } + + NSURL *registrationRequestURL = _configuration.registrationEndpoint; + NSMutableURLRequest *URLRequest = + [[NSURLRequest requestWithURL:registrationRequestURL] mutableCopy]; + URLRequest.HTTPMethod = kHTTPPost; + [URLRequest setValue:kHTTPContentTypeHeaderValue forHTTPHeaderField:kHTTPContentTypeHeaderKey]; + if (_initialAccessToken) { + NSString *value = [NSString stringWithFormat:@"%@ %@", kBearer, _initialAccessToken]; + [URLRequest setValue:value forHTTPHeaderField:kHTTPAuthorizationHeaderKey]; + } + URLRequest.HTTPBody = postBody; + return URLRequest; +} + +- (NSData *)JSONString { + // Dictionary with several kay/value pairs and the above array of arrays + NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; + NSMutableArray *redirectURIStrings = + [NSMutableArray arrayWithCapacity:[_redirectURIs count]]; + for (id obj in _redirectURIs) { + [redirectURIStrings addObject:[obj absoluteString]]; + } + dict[OIDRedirectURIsParam] = redirectURIStrings; + dict[OIDApplicationTypeParam] = _applicationType; + + if (_additionalParameters) { + // Add any additional parameters first to allow them + // to be overwritten by instance values + [dict addEntriesFromDictionary:_additionalParameters]; + } + if (_responseTypes) { + dict[OIDResponseTypesParam] = _responseTypes; + } + if (_grantTypes) { + dict[OIDGrantTypesParam] = _grantTypes; + } + if (_subjectType) { + dict[OIDSubjectTypeParam] = _subjectType; + } + if (_tokenEndpointAuthenticationMethod) { + dict[OIDTokenEndpointAuthenticationMethodParam] = _tokenEndpointAuthenticationMethod; + } + + NSError *error; + NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:kNilOptions error:&error]; + if (json == nil || error != nil) { + return nil; + } + + return json; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationResponse.h b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationResponse.h new file mode 100644 index 0000000..df62390 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationResponse.h @@ -0,0 +1,126 @@ +/*! @file OIDRegistrationResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + + +#import + +@class OIDRegistrationRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Parameter name for the client id. + */ +extern NSString *const OIDClientIDParam; + +/*! @brief Parameter name for the client id issuance timestamp. + */ +extern NSString *const OIDClientIDIssuedAtParam; + +/*! @brief Parameter name for the client secret. + */ +extern NSString *const OIDClientSecretParam; + +/*! @brief Parameter name for the client secret expiration time. + */ +extern NSString *const OIDClientSecretExpirestAtParam; + +/*! @brief Parameter name for the registration access token. + */ +extern NSString *const OIDRegistrationAccessTokenParam; + +/*! @brief Parameter name for the client configuration URI. + */ +extern NSString *const OIDRegistrationClientURIParam; + +/*! @brief Represents a registration response. + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse + */ +@interface OIDRegistrationResponse : NSObject + +/*! @brief The request which was serviced. + */ +@property(nonatomic, readonly) OIDRegistrationRequest *request; + +/*! @brief The registered client identifier. + @remarks client_id + @see https://tools.ietf.org/html/rfc6749#section-4 + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + */ +@property(nonatomic, readonly) NSString *clientID; + +/*! @brief Timestamp of when the client identifier was issued, if provided. + @remarks client_id_issued_at + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse + */ +@property(nonatomic, readonly, nullable) NSDate *clientIDIssuedAt; + +/*! @brief TThe client secret, which is part of the client credentials, if provided. + @remarks client_secret + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse + */ +@property(nonatomic, readonly, nullable) NSString *clientSecret; + +/*! @brief Timestamp of when the client credentials expires, if provided. + @remarks client_secret_expires_at + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse + */ +@property(nonatomic, readonly, nullable) NSDate *clientSecretExpiresAt; + +/*! @brief Client registration access token that can be used for subsequent operations upon the + client registration. + @remarks registration_access_token + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse + */ +@property(nonatomic, readonly, nullable) NSString *registrationAccessToken; + +/*! @brief Location of the client configuration endpoint, if provided. + @remarks registration_client_uri + @see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse + */ +@property(nonatomic, readonly, nullable) NSURL *registrationClientURI; + +/*! @brief Client authentication method to use at the token endpoint, if provided. + @remarks token_endpoint_auth_method + @see http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication + */ +@property(nonatomic, readonly, nullable) NSString *tokenEndpointAuthenticationMethod; + +/*! @brief Additional parameters returned from the token server. + */ +@property(nonatomic, readonly, nullable) NSDictionary *> + *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithRequest + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the Authorization Server. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (instancetype)initWithRequest:(OIDRegistrationRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationResponse.m b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationResponse.m new file mode 100644 index 0000000..ec0411b --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDRegistrationResponse.m @@ -0,0 +1,164 @@ +/*! @file OIDRegistrationResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDRegistrationResponse.h" + +#import "OIDClientMetadataParameters.h" +#import "OIDDefines.h" +#import "OIDFieldMapping.h" +#import "OIDRegistrationRequest.h" +#import "OIDTokenUtilities.h" + +NSString *const OIDClientIDParam = @"client_id"; +NSString *const OIDClientIDIssuedAtParam = @"client_id_issued_at"; +NSString *const OIDClientSecretParam = @"client_secret"; +NSString *const OIDClientSecretExpirestAtParam = @"client_secret_expires_at"; +NSString *const OIDRegistrationAccessTokenParam = @"registration_access_token"; +NSString *const OIDRegistrationClientURIParam = @"registration_client_uri"; + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +@implementation OIDRegistrationResponse + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[OIDClientIDParam] = [[OIDFieldMapping alloc] initWithName:@"_clientID" + type:[NSString class]]; + fieldMap[OIDClientIDIssuedAtParam] = + [[OIDFieldMapping alloc] initWithName:@"_clientIDIssuedAt" + type:[NSDate class] + conversion:[OIDFieldMapping dateEpochConversion]]; + fieldMap[OIDClientSecretParam] = + [[OIDFieldMapping alloc] initWithName:@"_clientSecret" + type:[NSString class]]; + fieldMap[OIDClientSecretExpirestAtParam] = + [[OIDFieldMapping alloc] initWithName:@"_clientSecretExpiresAt" + type:[NSDate class] + conversion:[OIDFieldMapping dateEpochConversion]]; + fieldMap[OIDRegistrationAccessTokenParam] = + [[OIDFieldMapping alloc] initWithName:@"_registrationAccessToken" + type:[NSString class]]; + fieldMap[OIDRegistrationClientURIParam] = + [[OIDFieldMapping alloc] initWithName:@"_registrationClientURI" + type:[NSURL class] + conversion:[OIDFieldMapping URLConversion]]; + fieldMap[OIDTokenEndpointAuthenticationMethodParam] = + [[OIDFieldMapping alloc] initWithName:@"_tokenEndpointAuthenticationMethod" + type:[NSString class]]; + }); + return fieldMap; +} + + +#pragma mark - Initializers + +- (nonnull instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:)) + +- (instancetype)initWithRequest:(OIDRegistrationRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super init]; + if (self) { + _request = [request copy]; + NSDictionary *> *additionalParameters = + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:parameters + instance:self]; + _additionalParameters = additionalParameters; + + if ((_clientSecret && !_clientSecretExpiresAt) + || (!!_registrationClientURI != !!_registrationAccessToken)) { + // If client_secret is issued, client_secret_expires_at is REQUIRED, + // and the response MUST contain "[...] both a Client Configuration Endpoint + // and a Registration Access Token or neither of them" + return nil; + } + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDRegistrationRequest *request = [aDecoder decodeObjectOfClass:[OIDRegistrationRequest class] + forKey:kRequestKey]; + self = [self initWithRequest:request + parameters:@{}]; + if (self) { + [OIDFieldMapping decodeWithCoder:aDecoder + map:[[self class] fieldMap] + instance:self]; + _additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes] + forKey:kAdditionalParametersKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self]; + [aCoder encodeObject:_request forKey:kRequestKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, clientID: \"%@\", clientIDIssuedAt: %@, " + "clientSecret: %@, clientSecretExpiresAt: \"%@\", " + "registrationAccessToken: \"%@\", " + "registrationClientURI: \"%@\", " + "additionalParameters: %@, request: %@>", + NSStringFromClass([self class]), + (void *)self, + _clientID, + _clientIDIssuedAt, + [OIDTokenUtilities redact:_clientSecret], + _clientSecretExpiresAt, + [OIDTokenUtilities redact:_registrationAccessToken], + _registrationClientURI, + _additionalParameters, + _request]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDResponseTypes.h b/Pods/AppAuth/Sources/AppAuthCore/OIDResponseTypes.h new file mode 100644 index 0000000..405ef93 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDResponseTypes.h @@ -0,0 +1,31 @@ +/*! @file OIDResponseTypes.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +/*! @brief A constant for the standard OAuth2 Response Type of 'code'. + */ +extern NSString *const OIDResponseTypeCode; + +/*! @brief A constant for the standard OAuth2 Response Type of 'token'. + */ +extern NSString *const OIDResponseTypeToken; + +/*! @brief A constant for the standard OAuth2 Response Type of 'id_token'. + */ +extern NSString *const OIDResponseTypeIDToken; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDResponseTypes.m b/Pods/AppAuth/Sources/AppAuthCore/OIDResponseTypes.m new file mode 100644 index 0000000..78eaf18 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDResponseTypes.m @@ -0,0 +1,25 @@ +/*! @file OIDResponseTypes.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDResponseTypes.h" + +NSString *const OIDResponseTypeCode = @"code"; + +NSString *const OIDResponseTypeToken = @"token"; + +NSString *const OIDResponseTypeIDToken = @"id_token"; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDScopeUtilities.h b/Pods/AppAuth/Sources/AppAuthCore/OIDScopeUtilities.h new file mode 100644 index 0000000..c0a5190 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDScopeUtilities.h @@ -0,0 +1,48 @@ +/*! @file OIDScopeUtilities.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides convenience methods for dealing with scope strings. + */ +@interface OIDScopeUtilities : NSObject + +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Converts an array of scope strings to a single scope string per the OAuth 2 spec. + @param scopes An array of scope strings. + @return A space-delimited string of scopes. + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ ++ (NSString *)scopesWithArray:(NSArray *)scopes; + +/*! @brief Converts an OAuth 2 spec-compliant scope string to an array of scopes. + @param scopes An OAuth 2 spec-compliant scope string. + @return An array of scope strings. + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ ++ (NSArray *)scopesArrayWithString:(NSString *)scopes; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDScopeUtilities.m b/Pods/AppAuth/Sources/AppAuthCore/OIDScopeUtilities.m new file mode 100644 index 0000000..a0bcb8c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDScopeUtilities.m @@ -0,0 +1,58 @@ +/*! @file OIDScopeUtilities.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDScopeUtilities.h" + +@implementation OIDScopeUtilities + +/*! @brief A character set with the characters NOT allowed in a scope name. + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ ++ (NSCharacterSet *)disallowedScopeCharacters { + static NSCharacterSet *disallowedCharacters; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSMutableCharacterSet *allowedCharacters; + allowedCharacters = + [NSMutableCharacterSet characterSetWithRange:NSMakeRange(0x23, 0x5B - 0x23 + 1)]; + [allowedCharacters addCharactersInRange:NSMakeRange(0x5D, 0x7E - 0x5D + 1)]; + [allowedCharacters addCharactersInString:@"\x21"]; + disallowedCharacters = [allowedCharacters invertedSet]; + }); + return disallowedCharacters; +} + ++ (NSString *)scopesWithArray:(NSArray *)scopes { +#if !defined(NS_BLOCK_ASSERTIONS) + NSCharacterSet *disallowedCharacters = [self disallowedScopeCharacters]; + for (NSString *scope in scopes) { + NSAssert(scope.length, @"Found illegal empty scope string."); + NSAssert([scope rangeOfCharacterFromSet:disallowedCharacters].location == NSNotFound, + @"Found illegal character in scope string."); + } +#endif // !defined(NS_BLOCK_ASSERTIONS) + + NSString *scopeString = [scopes componentsJoinedByString:@" "]; + return scopeString; +} + ++ (NSArray *)scopesArrayWithString:(NSString *)scopes { + return [scopes componentsSeparatedByString:@" "]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDScopes.h b/Pods/AppAuth/Sources/AppAuthCore/OIDScopes.h new file mode 100644 index 0000000..da8bb18 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDScopes.h @@ -0,0 +1,46 @@ +/*! @file OIDScopes.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +/*! @brief Scope that indicates this request is an OpenID Connect request. + @see http://openid.net/specs/openid-connect-core-1_0.html#AuthRequestValidation + */ +extern NSString *const OIDScopeOpenID; + +/*! @brief This scope value requests access to the End-User's default profile Claims, which are: + name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, + website, gender, birthdate, zoneinfo, locale, and updated_at. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopeProfile; + +/*! @brief This scope value requests access to the email and email_verified Claims. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopeEmail; + +/*! @brief This scope value requests access to the address Claim. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopeAddress; + +/*! @brief This scope value requests access to the phone_number and phone_number_verified Claims. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopePhone; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDScopes.m b/Pods/AppAuth/Sources/AppAuthCore/OIDScopes.m new file mode 100644 index 0000000..62dd707 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDScopes.m @@ -0,0 +1,29 @@ +/*! @file OIDScopes.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDScopes.h" + +NSString *const OIDScopeOpenID = @"openid"; + +NSString *const OIDScopeProfile = @"profile"; + +NSString *const OIDScopeEmail = @"email"; + +NSString *const OIDScopeAddress = @"address"; + +NSString *const OIDScopePhone = @"phone"; diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDServiceConfiguration.h b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceConfiguration.h new file mode 100644 index 0000000..a072a47 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceConfiguration.h @@ -0,0 +1,118 @@ +/*! @file OIDServiceConfiguration.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDServiceConfiguration; +@class OIDServiceDiscovery; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The type of block called when a @c OIDServiceConfiguration has been created + by loading a @c OIDServiceDiscovery from an @c NSURL. + */ +typedef void (^OIDServiceConfigurationCreated) + (OIDServiceConfiguration *_Nullable serviceConfiguration, + NSError *_Nullable error); + +/*! @brief Represents the information needed to construct a @c OIDAuthorizationService. + */ +@interface OIDServiceConfiguration : NSObject + +/*! @brief The authorization endpoint URI. + */ +@property(nonatomic, readonly) NSURL *authorizationEndpoint; + +/*! @brief The token exchange and refresh endpoint URI. + */ +@property(nonatomic, readonly) NSURL *tokenEndpoint; + +/*! @brief The OpenID Connect issuer. + */ +@property(nonatomic, readonly, nullable) NSURL *issuer; + +/*! @brief The dynamic client registration endpoint URI. + */ +@property(nonatomic, readonly, nullable) NSURL *registrationEndpoint; + +/*! @brief The end session logout endpoint URI. + */ +@property(nonatomic, readonly, nullable) NSURL *endSessionEndpoint; + +/*! @brief The discovery document. + */ +@property(nonatomic, readonly, nullable) OIDServiceDiscovery *discoveryDocument; + +/*! @internal + @brief Unavailable. Please use @c initWithAuthorizationEndpoint:tokenEndpoint: or + @c initWithDiscoveryDocument:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @param authorizationEndpoint The authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint; + +/*! @param authorizationEndpoint The authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + @param registrationEndpoint The dynamic client registration endpoint URI. + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + registrationEndpoint:(nullable NSURL *)registrationEndpoint; + +/*! @param authorizationEndpoint The authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + @param issuer The OpenID Connect issuer. + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer; + +/*! @param authorizationEndpoint The authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + @param issuer The OpenID Connect issuer. + @param registrationEndpoint The dynamic client registration endpoint URI. + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer + registrationEndpoint:(nullable NSURL *)registrationEndpoint; + +/*! @param authorizationEndpoint The authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + @param issuer The OpenID Connect issuer. + @param registrationEndpoint The dynamic client registration endpoint URI. + @param endSessionEndpoint The end session endpoint (logout) URI. + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer + registrationEndpoint:(nullable NSURL *)registrationEndpoint + endSessionEndpoint:(nullable NSURL *)endSessionEndpoint; + +/*! @param discoveryDocument The discovery document from which to extract the required OAuth + configuration. + */ +- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *)discoveryDocument; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDServiceConfiguration.m b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceConfiguration.m new file mode 100644 index 0000000..0e5c119 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceConfiguration.m @@ -0,0 +1,232 @@ +/*! @file OIDServiceConfiguration.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDServiceConfiguration.h" + +#import "OIDDefines.h" +#import "OIDErrorUtilities.h" +#import "OIDServiceDiscovery.h" + +/*! @brief The key for the @c authorizationEndpoint property. + */ +static NSString *const kAuthorizationEndpointKey = @"authorizationEndpoint"; + +/*! @brief The key for the @c tokenEndpoint property. + */ +static NSString *const kTokenEndpointKey = @"tokenEndpoint"; + +/*! @brief The key for the @c issuer property. + */ +static NSString *const kIssuerKey = @"issuer"; + +/*! @brief The key for the @c registrationEndpoint property. + */ +static NSString *const kRegistrationEndpointKey = @"registrationEndpoint"; + +/*! @brief The key for the @c endSessionEndpoint property. + */ +static NSString *const kEndSessionEndpointKey = @"endSessionEndpoint"; + +/*! @brief The key for the @c discoveryDocument property. + */ +static NSString *const kDiscoveryDocumentKey = @"discoveryDocument"; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDServiceConfiguration () + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer + registrationEndpoint:(nullable NSURL *)registrationEndpoint + endSessionEndpoint:(nullable NSURL *)endSessionEndpoint + discoveryDocument:(nullable OIDServiceDiscovery *)discoveryDocument + NS_DESIGNATED_INITIALIZER; + +@end + +@implementation OIDServiceConfiguration + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector( + initWithAuthorizationEndpoint: + tokenEndpoint:) + ) + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer + registrationEndpoint:(nullable NSURL *)registrationEndpoint + endSessionEndpoint:(nullable NSURL *)endSessionEndpoint + discoveryDocument:(nullable OIDServiceDiscovery *)discoveryDocument { + + self = [super init]; + if (self) { + _authorizationEndpoint = [authorizationEndpoint copy]; + _tokenEndpoint = [tokenEndpoint copy]; + _issuer = [issuer copy]; + _registrationEndpoint = [registrationEndpoint copy]; + _endSessionEndpoint = [endSessionEndpoint copy]; + _discoveryDocument = [discoveryDocument copy]; + } + return self; +} + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint { + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + issuer:nil + registrationEndpoint:nil + endSessionEndpoint:nil + discoveryDocument:nil]; +} + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + registrationEndpoint:(nullable NSURL *)registrationEndpoint { + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + issuer:nil + registrationEndpoint:registrationEndpoint + endSessionEndpoint:nil + discoveryDocument:nil]; +} + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer { + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + issuer:issuer + registrationEndpoint:nil + endSessionEndpoint:nil + discoveryDocument:nil]; +} + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer + registrationEndpoint:(nullable NSURL *)registrationEndpoint { + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + issuer:issuer + registrationEndpoint:registrationEndpoint + endSessionEndpoint:nil + discoveryDocument:nil]; +} + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + issuer:(nullable NSURL *)issuer + registrationEndpoint:(nullable NSURL *)registrationEndpoint + endSessionEndpoint:(nullable NSURL *)endSessionEndpoint { + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + issuer:issuer + registrationEndpoint:registrationEndpoint + endSessionEndpoint:endSessionEndpoint + discoveryDocument:nil]; +} + +- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *) discoveryDocument { + return [self initWithAuthorizationEndpoint:discoveryDocument.authorizationEndpoint + tokenEndpoint:discoveryDocument.tokenEndpoint + issuer:discoveryDocument.issuer + registrationEndpoint:discoveryDocument.registrationEndpoint + endSessionEndpoint:discoveryDocument.endSessionEndpoint + discoveryDocument:discoveryDocument]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSURL *authorizationEndpoint = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kAuthorizationEndpointKey]; + NSURL *tokenEndpoint = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kTokenEndpointKey]; + NSURL *issuer = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kIssuerKey]; + NSURL *registrationEndpoint = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kRegistrationEndpointKey]; + NSURL *endSessionEndpoint = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kEndSessionEndpointKey]; + // We don't accept nil authorizationEndpoints or tokenEndpoints. + if (!authorizationEndpoint || !tokenEndpoint) { + return nil; + } + + NSSet *allowedClasses = [NSSet setWithArray:@[[OIDServiceDiscovery class], + // The following classes are required in + // order to support secure decoding of the + // old OIDServiceDiscovery encoding. + [NSDictionary class], + [NSArray class], + [NSString class], + [NSNumber class], + [NSNull class]]]; + OIDServiceDiscovery *discoveryDocument = [aDecoder decodeObjectOfClasses:allowedClasses + forKey:kDiscoveryDocumentKey]; + + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + issuer:issuer + registrationEndpoint:registrationEndpoint + endSessionEndpoint:endSessionEndpoint + discoveryDocument:discoveryDocument]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_authorizationEndpoint forKey:kAuthorizationEndpointKey]; + [aCoder encodeObject:_tokenEndpoint forKey:kTokenEndpointKey]; + [aCoder encodeObject:_issuer forKey:kIssuerKey]; + [aCoder encodeObject:_registrationEndpoint forKey:kRegistrationEndpointKey]; + [aCoder encodeObject:_discoveryDocument forKey:kDiscoveryDocumentKey]; + [aCoder encodeObject:_endSessionEndpoint forKey:kEndSessionEndpointKey]; +} + +#pragma mark - description + +- (NSString *)description { + return [NSString stringWithFormat: + @"OIDServiceConfiguration authorizationEndpoint: %@, tokenEndpoint: %@, " + "registrationEndpoint: %@, endSessionEndpoint: %@, discoveryDocument: [%@]", + _authorizationEndpoint, + _tokenEndpoint, + _registrationEndpoint, + _endSessionEndpoint, + _discoveryDocument]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDServiceDiscovery.h b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceDiscovery.h new file mode 100644 index 0000000..1a4929c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceDiscovery.h @@ -0,0 +1,364 @@ +/*! @file OIDServiceDiscovery.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents an OpenID Connect 1.0 Discovery Document + @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +@interface OIDServiceDiscovery : NSObject + +/*! @brief The decoded OpenID Connect 1.0 Discovery Document as a dictionary. + */ +@property(nonatomic, readonly) NSDictionary *discoveryDictionary; + +/*! @brief REQUIRED. URL using the @c https scheme with no query or fragment component that the OP + asserts as its Issuer Identifier. If Issuer discovery is supported, this value MUST be + identical to the issuer value returned by WebFinger. This also MUST be identical to the + @c iss Claim value in ID Tokens issued from this Issuer. + @remarks issuer + @seealso https://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery + */ +@property(nonatomic, readonly) NSURL *issuer; + +/*! @brief REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint. + @remarks authorization_endpoint + @seealso http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint + */ +@property(nonatomic, readonly) NSURL *authorizationEndpoint; + +/*! @brief OPTIONAL. URL of the OP's OAuth 2.0 Device Authorization Endpoint. + @remarks device_authorization_endpoint + @seealso https://tools.ietf.org/html/rfc8628#section-4 + */ +@property(nonatomic, readonly, nullable) NSURL *deviceAuthorizationEndpoint; + +/*! @brief URL of the OP's OAuth 2.0 Token Endpoint. This is REQUIRED unless only the Implicit Flow + is used. + @remarks token_endpoint + @seealso http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint + */ +@property(nonatomic, readonly) NSURL *tokenEndpoint; + +/*! @brief RECOMMENDED. URL of the OP's UserInfo Endpoint. This URL MUST use the https scheme and + MAY contain port, path, and query parameter components. + @remarks userinfo_endpoint + @seealso http://openid.net/specs/openid-connect-core-1_0.html#UserInfo + */ +@property(nonatomic, readonly, nullable) NSURL *userinfoEndpoint; + +/*! @brief REQUIRED. URL of the OP's JSON Web Key Set document. This contains the signing key(s) the + RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's + encryption key(s), which are used by RPs to encrypt requests to the Server. When both + signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED + for all keys in the referenced JWK Set to indicate each key's intended usage. Although some + algorithms allow the same key to be used for both signatures and encryption, doing so is NOT + RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 + representations of keys provided. When used, the bare key values MUST still be present and + MUST match those in the certificate. + @remarks jwks_uri + @seealso http://tools.ietf.org/html/rfc7517 + */ +@property(nonatomic, readonly) NSURL *jwksURL; + +/*! @brief RECOMMENDED. URL of the OP's Dynamic Client Registration Endpoint. + @remarks registration_endpoint + @seealso http://openid.net/specs/openid-connect-registration-1_0.html + */ +@property(nonatomic, readonly, nullable) NSURL *registrationEndpoint; + +/* @brief OPTIONAL. URL of the OP's RP-Initiated Logout endpoint. + @remarks end_session_endpoint + @seealso http://openid.net/specs/openid-connect-session-1_0.html#OPMetadata + */ +@property(nonatomic, readonly, nullable) NSURL *endSessionEndpoint; + +/*! @brief RECOMMENDED. JSON array containing a list of the OAuth 2.0 [RFC6749] scope values that + this server supports. The server MUST support the openid scope value. Servers MAY choose not + to advertise some supported scope values even when this parameter is used, although those + defined in [OpenID.Core] SHOULD be listed, if supported. + @remarks scopes_supported + @seealso http://tools.ietf.org/html/rfc6749#section-3.3 + */ +@property(nonatomic, readonly, nullable) NSArray *scopesSupported; + +/*! @brief REQUIRED. JSON array containing a list of the OAuth 2.0 @c response_type values that this + OP supports. Dynamic OpenID Providers MUST support the @c code, @c id_token, and the token + @c id_token Response Type values. + @remarks response_types_supported + */ +@property(nonatomic, readonly) NSArray *responseTypesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the OAuth 2.0 @c response_mode values that this + OP supports, as specified in OAuth 2.0 Multiple Response Type Encoding Practices. If + omitted, the default for Dynamic OpenID Providers is @c ["query", "fragment"]. + @remarks response_modes_supported + @seealso http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html + */ +@property(nonatomic, readonly, nullable) NSArray *responseModesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the OAuth 2.0 Grant Type values that this OP + supports. Dynamic OpenID Providers MUST support the @c authorization_code and @c implicit + Grant Type values and MAY support other Grant Types. If omitted, the default value is + @c ["authorization_code", "implicit"]. + @remarks grant_types_supported + */ +@property(nonatomic, readonly, nullable) NSArray *grantTypesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the Authentication Context Class References + that this OP supports. + @remarks acr_values_supported + */ +@property(nonatomic, readonly, nullable) NSArray *acrValuesSupported; + +/*! @brief REQUIRED. JSON array containing a list of the Subject Identifier types that this OP + supports. Valid types include @c pairwise and @c public. + @remarks subject_types_supported + */ +@property(nonatomic, readonly) NSArray *subjectTypesSupported; + +/*! @brief REQUIRED. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the OP for the ID Token to encode the Claims in a JWT. The algorithm @c RS256 + MUST be included. The value @c none MAY be supported, but MUST NOT be used unless the + Response Type used returns no ID Token from the Authorization Endpoint (such as when using + the Authorization Code Flow). + @remarks id_token_signing_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly) NSArray *IDTokenSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c alg values) + supported by the OP for the ID Token to encode the Claims in a JWT. + @remarks id_token_encryption_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *IDTokenEncryptionAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c enc values) + supported by the OP for the ID Token to encode the Claims in a JWT. + @remarks id_token_encryption_enc_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *IDTokenEncryptionEncodingValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the UserInfo Endpoint to encode the Claims in a JWT. The value none MAY be + included. + @remarks userinfo_signing_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7515 + @seealso https://tools.ietf.org/html/rfc7518 + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *userinfoSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (alg values) + supported by the UserInfo Endpoint to encode the Claims in a JWT. + @remarks userinfo_encryption_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7516 + @seealso https://tools.ietf.org/html/rfc7518 + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *userinfoEncryptionAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c enc values) + supported by the UserInfo Endpoint to encode the Claims in a JWT. + @remarks userinfo_encryption_enc_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *userinfoEncryptionEncodingValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the OP for Request Objects, which are described in Section 6.1 of OpenID + Connect Core 1.0. These algorithms are used both when the Request Object is passed by value + (using the request parameter) and when it is passed by reference (using the @c request_uri + parameter). Servers SHOULD support @c none and @c RS256. + @remarks request_object_signing_alg_values_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + */ +@property(nonatomic, readonly, nullable) + NSArray *requestObjectSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c alg values) + supported by the OP for Request Objects. These algorithms are used both when the Request + Object is passed by value and when it is passed by reference. + @remarks request_object_encryption_alg_values_supported + */ +@property(nonatomic, readonly, nullable) + NSArray *requestObjectEncryptionAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c enc values) + supported by the OP for Request Objects. These algorithms are used both when the Request + Object is passed by value and when it is passed by reference. + @remarks request_object_encryption_enc_values_supported + */ +@property(nonatomic, readonly, nullable) + NSArray *requestObjectEncryptionEncodingValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of Client Authentication methods supported by this + Token Endpoint. The options are @c client_secret_post, @c client_secret_basic, + @c client_secret_jwt, and @c private_key_jwt, as described in Section 9 of OpenID Connect + Core 1.0. Other authentication methods MAY be defined by extensions. If omitted, the default + is @c client_secret_basic -- the HTTP Basic Authentication Scheme specified in Section 2.3.1 + of OAuth 2.0. + @remarks token_endpoint_auth_methods_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + @seealso http://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +@property(nonatomic, readonly, nullable) NSArray *tokenEndpointAuthMethodsSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the Token Endpoint for the signature on the JWT used to authenticate the Client + at the Token Endpoint for the @c private_key_jwt and @c client_secret_jwt authentication + methods. Servers SHOULD support @c RS256. The value @c none MUST NOT be used. + @remarks token_endpoint_auth_signing_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *tokenEndpointAuthSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the @c display parameter values that the OpenID + Provider supports. These values are described in Section 3.1.2.1 of OpenID Connect Core 1.0. + @remarks display_values_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + */ +@property(nonatomic, readonly, nullable) NSArray *displayValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the Claim Types that the OpenID Provider + supports. These Claim Types are described in Section 5.6 of OpenID Connect Core 1.0. Values + defined by this specification are @c normal, @c aggregated, and @c distributed. If omitted, + the implementation supports only @c normal Claims. + @remarks claim_types_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + */ +@property(nonatomic, readonly, nullable) NSArray *claimTypesSupported; + +/*! @brief RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the + OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, + this might not be an exhaustive list. + @remarks claims_supported + */ +@property(nonatomic, readonly, nullable) NSArray *claimsSupported; + +/*! @brief OPTIONAL. URL of a page containing human-readable information that developers might want + or need to know when using the OpenID Provider. In particular, if the OpenID Provider does + not support Dynamic Client Registration, then information on how to register Clients needs + to be provided in this documentation. + @remarks service_documentation + */ +@property(nonatomic, readonly, nullable) NSURL *serviceDocumentation; + +/*! @brief OPTIONAL. Languages and scripts supported for values in Claims being returned, + represented as a JSON array of BCP47 language tag values. Not all languages and scripts are + necessarily supported for all Claim values. + @remarks claims_locales_supported + @seealso http://tools.ietf.org/html/rfc5646 + */ +@property(nonatomic, readonly, nullable) NSArray *claimsLocalesSupported; + +/*! @brief OPTIONAL. Languages and scripts supported for the user interface, represented as a JSON + array of BCP47 language tag values. + @remarks ui_locales_supported + @seealso http://tools.ietf.org/html/rfc5646 + */ +@property(nonatomic, readonly, nullable) NSArray *UILocalesSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP supports use of the claims parameter, + with @c true indicating support. If omitted, the default value is @c false. + @remarks claims_parameter_supported + */ +@property(nonatomic, readonly) BOOL claimsParameterSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP supports use of the request parameter, + with @c true indicating support. If omitted, the default value is @c false. + @remarks request_parameter_supported + */ +@property(nonatomic, readonly) BOOL requestParameterSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP supports use of the @c request_uri + parameter, with true indicating support. If omitted, the default value is @c true. + @remarks request_uri_parameter_supported + */ +@property(nonatomic, readonly) BOOL requestURIParameterSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP requires any @c request_uri values used + to be pre-registered using the @c request_uris registration parameter. Pre-registration is + REQUIRED when the value is @c true. If omitted, the default value is @c false. + @remarks require_request_uri_registration + */ +@property(nonatomic, readonly) BOOL requireRequestURIRegistration; + +/*! @brief OPTIONAL. URL that the OpenID Provider provides to the person registering the Client to + read about the OP's requirements on how the Relying Party can use the data provided by the + OP. The registration process SHOULD display this URL to the person registering the Client if + it is given. + @remarks op_policy_uri + */ +@property(nonatomic, readonly, nullable) NSURL *OPPolicyURI; + +/*! @brief OPTIONAL. URL that the OpenID Provider provides to the person registering the Client to + read about OpenID Provider's terms of service. The registration process SHOULD display this + URL to the person registering the Client if it is given. + @remarks op_tos_uri + */ +@property(nonatomic, readonly, nullable) NSURL *OPTosURI; + +/*! @internal + @brief Unavailable. Please use @c initWithDictionary:error:, @c initWithJSON:error, or the + @c discoverServiceConfigurationForDiscoveryURL:callback: from @c OIDAuthorizationService. + */ +- (nonnull instancetype)init NS_UNAVAILABLE; + +/*! @brief Decodes a OpenID Connect Discovery 1.0 JSON document. + @param serviceDiscoveryJSON An OpenID Connect Service Discovery document. + @param error If a required field is missing from the dictionary, an error with domain + @c ::OIDGeneralErrorDomain and code @c ::OIDErrorCodeInvalidDiscoveryDocument will be + returned. + */ +- (nullable instancetype)initWithJSON:(NSString *)serviceDiscoveryJSON + error:(NSError **_Nullable)error; + +/*! @brief Decodes a OpenID Connect Discovery 1.0 JSON document. + @param serviceDiscoveryJSONData An OpenID Connect Service Discovery document. + @param error If a required field is missing from the dictionary, an error with domain + @c ::OIDGeneralErrorDomain and code @c ::OIDErrorCodeInvalidDiscoveryDocument will be + returned. + */ +- (nullable instancetype)initWithJSONData:(NSData *)serviceDiscoveryJSONData + error:(NSError **_Nullable)error; + +/*! @brief Designated initializer. The dictionary keys should match the keys defined in the OpenID + Connect Discovery 1.0 standard for OpenID Provider Metadata. + @param serviceDiscoveryDictionary A dictionary representing an OpenID Connect Service Discovery + document. + @param error If a required field is missing from the dictionary, an error with domain + @c ::OIDGeneralErrorDomain and code @c ::OIDErrorCodeInvalidDiscoveryDocument will be + returned. + */ +- (nullable instancetype)initWithDictionary:(NSDictionary *)serviceDiscoveryDictionary + error:(NSError **_Nullable)error NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDServiceDiscovery.m b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceDiscovery.m new file mode 100644 index 0000000..4d96f9d --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDServiceDiscovery.m @@ -0,0 +1,393 @@ +/*! @file OIDServiceDiscovery.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDServiceDiscovery.h" + +#import "OIDDefines.h" +#import "OIDErrorUtilities.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The key for the @c discoveryDictionary property. + */ +static NSString *const kDiscoveryDictionaryKey = @"discoveryDictionary"; + +/*! Field keys associated with an OpenID Connect Discovery Document. */ +static NSString *const kIssuerKey = @"issuer"; +static NSString *const kAuthorizationEndpointKey = @"authorization_endpoint"; +static NSString *const kDeviceAuthorizationEndpointKey = @"device_authorization_endpoint"; +static NSString *const kTokenEndpointKey = @"token_endpoint"; +static NSString *const kUserinfoEndpointKey = @"userinfo_endpoint"; +static NSString *const kJWKSURLKey = @"jwks_uri"; +static NSString *const kRegistrationEndpointKey = @"registration_endpoint"; +static NSString *const kEndSessionEndpointKey = @"end_session_endpoint"; +static NSString *const kScopesSupportedKey = @"scopes_supported"; +static NSString *const kResponseTypesSupportedKey = @"response_types_supported"; +static NSString *const kResponseModesSupportedKey = @"response_modes_supported"; +static NSString *const kGrantTypesSupportedKey = @"grant_types_supported"; +static NSString *const kACRValuesSupportedKey = @"acr_values_supported"; +static NSString *const kSubjectTypesSupportedKey = @"subject_types_supported"; +static NSString *const kIDTokenSigningAlgorithmValuesSupportedKey = + @"id_token_signing_alg_values_supported"; +static NSString *const kIDTokenEncryptionAlgorithmValuesSupportedKey = + @"id_token_encryption_alg_values_supported"; +static NSString *const kIDTokenEncryptionEncodingValuesSupportedKey = + @"id_token_encryption_enc_values_supported"; +static NSString *const kUserinfoSigningAlgorithmValuesSupportedKey = + @"userinfo_signing_alg_values_supported"; +static NSString *const kUserinfoEncryptionAlgorithmValuesSupportedKey = + @"userinfo_encryption_alg_values_supported"; +static NSString *const kUserinfoEncryptionEncodingValuesSupportedKey = + @"userinfo_encryption_enc_values_supported"; +static NSString *const kRequestObjectSigningAlgorithmValuesSupportedKey = + @"request_object_signing_alg_values_supported"; +static NSString *const kRequestObjectEncryptionAlgorithmValuesSupportedKey = + @"request_object_encryption_alg_values_supported"; +static NSString *const kRequestObjectEncryptionEncodingValuesSupported = + @"request_object_encryption_enc_values_supported"; +static NSString *const kTokenEndpointAuthMethodsSupportedKey = + @"token_endpoint_auth_methods_supported"; +static NSString *const kTokenEndpointAuthSigningAlgorithmValuesSupportedKey = + @"token_endpoint_auth_signing_alg_values_supported"; +static NSString *const kDisplayValuesSupportedKey = @"display_values_supported"; +static NSString *const kClaimTypesSupportedKey = @"claim_types_supported"; +static NSString *const kClaimsSupportedKey = @"claims_supported"; +static NSString *const kServiceDocumentationKey = @"service_documentation"; +static NSString *const kClaimsLocalesSupportedKey = @"claims_locales_supported"; +static NSString *const kUILocalesSupportedKey = @"ui_locales_supported"; +static NSString *const kClaimsParameterSupportedKey = @"claims_parameter_supported"; +static NSString *const kRequestParameterSupportedKey = @"request_parameter_supported"; +static NSString *const kRequestURIParameterSupportedKey = @"request_uri_parameter_supported"; +static NSString *const kRequireRequestURIRegistrationKey = @"require_request_uri_registration"; +static NSString *const kOPPolicyURIKey = @"op_policy_uri"; +static NSString *const kOPTosURIKey = @"op_tos_uri"; + +@implementation OIDServiceDiscovery { + NSDictionary *_discoveryDictionary; +} + +- (nonnull instancetype)init OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithDictionary:error:)) + +- (nullable instancetype)initWithJSON:(NSString *)serviceDiscoveryJSON error:(NSError **)error { + NSData *jsonData = [serviceDiscoveryJSON dataUsingEncoding:NSUTF8StringEncoding]; + return [self initWithJSONData:jsonData error:error]; +} + +- (nullable instancetype)initWithJSONData:(NSData *)serviceDiscoveryJSONData + error:(NSError **_Nullable)error { + NSError *jsonError; + NSDictionary *json = + [NSJSONSerialization JSONObjectWithData:serviceDiscoveryJSONData options:0 error:&jsonError]; + if (!json || jsonError) { + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONDeserializationError + underlyingError:jsonError + description:jsonError.localizedDescription]; + return nil; + } + if (![json isKindOfClass:[NSDictionary class]]) { + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeInvalidDiscoveryDocument + underlyingError:nil + description:@"Discovery document isn't a dictionary"]; + return nil; + } + + return [self initWithDictionary:json error:error]; +} + +- (nullable instancetype)initWithDictionary:(NSDictionary *)serviceDiscoveryDictionary + error:(NSError **_Nullable)error { + if (![[self class] dictionaryHasRequiredFields:serviceDiscoveryDictionary error:error]) { + return nil; + } + self = [super init]; + if (self) { + _discoveryDictionary = [serviceDiscoveryDictionary copy]; + } + return self; +} + +#pragma mark - + +/*! @brief Checks to see if the specified dictionary contains the required fields. + @discussion This test is not meant to provide semantic analysis of the document (eg. fields + where the value @c none is not an allowed option would not cause this method to fail if + their value was @c none.) We are just testing to make sure we can meet the nullability + contract we promised in the header. + */ ++ (BOOL)dictionaryHasRequiredFields:(NSDictionary *)dictionary + error:(NSError **_Nullable)error { + static NSString *const kMissingFieldErrorText = @"Missing field: %@"; + static NSString *const kInvalidURLFieldErrorText = @"Invalid URL: %@"; + + NSArray *requiredFields = @[ + kIssuerKey, + kAuthorizationEndpointKey, + kTokenEndpointKey, + kJWKSURLKey, + kResponseTypesSupportedKey, + kSubjectTypesSupportedKey, + kIDTokenSigningAlgorithmValuesSupportedKey + ]; + + for (NSString *field in requiredFields) { + if (!dictionary[field]) { + if (error) { + NSString *errorText = [NSString stringWithFormat:kMissingFieldErrorText, field]; + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeInvalidDiscoveryDocument + underlyingError:nil + description:errorText]; + } + return NO; + } + } + + // Check required URL fields are valid URLs. + NSArray *requiredURLFields = @[ + kIssuerKey, + kTokenEndpointKey, + kJWKSURLKey + ]; + + for (NSString *field in requiredURLFields) { + if (![NSURL URLWithString:dictionary[field]]) { + if (error) { + NSString *errorText = [NSString stringWithFormat:kInvalidURLFieldErrorText, field]; + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeInvalidDiscoveryDocument + underlyingError:nil + description:errorText]; + } + return NO; + } + } + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSError *error; + NSDictionary *dictionary; + if ([aDecoder containsValueForKey:kDiscoveryDictionaryKey]) { + // We're decoding a collection type (NSDictionary) from NSJSONSerialization's + // +JSONObjectWithData, so we need to include all classes that could potentially be contained + // within. + NSSet *allowedClasses = [NSSet setWithArray:@[[NSDictionary class], + [NSArray class], + [NSString class], + [NSNumber class], + [NSNull class]]]; + dictionary = [aDecoder decodeObjectOfClasses:allowedClasses + forKey:kDiscoveryDictionaryKey]; + } else { + // Decode using the old encoding which delegated to NSDictionary's encodeWithCoder: + // implementation: + // + // - (void)encodeWithCoder:(NSCoder *)aCoder { + // [_discoveryDictionary encodeWithCoder:aCoder]; + // } + dictionary = [[NSDictionary alloc] initWithCoder:aDecoder]; + } + self = [self initWithDictionary:dictionary error:&error]; + if (error) { + return nil; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_discoveryDictionary forKey:kDiscoveryDictionaryKey]; + // Provide forward compatibilty by continuing to add the old encoding. + [_discoveryDictionary encodeWithCoder:aCoder]; +} + +#pragma mark - Properties + +- (NSDictionary *)discoveryDictionary { + return _discoveryDictionary; +} + +- (NSURL *)issuer { + return [NSURL URLWithString:_discoveryDictionary[kIssuerKey]]; +} + +- (NSURL *)authorizationEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kAuthorizationEndpointKey]]; +} + +- (nullable NSURL *)deviceAuthorizationEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kDeviceAuthorizationEndpointKey]]; +} + +- (NSURL *)tokenEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kTokenEndpointKey]]; +} + +- (nullable NSURL *)userinfoEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kUserinfoEndpointKey]]; +} + +- (NSURL *)jwksURL { + return [NSURL URLWithString:_discoveryDictionary[kJWKSURLKey]]; +} + +- (nullable NSURL *)registrationEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kRegistrationEndpointKey]]; +} + +- (nullable NSURL *)endSessionEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kEndSessionEndpointKey]]; +} + +- (nullable NSArray *)scopesSupported { + return _discoveryDictionary[kScopesSupportedKey]; +} + +- (NSArray *)responseTypesSupported { + return _discoveryDictionary[kResponseTypesSupportedKey]; +} + +- (nullable NSArray *)responseModesSupported { + return _discoveryDictionary[kResponseModesSupportedKey]; +} + +- (nullable NSArray *)grantTypesSupported { + return _discoveryDictionary[kGrantTypesSupportedKey]; +} + +- (nullable NSArray *)acrValuesSupported { + return _discoveryDictionary[kACRValuesSupportedKey]; +} + +- (NSArray *)subjectTypesSupported { + return _discoveryDictionary[kSubjectTypesSupportedKey]; +} + +- (NSArray *) IDTokenSigningAlgorithmValuesSupported { + return _discoveryDictionary[kIDTokenSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)IDTokenEncryptionAlgorithmValuesSupported { + return _discoveryDictionary[kIDTokenEncryptionAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)IDTokenEncryptionEncodingValuesSupported { + return _discoveryDictionary[kIDTokenEncryptionEncodingValuesSupportedKey]; +} + +- (nullable NSArray *)userinfoSigningAlgorithmValuesSupported { + return _discoveryDictionary[kUserinfoSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)userinfoEncryptionAlgorithmValuesSupported { + return _discoveryDictionary[kUserinfoEncryptionAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)userinfoEncryptionEncodingValuesSupported { + return _discoveryDictionary[kUserinfoEncryptionEncodingValuesSupportedKey]; +} + +- (nullable NSArray *)requestObjectSigningAlgorithmValuesSupported { + return _discoveryDictionary[kRequestObjectSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *) requestObjectEncryptionAlgorithmValuesSupported { + return _discoveryDictionary[kRequestObjectEncryptionAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *) requestObjectEncryptionEncodingValuesSupported { + return _discoveryDictionary[kRequestObjectEncryptionEncodingValuesSupported]; +} + +- (nullable NSArray *)tokenEndpointAuthMethodsSupported { + return _discoveryDictionary[kTokenEndpointAuthMethodsSupportedKey]; +} + +- (nullable NSArray *)tokenEndpointAuthSigningAlgorithmValuesSupported { + return _discoveryDictionary[kTokenEndpointAuthSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)displayValuesSupported { + return _discoveryDictionary[kDisplayValuesSupportedKey]; +} + +- (nullable NSArray *)claimTypesSupported { + return _discoveryDictionary[kClaimTypesSupportedKey]; +} + +- (nullable NSArray *)claimsSupported { + return _discoveryDictionary[kClaimsSupportedKey]; +} + +- (nullable NSURL *)serviceDocumentation { + return [NSURL URLWithString:_discoveryDictionary[kServiceDocumentationKey]]; +} + +- (nullable NSArray *)claimsLocalesSupported { + return _discoveryDictionary[kClaimsLocalesSupportedKey]; +} + +- (nullable NSArray *)UILocalesSupported { + return _discoveryDictionary[kUILocalesSupportedKey]; +} + +- (BOOL)claimsParameterSupported { + return [_discoveryDictionary[kClaimsParameterSupportedKey] boolValue]; +} + +- (BOOL)requestParameterSupported { + return [_discoveryDictionary[kRequestParameterSupportedKey] boolValue]; +} + +- (BOOL)requestURIParameterSupported { + // Default is true/YES. + if (!_discoveryDictionary[kRequestURIParameterSupportedKey]) { + return YES; + } + return [_discoveryDictionary[kRequestURIParameterSupportedKey] boolValue]; +} + +- (BOOL)requireRequestURIRegistration { + return [_discoveryDictionary[kRequireRequestURIRegistrationKey] boolValue]; +} + +- (nullable NSURL *)OPPolicyURI { + return [NSURL URLWithString:_discoveryDictionary[kOPPolicyURIKey]]; +} + +- (nullable NSURL *)OPTosURI { + return [NSURL URLWithString:_discoveryDictionary[kOPTosURIKey]]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDTokenRequest.h b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenRequest.h new file mode 100644 index 0000000..53a0073 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenRequest.h @@ -0,0 +1,224 @@ +/*! @file OIDTokenRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +// This file only declares string constants useful for constructing a @c OIDTokenRequest, so it is +// imported here for convenience. +#import "OIDGrantTypes.h" + +@class OIDAuthorizationResponse; +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a token request. + @see https://tools.ietf.org/html/rfc6749#section-3.2 + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@interface OIDTokenRequest : NSObject + +/*! @brief The service's configuration. + @remarks This configuration specifies how to connect to a particular OAuth provider. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @brief The type of token being sent to the token endpoint, i.e. "authorization_code" for the + authorization code exchange, or "refresh_token" for an access token refresh request. + @remarks grant_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + @see https://www.google.com/url?sa=D&q=https%3A%2F%2Ftools.ietf.org%2Fhtml%2Frfc6749%23section-6 + */ +@property(nonatomic, readonly) NSString *grantType; + +/*! @brief The authorization code received from the authorization server. + @remarks code + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@property(nonatomic, readonly, nullable) NSString *authorizationCode; + +/*! @brief The client's redirect URI. + @remarks redirect_uri + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@property(nonatomic, readonly, nullable) NSURL *redirectURL; + +/*! @brief The client identifier. + @remarks client_id + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@property(nonatomic, readonly) NSString *clientID; + +/*! @brief The client secret. + @remarks client_secret + @see https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +@property(nonatomic, readonly, nullable) NSString *clientSecret; + +/*! @brief The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief The refresh token, which can be used to obtain new access tokens using the same + authorization grant. + @remarks refresh_token + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/*! @brief The PKCE code verifier used to redeem the authorization code. + @remarks code_verifier + @see https://tools.ietf.org/html/rfc7636#section-4.3 + */ +@property(nonatomic, readonly, nullable) NSString *codeVerifier; + +/*! @brief The client's additional token request parameters. + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalParameters; + +/*! @brief The client's additional token request headers. + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalHeaders; + +/*! @internal + @brief Unavailable. Please use + initWithConfiguration:grantType:code:redirectURL:clientID:additionalParameters:additionalHeaders:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @param configuration The service's configuration. + @param grantType the type of token being sent to the token endpoint, i.e. "authorization_code" + for the authorization code exchange, or "refresh_token" for an access token refresh request. + @see OIDGrantTypes.h + @param code The authorization code received from the authorization server. + @param redirectURL The client's redirect URI. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param refreshToken The refresh token. + @param codeVerifier The PKCE code verifier. + @param additionalParameters The client's additional token request parameters. + */ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @param configuration The service's configuration. + @param grantType the type of token being sent to the token endpoint, i.e. "authorization_code" + for the authorization code exchange, or "refresh_token" for an access token refresh request. + @see OIDGrantTypes.h + @param code The authorization code received from the authorization server. + @param redirectURL The client's redirect URI. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scope The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @param refreshToken The refresh token. + @param codeVerifier The PKCE code verifier. + @param additionalParameters The client's additional token request parameters. + */ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @param configuration The service's configuration. + @param grantType the type of token being sent to the token endpoint, i.e. "authorization_code" + for the authorization code exchange, or "refresh_token" for an access token refresh request. + @see OIDGrantTypes.h + @param code The authorization code received from the authorization server. + @param redirectURL The client's redirect URI. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param refreshToken The refresh token. + @param codeVerifier The PKCE code verifier. + @param additionalParameters The client's additional token request parameters. + @param additionalHeaders The client's additional token request headers. + */ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters + additionalHeaders:(nullable NSDictionary *)additionalHeaders; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param grantType the type of token being sent to the token endpoint, i.e. "authorization_code" + for the authorization code exchange, or "refresh_token" for an access token refresh request. + @see OIDGrantTypes.h + @param code The authorization code received from the authorization server. + @param redirectURL The client's redirect URI. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scope The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @param refreshToken The refresh token. + @param codeVerifier The PKCE code verifier. + @param additionalParameters The client's additional token request parameters. + @param additionalHeaders The client's additional token request headers. + */ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters + additionalHeaders:(nullable NSDictionary *)additionalHeaders + NS_DESIGNATED_INITIALIZER; + +/*! @brief Designated initializer for NSSecureCoding. + @param aDecoder Unarchiver object to decode + */ +- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; + +/*! @brief Constructs an @c NSURLRequest representing the token request. + @return An @c NSURLRequest representing the token request. + */ +- (NSURLRequest *)URLRequest; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDTokenRequest.m b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenRequest.m new file mode 100644 index 0000000..6d30b6d --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenRequest.m @@ -0,0 +1,385 @@ +/*! @file OIDTokenRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTokenRequest.h" + +#import "OIDDefines.h" +#import "OIDError.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDURLQueryComponent.h" +#import "OIDTokenUtilities.h" + +/*! @brief The key for the @c configuration property for @c NSSecureCoding + */ +static NSString *const kConfigurationKey = @"configuration"; + +/*! @brief Key used to encode the @c grantType property for @c NSSecureCoding + */ +static NSString *const kGrantTypeKey = @"grant_type"; + +/*! @brief The key for the @c authorizationCode property for @c NSSecureCoding. + */ +static NSString *const kAuthorizationCodeKey = @"code"; + +/*! @brief Key used to encode the @c clientID property for @c NSSecureCoding + */ +static NSString *const kClientIDKey = @"client_id"; + +/*! @brief Key used to encode the @c clientSecret property for @c NSSecureCoding + */ +static NSString *const kClientSecretKey = @"client_secret"; + +/*! @brief Key used to encode the @c redirectURL property for @c NSSecureCoding + */ +static NSString *const kRedirectURLKey = @"redirect_uri"; + +/*! @brief Key used to encode the @c scopes property for @c NSSecureCoding + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c refreshToken property for @c NSSecureCoding + */ +static NSString *const kRefreshTokenKey = @"refresh_token"; + +/*! @brief Key used to encode the @c codeVerifier property for @c NSSecureCoding and to build the + request URL. + */ +static NSString *const kCodeVerifierKey = @"code_verifier"; + +/*! @brief Key used to encode the @c additionalParameters property for + @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Key used to encode the @c additionalHeaders property for + @c NSSecureCoding + */ +static NSString *const kAdditionalHeadersKey = @"additionalHeaders"; + +@implementation OIDTokenRequest + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER( + @selector(initWithConfiguration: + grantType: + authorizationCode: + redirectURL: + clientID: + clientSecret: + scope: + refreshToken: + codeVerifier: + additionalParameters: + additionalHeaders:) + ) + +- (instancetype)initWithConfiguration:(nonnull OIDServiceConfiguration *)configuration + grantType:(nonnull NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(nonnull NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + grantType:grantType + authorizationCode:code + redirectURL:redirectURL + clientID:clientID + clientSecret:clientSecret + scopes:scopes + refreshToken:refreshToken + codeVerifier:codeVerifier + additionalParameters:additionalParameters + additionalHeaders:_additionalHeaders]; +} + +- (instancetype)initWithConfiguration:(nonnull OIDServiceConfiguration *)configuration + grantType:(nonnull NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(nonnull NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + grantType:grantType + authorizationCode:code + redirectURL:redirectURL + clientID:clientID + clientSecret:clientSecret + scope:scope + refreshToken:refreshToken + codeVerifier:codeVerifier + additionalParameters:additionalParameters + additionalHeaders:_additionalHeaders]; +} + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters + additionalHeaders:(nullable NSDictionary *)additionalHeaders { + return [self initWithConfiguration:configuration + grantType:grantType + authorizationCode:code + redirectURL:redirectURL + clientID:clientID + clientSecret:clientSecret + scope:[OIDScopeUtilities scopesWithArray:scopes] + refreshToken:refreshToken + codeVerifier:(NSString *)codeVerifier + additionalParameters:additionalParameters + additionalHeaders:additionalHeaders]; +} + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters + additionalHeaders:(nullable NSDictionary *)additionalHeaders { + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _grantType = [grantType copy]; + _authorizationCode = [code copy]; + _redirectURL = [redirectURL copy]; + _clientID = [clientID copy]; + _clientSecret = [clientSecret copy]; + _scope = [scope copy]; + _refreshToken = [refreshToken copy]; + _codeVerifier = [codeVerifier copy]; + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + _additionalHeaders = + [[NSDictionary alloc] initWithDictionary:additionalHeaders copyItems:YES]; + + // Additional validation for the authorization_code grant type + if ([_grantType isEqual:OIDGrantTypeAuthorizationCode]) { + // redirect URI must not be nil + if (!_redirectURL) { + [NSException raise:OIDOAuthExceptionInvalidTokenRequestNullRedirectURL + format:@"%@", OIDOAuthExceptionInvalidTokenRequestNullRedirectURL, nil]; + + } + } + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDServiceConfiguration *configuration = + [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] + forKey:kConfigurationKey]; + NSString *grantType = [aDecoder decodeObjectOfClass:[NSString class] forKey:kGrantTypeKey]; + NSString *code = [aDecoder decodeObjectOfClass:[NSString class] forKey:kAuthorizationCodeKey]; + NSString *clientID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientIDKey]; + NSString *clientSecret = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientSecretKey]; + NSString *scope = [aDecoder decodeObjectOfClass:[NSString class] forKey:kScopeKey]; + NSString *refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey]; + NSString *codeVerifier = [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeVerifierKey]; + NSURL *redirectURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kRedirectURLKey]; + NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class] + ]]; + + NSDictionary *additionalParameters = + [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses forKey:kAdditionalParametersKey]; + + + NSSet *additionalHeaderCodingClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class] + ]]; + + NSDictionary *additionalHeaders = + [aDecoder decodeObjectOfClasses:additionalHeaderCodingClasses forKey:kAdditionalHeadersKey]; + + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _grantType = [grantType copy]; + _authorizationCode = [code copy]; + _redirectURL = [redirectURL copy]; + _clientID = [clientID copy]; + _clientSecret = [clientSecret copy]; + _scope = [scope copy]; + _refreshToken = [refreshToken copy]; + _codeVerifier = [codeVerifier copy]; + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + _additionalHeaders = + [[NSDictionary alloc] initWithDictionary:additionalHeaders copyItems:YES]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_configuration forKey:kConfigurationKey]; + [aCoder encodeObject:_grantType forKey:kGrantTypeKey]; + [aCoder encodeObject:_authorizationCode forKey:kAuthorizationCodeKey]; + [aCoder encodeObject:_clientID forKey:kClientIDKey]; + [aCoder encodeObject:_clientSecret forKey:kClientSecretKey]; + [aCoder encodeObject:_redirectURL forKey:kRedirectURLKey]; + [aCoder encodeObject:_scope forKey:kScopeKey]; + [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey]; + [aCoder encodeObject:_codeVerifier forKey:kCodeVerifierKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; + [aCoder encodeObject:_additionalHeaders forKey:kAdditionalHeadersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + NSURLRequest *request = self.URLRequest; + NSString *requestBody = + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]; + return [NSString stringWithFormat:@"<%@: %p, request: >", + NSStringFromClass([self class]), + (void *)self, + request.URL, + requestBody]; +} + +#pragma mark - + +/*! @brief Constructs the request URI. + @return A URL representing the token request. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (NSURL *)tokenRequestURL { + return _configuration.tokenEndpoint; +} + +/*! @brief Constructs the request body data by combining the request parameters using the + "application/x-www-form-urlencoded" format. + @return The data to pass to the token request URL. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (OIDURLQueryComponent *)tokenRequestBody { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + // Add parameters, as applicable. + if (_grantType) { + [query addParameter:kGrantTypeKey value:_grantType]; + } + if (_scope) { + [query addParameter:kScopeKey value:_scope]; + } + if (_redirectURL) { + [query addParameter:kRedirectURLKey value:_redirectURL.absoluteString]; + } + if (_refreshToken) { + [query addParameter:kRefreshTokenKey value:_refreshToken]; + } + if (_authorizationCode) { + [query addParameter:kAuthorizationCodeKey value:_authorizationCode]; + } + if (_codeVerifier) { + [query addParameter:kCodeVerifierKey value:_codeVerifier]; + } + + // Add any additional parameters the client has specified. + [query addParameters:_additionalParameters]; + + return query; +} + +- (NSURLRequest *)URLRequest { + static NSString *const kHTTPPost = @"POST"; + static NSString *const kHTTPContentTypeHeaderKey = @"Content-Type"; + static NSString *const kHTTPContentTypeHeaderValue = + @"application/x-www-form-urlencoded; charset=UTF-8"; + + NSURL *tokenRequestURL = [self tokenRequestURL]; + NSMutableURLRequest *URLRequest = [[NSURLRequest requestWithURL:tokenRequestURL] mutableCopy]; + URLRequest.HTTPMethod = kHTTPPost; + [URLRequest setValue:kHTTPContentTypeHeaderValue forHTTPHeaderField:kHTTPContentTypeHeaderKey]; + + OIDURLQueryComponent *bodyParameters = [self tokenRequestBody]; + NSMutableDictionary *httpHeaders = [[NSMutableDictionary alloc] init]; + + if (_clientSecret) { + // The client id and secret are encoded using the "application/x-www-form-urlencoded" + // encoding algorithm per RFC 6749 Section 2.3.1. + // https://tools.ietf.org/html/rfc6749#section-2.3.1 + NSString *encodedClientID = [OIDTokenUtilities formUrlEncode:_clientID]; + NSString *encodedClientSecret = [OIDTokenUtilities formUrlEncode:_clientSecret]; + + NSString *credentials = + [NSString stringWithFormat:@"%@:%@", encodedClientID, encodedClientSecret]; + NSData *plainData = [credentials dataUsingEncoding:NSUTF8StringEncoding]; + NSString *basicAuth = [plainData base64EncodedStringWithOptions:kNilOptions]; + + NSString *authValue = [NSString stringWithFormat:@"Basic %@", basicAuth]; + [httpHeaders setObject:authValue forKey:@"Authorization"]; + } else { + [bodyParameters addParameter:kClientIDKey value:_clientID]; + } + + // Constructs request with the body string and headers. + NSString *bodyString = [bodyParameters URLEncodedParameters]; + NSData *body = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; + URLRequest.HTTPBody = body; + + for (id header in httpHeaders) { + [URLRequest setValue:httpHeaders[header] forHTTPHeaderField:header]; + } + + for (id header in _additionalHeaders) { + [URLRequest setValue:_additionalHeaders[header] forHTTPHeaderField:header]; + } + + return URLRequest; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDTokenResponse.h b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenResponse.h new file mode 100644 index 0000000..b446e94 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenResponse.h @@ -0,0 +1,110 @@ +/*! @file OIDTokenResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDTokenRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the response to an token request. + @see https://tools.ietf.org/html/rfc6749#section-3.2 + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@interface OIDTokenResponse : NSObject + +/*! @brief The request which was serviced. + */ +@property(nonatomic, readonly) OIDTokenRequest *request; + +/*! @brief The access token generated by the authorization server. + @remarks access_token + @see https://tools.ietf.org/html/rfc6749#section-4.1.4 + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/*! @brief The approximate expiration date & time of the access token. + @remarks expires_in + @seealso OIDTokenResponse.accessToken + @see https://tools.ietf.org/html/rfc6749#section-4.1.4 + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate; + +/*! @brief Typically "Bearer" when present. Otherwise, another token_type value that the Client has + negotiated with the Authorization Server. + @remarks token_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.4 + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *tokenType; + +/*! @brief ID Token value associated with the authenticated session. Always present for the + authorization code grant exchange when OpenID Connect is used, optional for responses to + access token refresh requests. Note that AppAuth does NOT verify the JWT signature. Users + of AppAuth are encouraged to verifying the JWT signature using the validation library of + their choosing. + @remarks id_token + @see http://openid.net/specs/openid-connect-core-1_0.html#TokenResponse + @see http://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + @see https://jwt.io + @discussion @c OIDIDToken can be used to parse the ID Token and extract the claims. As noted, + this class does not verify the JWT signature. +*/ +@property(nonatomic, readonly, nullable) NSString *idToken; + +/*! @brief The refresh token, which can be used to obtain new access tokens using the same + authorization grant + @remarks refresh_token + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/*! @brief The scope of the access token. OPTIONAL, if identical to the scopes requested, otherwise, + REQUIRED. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief Additional parameters returned from the token server. + */ +@property(nonatomic, readonly, nullable) + NSDictionary *> *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithParameters:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the Authorization Server. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (instancetype)initWithRequest:(OIDTokenRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDTokenResponse.m b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenResponse.m new file mode 100644 index 0000000..6995fb9 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenResponse.m @@ -0,0 +1,163 @@ +/*! @file OIDTokenResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTokenResponse.h" + +#import "OIDDefines.h" +#import "OIDFieldMapping.h" +#import "OIDTokenRequest.h" +#import "OIDTokenUtilities.h" + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +/*! @brief The key for the @c accessToken property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kAccessTokenKey = @"access_token"; + +/*! @brief The key for the @c accessTokenExpirationDate property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kExpiresInKey = @"expires_in"; + +/*! @brief The key for the @c tokenType property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kTokenTypeKey = @"token_type"; + +/*! @brief The key for the @c idToken property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kIDTokenKey = @"id_token"; + +/*! @brief The key for the @c refreshToken property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kRefreshTokenKey = @"refresh_token"; + +/*! @brief The key for the @c scope property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +@implementation OIDTokenResponse + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[kAccessTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessToken" type:[NSString class]]; + fieldMap[kExpiresInKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessTokenExpirationDate" + type:[NSDate class] + conversion:[OIDFieldMapping dateSinceNowConversion]]; + fieldMap[kTokenTypeKey] = + [[OIDFieldMapping alloc] initWithName:@"_tokenType" type:[NSString class]]; + fieldMap[kIDTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_idToken" type:[NSString class]]; + fieldMap[kRefreshTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_refreshToken" type:[NSString class]]; + fieldMap[kScopeKey] = + [[OIDFieldMapping alloc] initWithName:@"_scope" type:[NSString class]]; + }); + return fieldMap; +} + +#pragma mark - Initializers + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:)) + +- (instancetype)initWithRequest:(OIDTokenRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super init]; + if (self) { + _request = [request copy]; + NSDictionary *> *additionalParameters = + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:parameters + instance:self]; + _additionalParameters = additionalParameters; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDTokenRequest *request = + [aDecoder decodeObjectOfClass:[OIDTokenRequest class] forKey:kRequestKey]; + self = [self initWithRequest:request parameters:@{ }]; + if (self) { + [OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self]; + _additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes] + forKey:kAdditionalParametersKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self]; + [aCoder encodeObject:_request forKey:kRequestKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, accessToken: \"%@\", accessTokenExpirationDate: %@, " + "tokenType: %@, idToken: \"%@\", refreshToken: \"%@\", " + "scope: \"%@\", additionalParameters: %@, request: %@>", + NSStringFromClass([self class]), + (void *)self, + [OIDTokenUtilities redact:_accessToken], + _accessTokenExpirationDate, + _tokenType, + [OIDTokenUtilities redact:_idToken], + [OIDTokenUtilities redact:_refreshToken], + _scope, + _additionalParameters, + _request]; +} + +#pragma mark - + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDTokenUtilities.h b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenUtilities.h new file mode 100644 index 0000000..fda8985 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenUtilities.h @@ -0,0 +1,67 @@ +/*! @file OIDTokenUtilities.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides data encoding/decoding methods, random string generators, etc. + */ +@interface OIDTokenUtilities : NSObject + +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Base64url-nopadding encodes the given data. + @param data The input data. + @return The base64url encoded data as a NSString. + @discussion Base64url-nopadding is used in several identity specs such as PKCE and + OpenID Connect. + */ ++ (NSString *)encodeBase64urlNoPadding:(NSData *)data; + +/*! @brief Generates a URL-safe string of random data. + @param size The number of random bytes to encode. NB. the length of the output string will be + greater than the number of random bytes, due to the URL-safe encoding. + @return Random data encoded with base64url. + */ ++ (nullable NSString *)randomURLSafeStringWithSize:(NSUInteger)size; + +/*! @brief SHA256 hashes the input string. + @param inputString The input string. + @return The SHA256 data. + */ ++ (NSData *)sha256:(NSString *)inputString; + +/*! @brief Truncated intput string after first 6 characters followed by ellipses + @param inputString The input string. + @return Truncated string. + */ ++ (nullable NSString *)redact:(nullable NSString *)inputString; + +/*! @brief Form url encode the input string by applying application/x-www-form-urlencoded algorithm + @param inputString The input string. + @return The encoded string. + */ ++ (NSString*)formUrlEncode:(NSString*)inputString; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDTokenUtilities.m b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenUtilities.m new file mode 100644 index 0000000..3280c85 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDTokenUtilities.m @@ -0,0 +1,89 @@ +/*! @file OIDTokenUtilities.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTokenUtilities.h" + +#import + +/*! @brief String representing the set of characters that are allowed as is for the + application/x-www-form-urlencoded encoding algorithm. + */ +static NSString *const kFormUrlEncodedAllowedCharacters = + @" *-._0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; + +@implementation OIDTokenUtilities + ++ (NSString *)encodeBase64urlNoPadding:(NSData *)data { + NSString *base64string = [data base64EncodedStringWithOptions:0]; + // converts base64 to base64url + base64string = [base64string stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; + base64string = [base64string stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; + // strips padding + base64string = [base64string stringByReplacingOccurrencesOfString:@"=" withString:@""]; + return base64string; +} + ++ (nullable NSString *)randomURLSafeStringWithSize:(NSUInteger)size { + NSMutableData *randomData = [NSMutableData dataWithLength:size]; + int result = SecRandomCopyBytes(kSecRandomDefault, randomData.length, randomData.mutableBytes); + if (result != 0) { + return nil; + } + return [[self class] encodeBase64urlNoPadding:randomData]; +} + ++ (NSData *)sha256:(NSString *)inputString { + NSData *verifierData = [inputString dataUsingEncoding:NSUTF8StringEncoding]; + NSMutableData *sha256Verifier = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(verifierData.bytes, (CC_LONG)verifierData.length, sha256Verifier.mutableBytes); + return sha256Verifier; +} + ++ (NSString *)redact:(NSString *)inputString { + if (inputString == nil) { + return nil; + } + switch(inputString.length){ + case 0: + return @""; + case 1 ... 8: + return @"[redacted]"; + case 9: + default: + return [[inputString substringToIndex:6] stringByAppendingString:@"...[redacted]"]; + } +} + ++ (NSString*)formUrlEncode:(NSString*)inputString { + // https://www.w3.org/TR/html5/sec-forms.html#application-x-www-form-urlencoded-encoding-algorithm + // Following the spec from the above link, application/x-www-form-urlencoded percent encode all + // the characters except *-._A-Za-z0-9 + // Space character is replaced by + in the resulting bytes sequence + if (inputString.length == 0) { + return inputString; + } + NSCharacterSet *allowedCharacters = + [NSCharacterSet characterSetWithCharactersInString:kFormUrlEncodedAllowedCharacters]; + // Percent encode all characters not present in the provided set. + NSString *encodedString = + [inputString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; + // Replace occurences of space by '+' character + return [encodedString stringByReplacingOccurrencesOfString:@" " withString:@"+"]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDURLQueryComponent.h b/Pods/AppAuth/Sources/AppAuthCore/OIDURLQueryComponent.h new file mode 100644 index 0000000..054b11e --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDURLQueryComponent.h @@ -0,0 +1,93 @@ +/*! @file OIDURLQueryComponent.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorizationRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief If set to YES, will force the iOS 7-only code for @c OIDURLQueryComponent to be used, + even on non-iOS 7 devices and simulators. Useful for testing the iOS 7 code paths on the + simulator. Defaults to NO. + */ +extern BOOL gOIDURLQueryComponentForceIOS7Handling; + +/*! @brief A utility class for creating and parsing URL query components encoded with the + application/x-www-form-urlencoded format. + @description Supports application/x-www-form-urlencoded encoding and decoding, specifically + '+' is replaced with space before percent decoding. For encoding, simply percent encodes + space, as this is valid application/x-www-form-urlencoded. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2 + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + @see https://tools.ietf.org/html/rfc6749#appendix-B + @see https://url.spec.whatwg.org/#urlencoded-parsing + */ +@interface OIDURLQueryComponent : NSObject + +/*! @brief The parameter names in the query. + */ +@property(nonatomic, readonly) NSArray *parameters; + +/*! @brief The parameters represented as a dictionary. + @remarks All values are @c NSString except for parameters which contain multiple values, in + which case the value is an @c NSArray *. + */ +@property(nonatomic, readonly) NSDictionary *> *dictionaryValue; + +/*! @brief Creates an @c OIDURLQueryComponent by parsing the query string in a URL. + @param URL The URL from which to extract a query component. + */ +- (nullable instancetype)initWithURL:(NSURL *)URL; + +/*! @brief The value (or values) for a named parameter in the query. + @param parameter The parameter name. Case sensitive. + @return The value (or values) for a named parameter in the query. + */ +- (NSArray *)valuesForParameter:(NSString *)parameter; + +/*! @brief Adds a parameter value to the query. + @param parameter The name of the parameter. Case sensitive. + @param value The value to add. + */ +- (void)addParameter:(NSString *)parameter value:(NSString *)value; + +/*! @brief Adds multiple parameters with associated values to the query. + @param parameters The parameter name value pairs to add to the query. + */ +- (void)addParameters:(NSDictionary *)parameters; + +/*! @param URL The URL to add the query component to. + @return The original URL with the query component replaced by the parameters from this query. + */ +- (NSURL *)URLByReplacingQueryInURL:(NSURL *)URL; + +/*! @brief Builds an x-www-form-urlencoded string representing the parameters. + @return The x-www-form-urlencoded string representing the parameters. + */ +- (NSString *)URLEncodedParameters; + +/*! @brief A NSMutableCharacterSet containing allowed characters in URL parameter values (that is + the "value" part of "?key=value"). This has less allowed characters than + @c URLQueryAllowedCharacterSet, as the query component includes both the key & value. + */ ++ (NSMutableCharacterSet *)URLParamValueAllowedCharacters; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDURLQueryComponent.m b/Pods/AppAuth/Sources/AppAuthCore/OIDURLQueryComponent.m new file mode 100644 index 0000000..07050c9 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDURLQueryComponent.m @@ -0,0 +1,219 @@ +/*! @file OIDURLQueryComponent.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDURLQueryComponent.h" + +BOOL gOIDURLQueryComponentForceIOS7Handling = NO; + +/*! @brief String representing the set of characters that are valid for the URL query + (per @ NSCharacterSet.URLQueryAllowedCharacterSet), but are disallowed in URL query + parameters and values. + */ +static NSString *const kQueryStringParamAdditionalDisallowedCharacters = @"=&+"; + +@implementation OIDURLQueryComponent { + /*! @brief A dictionary of parameter names and values representing the contents of the query. + */ + NSMutableDictionary *> *_parameters; +} + +- (nullable instancetype)init { + self = [super init]; + if (self) { + _parameters = [NSMutableDictionary dictionary]; + } + return self; +} + +- (nullable instancetype)initWithURL:(NSURL *)URL { + self = [self init]; + if (self) { + if (@available(iOS 8.0, macOS 10.10, *)) { + // If NSURLQueryItem is available, use it for deconstructing the new URL. (iOS 8+) + if (!gOIDURLQueryComponentForceIOS7Handling) { + NSURLComponents *components = + [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + // As OAuth uses application/x-www-form-urlencoded encoding, interprets '+' as a space + // in addition to regular percent decoding. https://url.spec.whatwg.org/#urlencoded-parsing + components.percentEncodedQuery = + [components.percentEncodedQuery stringByReplacingOccurrencesOfString:@"+" + withString:@"%20"]; + // NB. @c queryItems are already percent decoded + NSArray *queryItems = components.queryItems; + for (NSURLQueryItem *queryItem in queryItems) { + [self addParameter:queryItem.name value:queryItem.value]; + } + return self; + } + } + + // Fallback for iOS 7 + NSString *query = URL.query; + // As OAuth uses application/x-www-form-urlencoded encoding, interprets '+' as a space + // in addition to regular percent decoding. https://url.spec.whatwg.org/#urlencoded-parsing + query = [query stringByReplacingOccurrencesOfString:@"+" withString:@"%20"]; + + NSArray *queryParts = [query componentsSeparatedByString:@"&"]; + for (NSString *queryPart in queryParts) { + NSRange equalsRange = [queryPart rangeOfString:@"="]; + if (equalsRange.location == NSNotFound) { + continue; + } + NSString *name = [queryPart substringToIndex:equalsRange.location]; + name = name.stringByRemovingPercentEncoding; + NSString *value = [queryPart substringFromIndex:equalsRange.location + equalsRange.length]; + value = value.stringByRemovingPercentEncoding; + [self addParameter:name value:value]; + } + return self; + } + return self; +} + +- (NSArray *)parameters { + return _parameters.allKeys; +} + +- (NSDictionary *> *)dictionaryValue { + // This method will flatten arrays in our @c _parameters' values if only one value exists. + NSMutableDictionary *> *values = [NSMutableDictionary dictionary]; + for (NSString *parameter in _parameters.allKeys) { + NSArray *value = _parameters[parameter]; + if (value.count == 1) { + values[parameter] = [value.firstObject copy]; + } else { + values[parameter] = [value copy]; + } + } + return values; +} + +- (NSArray *)valuesForParameter:(NSString *)parameter { + return _parameters[parameter]; +} + +- (void)addParameter:(NSString *)parameter value:(NSString *)value { + NSMutableArray *parameterValues = _parameters[parameter]; + if (!parameterValues) { + parameterValues = [NSMutableArray array]; + _parameters[parameter] = parameterValues; + } + [parameterValues addObject:value]; +} + +- (void)addParameters:(NSDictionary *)parameters { + for (NSString *parameterName in parameters.allKeys) { + [self addParameter:parameterName value:parameters[parameterName]]; + } +} + +/*! @brief Builds a query items array that can be set to @c NSURLComponents.queryItems + @discussion The parameter names and values are NOT URL encoded. + @return An array of unencoded @c NSURLQueryItem objects. + */ +- (NSMutableArray *)queryItems NS_AVAILABLE(10.10, 8.0) { + NSMutableArray *queryParameters = [NSMutableArray array]; + for (NSString *parameterName in _parameters.allKeys) { + NSArray *values = _parameters[parameterName]; + for (NSString *value in values) { + NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:parameterName value:value]; + [queryParameters addObject:item]; + } + } + return queryParameters; +} + ++ (NSMutableCharacterSet *)URLParamValueAllowedCharacters { + // Starts with the standard URL-allowed character set. + NSMutableCharacterSet *allowedParamCharacters = + [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + // Removes additional characters we don't want to see in the query component. + [allowedParamCharacters removeCharactersInString:kQueryStringParamAdditionalDisallowedCharacters]; + return allowedParamCharacters; +} + +/*! @brief Builds a query string that can be set to @c NSURLComponents.percentEncodedQuery + @discussion This string is percent encoded, and shouldn't be used with + @c NSURLComponents.query. + @return An percentage encoded query string. + */ +- (NSString *)percentEncodedQueryString { + NSMutableArray *parameterizedValues = [NSMutableArray array]; + + // Starts with the standard URL-allowed character set. + NSMutableCharacterSet *allowedParamCharacters = [[self class] URLParamValueAllowedCharacters]; + + for (NSString *parameterName in _parameters.allKeys) { + NSString *encodedParameterName = + [parameterName stringByAddingPercentEncodingWithAllowedCharacters:allowedParamCharacters]; + + NSArray *values = _parameters[parameterName]; + for (NSString *value in values) { + NSString *encodedValue = + [value stringByAddingPercentEncodingWithAllowedCharacters:allowedParamCharacters]; + NSString *parameterizedValue = + [NSString stringWithFormat:@"%@=%@", encodedParameterName, encodedValue]; + [parameterizedValues addObject:parameterizedValue]; + } + } + + NSString *queryString = [parameterizedValues componentsJoinedByString:@"&"]; + return queryString; +} + +- (NSString *)URLEncodedParameters { + // If NSURLQueryItem is available, uses it for constructing the encoded parameters. (iOS 8+) + if (@available(iOS 8.0, macOS 10.10, *)) { + if (!gOIDURLQueryComponentForceIOS7Handling) { + NSURLComponents *components = [[NSURLComponents alloc] init]; + components.queryItems = [self queryItems]; + NSString *encodedQuery = components.percentEncodedQuery; + // NSURLComponents.percentEncodedQuery creates a validly escaped URL query component, but + // doesn't encode the '+' leading to potential ambiguity with application/x-www-form-urlencoded + // encoding. Percent encodes '+' to avoid this ambiguity. + encodedQuery = [encodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]; + return encodedQuery; + } + } + + // else, falls back to building query string manually (iOS 7) + return [self percentEncodedQueryString]; +} + +- (NSURL *)URLByReplacingQueryInURL:(NSURL *)URL { + NSURLComponents *components = + [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + + // Replaces encodedQuery component + NSString *queryString = [self URLEncodedParameters]; + components.percentEncodedQuery = queryString; + + NSURL *URLWithParameters = components.URL; + return URLWithParameters; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, parameters: %@>", + NSStringFromClass([self class]), + (void *)self, + _parameters]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDURLSessionProvider.h b/Pods/AppAuth/Sources/AppAuthCore/OIDURLSessionProvider.h new file mode 100644 index 0000000..28e9116 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDURLSessionProvider.h @@ -0,0 +1,40 @@ +/*! @file OIDURLSessionProvider.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief A NSURLSession provider that allows clients to provide custom implementation + for NSURLSession + */ +@interface OIDURLSessionProvider : NSObject + +/*! @brief Obtains the current @c NSURLSession; using the +[NSURLSession sharedSession] if + no custom implementation is provided. + @return NSURLSession object to be used for making network requests. + */ ++ (NSURLSession *)session; + +/*! @brief Allows library consumers to change the @c NSURLSession instance used to make + network requests. + @param session The @c NSURLSession instance that should be used for making network requests. + */ ++ (void)setSession:(NSURLSession *)session; +@end +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/OIDURLSessionProvider.m b/Pods/AppAuth/Sources/AppAuthCore/OIDURLSessionProvider.m new file mode 100644 index 0000000..fca17fe --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/OIDURLSessionProvider.m @@ -0,0 +1,39 @@ +/*! @file OIDURLSessionProvider.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDURLSessionProvider.h" + +NS_ASSUME_NONNULL_BEGIN + +static NSURLSession *__nullable gURLSession; + +@implementation OIDURLSessionProvider + ++ (NSURLSession *)session { + if (!gURLSession) { + gURLSession = [NSURLSession sharedSession]; + } + return gURLSession; +} + ++ (void)setSession:(NSURLSession *)session { + NSAssert(session, @"Parameter: |session| must be non-nil."); + gURLSession = session; +} +@end +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthCore/Resources/PrivacyInfo.xcprivacy b/Pods/AppAuth/Sources/AppAuthCore/Resources/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..cc6746d --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthCore/Resources/PrivacyInfo.xcprivacy @@ -0,0 +1,16 @@ + + + + + NSPrivacyAccessedAPITypes + + + NSPrivacyCollectedDataTypes + + + NSPrivacyTrackingDomains + + NSPrivacyTracking + + + diff --git a/Pods/AppAuth/Sources/AppAuthTV.h b/Pods/AppAuth/Sources/AppAuthTV.h new file mode 100644 index 0000000..3768c6c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV.h @@ -0,0 +1,22 @@ +/*! @file AppAuthTV.h + @brief AppAuthTV SDK + @copyright + Copyright 2020 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTVAuthorizationRequest.h" +#import "OIDTVAuthorizationResponse.h" +#import "OIDTVAuthorizationService.h" +#import "OIDTVServiceConfiguration.h" diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationRequest.h b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationRequest.h new file mode 100644 index 0000000..2496948 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationRequest.h @@ -0,0 +1,53 @@ +/*! @file OIDTVAuthorizationRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDAuthorizationRequest.h" + +@class OIDTVServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a TV and limited input device authorization request. + @see https://tools.ietf.org/html/rfc8628#section-3.1 + */ +@interface OIDTVAuthorizationRequest : OIDAuthorizationRequest + +/*! @brief Creates a TV authorization request with opinionated defaults + @param configuration The service's configuration. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param additionalParameters The client's additional authorization parameters. + */ +- (instancetype) + initWithConfiguration:(OIDTVServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(NSString *)clientSecret + scopes:(nullable NSArray *)scopes + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Constructs an @c NSURLRequest representing the TV authorization request. + @return An @c NSURLRequest representing the TV authorization request. + */ +- (NSURLRequest *)URLRequest; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationRequest.m b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationRequest.m new file mode 100644 index 0000000..da524d3 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationRequest.m @@ -0,0 +1,117 @@ +/*! @file OIDTVAuthorizationRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +#import "OIDTVAuthorizationRequest.h" +#import "OIDTVServiceConfiguration.h" +#import "OIDURLQueryComponent.h" + +@implementation OIDTVAuthorizationRequest + +- (instancetype) + initWithConfiguration:(OIDTVServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + state:(nullable NSString *)state + nonce:(nullable NSString *)nonce + codeVerifier:(nullable NSString *)codeVerifier + codeChallenge:(nullable NSString *)codeChallenge + codeChallengeMethod:(nullable NSString *)codeChallengeMethod + additionalParameters:(nullable NSDictionary *)additionalParameters { + + if (![configuration isKindOfClass:[OIDTVServiceConfiguration class]]) { + NSAssert([configuration isKindOfClass:[OIDTVServiceConfiguration class]], + @"configuration parameter must be of type OIDTVServiceConfiguration, encountered %@", + NSStringFromClass([configuration class])); + return nil; + } + + return [super initWithConfiguration:configuration + clientId:clientID + clientSecret:clientSecret + scope:scope + redirectURL:redirectURL + responseType:responseType + state:state + nonce:nonce + codeVerifier:codeVerifier + codeChallenge:codeChallenge + codeChallengeMethod:codeChallengeMethod + additionalParameters:additionalParameters]; +} + +- (instancetype) + initWithConfiguration:(OIDTVServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(NSString *)clientSecret + scopes:(nullable NSArray *)scopes + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + clientId:clientID + clientSecret:clientSecret + scopes:scopes + redirectURL:[[NSURL alloc] initWithString:@""] + responseType:OIDResponseTypeCode + additionalParameters:additionalParameters]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, request: %@>", + NSStringFromClass([self class]), + (void *)self, + self.authorizationRequestURL]; +} + +#pragma mark - + +- (NSURLRequest *)URLRequest { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + // Required parameters. + [query addParameter:@"client_id" value:self.clientID]; + + if (self.additionalParameters) { + // Add any additional parameters the client has specified. + [query addParameters:(NSDictionary *)self.additionalParameters]; + } + + if (self.scope) { + [query addParameter:@"scope" value:(NSString *)self.scope]; + } + + static NSString *const kHTTPPost = @"POST"; + static NSString *const kHTTPContentTypeHeaderKey = @"Content-Type"; + static NSString *const kHTTPContentTypeHeaderValue = + @"application/x-www-form-urlencoded; charset=UTF-8"; + + OIDTVServiceConfiguration *tvConfiguration = (OIDTVServiceConfiguration *)self.configuration; + + NSMutableURLRequest *URLRequest = + [[NSURLRequest requestWithURL:tvConfiguration.deviceAuthorizationEndpoint] mutableCopy]; + URLRequest.HTTPMethod = kHTTPPost; + [URLRequest setValue:kHTTPContentTypeHeaderValue forHTTPHeaderField:kHTTPContentTypeHeaderKey]; + NSString *bodyString = [query URLEncodedParameters]; + NSData *body = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; + URLRequest.HTTPBody = body; + return URLRequest; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationResponse.h b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationResponse.h new file mode 100644 index 0000000..c57847c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationResponse.h @@ -0,0 +1,111 @@ +/*! @file OIDTVAuthorizationResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDAuthorizationResponse.h" + +@class OIDTVAuthorizationRequest; +@class OIDTVTokenRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the response to a TV authorization request. + @see https://tools.ietf.org/html/rfc8628#section-3.5 + */ +@interface OIDTVAuthorizationResponse : OIDAuthorizationResponse + +/*! @brief The verification URI that should be displayed to the user instructing them to visit the + URI and enter the code. + @remarks verification_uri + */ +@property(nonatomic, readonly, nullable) NSString *verificationURI; + +/*! @brief A complete verification URI to allow for verification without entering the user code. + @remarks verification_uri + */ +@property(nonatomic, readonly, nullable) NSString *verificationURIComplete; + +/*! @brief The code that should be displayed to the user which they enter at the @c verificationURI. + @remarks user_code + */ +@property(nonatomic, readonly, nullable) NSString *userCode; + +/*! @brief The device code grant used to poll the token endpoint. Rather than using this directly, + use the provided @c tokenPollRequest method to create the token request. + @remarks device_code + */ +@property(nonatomic, readonly, nullable) NSString *deviceCode; + +/*! @brief The interval at which the token endpoint should be polled with the @c deviceCode. + @remarks interval + */ +@property(nonatomic, readonly, nullable) NSNumber *interval; + +/*! @brief The date at which the user can no longer authorize this request. + @remarks expires_in + */ +@property(nonatomic, readonly, nullable) NSDate *expirationDate; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the Authorization Server. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (instancetype)initWithRequest:(OIDTVAuthorizationRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Creates a token request suitable for polling the token endpoint with the @c deviceCode. + @return A @c OIDTVTokenRequest suitable for polling the token endpoint. + @see https://tools.ietf.org/html/rfc8628#section-3.4 + */ +- (nullable OIDTVTokenRequest *)tokenPollRequest; + +/*! @brief Creates a token request suitable for polling the token endpoint with the @c deviceCode. + @param additionalParameters Additional parameters for the token request. + @return A @c OIDTVTokenRequest suitable for polling the token endpoint. + @see https://tools.ietf.org/html/rfc8628#section-3.4 + */ +- (nullable OIDTVTokenRequest *)tokenPollRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Creates a token request suitable for polling the token endpoint with the @c deviceCode. + @param additionalHeaders Additional headers for the token request. + @return A @c OIDTVTokenRequest suitable for polling the token endpoint. + @see https://tools.ietf.org/html/rfc8628#section-3.4 + */ +- (nullable OIDTVTokenRequest *)tokenPollRequestWithAdditionalHeaders: + (nullable NSDictionary *)additionalHeaders; + +/*! @brief Creates a token request suitable for polling the token endpoint with the @c deviceCode. + @param additionalParameters Additional parameters for the token request. + @param additionalHeaders Additional headers for the token request. + @return A @c OIDTVTokenRequest suitable for polling the token endpoint. + @see https://tools.ietf.org/html/rfc8628#section-3.4 + */ +- (nullable OIDTVTokenRequest *)tokenPollRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationResponse.m b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationResponse.m new file mode 100644 index 0000000..b45fc85 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationResponse.m @@ -0,0 +1,190 @@ +/*! @file OIDTVAuthorizationResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTVAuthorizationResponse.h" + +#import "OIDDefines.h" +#import "OIDFieldMapping.h" + +#import "OIDTVTokenRequest.h" +#import "OIDTVAuthorizationRequest.h" + +/*! @brief The key for the @c verificationURI property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kVerificationURIKey = @"verification_uri"; + +/*! @brief An alternative key for the @c verificationURI property in the incoming parameters and for + @c NSSecureCoding. If "verification_uri" is not found in the response, a "verification_url" + key is considered equivalent. This is included for compatibility with legacy implementations + and should ideally be removed in the future. + */ +static NSString *const kVerificationURIAlternativeKey = @"verification_url"; + +/*! @brief The key for the @c verificationURIComplete property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kVerificationURICompleteKey = @"verification_uri_complete"; + +/*! @brief The key for the @c userCode property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kUserCodeKey = @"user_code"; + +/*! @brief The key for the @c deviceCode property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kDeviceCodeKey = @"device_code"; + +/*! @brief The key for the @c expirationDate property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kExpiresInKey = @"expires_in"; + +/*! @brief The key for the @c interval property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kIntervalKey = @"interval"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +@implementation OIDTVAuthorizationResponse + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[kVerificationURIKey] = + [[OIDFieldMapping alloc] initWithName:@"_verificationURI" type:[NSString class]]; + fieldMap[kVerificationURICompleteKey] = + [[OIDFieldMapping alloc] initWithName:@"_verificationURIComplete" type:[NSString class]]; + fieldMap[kUserCodeKey] = + [[OIDFieldMapping alloc] initWithName:@"_userCode" type:[NSString class]]; + fieldMap[kDeviceCodeKey] = + [[OIDFieldMapping alloc] initWithName:@"_deviceCode" type:[NSString class]]; + fieldMap[kExpiresInKey] = + [[OIDFieldMapping alloc] initWithName:@"_expirationDate" + type:[NSDate class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]]; + }]; + fieldMap[kIntervalKey] = + [[OIDFieldMapping alloc] initWithName:@"_interval" type:[NSNumber class]]; + + // Map the alternative verification URI key to "_verificationURI" to support legacy + // implementations using the alternative key + fieldMap[kVerificationURIAlternativeKey] = + [[OIDFieldMapping alloc] initWithName:@"_verificationURI" type:[NSString class]]; + }); + return fieldMap; +} + +#pragma mark - Initializers + +- (instancetype)initWithRequest:(OIDTVAuthorizationRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super initWithRequest:request parameters:parameters]; + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, verificationURI: %@, verificationURIComplete: %@, " + "userCode: \"%@\", deviceCode: " + "\"%@\", interval: %@, expirationDate: %@, " + "additionalParameters: %@, " + "request: %@>", + NSStringFromClass([self class]), + (void *)self, + _verificationURI, + _verificationURIComplete, + _userCode, + _deviceCode, + _interval, + _expirationDate, + self.additionalParameters, + self.request]; +} + +#pragma mark - + +- (OIDTVTokenRequest *)tokenPollRequest { + return [self tokenPollRequestWithAdditionalParameters:nil additionalHeaders:nil]; +} + +- (OIDTVTokenRequest *)tokenPollRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters { + return [[OIDTVTokenRequest alloc] + initWithConfiguration:(OIDTVServiceConfiguration *)self.request.configuration + deviceCode:_deviceCode + clientID:self.request.clientID + clientSecret:self.request.clientSecret + additionalParameters:additionalParameters + additionalHeaders:nil]; +} + +- (OIDTVTokenRequest *)tokenPollRequestWithAdditionalHeaders: + (NSDictionary *)additionalHeaders { + return [[OIDTVTokenRequest alloc] + initWithConfiguration:(OIDTVServiceConfiguration *)self.request.configuration + deviceCode:_deviceCode + clientID:self.request.clientID + clientSecret:self.request.clientSecret + additionalParameters:nil + additionalHeaders:additionalHeaders]; +} + +- (OIDTVTokenRequest *)tokenPollRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters + additionalHeaders: + (NSDictionary *)additionalHeaders { + return [[OIDTVTokenRequest alloc] + initWithConfiguration:(OIDTVServiceConfiguration *)self.request.configuration + deviceCode:_deviceCode + clientID:self.request.clientID + clientSecret:self.request.clientSecret + additionalParameters:additionalParameters + additionalHeaders:additionalHeaders]; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationService.h b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationService.h new file mode 100644 index 0000000..9315857 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationService.h @@ -0,0 +1,111 @@ +/*! @file OIDTVAuthorizationService.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +@class OIDAuthState; +@class OIDTVAuthorizationRequest; +@class OIDTVAuthorizationResponse; +@class OIDTVServiceConfiguration; + +/*! @brief Represents the type of block used as a callback for creating a TV service configuration from + a remote OpenID Connect Discovery document. + @param configuration The TV service configuration, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDTVDiscoveryCallback)(OIDTVServiceConfiguration *_Nullable configuration, + NSError *_Nullable error); + +/*! @brief The block that is called when the TV authorization has initialized. + @param response The authorization response, or nil if there was an error. Display + @c OIDTVAuthorizationResponse.userCode and @c OIDTVAuthorizationResponse.verificationURI to + the user so they can action the request. + @param error The error if an error occurred. + */ +typedef void (^OIDTVAuthorizationInitialization)(OIDTVAuthorizationResponse *_Nullable response, + NSError *_Nullable error); + +/*! @brief The block that is called when the TV authorization has completed. + @param authorization The @c OIDAuthState which you can use to authorize + API calls, or nil if there was an error. + @param error The error if an error occurred. + */ +typedef void (^OIDTVAuthorizationCompletion) + (OIDAuthState *_Nullable authorization, + NSError *_Nullable error); + +/*! @brief Block returned when authorization is initialized that will cancel the pending + authorization when executed. Has no effect if called twice or after the authorization + concluded. + */ +typedef void (^OIDTVAuthorizationCancelBlock)(void); + +/*! @brief Performs authorization flows designed for TVs and other limited input devices. + */ +@interface OIDTVAuthorizationService : NSObject +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Convenience method for creating a TV authorization service configuration from an OpenID + Connect compliant issuer URL. This method validates the presence of a device authorization + endpoint in the retrieved discovery document and instantiates an + @c OIDTVServiceConfiguration. + @param issuerURL The service provider's OpenID Connect issuer. + @param completion A block which will be invoked when the authorization service configuration has + been created, or when an error has occurred. + @see https://openid.net/specs/openid-connect-discovery-1_0.html + */ ++ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL + completion:(OIDTVDiscoveryCallback)completion; + +/*! @brief Convenience method for creating a TV authorization service configuration from an OpenID + Connect compliant identity provider's discovery document. This method validates the presence + of a device authorization endpoint in the retrieved discovery document and instantiates an + @c OIDTVServiceConfiguration. + @param discoveryURL The URL of the service provider's OpenID Connect discovery document. + @param completion A block which will be invoked when the authorization service configuration has + been created, or when an error has occurred. + @see https://openid.net/specs/openid-connect-discovery-1_0.html + */ ++ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL + completion:(OIDTVDiscoveryCallback)completion; + +/*! @brief Starts a TV authorization flow with the given request and polls for a response. + @param request The TV authorization request to initiate. + @param initialization Block that is called with the initial authorization response. Unlike other + OAuth authorization responses, the TV authorization response doesn't contain the + authorization as the user has yet to grant it. Rather, it contains the information that you + show to the user in order for them to authorize the request on another device. + @param completion Block that is called on the success or failure of the authorization. If the + user approves the request, you will get a @c OIDAuthState that you can use + to authenticate API calls, otherwis eyou will get an error. + @return A block which you can execute if you need to cancel the ongoing authorization. Has no + effect if called twice, or called after the authorization concludes. + @see https://tools.ietf.org/html/rfc8628 + */ ++ (OIDTVAuthorizationCancelBlock)authorizeTVRequest:(OIDTVAuthorizationRequest *)request + initialization:(OIDTVAuthorizationInitialization)initialization + completion:(OIDTVAuthorizationCompletion)completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationService.m b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationService.m new file mode 100644 index 0000000..eaa4d6b --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVAuthorizationService.m @@ -0,0 +1,285 @@ +/*! @file OIDTVAuthorizationService.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTVAuthorizationService.h" + +#import "OIDAuthorizationService.h" +#import "OIDAuthState.h" +#import "OIDDefines.h" +#import "OIDErrorUtilities.h" +#import "OIDServiceDiscovery.h" +#import "OIDURLQueryComponent.h" +#import "OIDURLSessionProvider.h" + +#import "OIDTVAuthorizationRequest.h" +#import "OIDTVAuthorizationResponse.h" +#import "OIDTVServiceConfiguration.h" +#import "OIDTVTokenRequest.h" + +/*! @brief The authorization pending error code. + @see https://tools.ietf.org/html/rfc8628#section-3.5 + */ +NSString *const kErrorCodeAuthorizationPending = @"authorization_pending"; + +/*! @brief The slow down error code. + @see https://tools.ietf.org/html/rfc8628#section-3.5 + */ +NSString *const kErrorCodeSlowDown = @"slow_down"; + +/*! @brief Path appended to an OpenID Connect issuer for discovery + @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig + */ +static NSString *const kOpenIDConfigurationWellKnownPath = @".well-known/openid-configuration"; + +@implementation OIDTVAuthorizationService + +#pragma mark OIDC Discovery + ++ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL + completion:(OIDTVDiscoveryCallback)completion { + NSURL *fullDiscoveryURL = + [issuerURL URLByAppendingPathComponent:kOpenIDConfigurationWellKnownPath]; + + [[self class] discoverServiceConfigurationForDiscoveryURL:fullDiscoveryURL + completion:completion]; +} + ++ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL + completion:(OIDTVDiscoveryCallback)completion { + // Call the corresponding discovery method in OIDAuthorizationService + [OIDAuthorizationService discoverServiceConfigurationForDiscoveryURL:discoveryURL + completion:^(OIDServiceConfiguration * _Nullable configuration, NSError * _Nullable error) { + if (configuration == nil) { + completion(nil, error); + return; + } + + if (configuration.discoveryDocument.deviceAuthorizationEndpoint == nil) { + NSError *missingEndpointError = [OIDErrorUtilities + errorWithCode:OIDErrorCodeInvalidDiscoveryDocument + underlyingError:nil + description:@"Discovery document does not contain device authorization endpoint."]; + + completion(nil, missingEndpointError); + return; + } + + // Create an OIDTVServiceConfiguration from the discovery document of the configuration + OIDTVServiceConfiguration *TVConfiguration = [[OIDTVServiceConfiguration alloc] + initWithDiscoveryDocument:configuration.discoveryDocument]; + + completion(TVConfiguration, nil); + }]; +} + +#pragma mark - Initializers + ++ (OIDTVAuthorizationCancelBlock)authorizeTVRequest:(OIDTVAuthorizationRequest *)request + initialization:(OIDTVAuthorizationInitialization)initialization + completion:(OIDTVAuthorizationCompletion)completion { + // Block level variable that can be used to cancel the polling. + __block BOOL pollRunning = YES; + + // Block that will be returned allowign the caller to cancel the polling. + OIDTVAuthorizationCancelBlock cancelBlock = ^{ + if (pollRunning) { + dispatch_async(dispatch_get_main_queue(), ^{ + NSError *cancelError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeProgramCanceledAuthorizationFlow + underlyingError:nil + description:@"Authorization cancelled"]; + completion(nil, cancelError); + }); + } + pollRunning = NO; + }; + + // Performs the initial authorization reqeust. + NSURLRequest *URLRequest = [request URLRequest]; + NSURLSession *session = [NSURLSession sharedSession]; + [[session dataTaskWithRequest:URLRequest + completionHandler:^(NSData *_Nullable data, + NSURLResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + // A network error or server error occurred. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + initialization(nil, returnedError); + }); + return; + } + + NSHTTPURLResponse *HTTPURLResponse = (NSHTTPURLResponse *)response; + + if (HTTPURLResponse.statusCode != 200) { + // A server error occurred. + NSError *serverError = + [OIDErrorUtilities HTTPErrorWithHTTPResponse:HTTPURLResponse data:data]; + + // HTTP 400 may indicate an RFC6749 Section 5.2 error response, checks for that + if (HTTPURLResponse.statusCode == 400) { + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:(NSData *)data + options:0 + error:&jsonDeserializationError]; + + // if the HTTP 400 response parses as JSON and has an 'error' key, it's an OAuth error + // these errors are special as they indicate a problem with the authorization grant + if (json[OIDOAuthErrorFieldError]) { + NSError *oauthError = + [OIDErrorUtilities OAuthErrorWithDomain:OIDOAuthTokenErrorDomain + OAuthResponse:json + underlyingError:serverError]; + dispatch_async(dispatch_get_main_queue(), ^{ + initialization(nil, oauthError); + }); + return; + } + } + + // not an OAuth error, just a generic server error + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeServerError + underlyingError:serverError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + initialization(nil, returnedError); + }); + return; + } + + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:(NSData *)data + options:0 + error:&jsonDeserializationError]; + if (jsonDeserializationError) { + // A problem occurred deserializing the response/JSON. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONDeserializationError + underlyingError:jsonDeserializationError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + initialization(nil, returnedError); + }); + return; + } + + // Parses the authorization response. + OIDTVAuthorizationResponse *TVAuthorizationResponse = + [[OIDTVAuthorizationResponse alloc] initWithRequest:request parameters:json]; + if (!TVAuthorizationResponse) { + // A problem occurred constructing the token response from the JSON. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeTokenResponseConstructionError + underlyingError:jsonDeserializationError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + initialization(nil, returnedError); + }); + return; + } + + // Calls the initialization block to signal that we received a TV authorization response. + dispatch_async(dispatch_get_main_queue(), ^() { + initialization(TVAuthorizationResponse, nil); + }); + + // Creates the token request that will be used to poll the token endpoint. + OIDTVTokenRequest *pollRequest = [TVAuthorizationResponse tokenPollRequest]; + + // Starting polling interval (may be increased if a slow down message is received). + __block NSTimeInterval interval = [TVAuthorizationResponse.interval doubleValue]; + + // If no interval is set, use default value of 5 as per RFC. + // If interval is set to 0, use value of 1 to prevent infinite polling. + if (TVAuthorizationResponse.interval == nil) { + interval = 5.0; + } else if (interval == 0.0) { + interval = 1.0; + } + + // Polls the token endpoint until the authorization completes or expires. + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + do { + // Sleeps for polling interval. + [NSThread sleepForTimeInterval:interval]; + + if (!pollRunning) { + break; + } + + // Polls token endpoint. + [OIDAuthorizationService performTokenRequest:pollRequest + callback:^(OIDTokenResponse *_Nullable tokenResponse, + NSError *_Nullable tokenError) { + if (!pollRunning) { + return; + } + dispatch_async(dispatch_get_main_queue(), ^() { + if (tokenResponse) { + // Success response. + pollRunning = NO; + dispatch_async(dispatch_get_main_queue(), ^{ + OIDAuthState *authState = + [[OIDAuthState alloc] initWithAuthorizationResponse:TVAuthorizationResponse + tokenResponse:tokenResponse]; + completion(authState, nil); + }); + } else { + if (tokenError.domain == OIDOAuthTokenErrorDomain) { + // OAuth token errors inspected for device flow specific errors. + NSString *errorCode = + tokenError.userInfo[OIDOAuthErrorResponseErrorKey][OIDOAuthErrorFieldError]; + if ([errorCode isEqual:kErrorCodeAuthorizationPending]) { + // authorization_pending is an expected response. + return; + } else if ([errorCode isEqual:kErrorCodeSlowDown]) { + // Increase interval by 20%, enforce a lower bound of 5s. + interval *= 1.20; + interval = MAX(5.0, interval); + } else { + // Unhandled token error, considered fatal. + pollRunning = NO; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, tokenError); + }); + } + } else { + // All other errors considered fatal. + pollRunning = NO; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, tokenError); + }); + } + } + }); + }]; + } while ([TVAuthorizationResponse.expirationDate timeIntervalSinceNow] > 0 && pollRunning); + }); + }] resume]; + + return cancelBlock; +} + +@end diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVServiceConfiguration.h b/Pods/AppAuth/Sources/AppAuthTV/OIDTVServiceConfiguration.h new file mode 100644 index 0000000..2afea6c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVServiceConfiguration.h @@ -0,0 +1,61 @@ +/*! @file OIDTVServiceConfiguration.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDServiceConfiguration.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Configuration for authorizing the user with the @c OIDTVAuthorizationService. + */ +@interface OIDTVServiceConfiguration : OIDServiceConfiguration + +/*! @brief The device authorization endpoint URI. + */ +@property(nonatomic, readonly) NSURL *deviceAuthorizationEndpoint; + +/*! @internal + @brief Unavailable. Please use + @c initWithDeviceAuthorizationEndpoint:tokenEndpoint: + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @internal + @brief Unavailable. Please use + @c initWithDeviceAuthorizationEndpoint:tokenEndpoint: + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param discoveryDocument The discovery document from which to extract the required OAuth + configuration. +*/ +- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *)discoveryDocument + NS_DESIGNATED_INITIALIZER; + +/*! @brief Designated initializer. + @param deviceAuthorizationEndpoint The device authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + */ +- (instancetype)initWithDeviceAuthorizationEndpoint:(NSURL *)deviceAuthorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVServiceConfiguration.m b/Pods/AppAuth/Sources/AppAuthTV/OIDTVServiceConfiguration.m new file mode 100644 index 0000000..202aa91 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVServiceConfiguration.m @@ -0,0 +1,105 @@ +/*! @file OIDTVServiceConfiguration.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTVServiceConfiguration.h" + +#import "OIDDefines.h" +#import "OIDServiceDiscovery.h" + +/*! @brief The key for the @c deviceAuthorizationEndpoint property. + */ +static NSString *const kDeviceAuthorizationEndpointKey = @"deviceAuthorizationEndpoint"; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDTVServiceConfiguration () + +/*! @brief Designated initializer. + @param aDecoder NSCoder to unserialize the object from. + */ +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; + +@end + +@implementation OIDTVServiceConfiguration + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithDeviceAuthorizationEndpoint:tokenEndpoint:)) + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithDeviceAuthorizationEndpoint:tokenEndpoint:)) + +- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *)discoveryDocument { + self = [super initWithDiscoveryDocument:discoveryDocument]; + + if (self) { + if (discoveryDocument.deviceAuthorizationEndpoint == nil) { + NSLog(@"Warning: Discovery document used to initialize %@ " + @"does not contain device authorization endpoint.", self); + } else { + _deviceAuthorizationEndpoint = [discoveryDocument.deviceAuthorizationEndpoint copy]; + } + } + return self; +} + +- (instancetype)initWithDeviceAuthorizationEndpoint:(NSURL *)deviceAuthorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint { + self = [super initWithAuthorizationEndpoint:[[NSURL alloc] initWithString:@""] + tokenEndpoint:tokenEndpoint]; + if (self) { + _deviceAuthorizationEndpoint = [deviceAuthorizationEndpoint copy]; + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [super initWithCoder:aDecoder]; + if (self) { + NSURL *deviceAuthorizationEndpoint = + [aDecoder decodeObjectOfClass:[NSURL class] forKey:kDeviceAuthorizationEndpointKey]; + _deviceAuthorizationEndpoint = deviceAuthorizationEndpoint; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [super encodeWithCoder:aCoder]; + [aCoder encodeObject:_deviceAuthorizationEndpoint forKey:kDeviceAuthorizationEndpointKey]; +} + +#pragma mark - description + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, deviceAuthorizationEndpoint: %@ tokenEndpoint: %@>", + NSStringFromClass([self class]), + (void *)self, + _deviceAuthorizationEndpoint, + self.tokenEndpoint]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVTokenRequest.h b/Pods/AppAuth/Sources/AppAuthTV/OIDTVTokenRequest.h new file mode 100644 index 0000000..8643b4c --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVTokenRequest.h @@ -0,0 +1,122 @@ +/*! @file OIDTVTokenRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2020 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#import "OIDTokenRequest.h" + +#import + +@class OIDServiceConfiguration; +@class OIDTVServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDTVTokenRequest : OIDTokenRequest + +/*! @brief The device code received from the authorization server. + @remarks device_code + @see https://tools.ietf.org/html/rfc8628#section-3.4 + */ +@property(nonatomic, readonly) NSString *deviceCode; + +/*! @internal + @brief Unavailable. Please use + @c initWithConfiguration:deviceCode:clientID:clientSecret:additionalParameters:additionalHeaders: + or @c initWithCoder:. +*/ +- (instancetype)init NS_UNAVAILABLE; + +/*! @internal + @brief Unavailable. Please use + @c initWithConfiguration:deviceCode:clientID:clientSecret:additionalParameters:additionalHeaders: + or @c initWithCoder:. +*/ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders + NS_UNAVAILABLE; + +/*! @internal + @brief Unavailable. Please use + @c initWithConfiguration:deviceCode:clientID:clientSecret:additionalParameters:additionalHeaders: + or @c initWithCoder:. +*/ +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders + NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param deviceCode The device verification code received from the authorization server. + @param clientID The client identifier. + @param clientSecret The client secret (nullable). + @param additionalParameters The client's additional token request parameters. +*/ +- (instancetype)initWithConfiguration:(OIDTVServiceConfiguration *)configuration + deviceCode:(NSString *)deviceCode + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + additionalParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param deviceCode The device verification code received from the authorization server. + @param clientID The client identifier. + @param clientSecret The client secret (nullable). + @param additionalParameters The client's additional token request parameters. + @param additionalHeaders The client's additional token request headers. +*/ +- (instancetype)initWithConfiguration:(OIDTVServiceConfiguration *)configuration + deviceCode:(NSString *)deviceCode + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + additionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders + NS_DESIGNATED_INITIALIZER; + +/*! @brief Designated initializer for NSSecureCoding. + @param aDecoder Unarchiver object to decode + */ +- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/AppAuth/Sources/AppAuthTV/OIDTVTokenRequest.m b/Pods/AppAuth/Sources/AppAuthTV/OIDTVTokenRequest.m new file mode 100644 index 0000000..0878c79 --- /dev/null +++ b/Pods/AppAuth/Sources/AppAuthTV/OIDTVTokenRequest.m @@ -0,0 +1,174 @@ +/*! @file OIDTVTokenRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2020 Google Inc. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#import "OIDTVTokenRequest.h" + +#import "OIDDefines.h" +#import "OIDTVServiceConfiguration.h" +#import "OIDURLQueryComponent.h" + +/*! @brief The key for the @c deviceCode property for @c NSSecureCoding and request body. + */ +static NSString *const kDeviceCodeKey = @"device_code"; + +/*! @brief Key used to encode the @c grantType property for @c NSSecureCoding and request body. + */ +static NSString *const kGrantTypeKey = @"grant_type"; + +/*! @brief Value for @c grant_type key in the request body + @see https://tools.ietf.org/html/rfc8628#section-3.4 + */ +static NSString *const kOIDTVDeviceTokenGrantType = @"urn:ietf:params:oauth:grant-type:device_code"; + +@implementation OIDTVTokenRequest + +- (instancetype)init OID_UNAVAILABLE_USE_INITIALIZER(@selector + (initWithConfiguration: + deviceCode: + clientID: + clientSecret: + additionalParameters: + additionalHeaders: + )) + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders + OID_UNAVAILABLE_USE_INITIALIZER(@selector + (initWithConfiguration: + deviceCode: + clientID: + clientSecret: + additionalParameters: + additionalHeaders: + )) + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(nullable NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters: + (nullable NSDictionary *)additionalParameters + additionalHeaders: + (nullable NSDictionary *)additionalHeaders + OID_UNAVAILABLE_USE_INITIALIZER(@selector + (initWithConfiguration: + deviceCode: + clientID: + clientSecret: + additionalParameters: + additionalHeaders: + )) + +- (instancetype)initWithConfiguration:(OIDTVServiceConfiguration *)configuration + deviceCode:(NSString *)deviceCode + clientID:(NSString *)clientID + clientSecret:(NSString *)clientSecret + additionalParameters:(NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + deviceCode:deviceCode + clientID:clientID + clientSecret:clientSecret + additionalParameters:additionalParameters + additionalHeaders:nil]; +} + +- (instancetype)initWithConfiguration:(OIDTVServiceConfiguration *)configuration + deviceCode:(NSString *)deviceCode + clientID:(NSString *)clientID + clientSecret:(NSString *)clientSecret + additionalParameters:(NSDictionary *)additionalParameters + additionalHeaders:(NSDictionary *)additionalHeaders { + self = [super initWithConfiguration:configuration + grantType:kOIDTVDeviceTokenGrantType + authorizationCode:nil + redirectURL:[[NSURL alloc] initWithString:@""] + clientID:clientID + clientSecret:clientSecret + scope:nil + refreshToken:nil + codeVerifier:nil + additionalParameters:additionalParameters + additionalHeaders:additionalHeaders]; + + if (self) { + _deviceCode = [deviceCode copy]; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + self = [super initWithCoder:aDecoder]; + if (self) { + NSString *deviceCode = [aDecoder decodeObjectOfClass:[NSString class] forKey:kDeviceCodeKey]; + _deviceCode = deviceCode; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [super encodeWithCoder:aCoder]; + [aCoder encodeObject:_deviceCode forKey:kDeviceCodeKey]; +} + +- (OIDURLQueryComponent *)tokenRequestBody { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + if (self.grantType) { + [query addParameter:kGrantTypeKey value:self.grantType]; + } + + [query addParameter:kDeviceCodeKey value:self.deviceCode]; + + [query addParameters:self.additionalParameters]; + + return query; +} + +@end diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/Info.plist b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/Info.plist new file mode 100644 index 0000000..57b349a --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/Info.plist @@ -0,0 +1,44 @@ + + + + + AvailableLibraries + + + BinaryPath + AppLovinSDK.framework/AppLovinSDK + LibraryIdentifier + ios-arm64 + LibraryPath + AppLovinSDK.framework + SupportedArchitectures + + arm64 + + SupportedPlatform + ios + + + BinaryPath + AppLovinSDK.framework/AppLovinSDK + LibraryIdentifier + ios-arm64_x86_64-simulator + LibraryPath + AppLovinSDK.framework + SupportedArchitectures + + arm64 + x86_64 + + SupportedPlatform + ios + SupportedPlatformVariant + simulator + + + CFBundlePackageType + XFWK + XCFrameworkFormatVersion + 1.0 + + diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDK b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDK new file mode 100755 index 0000000..ae7cec4 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDK differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowATT.json b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowATT.json new file mode 100644 index 0000000..bc34d6d --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowATT.json @@ -0,0 +1,11 @@ +{ + "states": [{ + "id": 14, + "is_initial_state": true, + "type": "att", + "destination_state_id": 99 + }, { + "id": 99, + "type": "reinit" + }] +} diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowPrivacyPolicy.json b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowPrivacyPolicy.json new file mode 100644 index 0000000..04ae485 --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowPrivacyPolicy.json @@ -0,0 +1,32 @@ +{ + "states": [{ + "id": 1, + "is_initial_state": true, + "type": "alert", + "title": { + "key": "PP_TITLE", + "key_unified_flow": "PP_TITLE_UNIFIED_FLOW", + "replacements": [""] + }, + "message": { + "key": "AGREE_MESSAGE", + "key_unified_flow": "AGREE_MESSAGE_UNIFIED_FLOW" + }, + "transitions": [{ + "title": { + "key": "AGREE_TO_TERMS_BUTTON_TITLE", + "key_unified_flow": "CONTINUE_BUTTON_TITLE_UNIFIED_FLOW" + }, + "style": "default", + "destination_state_id": 12 + }] + }, { + "id": 12, + "type": "event", + "name": "tos_ok", + "destination_state_id": 99 + }, { + "id": 99, + "type": "reinit" + }] +} diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowPrivacyPolicyAndATT.json b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowPrivacyPolicyAndATT.json new file mode 100644 index 0000000..3d49ee2 --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowPrivacyPolicyAndATT.json @@ -0,0 +1,36 @@ +{ + "states": [{ + "id": 1, + "is_initial_state": true, + "type": "alert", + "title": { + "key": "PP_TITLE", + "key_unified_flow": "PP_TITLE_UNIFIED_FLOW", + "replacements": [""] + }, + "message": { + "key": "AGREE_MESSAGE", + "key_unified_flow": "AGREE_MESSAGE_UNIFIED_FLOW" + }, + "transitions": [{ + "title": { + "key": "AGREE_TO_TERMS_BUTTON_TITLE", + "key_unified_flow": "CONTINUE_BUTTON_TITLE_UNIFIED_FLOW" + }, + "style": "default", + "destination_state_id": 12 + }] + }, { + "id": 12, + "type": "event", + "name": "tos_ok", + "destination_state_id": 14 + }, { + "id": 14, + "type": "att", + "destination_state_id": 99 + }, { + "id": 99, + "type": "reinit" + }] +} diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowTermsOfServiceAndPrivacyPolicy.json b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowTermsOfServiceAndPrivacyPolicy.json new file mode 100644 index 0000000..bbd4b2e --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowTermsOfServiceAndPrivacyPolicy.json @@ -0,0 +1,32 @@ +{ + "states": [{ + "id": 1, + "is_initial_state": true, + "type": "alert", + "title": { + "key": "PP_AND_TOS_TITLE", + "key_unified_flow": "PP_AND_TOS_TITLE_UNIFIED_FLOW", + "replacements": [""] + }, + "message": { + "key": "AGREE_MESSAGE", + "key_unified_flow": "AGREE_MESSAGE_UNIFIED_FLOW" + }, + "transitions": [{ + "title": { + "key": "AGREE_TO_TERMS_BUTTON_TITLE", + "key_unified_flow": "CONTINUE_BUTTON_TITLE_UNIFIED_FLOW" + }, + "style": "default", + "destination_state_id": 12 + }] + }, { + "id": 12, + "type": "event", + "name": "tos_ok", + "destination_state_id": 99 + }, { + "id": 99, + "type": "reinit" + }] +} diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowTermsOfServiceAndPrivacyPolicyAndATT.json b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowTermsOfServiceAndPrivacyPolicyAndATT.json new file mode 100644 index 0000000..1771de3 --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowTermsOfServiceAndPrivacyPolicyAndATT.json @@ -0,0 +1,36 @@ +{ + "states": [{ + "id": 1, + "is_initial_state": true, + "type": "alert", + "title": { + "key": "PP_AND_TOS_TITLE", + "key_unified_flow": "PP_AND_TOS_TITLE_UNIFIED_FLOW", + "replacements": [""] + }, + "message": { + "key": "AGREE_MESSAGE", + "key_unified_flow": "AGREE_MESSAGE_UNIFIED_FLOW" + }, + "transitions": [{ + "title": { + "key": "AGREE_TO_TERMS_BUTTON_TITLE", + "key_unified_flow": "CONTINUE_BUTTON_TITLE_UNIFIED_FLOW" + }, + "style": "default", + "destination_state_id": 12 + }] + }, { + "id": 12, + "type": "event", + "name": "tos_ok", + "destination_state_id": 14 + }, { + "id": 14, + "type": "att", + "destination_state_id": 99 + }, { + "id": 99, + "type": "reinit" + }] +} diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowUnifiedCMP.json b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowUnifiedCMP.json new file mode 100644 index 0000000..f397308 --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALConsentFlowUnifiedCMP.json @@ -0,0 +1,41 @@ +{ + "states": [{ + "is_initial_state": true, + "id": 1000, + "type": "decision", + "decision_type": "is_al_gdpr", + "destination_state_id_true": 20, + "destination_state_id_false": 500 + }, { + "id": 20, + "type": "cmp_load", + "decision_type": "cmp_load_success", + "destination_state_id_true": 21, + "destination_state_id_false": 500 + }, { + "id": 21, + "type": "cmp_show", + "destination_state_id": 13 + }, { + "id": 13, + "type": "event", + "name": "gdpr_ok", + "destination_state_id": 1001 + }, { + "id": 1001, + "type": "decision", + "decision_type": "is_user_eligible_for_att_alert", + "destination_state_id_true": 14, + "destination_state_id_false": 99 + }, { + "id": 14, + "type": "att", + "destination_state_id": 99 + }, { + "id": 500, + "type": "terms_flow" + }, { + "id": 99, + "type": "reinit" + }] +} diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDDetailTableViewCell.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDDetailTableViewCell.nib new file mode 100644 index 0000000..1c61b7b Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDDetailTableViewCell.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/3jf-B1-XNL-view-Iqa-CO-DFs.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/3jf-B1-XNL-view-Iqa-CO-DFs.nib new file mode 100644 index 0000000..ffc5ab1 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/3jf-B1-XNL-view-Iqa-CO-DFs.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/ALDMultiAdViewController.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/ALDMultiAdViewController.nib new file mode 100644 index 0000000..cb36332 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/ALDMultiAdViewController.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/Info.plist b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/Info.plist new file mode 100644 index 0000000..5980163 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDMultiAdViewController.storyboardc/Info.plist differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDRightDetailTableViewCell.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDRightDetailTableViewCell.nib new file mode 100644 index 0000000..6642acf Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ALDRightDetailTableViewCell.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Assets.car b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Assets.car new file mode 100644 index 0000000..aebf1eb Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Assets.car differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Base.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Base.lproj/Localizable.strings new file mode 100644 index 0000000..2b6dce4 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Base.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Info.plist b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Info.plist new file mode 100644 index 0000000..acda023 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/Info.plist differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MAHybridNativeAdView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MAHybridNativeAdView.nib new file mode 100644 index 0000000..2c388f7 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MAHybridNativeAdView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdBannerView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdBannerView.nib new file mode 100644 index 0000000..dac5848 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdBannerView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdLeaderView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdLeaderView.nib new file mode 100644 index 0000000..f2d7247 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdLeaderView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMRecView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMRecView.nib new file mode 100644 index 0000000..a4f42e5 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMRecView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMediaBannerView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMediaBannerView.nib new file mode 100644 index 0000000..a67c195 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMediaBannerView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMediumTemplate1.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMediumTemplate1.nib new file mode 100644 index 0000000..3d5f54d Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdMediumTemplate1.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdSmallTemplate1.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdSmallTemplate1.nib new file mode 100644 index 0000000..8cb4040 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdSmallTemplate1.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalBannerView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalBannerView.nib new file mode 100644 index 0000000..f4f1826 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalBannerView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalLeaderView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalLeaderView.nib new file mode 100644 index 0000000..d0bb35f Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalLeaderView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalMediaBannerView.nib b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalMediaBannerView.nib new file mode 100644 index 0000000..7fc40fa Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/MANativeAdVerticalMediaBannerView.nib differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/OMLICENSE b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/OMLICENSE new file mode 100644 index 0000000..6a34d05 --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/OMLICENSE @@ -0,0 +1,81 @@ +Open Measurement (OM) License, V 1.0 + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +“Ad Verification” shall mean methods and practices for determining whether ads appear on intended sites, reach the targeted audience, and/or are viewable. + +“Approve” “Approved” and “Approval” shall mean Licensor’s written approval, which may be granted or withheld in Licensor’s sole discretion. + +“License” or “OM License” shall mean the terms and conditions for use, reproduction, and distribution as defined herein in this Open Measurement License, Version 1.0 or (at Your option) any later version of the Open Measurement License published by Licensor on the Licensor Website. For the avoidance of doubt, You may elect to use the OM Work under any version of the OM License that has been published by Licensor on the Licensor Website at the time of such use but must give any other recipients of the Work a copy of the OM License version you have elected in connection with any such distribution as required by Section 4 (Redistribution) below. + +“Licensor” shall mean the copyright owners or entity authorized by the copyright owners of the Work that are granting the License, which authorized representative shall initially be IAB Technology Laboratory, Inc. + +“Licensor Website” shall mean https://iabtechlab.com/specifications-guidelines/open-measurement-sdk/ or any other website subsequently identified by Licensor. + +“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of more than fifty percent (50%) of the outstanding shares of such entity, or (iii) beneficial ownership of such entity. + +“You” (or “Your”) shall mean an individual or Legal Entity exercising the permitted rights granted by this License. + +“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +“SDK” shall mean a software development kit to enable use of the Object form of the Work for mobile Ad Verification purposes. + +“SSP” shall mean a mobile advertising supply-side platform that operates an advertising SDK to monetize mobile applications mobile ads. + +“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +“OMWG” shall mean the Open Measurement Working Group. + +“Work” shall mean the OMWG mobile application Ad Verification software and related SDK made available under this License in Object form (unless otherwise expressly stated herein). + +“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work, including without limitation such code as is required for integration of the SDK by an implementer thereof. + +“Contribution” shall mean any work of authorship or other intellectual property, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is or was intentionally submitted to the Licensor by a member of the OMWG, or other Contributor, for inclusion in the Work where it will be licensed as part of the Work under the OM License. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the owner as “Not a Contribution.” + +“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +(a) Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, royalty-free, irrevocable (except as stated in this License) copyright license to use, reproduce, publicly display, publicly perform, sublicense, and distribute the Work in Object form only. For clarity, this grant does not include the right to prepare, reproduce, publicly display, publicly perform, sublicense, or distribute Derivative Works. + +(b) Notwithstanding the generality of the foregoing, except as otherwise Approved, the license to the Work is limited to the use of the Work and Work integrations by mobile application publishers implementing the Object form of the Work in their mobile apps for mobile Ad Verification purposes and SSPs implementing within their advertising monetization SDKs that are integrated by app publishers to serve advertisements that are subject to verification via the Work. + +(c) In addition, subject to Approval, this License shall also include use of the Object form of the Work in an Approved proprietary mobile application plug-in, so long as it is either bundled within the official binary that is distributed by or under authority of Licensor, or is otherwise modular / additive to such official binary and does not require modification to the Source form of the Work (whether to the official binary or otherwise). + +(d) In addition, You shall have a license to access or use the Source form of the Work only if specifically Approved by Licensor, but then only to the extent Approved and for such limited Approved purpose(s) (such as may be the case for purposes of merging Approved Contributions into the Work), which approval is revocable at any time by Licensor. The Source form of the Work shall be Licensor’s confidential information and shall not be used, distributed or disclosed except as Approved or authorized under Section 2(e) of this License; provided, however, individual Contributors retain all of their rights to their respective Contributions outside of the Work. In the event of any Source form modifications, whether for bug fixes or otherwise, the modifications must be submitted back to the Licensor as a Contribution within three (3) business days of completion and unless exigent circumstances reasonably require, before any public use, or otherwise upon request by Licensor. + +(e) You acknowledge that the Source form of the Work is the confidential information of the Licensor and Contributors, as applicable. You may not disclose the Source form of the Work without prior written consent of Licensor, except (a) to Your employees, subcontractors and professional advisors under a strict duty of confidentiality, (b) to third parties only as expressly provided for herein, or (c) if and as required by court order, law or governmental or regulatory agency (after, if permitted, giving reasonable notice to the Licensor and using commercially reasonable efforts to provide Licensor with the opportunity to seek a protective order or the equivalent (at Licensor’s expense)). In the event that such protective order or other remedy is not obtained, or that Licensor waives compliance with the provisions hereof, You shall furnish only that portion of the Work which You are advised by counsel is legally required to be disclosed, and You shall use commercially reasonable efforts to ensure that confidential treatment shall be afforded such disclosed portion of the Work. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as set forth in this License) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work, subject to the terms and conditions of this License, solely without modifications in any medium, and in Object form only, provided that (a) You give any other recipients of the Work a copy of this License and (b) if the Work includes a “NOTICE” text file as part of its distribution, then any copies of the Work that You distribute must include a copy of that NOTICE file. + +5. Submission of Contributions. Any Contribution You intentionally submit, or are otherwise required by this License or an Approval to submit, for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. For the avoidance of doubt, all Contributions to the Work are licensed and not assigned. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor nor any Contributor, except as required for reasonable and customary use in describing the origin of the Work. + +7. Disclaimer of Warranty. Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any and all risks associated with Your exercise of permissions and rights under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Licensor or Contributor be liable to You for any damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if Licensor or any such Contributor has been advised of the possibility of such damages. You are obligated to comply with all applicable local, state, federal, national, and/or international laws and regulations (as applicable) in the course of using the Work, including, without limitation, all applicable data privacy laws and regulations (including, without limitation, any applicable self-regulatory guidelines) relevant to Your collection, use, and transfer of any data collected by the Work. Additionally, You acknowledge that use of the Work must follow appropriate guidance on use of parameters in the SDK, for example, as defined in relevant documentation associated with SDK and Work usage. + +9. Indemnity. + +(a) You will indemnify, defend (at the Licensor’s option) and hold Licensor, each Contributor and their related Legal Entities harmless against any claim, costs, losses, damages, liabilities, judgments, fees (including reasonable fees of attorneys and other professionals), and expenses arising out of or in connection with any claim, action or proceeding (any and all of which are “Claims”) by a third party arising out of Your (i) breach of the confidentiality provisions set forth in this License, (ii) intentional misconduct with respect to this License or the Work, (iii) unauthorized use or distribution of the Work, and/or (iv) use of the Work to collect, send, and/or use personal data in violation of applicable privacy laws or regulations (including, without limitation, any applicable self-regulatory guidelines). + +(b) Except for (i) Claims by a third party arising out of Your intentional misconduct with respect to this License or the Work, including, without limitation, intentional violation of applicable privacy laws or regulations (including, without limitation, any applicable self-regulatory guidelines), and/or (ii) breach of any confidentiality obligation set forth herein, Your liability for defense and indemnity under this License will not exceed $10,000,000. + +(c) The indemnified entity may, at its sole discretion, elect for You to assume control of the defense of the Claim for which you are required to indemnify the indemnified entity and related Legal Entities under this Section 9. If the defense or settlement is assumed by You, the indemnified entity may at any time thereafter elect to appoint its own counsel (at its own expense); or the indemnified entity may take over control of the defense and settlement of such Claim. You will not settle any Claim without the indemnified entity’s prior written consent. + +10. Accepting Warranty or Additional Liability. While redistributing the Work, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of Licensor or any other Contributor, and only if You agree to indemnify, defend, and hold Licensor, each Contributor and their related Legal Entities harmless for any liability incurred by, or claims asserted against, such Licensor or Contributor or related Legal Entities by reason of your accepting any such warranty or additional liability. + +11. Termination. + +(a) In the event that You materially breach this License, You shall promptly stop using the Work and submit written notice of the material breach to Licensor using the contact information for Licensor identified on the Licensor Website. If the breach is curable, You may attempt to cure the breach within 30 days. If either (i) You are not able to cure the breach within 30 days to the reasonable satisfaction of Licensor or (ii) the breach is not curable, then this License shall immediately terminate and You must destroy all copies of the Work unless Licensor Approves a different resolution in writing. + +(b) If You commit a non-material breach of this License, You shall promptly provide written notice of the breach to Licensor using the contact information for Licensor identified on the Licensor Website and attempt to cure the non-material breach within 30 days. If You fail to cure the non-material breach within the 30 day period, this License shall terminate at the end of such 30 day period and You shall immediately stop using and destroy all copies of the Work unless Licensor Approves a different resolution in writing. + +(c) Termination of Your rights under this section does not terminate the licenses of parties who have received copies of the Work or rights from You under this License prior to that termination. + +12. Miscellaneous. This License will be binding upon, inure to the benefit of, and be enforceable by and against, the permitted successors and transferees of the parties; provided that any such successor and/or transferee agrees, and by downloading or using the Work agrees, like all other licensees of the Work, to be bound by the terms of this OM License. This License will be governed by, and construed in accordance with, the laws of the State of New York applicable to contracts executed in and to be performed entirely within that state, without reference to conflicts of laws provisions. The parties hereby agree that the exclusive venue for any disputes hereunder will be in the state and federal courts in the City of New York in the State of New York, and the parties waive any objection based on inconvenient forum and/or all other choice of forum issues. This License contains and constitutes the entire agreement among the parties with respect to the subject matter hereof and supersedes all prior negotiations, agreements and understandings of the parties, whether written or oral. If any term or provision of this License is determined to be invalid, illegal or incapable of being enforced by any rule of law, public policy or other reason, all other conditions and provisions of this License will nevertheless remain in full force and effect, and the invalid or unenforceable term or provision will be deemed replaced by a term or provision as determined by a court to be valid and enforceable to the maximum extent possible, and to express the intention of the parties with respect to the invalid or unenforceable term or provision. No failure or delay by any party in exercising any right, power or privilege under this License will operate as a waiver of such right, power or privilege unless such waiver is made in an instrument in writing signed on behalf of the waiving party. A single or partial exercise of any right, power or privilege will not preclude any other or further exercise of such right, power or privilege or the exercise of any other right, power or privilege. The rights and remedies provided in this License will be cumulative and not exclusive of any rights or remedies provided by law. The parties are independent contractors, and this License does not create an agency, partnership, joint venture, or other legal entity. There are no third-party beneficiaries to this License. diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeDirectory b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeDirectory new file mode 100644 index 0000000..ae2f52a Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeDirectory differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeRequirements b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeRequirements new file mode 100644 index 0000000..accf313 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeRequirements differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeRequirements-1 b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeRequirements-1 new file mode 100644 index 0000000..4c61808 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeRequirements-1 differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeResources b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeResources new file mode 100644 index 0000000..55e6fcc --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeResources @@ -0,0 +1,664 @@ + + + + + files + + ALConsentFlowATT.json + + B68lBq++BAY+jMXppPQMeodKf6Y= + + ALConsentFlowPrivacyPolicy.json + + enyHoRRZjqG0QtIreZ5uiMYon1w= + + ALConsentFlowPrivacyPolicyAndATT.json + + M1YfYt8Q3Tngv9OPVAIjkZXWZ9g= + + ALConsentFlowTermsOfServiceAndPrivacyPolicy.json + + Nno9A+Zy29yupWDRdQb4wo3vGhs= + + ALConsentFlowTermsOfServiceAndPrivacyPolicyAndATT.json + + vr86VwQ/b4cOzV27eqTu2wNioxY= + + ALConsentFlowUnifiedCMP.json + + 3pB6zSdaV+Z8cSBJ0rdpDjBeQ+s= + + ALDDetailTableViewCell.nib + + Zyi97C3fqF3nuoSWx0vZ2rlSrHs= + + ALDMultiAdViewController.storyboardc/3jf-B1-XNL-view-Iqa-CO-DFs.nib + + OUumxhxGK6JY0ouO409PaBcLlRo= + + ALDMultiAdViewController.storyboardc/ALDMultiAdViewController.nib + + YixE7Ily2Gx2iXBG2tTtK+vc4b0= + + ALDMultiAdViewController.storyboardc/Info.plist + + xijY85+UClEbMFNODNsBsfMLfPk= + + ALDRightDetailTableViewCell.nib + + lZuWY0s70xQfBKFvaZMzYdcQX4o= + + Assets.car + + HUNPz/aUoOxUjKaOxdzA0KaR5fw= + + Base.lproj/Localizable.strings + + 8pvUn0qQ2xTKSNX6tpyIHSqzp3E= + + MAHybridNativeAdView.nib + + vexfWf9Q6UU9GOyqEi/3MYhzNnc= + + MANativeAdBannerView.nib + + Zhnd0D190bTEci4hfkcvnjE5MiU= + + MANativeAdLeaderView.nib + + W8n09k/qe4GZ8GkuC1qxAxA+tf4= + + MANativeAdMRecView.nib + + t23bFlKJkY0k7rJd342cniG/SV8= + + MANativeAdMediaBannerView.nib + + 8h9oVqkvdECBLXJpt/XR2b4XKcQ= + + MANativeAdMediumTemplate1.nib + + JSPAJ+qqDHArQPPIRyt0a79Im7c= + + MANativeAdSmallTemplate1.nib + + g9B+CRz+6arjXe59t8i2fb35dbE= + + MANativeAdVerticalBannerView.nib + + aNr+7OqR/d0p1c7vc7M8Dx4BdQ4= + + MANativeAdVerticalLeaderView.nib + + mBmWf7kQLoneFqk/tfE7qhTXJus= + + MANativeAdVerticalMediaBannerView.nib + + 2kqq27Qoue4IF/+49Vd34PW7jo4= + + OMLICENSE + + Eq/AvBcL2+jfm6NHJidXNHfgAcM= + + de.lproj/Localizable.strings + + hash + + ohhHvMyMKZVhQHXV+J/usUwLslQ= + + optional + + + en.lproj/Localizable.strings + + hash + + 8pvUn0qQ2xTKSNX6tpyIHSqzp3E= + + optional + + + es.lproj/Localizable.strings + + hash + + J/x2Yz28jZFPsr0V02HiyGDDUpU= + + optional + + + fr.lproj/Localizable.strings + + hash + + aEyTBN1QDxMWNy8U0M4oObT1QDs= + + optional + + + ja.lproj/Localizable.strings + + hash + + RoOmq/+S/CtK1Gn53iWsCTGIHlA= + + optional + + + ko.lproj/Localizable.strings + + hash + + WdngiPQi12OfpuFcuaTOgVKtYAM= + + optional + + + mute.aiff + + xrLmOHGKRkA1PdlxjX8QdhUlYC8= + + omsdk-v1.4.12.js + + xFoo41tIvFKNNRq9NwW500wQtM8= + + zh-Hans.lproj/Localizable.strings + + hash + + sqX/YwkwsL3gUrf1zFkTDvstel8= + + optional + + + zh-Hant.lproj/Localizable.strings + + hash + + CMHCzbGGWkb1Mxtxi4jCK2Qb208= + + optional + + + + files2 + + ALConsentFlowATT.json + + hash + + B68lBq++BAY+jMXppPQMeodKf6Y= + + hash2 + + I8MC8PiNfLd6AniG/Eh/oN+UTAXcJtpbvta9wCZsxdo= + + + ALConsentFlowPrivacyPolicy.json + + hash + + enyHoRRZjqG0QtIreZ5uiMYon1w= + + hash2 + + LlaOA+a1j/MsNy6vusWOguLrCvK1PAEGAI5QrR2ZeUM= + + + ALConsentFlowPrivacyPolicyAndATT.json + + hash + + M1YfYt8Q3Tngv9OPVAIjkZXWZ9g= + + hash2 + + 5+zqoKOk6gCeRTyqiyfRcI7V0dMF7qzXgE92rlqBUhY= + + + ALConsentFlowTermsOfServiceAndPrivacyPolicy.json + + hash + + Nno9A+Zy29yupWDRdQb4wo3vGhs= + + hash2 + + OsR3ZQjKEcpx6udatYTaipCgK/X8gGqenR0EQE+pzIw= + + + ALConsentFlowTermsOfServiceAndPrivacyPolicyAndATT.json + + hash + + vr86VwQ/b4cOzV27eqTu2wNioxY= + + hash2 + + KYvnbTHl9K8RsJQY3kxmuOT5HWME+C3Xpra9hypMYfU= + + + ALConsentFlowUnifiedCMP.json + + hash + + 3pB6zSdaV+Z8cSBJ0rdpDjBeQ+s= + + hash2 + + MAubWAHFLBEYGMvyipzwZAuZt/SFoln0bAupnAD3OWw= + + + ALDDetailTableViewCell.nib + + hash + + Zyi97C3fqF3nuoSWx0vZ2rlSrHs= + + hash2 + + /EVChlPRWKjxfidIl9fzkKchDQR4aM32ItYgVoFh+/0= + + + ALDMultiAdViewController.storyboardc/3jf-B1-XNL-view-Iqa-CO-DFs.nib + + hash + + OUumxhxGK6JY0ouO409PaBcLlRo= + + hash2 + + i/xncX/qwDYlEm1bKfIuQmJ7rHdsABZ5wVaMBcxtHIM= + + + ALDMultiAdViewController.storyboardc/ALDMultiAdViewController.nib + + hash + + YixE7Ily2Gx2iXBG2tTtK+vc4b0= + + hash2 + + D5JyDD9lMoo0k4f5RMLH4evZS19nW5bwb6/EHv345QQ= + + + ALDMultiAdViewController.storyboardc/Info.plist + + hash + + xijY85+UClEbMFNODNsBsfMLfPk= + + hash2 + + rkcLG/PDdYWwCEmB6Nq/+enWbY+G4PCOQyMEkOP6KA4= + + + ALDRightDetailTableViewCell.nib + + hash + + lZuWY0s70xQfBKFvaZMzYdcQX4o= + + hash2 + + 7YB/bsKG4F6uX4tFdcPNd9fySYlm3PrUD94v+mtdhDQ= + + + Assets.car + + hash + + HUNPz/aUoOxUjKaOxdzA0KaR5fw= + + hash2 + + zjUTk7uO085wGMJpYlIPqGAeZuaLPBw3e4eCk80BBSc= + + + Base.lproj/Localizable.strings + + hash + + 8pvUn0qQ2xTKSNX6tpyIHSqzp3E= + + hash2 + + Z8ITLLftSgpbuRES/hELT2qso0qJnZPP/IwSB+xepnY= + + + MAHybridNativeAdView.nib + + hash + + vexfWf9Q6UU9GOyqEi/3MYhzNnc= + + hash2 + + zUF32N+bD2EFU0zlDYGGKapPU/6hdVV0RuNyD5FYthQ= + + + MANativeAdBannerView.nib + + hash + + Zhnd0D190bTEci4hfkcvnjE5MiU= + + hash2 + + Tl40iZ+gr5SSfJJjyjZ8vIUIjg/f+ktG7DETNL/9Q90= + + + MANativeAdLeaderView.nib + + hash + + W8n09k/qe4GZ8GkuC1qxAxA+tf4= + + hash2 + + GDub5EvXqMBUEFPQ7Uc2SaZJvorKjkE2egjcKDJtATM= + + + MANativeAdMRecView.nib + + hash + + t23bFlKJkY0k7rJd342cniG/SV8= + + hash2 + + vXrtRZ54Xm8zbugCXm/X0Y06baI4A4zH7qlPP4pzaz4= + + + MANativeAdMediaBannerView.nib + + hash + + 8h9oVqkvdECBLXJpt/XR2b4XKcQ= + + hash2 + + 5as5tn265qeA8rm0pCgrn/LZoJpb/o/xhEmCk1ozH7I= + + + MANativeAdMediumTemplate1.nib + + hash + + JSPAJ+qqDHArQPPIRyt0a79Im7c= + + hash2 + + OJ+RQWr2V+mfqe2CDPIsysgLxic/qCDIlOyf0ZVUXSI= + + + MANativeAdSmallTemplate1.nib + + hash + + g9B+CRz+6arjXe59t8i2fb35dbE= + + hash2 + + orSAEKNkPyklTYnt+XruYp6/o8LM0Y5hzmQwem9/azY= + + + MANativeAdVerticalBannerView.nib + + hash + + aNr+7OqR/d0p1c7vc7M8Dx4BdQ4= + + hash2 + + CrdSvA0VRiq+S60kSX+ul6PYOQmmncVWv5JBJ3scHAM= + + + MANativeAdVerticalLeaderView.nib + + hash + + mBmWf7kQLoneFqk/tfE7qhTXJus= + + hash2 + + PncOt36cfdnk/hiJtD4V2n9pO9gmA+Aqz6nPeSGdXWI= + + + MANativeAdVerticalMediaBannerView.nib + + hash + + 2kqq27Qoue4IF/+49Vd34PW7jo4= + + hash2 + + gyn0OWDTtypL9j49DgJuDsJpRfMj2+J/udh1pdlKfDY= + + + OMLICENSE + + hash + + Eq/AvBcL2+jfm6NHJidXNHfgAcM= + + hash2 + + YeXJiTAU447VjJbPUiB4yoLGGli+nQlwWl1J5cZT9+I= + + + de.lproj/Localizable.strings + + hash + + ohhHvMyMKZVhQHXV+J/usUwLslQ= + + hash2 + + q7DF4q+ybW1RG3Dt0vXBU51stk4yMWw1CwPDLHzQ3vY= + + optional + + + en.lproj/Localizable.strings + + hash + + 8pvUn0qQ2xTKSNX6tpyIHSqzp3E= + + hash2 + + Z8ITLLftSgpbuRES/hELT2qso0qJnZPP/IwSB+xepnY= + + optional + + + es.lproj/Localizable.strings + + hash + + J/x2Yz28jZFPsr0V02HiyGDDUpU= + + hash2 + + 5Flxn1RDNNY9K8n94H2Arw4hpvDyWjeUst4ogy6OaO0= + + optional + + + fr.lproj/Localizable.strings + + hash + + aEyTBN1QDxMWNy8U0M4oObT1QDs= + + hash2 + + ygKi1mBC+D8Tz2AelBIheQ0gIXEg8VJz61Bg00Yw5KY= + + optional + + + ja.lproj/Localizable.strings + + hash + + RoOmq/+S/CtK1Gn53iWsCTGIHlA= + + hash2 + + gyRb43WpJIbzYPifWcQ5USW42H3WbU0izJEwsOJKnBU= + + optional + + + ko.lproj/Localizable.strings + + hash + + WdngiPQi12OfpuFcuaTOgVKtYAM= + + hash2 + + umtilSrgw0YG3Tw8EYLcwrNsa5gWJXGO6RdxUS0O02I= + + optional + + + mute.aiff + + hash + + xrLmOHGKRkA1PdlxjX8QdhUlYC8= + + hash2 + + WUTtOynoFPERt7tbMpqwDPv3YX9EfZjQDLz1X3hRVww= + + + omsdk-v1.4.12.js + + hash + + xFoo41tIvFKNNRq9NwW500wQtM8= + + hash2 + + iWz5BbK1YoGNpY4Z4ltSUIPxhjj2ubDXxq6kEamQdYU= + + + zh-Hans.lproj/Localizable.strings + + hash + + sqX/YwkwsL3gUrf1zFkTDvstel8= + + hash2 + + NSLXnZpRgGv4o+wwveW/Xf+RV1mBebHIT8Be6Sh7LU0= + + optional + + + zh-Hant.lproj/Localizable.strings + + hash + + CMHCzbGGWkb1Mxtxi4jCK2Qb208= + + hash2 + + RLMKQwwVnkKqjDHsmSFDugq6aF2Fk8GONR12ATDMky4= + + optional + + + + rules + + ^.* + + ^.*\.lproj/ + + optional + + weight + 1000 + + ^.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Base\.lproj/ + + weight + 1010 + + ^version.plist$ + + + rules2 + + .*\.dSYM($|/) + + weight + 11 + + ^(.*/)?\.DS_Store$ + + omit + + weight + 2000 + + ^.* + + ^.*\.lproj/ + + optional + + weight + 1000 + + ^.*\.lproj/locversion.plist$ + + omit + + weight + 1100 + + ^Base\.lproj/ + + weight + 1010 + + ^Info\.plist$ + + omit + + weight + 20 + + ^PkgInfo$ + + omit + + weight + 20 + + ^embedded\.provisionprofile$ + + weight + 20 + + ^version\.plist$ + + weight + 20 + + + + diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeSignature b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeSignature new file mode 100644 index 0000000..04c47c5 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/_CodeSignature/CodeSignature differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/de.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/de.lproj/Localizable.strings new file mode 100644 index 0000000..eb74178 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/de.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/en.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/en.lproj/Localizable.strings new file mode 100644 index 0000000..2b6dce4 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/en.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/es.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/es.lproj/Localizable.strings new file mode 100644 index 0000000..4e979c8 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/es.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/fr.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/fr.lproj/Localizable.strings new file mode 100644 index 0000000..fbc42f4 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/fr.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ja.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ja.lproj/Localizable.strings new file mode 100644 index 0000000..e361696 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ja.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ko.lproj/Localizable.strings b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ko.lproj/Localizable.strings new file mode 100644 index 0000000..d116154 Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/ko.lproj/Localizable.strings differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/mute.aiff b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/mute.aiff new file mode 100644 index 0000000..c968a3c Binary files /dev/null and b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/mute.aiff differ diff --git a/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/omsdk-v1.4.12.js b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/omsdk-v1.4.12.js new file mode 100644 index 0000000..a3faac7 --- /dev/null +++ b/Pods/AppLovinSDK/applovin-ios-sdk-12.5.0/AppLovinSDK.xcframework/ios-arm64/AppLovinSDK.framework/AppLovinSDKResources.bundle/omsdk-v1.4.12.js @@ -0,0 +1,87 @@ +;(function(omidGlobal) { + var m;function aa(a){var b=0;return function(){return b>>0)+'_',e=0;return b}); +u('Symbol.iterator',function(a){if(a)return a;a=Symbol('Symbol.iterator');for(var b='Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' '),c=0;cc&&(c=Math.max(c+e,0));cMath.abs(f-c))||(f=b.x,f=f>e||.01>Math.abs(f-e));(e=f)||(e=b.endY,e=eMath.abs(e-d));(d=e)||(b=b.y,d=b>a||.01>Math.abs(b-a));b=!d}return b}function K(a,b){for(var c=!1,d=0;dh&&H.yt){y=!0;break}}y&&(f+=Math.round(l)*Math.round(C))}}return c.call(b,0,d-f)};function Ga(){};function Ha(){} +function Ia(a,b,c,d,e){var f=new J;b=new A(b,!1);Aa(f,b);Ja(a,b,f,d);if(!e)return f.i=['unmeasurable'],f.s=void 0,f.A=0,f.j=[],f.g&&(a=f.g,c={},a=new A((c.x=0,c.y=0,c.width=a.width,c.height=a.height,c),a.g),f.g=a),f.h=Ba(),f;b.noOutputDevice&&(K(f,'backgrounded'),K(f,'noOutputDevice'));if('backgrounded'===c)K(f,'backgrounded');else if(void 0!==f.g){for(a=0;ad.time&&(d=b[e]);c=d;a.j=Kb(c.rootBounds);a.g=Kb(c.boundingClientRect);a.C=Kb(c.intersectionRect);a.N=!!c.isIntersecting;Bb(a)}}catch(f){a.A(),bb(a.L,'generic','Problem handling IntersectionObserver callback: '+f.message)}},{root:null,rootMargin:'0px',threshold:[0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1]})} +function Jb(a){a.m.ResizeObserver?a.u||(a.u=Lb(a,function(){return Mb(a)}),a.u.observe(a.h)):(a.v||(a.v=function(){return Mb(a)},(0,a.m.addEventListener)('resize',a.v)),a.s||(a.s=new MutationObserver(function(){return Mb(a)}),a.s.observe(a.h,{childList:!1,attributes:!0,subtree:!1})))}function Mb(a){a.h&&!Ib(a.h)&&(Hb(a),Fb(a))}function Lb(a,b){return new a.m.ResizeObserver(b)}function Kb(a){if(a&&null!==a.x&&null!==a.y&&null!==a.width&&null!==a.height)return new A(a,!1)};function Ob(a,b){this.h=a;this.g=b};function Pb(){return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(a){var b=16*Math.random()|0;return'y'===a?(b&3|8).toString(16):b.toString(16)})};function Qb(a,b){var c=void 0===c?L:c;this.j=a;this.g=c;this.i=b;this.h=[]} +function Rb(a){if(!a.g||!a.g.document)throw Error('OMID Service Script is not running within a window.');var b=a.h;a.h=[];b.forEach(function(c){try{var d=a.i.I?'limited':'full',e=R(c.accessMode,qa)?c.accessMode:null;var f=e?'full'==e&&'limited'==d?d:'domain'==e?'limited':e:d;c.accessMode=f;a:{var k=c.resourceUrl,g=a.g.location.origin;try{var h=new URL(k,g);break a}catch(G){}try{h=new URL(k);break a}catch(G){}h=null}if(d=h){var l=Pb(),n=a.g.document,t=n.createElement('iframe');t.id='omid-verification-script-frame-'+ +l;t.style.display='none';['full','limited'].includes(f)?t.srcdoc="\n