commit 860d87f44648143020b3e93038d162ebe081caa5 Author: Deniz Duezgoeren Date: Tue Jul 9 19:39:06 2019 +0200 Initial commit; substitutions can be reviewed, no further functionality implemented yet diff --git a/AvH Plan.xcodeproj/project.pbxproj b/AvH Plan.xcodeproj/project.pbxproj new file mode 100644 index 0000000..113a81a --- /dev/null +++ b/AvH Plan.xcodeproj/project.pbxproj @@ -0,0 +1,742 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 1BF3A6CA97BA41C38482C1A6 /* Pods_AvH_PlanTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D9D6269E96544A9242A29611 /* Pods_AvH_PlanTests.framework */; }; + 2E65263AFD35D6B542E89AE4 /* Pods_AvH_Plan.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7605BB0678C9E27A1D3E9DAA /* Pods_AvH_Plan.framework */; }; + A96133802299867400B541D4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A961337F2299867400B541D4 /* AppDelegate.swift */; }; + A96133822299867400B541D4 /* FirstViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133812299867400B541D4 /* FirstViewController.swift */; }; + A96133842299867400B541D4 /* SecondViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133832299867400B541D4 /* SecondViewController.swift */; }; + A96133872299867400B541D4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A96133852299867400B541D4 /* Main.storyboard */; }; + A96133892299867A00B541D4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A96133882299867A00B541D4 /* Assets.xcassets */; }; + A961338C2299867A00B541D4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A961338A2299867A00B541D4 /* LaunchScreen.storyboard */; }; + A96133972299867A00B541D4 /* AvH_PlanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133962299867A00B541D4 /* AvH_PlanTests.swift */; }; + A96133A22299867A00B541D4 /* AvH_PlanUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133A12299867A00B541D4 /* AvH_PlanUITests.swift */; }; + A96133B0229986DF00B541D4 /* CollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = A96133AF229986DF00B541D4 /* CollectionViewCell.swift */; }; + A9A3496C22D4859200F35AE0 /* SubstModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9A3496B22D4859200F35AE0 /* SubstModel.swift */; }; + C736A19A44C64423F3A695B7 /* Pods_AvH_PlanUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 74EDE3D8134812AB76BEB988 /* Pods_AvH_PlanUITests.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + A96133932299867A00B541D4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A96133742299867300B541D4 /* Project object */; + proxyType = 1; + remoteGlobalIDString = A961337B2299867300B541D4; + remoteInfo = "AvH Plan"; + }; + A961339E2299867A00B541D4 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A96133742299867300B541D4 /* Project object */; + proxyType = 1; + remoteGlobalIDString = A961337B2299867300B541D4; + remoteInfo = "AvH Plan"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 589FBD2CE6A9C73CD9B81441 /* Pods-AvH PlanUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanUITests.release.xcconfig"; path = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.release.xcconfig"; sourceTree = ""; }; + 74EDE3D8134812AB76BEB988 /* Pods_AvH_PlanUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AvH_PlanUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 7605BB0678C9E27A1D3E9DAA /* Pods_AvH_Plan.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AvH_Plan.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A961337C2299867400B541D4 /* AvH Plan.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "AvH Plan.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + A961337F2299867400B541D4 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + A96133812299867400B541D4 /* FirstViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FirstViewController.swift; sourceTree = ""; }; + A96133832299867400B541D4 /* SecondViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecondViewController.swift; sourceTree = ""; }; + A96133862299867400B541D4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + A96133882299867A00B541D4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + A961338B2299867A00B541D4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + A961338D2299867A00B541D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A96133922299867A00B541D4 /* AvH PlanTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AvH PlanTests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + A96133962299867A00B541D4 /* AvH_PlanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvH_PlanTests.swift; sourceTree = ""; }; + A96133982299867A00B541D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A961339D2299867A00B541D4 /* AvH PlanUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = "AvH PlanUITests.xctest"; sourceTree = BUILT_PRODUCTS_DIR; }; + A96133A12299867A00B541D4 /* AvH_PlanUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AvH_PlanUITests.swift; sourceTree = ""; }; + A96133A32299867A00B541D4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A96133AF229986DF00B541D4 /* CollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionViewCell.swift; sourceTree = ""; }; + A9A3496B22D4859200F35AE0 /* SubstModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SubstModel.swift; sourceTree = ""; }; + C6EC6ACE7893F2BB0A157817 /* Pods-AvH Plan.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH Plan.release.xcconfig"; path = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan.release.xcconfig"; sourceTree = ""; }; + D9D6269E96544A9242A29611 /* Pods_AvH_PlanTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AvH_PlanTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + E596AED9E99670CBF1B6F49E /* Pods-AvH Plan.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH Plan.debug.xcconfig"; path = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan.debug.xcconfig"; sourceTree = ""; }; + F0769608C3BBAAEBCCA008F6 /* Pods-AvH PlanTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanTests.debug.xcconfig"; path = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.debug.xcconfig"; sourceTree = ""; }; + F0FCFF5036EBDC7E5902C52D /* Pods-AvH PlanTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanTests.release.xcconfig"; path = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.release.xcconfig"; sourceTree = ""; }; + F8A7FDE248283EAE3C45555A /* Pods-AvH PlanUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AvH PlanUITests.debug.xcconfig"; path = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.debug.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + A96133792299867300B541D4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2E65263AFD35D6B542E89AE4 /* Pods_AvH_Plan.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A961338F2299867A00B541D4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 1BF3A6CA97BA41C38482C1A6 /* Pods_AvH_PlanTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A961339A2299867A00B541D4 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C736A19A44C64423F3A695B7 /* Pods_AvH_PlanUITests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0FCE2FEB0B034FB375960A54 /* Pods */ = { + isa = PBXGroup; + children = ( + E596AED9E99670CBF1B6F49E /* Pods-AvH Plan.debug.xcconfig */, + C6EC6ACE7893F2BB0A157817 /* Pods-AvH Plan.release.xcconfig */, + F0769608C3BBAAEBCCA008F6 /* Pods-AvH PlanTests.debug.xcconfig */, + F0FCFF5036EBDC7E5902C52D /* Pods-AvH PlanTests.release.xcconfig */, + F8A7FDE248283EAE3C45555A /* Pods-AvH PlanUITests.debug.xcconfig */, + 589FBD2CE6A9C73CD9B81441 /* Pods-AvH PlanUITests.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + A7F8C8C9CE4E171D98EE659D /* Frameworks */ = { + isa = PBXGroup; + children = ( + 7605BB0678C9E27A1D3E9DAA /* Pods_AvH_Plan.framework */, + D9D6269E96544A9242A29611 /* Pods_AvH_PlanTests.framework */, + 74EDE3D8134812AB76BEB988 /* Pods_AvH_PlanUITests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + A96133732299867300B541D4 = { + isa = PBXGroup; + children = ( + A961337E2299867400B541D4 /* AvH Plan */, + A96133952299867A00B541D4 /* AvH PlanTests */, + A96133A02299867A00B541D4 /* AvH PlanUITests */, + A961337D2299867400B541D4 /* Products */, + 0FCE2FEB0B034FB375960A54 /* Pods */, + A7F8C8C9CE4E171D98EE659D /* Frameworks */, + ); + sourceTree = ""; + }; + A961337D2299867400B541D4 /* Products */ = { + isa = PBXGroup; + children = ( + A961337C2299867400B541D4 /* AvH Plan.app */, + A96133922299867A00B541D4 /* AvH PlanTests.xctest */, + A961339D2299867A00B541D4 /* AvH PlanUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + A961337E2299867400B541D4 /* AvH Plan */ = { + isa = PBXGroup; + children = ( + A961337F2299867400B541D4 /* AppDelegate.swift */, + A96133812299867400B541D4 /* FirstViewController.swift */, + A9A3496B22D4859200F35AE0 /* SubstModel.swift */, + A96133832299867400B541D4 /* SecondViewController.swift */, + A96133852299867400B541D4 /* Main.storyboard */, + A96133882299867A00B541D4 /* Assets.xcassets */, + A961338A2299867A00B541D4 /* LaunchScreen.storyboard */, + A961338D2299867A00B541D4 /* Info.plist */, + A96133AF229986DF00B541D4 /* CollectionViewCell.swift */, + ); + path = "AvH Plan"; + sourceTree = ""; + }; + A96133952299867A00B541D4 /* AvH PlanTests */ = { + isa = PBXGroup; + children = ( + A96133962299867A00B541D4 /* AvH_PlanTests.swift */, + A96133982299867A00B541D4 /* Info.plist */, + ); + path = "AvH PlanTests"; + sourceTree = ""; + }; + A96133A02299867A00B541D4 /* AvH PlanUITests */ = { + isa = PBXGroup; + children = ( + A96133A12299867A00B541D4 /* AvH_PlanUITests.swift */, + A96133A32299867A00B541D4 /* Info.plist */, + ); + path = "AvH PlanUITests"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A961337B2299867300B541D4 /* AvH Plan */ = { + isa = PBXNativeTarget; + buildConfigurationList = A96133A62299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH Plan" */; + buildPhases = ( + BD3857CC61F238E4A90FF1BA /* [CP] Check Pods Manifest.lock */, + A96133782299867300B541D4 /* Sources */, + A96133792299867300B541D4 /* Frameworks */, + A961337A2299867300B541D4 /* Resources */, + D4638A8231BADABB6CD590D7 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "AvH Plan"; + productName = "AvH Plan"; + productReference = A961337C2299867400B541D4 /* AvH Plan.app */; + productType = "com.apple.product-type.application"; + }; + A96133912299867A00B541D4 /* AvH PlanTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A96133A92299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanTests" */; + buildPhases = ( + 65F085C1A4E8355ADC705123 /* [CP] Check Pods Manifest.lock */, + A961338E2299867A00B541D4 /* Sources */, + A961338F2299867A00B541D4 /* Frameworks */, + A96133902299867A00B541D4 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A96133942299867A00B541D4 /* PBXTargetDependency */, + ); + name = "AvH PlanTests"; + productName = "AvH PlanTests"; + productReference = A96133922299867A00B541D4 /* AvH PlanTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + A961339C2299867A00B541D4 /* AvH PlanUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A96133AC2299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanUITests" */; + buildPhases = ( + 68D555593A47B6FCAD9D4C33 /* [CP] Check Pods Manifest.lock */, + A96133992299867A00B541D4 /* Sources */, + A961339A2299867A00B541D4 /* Frameworks */, + A961339B2299867A00B541D4 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A961339F2299867A00B541D4 /* PBXTargetDependency */, + ); + name = "AvH PlanUITests"; + productName = "AvH PlanUITests"; + productReference = A961339D2299867A00B541D4 /* AvH PlanUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A96133742299867300B541D4 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1020; + LastUpgradeCheck = 1020; + ORGANIZATIONNAME = "Deniz Duezgoeren"; + TargetAttributes = { + A961337B2299867300B541D4 = { + CreatedOnToolsVersion = 10.2; + }; + A96133912299867A00B541D4 = { + CreatedOnToolsVersion = 10.2; + TestTargetID = A961337B2299867300B541D4; + }; + A961339C2299867A00B541D4 = { + CreatedOnToolsVersion = 10.2; + TestTargetID = A961337B2299867300B541D4; + }; + }; + }; + buildConfigurationList = A96133772299867300B541D4 /* Build configuration list for PBXProject "AvH Plan" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = A96133732299867300B541D4; + productRefGroup = A961337D2299867400B541D4 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A961337B2299867300B541D4 /* AvH Plan */, + A96133912299867A00B541D4 /* AvH PlanTests */, + A961339C2299867A00B541D4 /* AvH PlanUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + A961337A2299867300B541D4 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A961338C2299867A00B541D4 /* LaunchScreen.storyboard in Resources */, + A96133892299867A00B541D4 /* Assets.xcassets in Resources */, + A96133872299867400B541D4 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A96133902299867A00B541D4 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A961339B2299867A00B541D4 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 65F085C1A4E8355ADC705123 /* [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-AvH PlanTests-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; + }; + 68D555593A47B6FCAD9D4C33 /* [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-AvH PlanUITests-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; + }; + BD3857CC61F238E4A90FF1BA /* [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-AvH Plan-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; + }; + D4638A8231BADABB6CD590D7 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework", + "${BUILT_PRODUCTS_DIR}/Kanna/Kanna.framework", + "${BUILT_PRODUCTS_DIR}/SwiftSoup/SwiftSoup.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + ); + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Alamofire.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/Kanna.framework", + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/SwiftSoup.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A96133782299867300B541D4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A96133842299867400B541D4 /* SecondViewController.swift in Sources */, + A96133802299867400B541D4 /* AppDelegate.swift in Sources */, + A9A3496C22D4859200F35AE0 /* SubstModel.swift in Sources */, + A96133B0229986DF00B541D4 /* CollectionViewCell.swift in Sources */, + A96133822299867400B541D4 /* FirstViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A961338E2299867A00B541D4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A96133972299867A00B541D4 /* AvH_PlanTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A96133992299867A00B541D4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A96133A22299867A00B541D4 /* AvH_PlanUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + A96133942299867A00B541D4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A961337B2299867300B541D4 /* AvH Plan */; + targetProxy = A96133932299867A00B541D4 /* PBXContainerItemProxy */; + }; + A961339F2299867A00B541D4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A961337B2299867300B541D4 /* AvH Plan */; + targetProxy = A961339E2299867A00B541D4 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + A96133852299867400B541D4 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + A96133862299867400B541D4 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + A961338A2299867A00B541D4 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + A961338B2299867A00B541D4 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + A96133A42299867A00B541D4 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A96133A52299867A00B541D4 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + A96133A72299867A00B541D4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = E596AED9E99670CBF1B6F49E /* Pods-AvH Plan.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = "AvH Plan/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-Plan"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + A96133A82299867A00B541D4 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C6EC6ACE7893F2BB0A157817 /* Pods-AvH Plan.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = "AvH Plan/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-Plan"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + A96133AA2299867A00B541D4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F0769608C3BBAAEBCCA008F6 /* Pods-AvH PlanTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = "AvH PlanTests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AvH Plan.app/AvH Plan"; + }; + name = Debug; + }; + A96133AB2299867A00B541D4 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F0FCFF5036EBDC7E5902C52D /* Pods-AvH PlanTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = "AvH PlanTests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanTests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AvH Plan.app/AvH Plan"; + }; + name = Release; + }; + A96133AD2299867A00B541D4 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F8A7FDE248283EAE3C45555A /* Pods-AvH PlanUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = "AvH PlanUITests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanUITests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = "AvH Plan"; + }; + name = Debug; + }; + A96133AE2299867A00B541D4 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 589FBD2CE6A9C73CD9B81441 /* Pods-AvH PlanUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = "AvH PlanUITests/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = "denizd.AvH-PlanUITests"; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = "AvH Plan"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A96133772299867300B541D4 /* Build configuration list for PBXProject "AvH Plan" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A96133A42299867A00B541D4 /* Debug */, + A96133A52299867A00B541D4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A96133A62299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH Plan" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A96133A72299867A00B541D4 /* Debug */, + A96133A82299867A00B541D4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A96133A92299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A96133AA2299867A00B541D4 /* Debug */, + A96133AB2299867A00B541D4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A96133AC2299867A00B541D4 /* Build configuration list for PBXNativeTarget "AvH PlanUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A96133AD2299867A00B541D4 /* Debug */, + A96133AE2299867A00B541D4 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = A96133742299867300B541D4 /* Project object */; +} diff --git a/AvH Plan.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/AvH Plan.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..20c0a54 --- /dev/null +++ b/AvH Plan.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/AvH Plan.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/AvH Plan.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/AvH Plan.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/AvH Plan.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/xcschememanagement.plist b/AvH Plan.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..1e25031 --- /dev/null +++ b/AvH Plan.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + AvH Plan.xcscheme_^#shared#^_ + + orderHint + 6 + + + + diff --git a/AvH Plan.xcworkspace/contents.xcworkspacedata b/AvH Plan.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..9634b7f --- /dev/null +++ b/AvH Plan.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/AvH Plan.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/AvH Plan.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/AvH Plan.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/AvH Plan.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/AvH Plan.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..0c67376 --- /dev/null +++ b/AvH Plan.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,5 @@ + + + + + diff --git a/AvH Plan.xcworkspace/xcuserdata/kduez.xcuserdatad/WorkspaceSettings.xcsettings b/AvH Plan.xcworkspace/xcuserdata/kduez.xcuserdatad/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f25782d --- /dev/null +++ b/AvH Plan.xcworkspace/xcuserdata/kduez.xcuserdatad/WorkspaceSettings.xcsettings @@ -0,0 +1,18 @@ + + + + + BuildLocationStyle + UseAppPreferences + CustomBuildLocationType + RelativeToDerivedData + DerivedDataLocationStyle + Default + EnabledFullIndexStoreVisibility + + IssueFilterStyle + ShowActiveSchemeOnly + LiveSourceIssuesEnabled + + + diff --git a/AvH Plan.xcworkspace/xcuserdata/kduez.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/AvH Plan.xcworkspace/xcuserdata/kduez.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..ed9a9b4 --- /dev/null +++ b/AvH Plan.xcworkspace/xcuserdata/kduez.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,5 @@ + + + diff --git a/AvH Plan/AppDelegate.swift b/AvH Plan/AppDelegate.swift new file mode 100644 index 0000000..275d71e --- /dev/null +++ b/AvH Plan/AppDelegate.swift @@ -0,0 +1,46 @@ +// +// AppDelegate.swift +// AvH Plan +// +// Created by Deniz Duezgoeren on 25.05.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/AvH Plan/Assets.xcassets/AppIcon.appiconset/Contents.json b/AvH Plan/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d8db8d6 --- /dev/null +++ b/AvH Plan/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + }, + { + "idiom" : "ios-marketing", + "size" : "1024x1024", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/AvH Plan/Assets.xcassets/Contents.json b/AvH Plan/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/AvH Plan/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/AvH Plan/Assets.xcassets/first.imageset/Contents.json b/AvH Plan/Assets.xcassets/first.imageset/Contents.json new file mode 100644 index 0000000..33a7451 --- /dev/null +++ b/AvH Plan/Assets.xcassets/first.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "first.pdf" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/AvH Plan/Assets.xcassets/first.imageset/first.pdf b/AvH Plan/Assets.xcassets/first.imageset/first.pdf new file mode 100644 index 0000000..47d911d Binary files /dev/null and b/AvH Plan/Assets.xcassets/first.imageset/first.pdf differ diff --git a/AvH Plan/Assets.xcassets/second.imageset/Contents.json b/AvH Plan/Assets.xcassets/second.imageset/Contents.json new file mode 100644 index 0000000..03bd9c9 --- /dev/null +++ b/AvH Plan/Assets.xcassets/second.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "second.pdf" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/AvH Plan/Assets.xcassets/second.imageset/second.pdf b/AvH Plan/Assets.xcassets/second.imageset/second.pdf new file mode 100644 index 0000000..401614e Binary files /dev/null and b/AvH Plan/Assets.xcassets/second.imageset/second.pdf differ diff --git a/AvH Plan/Base.lproj/LaunchScreen.storyboard b/AvH Plan/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..bfa3612 --- /dev/null +++ b/AvH Plan/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AvH Plan/Base.lproj/Main.storyboard b/AvH Plan/Base.lproj/Main.storyboard new file mode 100644 index 0000000..8c5c7b7 --- /dev/null +++ b/AvH Plan/Base.lproj/Main.storyboard @@ -0,0 +1,211 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AvH Plan/CollectionViewCell.swift b/AvH Plan/CollectionViewCell.swift new file mode 100644 index 0000000..316bc3b --- /dev/null +++ b/AvH Plan/CollectionViewCell.swift @@ -0,0 +1,19 @@ +// +// CollectionViewCell.swift +// AvH Plan +// +// Created by Deniz Duezgoeren on 25.05.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import UIKit + +class CollectionViewCell: UICollectionViewCell { + @IBOutlet weak var group: UILabel! + @IBOutlet weak var course: UILabel! + @IBOutlet weak var additional: UILabel! + @IBOutlet weak var date: UILabel! + @IBOutlet weak var time: UILabel! + @IBOutlet weak var room: UILabel! + @IBOutlet weak var tintView: UIView! +} diff --git a/AvH Plan/FirstViewController.swift b/AvH Plan/FirstViewController.swift new file mode 100644 index 0000000..13d0bc9 --- /dev/null +++ b/AvH Plan/FirstViewController.swift @@ -0,0 +1,168 @@ +// +// FirstViewController.swift +// AvH Plan +// +// Created by Deniz Duezgoeren on 25.05.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import UIKit +import SwiftSoup +import Alamofire +import SQLite3 + +class FirstViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { + + let reuseIdentifier = "cell" + @IBOutlet weak var collectionView: UICollectionView! + let queue = DispatchQueue(label: "work-queue") + var group: Array = Array() + var course: Array = Array() + var additional: Array = Array() + var date: Array = Array() + var time: Array = Array() + var room: Array = Array() + private let refreshControl = UIRefreshControl() + var db: OpaquePointer? + + override func viewWillAppear(_ animated: Bool) { + super.viewWillAppear(animated) + if #available(iOS 10.0, *) { + collectionView.refreshControl = refreshControl + } else { + collectionView.addSubview(refreshControl) + } + refreshControl.addTarget(self, action: #selector(objDoAsync(_:)), for: .valueChanged) + refreshControl.tintColor = UIColor(red: 0.39, green: 0.71, blue: 0.96, alpha: 1.0) + refreshControl.attributedTitle = NSAttributedString(string: "Fetching the plan...") + self.refreshControl.beginRefreshing() + self.doAsync() + } + + @objc private func objDoAsync(_ sender: Any) { + self.doAsync() + } + + override func viewDidLoad() { + super.viewDidLoad() + + collectionView.backgroundColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0) + +// let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout +// layout.itemSize = CGSize(width: view.frame.size.width, height: 129) + +// let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) +// .appendingPathComponent("SubstDB.sqlite") +// +// if (sqlite3_open(fileURL.path, &db) != SQLITE_OK) { +// print("Error opening database connection") +// } +// sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS subst_table (id INTEGER PRIMARY KEY AUTOINCREMENT, group TEXT, course TEXT, add TEXT, date TEXT, time TEXT, room TEXT)", nil, nil, nil) + } + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return self.group.count + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! CollectionViewCell + if self.group.count != 0 { + cell.group.text = self.group[indexPath.item] + cell.course.text = self.course[indexPath.item] + cell.additional.text = self.additional[indexPath.item] + cell.date.text = self.date[indexPath.item] + cell.time.text = self.time[indexPath.item] + cell.room.text = self.room[indexPath.item] + } +// cell.backgroundColor = UIColor(red: 0.39, green: 0.71, blue: 0.96, alpha: 1.0) + cell.backgroundColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) + cell.tintView.backgroundColor = cell.backgroundColor + return cell + } + + func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { + print("You selected cell#\(indexPath.item)!") + } + + func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { + return CGSize(width: view.frame.size.width, height: 108) + } + + func doAsync() { + queue.async { + let url = "https://djd4rkn355.github.io/subst_test.html" + Alamofire.request(url).responseString { response in + if let html = response.result.value { + self.parseHTML(html: html) + } + } + + } + } + + func insertInDb() { + +// let insertString = "INSERT INTO subst_table VALUES (?, ?, ?, ?, ?, ?)" +// +// if (sqlite3_prepare_v2(db, insertString, nil, nil, nil) != SQLITE_OK) { +// print("error db") +// } +// if ( + } + + func parseHTML(html: String) { + do { + let doc: Document = try SwiftSoup.parse(html) + let rows: Elements = try doc.select("tr") + + self.group.removeAll() + self.date.removeAll() + self.time.removeAll() + self.course.removeAll() + self.room.removeAll() + self.additional.removeAll() + + var group: String + var date: String + var time: String + var course: String + var room: String + var add: String + +// sqlite3_exec(db, "DELETE FROM subst_table", nil, nil, nil) + + for i in (0.. + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UIStatusBarTintParameters + + UINavigationBar + + Style + UIBarStyleDefault + Translucent + + + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/AvH Plan/SecondViewController.swift b/AvH Plan/SecondViewController.swift new file mode 100644 index 0000000..ff714a8 --- /dev/null +++ b/AvH Plan/SecondViewController.swift @@ -0,0 +1,20 @@ +// +// SecondViewController.swift +// AvH Plan +// +// Created by Deniz Duezgoeren on 25.05.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import UIKit + +class SecondViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view. + } + + +} + diff --git a/AvH Plan/SubstModel.swift b/AvH Plan/SubstModel.swift new file mode 100644 index 0000000..d564aec --- /dev/null +++ b/AvH Plan/SubstModel.swift @@ -0,0 +1,13 @@ +// +// SubstModel.swift +// AvH Plan +// +// Created by Deniz Duezgoeren on 09.07.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import Foundation + +class SubstModel { + +} diff --git a/AvH PlanTests/AvH_PlanTests.swift b/AvH PlanTests/AvH_PlanTests.swift new file mode 100644 index 0000000..f882192 --- /dev/null +++ b/AvH PlanTests/AvH_PlanTests.swift @@ -0,0 +1,34 @@ +// +// AvH_PlanTests.swift +// AvH PlanTests +// +// Created by Deniz Duezgoeren on 25.05.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import XCTest +@testable import AvH_Plan + +class AvH_PlanTests: XCTestCase { + + override func setUp() { + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testPerformanceExample() { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } + +} diff --git a/AvH PlanTests/Info.plist b/AvH PlanTests/Info.plist new file mode 100644 index 0000000..6c40a6c --- /dev/null +++ b/AvH PlanTests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/AvH PlanUITests/AvH_PlanUITests.swift b/AvH PlanUITests/AvH_PlanUITests.swift new file mode 100644 index 0000000..07a057c --- /dev/null +++ b/AvH PlanUITests/AvH_PlanUITests.swift @@ -0,0 +1,34 @@ +// +// AvH_PlanUITests.swift +// AvH PlanUITests +// +// Created by Deniz Duezgoeren on 25.05.19. +// Copyright © 2019 Deniz Duezgoeren. All rights reserved. +// + +import XCTest + +class AvH_PlanUITests: XCTestCase { + + override func setUp() { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. + XCUIApplication().launch() + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() { + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + +} diff --git a/AvH PlanUITests/Info.plist b/AvH PlanUITests/Info.plist new file mode 100644 index 0000000..6c40a6c --- /dev/null +++ b/AvH PlanUITests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..e9144b1 --- /dev/null +++ b/Podfile @@ -0,0 +1,23 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'AvH Plan' do + # Comment the next line if you're not using Swift and don't want to use dynamic frameworks + use_frameworks! + + # Pods for AvH Plan + pod 'SwiftSoup' + pod 'Kanna' + pod 'Alamofire' + + target 'AvH PlanTests' do + inherit! :search_paths + # Pods for testing + end + + target 'AvH PlanUITests' do + inherit! :search_paths + # Pods for testing + end + +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..2ade6aa --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (4.8.2) + - Kanna (5.0.0) + - SwiftSoup (1.7.4) + +DEPENDENCIES: + - Alamofire + - Kanna + - SwiftSoup + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Alamofire + - Kanna + - SwiftSoup + +SPEC CHECKSUMS: + Alamofire: ae5c501addb7afdbb13687d7f2f722c78734c2d3 + Kanna: a32875df62975f8f4b871e933b4ea1a5c3b8be0f + SwiftSoup: 92f5b348c131aed8af04f4326db1579ab19fa08c + +PODFILE CHECKSUM: 30581c398549a5f1d7f1c358553c9bcad81e21a6 + +COCOAPODS: 1.6.1 diff --git a/Pods/Alamofire/LICENSE b/Pods/Alamofire/LICENSE new file mode 100644 index 0000000..38a301a --- /dev/null +++ b/Pods/Alamofire/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 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/Alamofire/README.md b/Pods/Alamofire/README.md new file mode 100644 index 0000000..26e364a --- /dev/null +++ b/Pods/Alamofire/README.md @@ -0,0 +1,243 @@ +![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) + +[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) +[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.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/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire) +[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF) +[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Alamofire is an HTTP networking library written in Swift. + +- [Features](#features) +- [Component Libraries](#component-libraries) +- [Requirements](#requirements) +- [Migration Guides](#migration-guides) +- [Communication](#communication) +- [Installation](#installation) +- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) + - **Intro -** [Making a Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) + - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameter Encoding](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) + - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) + - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) +- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) + - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) + - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests) + - **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization) + - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) +- [Open Radars](#open-radars) +- [FAQ](#faq) +- [Credits](#credits) +- [Donations](#donations) +- [License](#license) + +## Features + +- [x] Chainable Request / Response Methods +- [x] URL / JSON / plist Parameter Encoding +- [x] Upload File / Data / Stream / MultipartFormData +- [x] Download File using Request or Resume Data +- [x] Authentication with URLCredential +- [x] HTTP Response Validation +- [x] Upload and Download Progress Closures with Progress +- [x] cURL Command Output +- [x] Dynamically Adapt and Retry Requests +- [x] TLS Certificate and Public Key Pinning +- [x] Network Reachability +- [x] Comprehensive Unit and Integration Test Coverage +- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) + +## Component Libraries + +In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. + +- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. +- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. + +## Requirements + +- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ +- Xcode 8.3+ +- Swift 3.1+ + +## Migration Guides + +- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) +- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) +- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) + +## Communication +- If you **need help with making network requests**, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. +- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. +- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). +- If you **found a bug**, open an issue and follow the guide. The more detail the better! +- If you **want to contribute**, submit a pull request. + +## Installation + +### CocoaPods + +[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: + +```bash +$ gem install cocoapods +``` + +> CocoaPods 1.1+ is required to build Alamofire 4.0+. + +To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '10.0' +use_frameworks! + +target '' do + pod 'Alamofire', '~> 4.7' +end +``` + +Then, run the following command: + +```bash +$ pod install +``` + +### Carthage + +[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. + +You can install Carthage with [Homebrew](https://brew.sh/) using the following command: + +```bash +$ brew update +$ brew install carthage +``` + +To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: + +```ogdl +github "Alamofire/Alamofire" ~> 4.7 +``` + +Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. + +### Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. + +Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. + +#### Swift 3 + +```swift +dependencies: [ + .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) +] +``` + +#### Swift 4 + +```swift +dependencies: [ + .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.0.0") +] +``` + +### Manually + +If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. + +#### Embedded Framework + +- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: + + ```bash + $ git init + ``` + +- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: + + ```bash + $ git submodule add https://github.com/Alamofire/Alamofire.git + ``` + +- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. + + > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. + +- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. +- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. +- In the tab bar at the top of that window, open the "General" panel. +- Click on the `+` button under the "Embedded Binaries" section. +- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. + + > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. + +- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. + + > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. + +- And that's it! + + > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. + +## Open Radars + +The following radars have some effect on the current implementation of Alamofire. + +- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case +- `rdar://26870455` - Background URL Session Configurations do not work in the simulator +- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` +- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ + +## Resolved Radars + +The following radars have been resolved over time after being filed against the Alamofire project. + +- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage (Resolved on 9/1/17 in Xcode 9 beta 6). + +## FAQ + +### What's the origin of the name Alamofire? + +Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. + +### What logic belongs in a Router vs. a Request Adapter? + +Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. + +The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. + +## Credits + +Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. + +### Security Disclosure + +If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. + +## Donations + +The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. +Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. +Donating to the ASF will enable us to: + +- Pay our yearly legal fees to keep the non-profit in good status +- Pay for our mail servers to help us stay on top of all questions and security issues +- Potentially fund test servers to make it easier for us to test the edge cases +- Potentially fund developers to work on one of our projects full-time + +The community adoption of the ASF libraries has been amazing. +We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. +With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. +If you use any of our libraries for work, see if your employers would be interested in donating. +Any amount you can donate today to help us reach our goal would be greatly appreciated. + +[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) + +## License + +Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/Pods/Alamofire/Source/AFError.swift b/Pods/Alamofire/Source/AFError.swift new file mode 100644 index 0000000..b163f60 --- /dev/null +++ b/Pods/Alamofire/Source/AFError.swift @@ -0,0 +1,460 @@ +// +// AFError.swift +// +// Copyright (c) 2014 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 Foundation + +/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with +/// their own associated reasons. +/// +/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. +/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. +/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. +/// - responseValidationFailed: Returned when a `validate()` call fails. +/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. +public enum AFError: Error { + /// The underlying reason the parameter encoding error occurred. + /// + /// - missingURL: The URL request did not have a URL to encode. + /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the + /// encoding process. + /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during + /// encoding process. + public enum ParameterEncodingFailureReason { + case missingURL + case jsonEncodingFailed(error: Error) + case propertyListEncodingFailed(error: Error) + } + + /// The underlying reason the multipart encoding error occurred. + /// + /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a + /// file URL. + /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty + /// `lastPathComponent` or `pathExtension. + /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. + /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw + /// an error. + /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. + /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by + /// the system. + /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided + /// threw an error. + /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. + /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the + /// encoded data to disk. + /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file + /// already exists at the provided `fileURL`. + /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is + /// not a file URL. + /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an + /// underlying error. + /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with + /// underlying system error. + public enum MultipartEncodingFailureReason { + case bodyPartURLInvalid(url: URL) + case bodyPartFilenameInvalid(in: URL) + case bodyPartFileNotReachable(at: URL) + case bodyPartFileNotReachableWithError(atURL: URL, error: Error) + case bodyPartFileIsDirectory(at: URL) + case bodyPartFileSizeNotAvailable(at: URL) + case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) + case bodyPartInputStreamCreationFailed(for: URL) + + case outputStreamCreationFailed(for: URL) + case outputStreamFileAlreadyExists(at: URL) + case outputStreamURLInvalid(url: URL) + case outputStreamWriteFailed(error: Error) + + case inputStreamReadFailed(error: Error) + } + + /// The underlying reason the response validation error occurred. + /// + /// - dataFileNil: The data file containing the server response did not exist. + /// - dataFileReadFailed: The data file containing the server response could not be read. + /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` + /// provided did not contain wildcard type. + /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided + /// `acceptableContentTypes`. + /// - unacceptableStatusCode: The response status code was not acceptable. + public enum ResponseValidationFailureReason { + case dataFileNil + case dataFileReadFailed(at: URL) + case missingContentType(acceptableContentTypes: [String]) + case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) + case unacceptableStatusCode(code: Int) + } + + /// The underlying reason the response serialization error occurred. + /// + /// - inputDataNil: The server response contained no data. + /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. + /// - inputFileNil: The file containing the server response did not exist. + /// - inputFileReadFailed: The file containing the server response could not be read. + /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. + /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. + /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. + public enum ResponseSerializationFailureReason { + case inputDataNil + case inputDataNilOrZeroLength + case inputFileNil + case inputFileReadFailed(at: URL) + case stringSerializationFailed(encoding: String.Encoding) + case jsonSerializationFailed(error: Error) + case propertyListSerializationFailed(error: Error) + } + + case invalidURL(url: URLConvertible) + case parameterEncodingFailed(reason: ParameterEncodingFailureReason) + case multipartEncodingFailed(reason: MultipartEncodingFailureReason) + case responseValidationFailed(reason: ResponseValidationFailureReason) + case responseSerializationFailed(reason: ResponseSerializationFailureReason) +} + +// MARK: - Adapt Error + +struct AdaptError: Error { + let error: Error +} + +extension Error { + var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } +} + +// MARK: - Error Booleans + +extension AFError { + /// Returns whether the AFError is an invalid URL error. + public var isInvalidURLError: Bool { + if case .invalidURL = self { return true } + return false + } + + /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will + /// contain the associated value. + public var isParameterEncodingError: Bool { + if case .parameterEncodingFailed = self { return true } + return false + } + + /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties + /// will contain the associated values. + public var isMultipartEncodingError: Bool { + if case .multipartEncodingFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, + /// `responseContentType`, and `responseCode` properties will contain the associated values. + public var isResponseValidationError: Bool { + if case .responseValidationFailed = self { return true } + return false + } + + /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and + /// `underlyingError` properties will contain the associated values. + public var isResponseSerializationError: Bool { + if case .responseSerializationFailed = self { return true } + return false + } +} + +// MARK: - Convenience Properties + +extension AFError { + /// The `URLConvertible` associated with the error. + public var urlConvertible: URLConvertible? { + switch self { + case .invalidURL(let url): + return url + default: + return nil + } + } + + /// The `URL` associated with the error. + public var url: URL? { + switch self { + case .multipartEncodingFailed(let reason): + return reason.url + default: + return nil + } + } + + /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, + /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. + public var underlyingError: Error? { + switch self { + case .parameterEncodingFailed(let reason): + return reason.underlyingError + case .multipartEncodingFailed(let reason): + return reason.underlyingError + case .responseSerializationFailed(let reason): + return reason.underlyingError + default: + return nil + } + } + + /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. + public var acceptableContentTypes: [String]? { + switch self { + case .responseValidationFailed(let reason): + return reason.acceptableContentTypes + default: + return nil + } + } + + /// The response `Content-Type` of a `.responseValidationFailed` error. + public var responseContentType: String? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseContentType + default: + return nil + } + } + + /// The response code of a `.responseValidationFailed` error. + public var responseCode: Int? { + switch self { + case .responseValidationFailed(let reason): + return reason.responseCode + default: + return nil + } + } + + /// The `String.Encoding` associated with a failed `.stringResponse()` call. + public var failedStringEncoding: String.Encoding? { + switch self { + case .responseSerializationFailed(let reason): + return reason.failedStringEncoding + default: + return nil + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var underlyingError: Error? { + switch self { + case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var url: URL? { + switch self { + case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), + .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), + .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), + .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), + .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): + return url + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), + .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): + return error + default: + return nil + } + } +} + +extension AFError.ResponseValidationFailureReason { + var acceptableContentTypes: [String]? { + switch self { + case .missingContentType(let types), .unacceptableContentType(let types, _): + return types + default: + return nil + } + } + + var responseContentType: String? { + switch self { + case .unacceptableContentType(_, let responseType): + return responseType + default: + return nil + } + } + + var responseCode: Int? { + switch self { + case .unacceptableStatusCode(let code): + return code + default: + return nil + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var failedStringEncoding: String.Encoding? { + switch self { + case .stringSerializationFailed(let encoding): + return encoding + default: + return nil + } + } + + var underlyingError: Error? { + switch self { + case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): + return error + default: + return nil + } + } +} + +// MARK: - Error Descriptions + +extension AFError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidURL(let url): + return "URL is not valid: \(url)" + case .parameterEncodingFailed(let reason): + return reason.localizedDescription + case .multipartEncodingFailed(let reason): + return reason.localizedDescription + case .responseValidationFailed(let reason): + return reason.localizedDescription + case .responseSerializationFailed(let reason): + return reason.localizedDescription + } + } +} + +extension AFError.ParameterEncodingFailureReason { + var localizedDescription: String { + switch self { + case .missingURL: + return "URL request to encode was missing a URL" + case .jsonEncodingFailed(let error): + return "JSON could not be encoded because of error:\n\(error.localizedDescription)" + case .propertyListEncodingFailed(let error): + return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.MultipartEncodingFailureReason { + var localizedDescription: String { + switch self { + case .bodyPartURLInvalid(let url): + return "The URL provided is not a file URL: \(url)" + case .bodyPartFilenameInvalid(let url): + return "The URL provided does not have a valid filename: \(url)" + case .bodyPartFileNotReachable(let url): + return "The URL provided is not reachable: \(url)" + case .bodyPartFileNotReachableWithError(let url, let error): + return ( + "The system returned an error while checking the provided URL for " + + "reachability.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartFileIsDirectory(let url): + return "The URL provided is a directory: \(url)" + case .bodyPartFileSizeNotAvailable(let url): + return "Could not fetch the file size from the provided URL: \(url)" + case .bodyPartFileSizeQueryFailedWithError(let url, let error): + return ( + "The system returned an error while attempting to fetch the file size from the " + + "provided URL.\nURL: \(url)\nError: \(error)" + ) + case .bodyPartInputStreamCreationFailed(let url): + return "Failed to create an InputStream for the provided URL: \(url)" + case .outputStreamCreationFailed(let url): + return "Failed to create an OutputStream for URL: \(url)" + case .outputStreamFileAlreadyExists(let url): + return "A file already exists at the provided URL: \(url)" + case .outputStreamURLInvalid(let url): + return "The provided OutputStream URL is invalid: \(url)" + case .outputStreamWriteFailed(let error): + return "OutputStream write failed with error: \(error)" + case .inputStreamReadFailed(let error): + return "InputStream read failed with error: \(error)" + } + } +} + +extension AFError.ResponseSerializationFailureReason { + var localizedDescription: String { + switch self { + case .inputDataNil: + return "Response could not be serialized, input data was nil." + case .inputDataNilOrZeroLength: + return "Response could not be serialized, input data was nil or zero length." + case .inputFileNil: + return "Response could not be serialized, input file was nil." + case .inputFileReadFailed(let url): + return "Response could not be serialized, input file could not be read: \(url)." + case .stringSerializationFailed(let encoding): + return "String could not be serialized with encoding: \(encoding)." + case .jsonSerializationFailed(let error): + return "JSON could not be serialized because of error:\n\(error.localizedDescription)" + case .propertyListSerializationFailed(let error): + return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" + } + } +} + +extension AFError.ResponseValidationFailureReason { + var localizedDescription: String { + switch self { + case .dataFileNil: + return "Response could not be validated, data file was nil." + case .dataFileReadFailed(let url): + return "Response could not be validated, data file could not be read: \(url)." + case .missingContentType(let types): + return ( + "Response Content-Type was missing and acceptable content types " + + "(\(types.joined(separator: ","))) do not match \"*/*\"." + ) + case .unacceptableContentType(let acceptableTypes, let responseType): + return ( + "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + + "\(acceptableTypes.joined(separator: ","))." + ) + case .unacceptableStatusCode(let code): + return "Response status code was unacceptable: \(code)." + } + } +} diff --git a/Pods/Alamofire/Source/Alamofire.swift b/Pods/Alamofire/Source/Alamofire.swift new file mode 100644 index 0000000..20c3672 --- /dev/null +++ b/Pods/Alamofire/Source/Alamofire.swift @@ -0,0 +1,465 @@ +// +// Alamofire.swift +// +// Copyright (c) 2014 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 Foundation + +/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct +/// URL requests. +public protocol URLConvertible { + /// Returns a URL that conforms to RFC 2396 or throws an `Error`. + /// + /// - throws: An `Error` if the type cannot be converted to a `URL`. + /// + /// - returns: A URL or throws an `Error`. + func asURL() throws -> URL +} + +extension String: URLConvertible { + /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. + /// + /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } + return url + } +} + +extension URL: URLConvertible { + /// Returns self. + public func asURL() throws -> URL { return self } +} + +extension URLComponents: URLConvertible { + /// Returns a URL if `url` is not nil, otherwise throws an `Error`. + /// + /// - throws: An `AFError.invalidURL` if `url` is `nil`. + /// + /// - returns: A URL or throws an `AFError`. + public func asURL() throws -> URL { + guard let url = url else { throw AFError.invalidURL(url: self) } + return url + } +} + +// MARK: - + +/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. +public protocol URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + /// + /// - throws: An `Error` if the underlying `URLRequest` is `nil`. + /// + /// - returns: A URL request. + func asURLRequest() throws -> URLRequest +} + +extension URLRequestConvertible { + /// The URL request. + public var urlRequest: URLRequest? { return try? asURLRequest() } +} + +extension URLRequest: URLRequestConvertible { + /// Returns a URL request or throws if an `Error` was encountered. + public func asURLRequest() throws -> URLRequest { return self } +} + +// MARK: - + +extension URLRequest { + /// Creates an instance with the specified `method`, `urlString` and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The new `URLRequest` instance. + public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { + let url = try url.asURL() + + self.init(url: url) + + httpMethod = method.rawValue + + if let headers = headers { + for (headerField, headerValue) in headers { + setValue(headerValue, forHTTPHeaderField: headerField) + } + } + } + + func adapt(using adapter: RequestAdapter?) throws -> URLRequest { + guard let adapter = adapter else { return self } + return try adapter.adapt(self) + } +} + +// MARK: - Data Request + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding` and `headers`. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest +{ + return SessionManager.default.request( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers + ) +} + +/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest`. +/// +/// - parameter urlRequest: The URL request +/// +/// - returns: The created `DataRequest`. +@discardableResult +public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + return SessionManager.default.request(urlRequest) +} + +// MARK: - Download Request + +// MARK: URL Request + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, +/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.get` by default. +/// - parameter parameters: The parameters. `nil` by default. +/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download( + url, + method: method, + parameters: parameters, + encoding: encoding, + headers: headers, + to: destination + ) +} + +/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the +/// specified `urlRequest` and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// - parameter urlRequest: The URL request. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(urlRequest, to: destination) +} + +// MARK: Resume Data + +/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a +/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. +/// +/// If `destination` is not specified, the contents will remain in the temporary location determined by the +/// underlying URL session. +/// +/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken +/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the +/// data is written incorrectly and will always fail to resume the download. For more information about the bug and +/// possible workarounds, please refer to the following Stack Overflow post: +/// +/// - http://stackoverflow.com/a/39347461/1342462 +/// +/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` +/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional +/// information. +/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. +/// +/// - returns: The created `DownloadRequest`. +@discardableResult +public func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest +{ + return SessionManager.default.download(resumingWith: resumeData, to: destination) +} + +// MARK: - Upload Request + +// MARK: File + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) +} + +/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `file`. +/// +/// - parameter file: The file to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(fileURL, with: urlRequest) +} + +// MARK: Data + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(data, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `data`. +/// +/// - parameter data: The data to upload. +/// - parameter urlRequest: The URL request. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(data, with: urlRequest) +} + +// MARK: InputStream + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` +/// for uploading the `stream`. +/// +/// - parameter stream: The stream to upload. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest +{ + return SessionManager.default.upload(stream, to: url, method: method, headers: headers) +} + +/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for +/// uploading the `stream`. +/// +/// - parameter urlRequest: The URL request. +/// - parameter stream: The stream to upload. +/// +/// - returns: The created `UploadRequest`. +@discardableResult +public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + return SessionManager.default.upload(stream, with: urlRequest) +} + +// MARK: MultipartFormData + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls +/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter url: The URL. +/// - parameter method: The HTTP method. `.post` by default. +/// - parameter headers: The HTTP headers. `nil` by default. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + to: url, + method: method, + headers: headers, + encodingCompletion: encodingCompletion + ) +} + +/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and +/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. +/// +/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative +/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most +/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to +/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory +/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be +/// used for larger payloads such as video content. +/// +/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory +/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, +/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk +/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding +/// technique was used. +/// +/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. +/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. +/// `multipartFormDataEncodingMemoryThreshold` by default. +/// - parameter urlRequest: The URL request. +/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. +public func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) +{ + return SessionManager.default.upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + encodingCompletion: encodingCompletion + ) +} + +#if !os(watchOS) + +// MARK: - Stream Request + +// MARK: Hostname and Port + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` +/// and `port`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter hostName: The hostname of the server to connect to. +/// - parameter port: The port of the server to connect to. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return SessionManager.default.stream(withHostName: hostName, port: port) +} + +// MARK: NetService + +/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. +/// +/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. +/// +/// - parameter netService: The net service used to identify the endpoint. +/// +/// - returns: The created `StreamRequest`. +@discardableResult +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +public func stream(with netService: NetService) -> StreamRequest { + return SessionManager.default.stream(with: netService) +} + +#endif diff --git a/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift new file mode 100644 index 0000000..a54673c --- /dev/null +++ b/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift @@ -0,0 +1,37 @@ +// +// DispatchQueue+Alamofire.swift +// +// Copyright (c) 2014 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 Dispatch +import Foundation + +extension DispatchQueue { + static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } + static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } + static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } + static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } + + func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { + asyncAfter(deadline: .now() + delay, execute: closure) + } +} diff --git a/Pods/Alamofire/Source/MultipartFormData.swift b/Pods/Alamofire/Source/MultipartFormData.swift new file mode 100644 index 0000000..b840138 --- /dev/null +++ b/Pods/Alamofire/Source/MultipartFormData.swift @@ -0,0 +1,580 @@ +// +// MultipartFormData.swift +// +// Copyright (c) 2014 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 Foundation + +#if os(iOS) || os(watchOS) || os(tvOS) +import MobileCoreServices +#elseif os(macOS) +import CoreServices +#endif + +/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode +/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead +/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the +/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for +/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. +/// +/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well +/// and the w3 form documentation. +/// +/// - https://www.ietf.org/rfc/rfc2388.txt +/// - https://www.ietf.org/rfc/rfc2045.txt +/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 +open class MultipartFormData { + + // MARK: - Helper Types + + struct EncodingCharacters { + static let crlf = "\r\n" + } + + struct BoundaryGenerator { + enum BoundaryType { + case initial, encapsulated, final + } + + static func randomBoundary() -> String { + return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) + } + + static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { + let boundaryText: String + + switch boundaryType { + case .initial: + boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" + case .encapsulated: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" + case .final: + boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" + } + + return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + } + + class BodyPart { + let headers: HTTPHeaders + let bodyStream: InputStream + let bodyContentLength: UInt64 + var hasInitialBoundary = false + var hasFinalBoundary = false + + init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { + self.headers = headers + self.bodyStream = bodyStream + self.bodyContentLength = bodyContentLength + } + } + + // MARK: - Properties + + /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. + open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" + + /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. + public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } + + /// The boundary used to separate the body parts in the encoded form data. + public var boundary: String + + private var bodyParts: [BodyPart] + private var bodyPartError: AFError? + private let streamBufferSize: Int + + // MARK: - Lifecycle + + /// Creates a multipart form data object. + /// + /// - returns: The multipart form data object. + public init() { + self.boundary = BoundaryGenerator.randomBoundary() + self.bodyParts = [] + + /// + /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more + /// information, please refer to the following article: + /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html + /// + + self.streamBufferSize = 1024 + } + + // MARK: - Body Parts + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + public func append(_ data: Data, withName name: String) { + let headers = contentHeaders(withName: name) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, mimeType: String) { + let headers = contentHeaders(withName: name, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the data and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter data: The data to encode into the multipart form data. + /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. + public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + let stream = InputStream(data: data) + let length = UInt64(data.count) + + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) + /// - `Content-Type: #{generated mimeType}` (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the + /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the + /// system associated MIME type. + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + public func append(_ fileURL: URL, withName name: String) { + let fileName = fileURL.lastPathComponent + let pathExtension = fileURL.pathExtension + + if !fileName.isEmpty && !pathExtension.isEmpty { + let mime = mimeType(forPathExtension: pathExtension) + append(fileURL, withName: name, fileName: fileName, mimeType: mime) + } else { + setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) + } + } + + /// Creates a body part from the file and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) + /// - Content-Type: #{mimeType} (HTTP Header) + /// - Encoded file data + /// - Multipart form boundary + /// + /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. + /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. + public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + + //============================================================ + // Check 1 - is file URL? + //============================================================ + + guard fileURL.isFileURL else { + setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) + return + } + + //============================================================ + // Check 2 - is file URL reachable? + //============================================================ + + do { + let isReachable = try fileURL.checkPromisedItemIsReachable() + guard isReachable else { + setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) + return + } + } catch { + setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 3 - is file URL a directory? + //============================================================ + + var isDirectory: ObjCBool = false + let path = fileURL.path + + guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { + setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) + return + } + + //============================================================ + // Check 4 - can the file size be extracted? + //============================================================ + + let bodyContentLength: UInt64 + + do { + guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { + setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) + return + } + + bodyContentLength = fileSize.uint64Value + } + catch { + setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) + return + } + + //============================================================ + // Check 5 - can a stream be created from file URL? + //============================================================ + + guard let stream = InputStream(url: fileURL) else { + setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) + return + } + + append(stream, withLength: bodyContentLength, headers: headers) + } + + /// Creates a body part from the stream and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) + /// - `Content-Type: #{mimeType}` (HTTP Header) + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. + /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. + public func append( + _ stream: InputStream, + withLength length: UInt64, + name: String, + fileName: String, + mimeType: String) + { + let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) + append(stream, withLength: length, headers: headers) + } + + /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. + /// + /// The body part data will be encoded using the following format: + /// + /// - HTTP headers + /// - Encoded stream data + /// - Multipart form boundary + /// + /// - parameter stream: The input stream to encode in the multipart form data. + /// - parameter length: The content length of the stream. + /// - parameter headers: The HTTP headers for the body part. + public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { + let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) + bodyParts.append(bodyPart) + } + + // MARK: - Data Encoding + + /// Encodes all the appended body parts into a single `Data` value. + /// + /// It is important to note that this method will load all the appended body parts into memory all at the same + /// time. This method should only be used when the encoded data will have a small memory footprint. For large data + /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. + /// + /// - throws: An `AFError` if encoding encounters an error. + /// + /// - returns: The encoded `Data` if encoding is successful. + public func encode() throws -> Data { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + var encoded = Data() + + bodyParts.first?.hasInitialBoundary = true + bodyParts.last?.hasFinalBoundary = true + + for bodyPart in bodyParts { + let encodedData = try encode(bodyPart) + encoded.append(encodedData) + } + + return encoded + } + + /// Writes the appended body parts into the given file URL. + /// + /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, + /// this approach is very memory efficient and should be used for large body part data. + /// + /// - parameter fileURL: The file URL to write the multipart form data into. + /// + /// - throws: An `AFError` if encoding encounters an error. + public func writeEncodedData(to fileURL: URL) throws { + if let bodyPartError = bodyPartError { + throw bodyPartError + } + + if FileManager.default.fileExists(atPath: fileURL.path) { + throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) + } else if !fileURL.isFileURL { + throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) + } + + guard let outputStream = OutputStream(url: fileURL, append: false) else { + throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) + } + + outputStream.open() + defer { outputStream.close() } + + self.bodyParts.first?.hasInitialBoundary = true + self.bodyParts.last?.hasFinalBoundary = true + + for bodyPart in self.bodyParts { + try write(bodyPart, to: outputStream) + } + } + + // MARK: - Private - Body Part Encoding + + private func encode(_ bodyPart: BodyPart) throws -> Data { + var encoded = Data() + + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + encoded.append(initialData) + + let headerData = encodeHeaders(for: bodyPart) + encoded.append(headerData) + + let bodyStreamData = try encodeBodyStream(for: bodyPart) + encoded.append(bodyStreamData) + + if bodyPart.hasFinalBoundary { + encoded.append(finalBoundaryData()) + } + + return encoded + } + + private func encodeHeaders(for bodyPart: BodyPart) -> Data { + var headerText = "" + + for (key, value) in bodyPart.headers { + headerText += "\(key): \(value)\(EncodingCharacters.crlf)" + } + headerText += EncodingCharacters.crlf + + return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! + } + + private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { + let inputStream = bodyPart.bodyStream + inputStream.open() + defer { inputStream.close() } + + var encoded = Data() + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let error = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) + } + + if bytesRead > 0 { + encoded.append(buffer, count: bytesRead) + } else { + break + } + } + + return encoded + } + + // MARK: - Private - Writing Body Part to Output Stream + + private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { + try writeInitialBoundaryData(for: bodyPart, to: outputStream) + try writeHeaderData(for: bodyPart, to: outputStream) + try writeBodyStream(for: bodyPart, to: outputStream) + try writeFinalBoundaryData(for: bodyPart, to: outputStream) + } + + private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() + return try write(initialData, to: outputStream) + } + + private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let headerData = encodeHeaders(for: bodyPart) + return try write(headerData, to: outputStream) + } + + private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { + let inputStream = bodyPart.bodyStream + + inputStream.open() + defer { inputStream.close() } + + while inputStream.hasBytesAvailable { + var buffer = [UInt8](repeating: 0, count: streamBufferSize) + let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) + + if let streamError = inputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) + } + + if bytesRead > 0 { + if buffer.count != bytesRead { + buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { + let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) + + if let error = outputStream.streamError { + throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) + } + + bytesToWrite -= bytesWritten + + if bytesToWrite > 0 { + buffer = Array(buffer[bytesWritten.. String { + if + let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), + let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() + { + return contentType as String + } + + return "application/octet-stream" + } + + // MARK: - Private - Content Headers + + private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { + var disposition = "form-data; name=\"\(name)\"" + if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } + + var headers = ["Content-Disposition": disposition] + if let mimeType = mimeType { headers["Content-Type"] = mimeType } + + return headers + } + + // MARK: - Private - Boundary Encoding + + private func initialBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) + } + + private func encapsulatedBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) + } + + private func finalBoundaryData() -> Data { + return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) + } + + // MARK: - Private - Errors + + private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { + guard bodyPartError == nil else { return } + bodyPartError = AFError.multipartEncodingFailed(reason: reason) + } +} diff --git a/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/Pods/Alamofire/Source/NetworkReachabilityManager.swift new file mode 100644 index 0000000..5470eec --- /dev/null +++ b/Pods/Alamofire/Source/NetworkReachabilityManager.swift @@ -0,0 +1,235 @@ +// +// NetworkReachabilityManager.swift +// +// Copyright (c) 2014 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. +// + +#if !os(watchOS) + +import Foundation +import SystemConfiguration + +/// The `NetworkReachabilityManager` class listens for reachability changes of hosts 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 retry +/// network requests 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. +open class NetworkReachabilityManager { + /// Defines the various states of network reachability. + /// + /// - unknown: It is unknown whether the network is reachable. + /// - notReachable: The network is not reachable. + /// - reachable: The network is reachable. + public enum NetworkReachabilityStatus { + case unknown + case notReachable + case reachable(ConnectionType) + } + + /// Defines the various connection types detected by reachability flags. + /// + /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. + /// - wwan: The connection type is a WWAN connection. + public enum ConnectionType { + case ethernetOrWiFi + case wwan + } + + /// A closure executed when the network reachability status changes. The closure takes a single argument: the + /// network reachability status. + public typealias Listener = (NetworkReachabilityStatus) -> Void + + // MARK: - Properties + + /// Whether the network is currently reachable. + open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } + + /// Whether the network is currently reachable over the WWAN interface. + open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } + + /// Whether the network is currently reachable over Ethernet or WiFi interface. + open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } + + /// The current network reachability status. + open var networkReachabilityStatus: NetworkReachabilityStatus { + guard let flags = self.flags else { return .unknown } + return networkReachabilityStatusForFlags(flags) + } + + /// The dispatch queue to execute the `listener` closure on. + open var listenerQueue: DispatchQueue = DispatchQueue.main + + /// A closure executed when the network reachability status changes. + open var listener: Listener? + + open var flags: SCNetworkReachabilityFlags? { + var flags = SCNetworkReachabilityFlags() + + if SCNetworkReachabilityGetFlags(reachability, &flags) { + return flags + } + + return nil + } + + private let reachability: SCNetworkReachability + open var previousFlags: SCNetworkReachabilityFlags + + // MARK: - Initialization + + /// Creates a `NetworkReachabilityManager` instance with the specified host. + /// + /// - parameter host: The host used to evaluate network reachability. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?(host: String) { + guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } + self.init(reachability: reachability) + } + + /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. + /// + /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing + /// status of the device, both IPv4 and IPv6. + /// + /// - returns: The new `NetworkReachabilityManager` instance. + public convenience init?() { + var address = sockaddr_in() + address.sin_len = UInt8(MemoryLayout.size) + address.sin_family = sa_family_t(AF_INET) + + guard let reachability = withUnsafePointer(to: &address, { pointer in + return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { + return SCNetworkReachabilityCreateWithAddress(nil, $0) + } + }) else { return nil } + + self.init(reachability: reachability) + } + + private init(reachability: SCNetworkReachability) { + self.reachability = reachability + + // Set the previous flags to an unreserved value to represent unknown status + self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) + } + + deinit { + stopListening() + } + + // MARK: - Listening + + /// Starts listening for changes in network reachability status. + /// + /// - returns: `true` if listening was started successfully, `false` otherwise. + @discardableResult + open func startListening() -> Bool { + var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) + context.info = Unmanaged.passUnretained(self).toOpaque() + + let callbackEnabled = SCNetworkReachabilitySetCallback( + reachability, + { (_, flags, info) in + let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() + reachability.notifyListener(flags) + }, + &context + ) + + let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) + + listenerQueue.async { + guard let flags = self.flags else { return } + self.notifyListener(flags) + } + + return callbackEnabled && queueEnabled + } + + /// Stops listening for changes in network reachability status. + open func stopListening() { + SCNetworkReachabilitySetCallback(reachability, nil, nil) + SCNetworkReachabilitySetDispatchQueue(reachability, nil) + } + + // MARK: - Internal - Listener Notification + + func notifyListener(_ flags: SCNetworkReachabilityFlags) { + guard previousFlags != flags else { return } + previousFlags = flags + + listener?(networkReachabilityStatusForFlags(flags)) + } + + // MARK: - Internal - Network Reachability Status + + func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { + guard isNetworkReachable(with: flags) else { return .notReachable } + + var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) + + #if os(iOS) + if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } + #endif + + return networkStatus + } + + func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { + let isReachable = flags.contains(.reachable) + let needsConnection = flags.contains(.connectionRequired) + let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) + let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) + + return isReachable && (!needsConnection || canConnectWithoutUserInteraction) + } +} + +// MARK: - + +extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} + +/// Returns whether the two network reachability status values are equal. +/// +/// - parameter lhs: The left-hand side value to compare. +/// - parameter rhs: The right-hand side value to compare. +/// +/// - returns: `true` if the two values are equal, `false` otherwise. +public func ==( + lhs: NetworkReachabilityManager.NetworkReachabilityStatus, + rhs: NetworkReachabilityManager.NetworkReachabilityStatus) + -> Bool +{ + switch (lhs, rhs) { + case (.unknown, .unknown): + return true + case (.notReachable, .notReachable): + return true + case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): + return lhsConnectionType == rhsConnectionType + default: + return false + } +} + +#endif diff --git a/Pods/Alamofire/Source/Notifications.swift b/Pods/Alamofire/Source/Notifications.swift new file mode 100644 index 0000000..e1ac31b --- /dev/null +++ b/Pods/Alamofire/Source/Notifications.swift @@ -0,0 +1,55 @@ +// +// Notifications.swift +// +// Copyright (c) 2014 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 Foundation + +extension Notification.Name { + /// Used as a namespace for all `URLSessionTask` related notifications. + public struct Task { + /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. + public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") + + /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. + public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") + + /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. + public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") + + /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. + public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") + } +} + +// MARK: - + +extension Notification { + /// Used as a namespace for all `Notification` user info dictionary keys. + public struct Key { + /// User info dictionary key representing the `URLSessionTask` associated with the notification. + public static let Task = "org.alamofire.notification.key.task" + + /// User info dictionary key representing the responseData associated with the notification. + public static let ResponseData = "org.alamofire.notification.key.responseData" + } +} diff --git a/Pods/Alamofire/Source/ParameterEncoding.swift b/Pods/Alamofire/Source/ParameterEncoding.swift new file mode 100644 index 0000000..6195809 --- /dev/null +++ b/Pods/Alamofire/Source/ParameterEncoding.swift @@ -0,0 +1,483 @@ +// +// ParameterEncoding.swift +// +// Copyright (c) 2014 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 Foundation + +/// HTTP method definitions. +/// +/// See https://tools.ietf.org/html/rfc7231#section-4.3 +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +// MARK: - + +/// A dictionary of parameters to apply to a `URLRequest`. +public typealias Parameters = [String: Any] + +/// A type used to define how a set of parameters are applied to a `URLRequest`. +public protocol ParameterEncoding { + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. + /// + /// - returns: The encoded request. + func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest +} + +// MARK: - + +/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP +/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as +/// the HTTP body depends on the destination of the encoding. +/// +/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to +/// `application/x-www-form-urlencoded; charset=utf-8`. +/// +/// There is no published specification for how to encode collection types. By default the convention of appending +/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for +/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the +/// square brackets appended to array keys. +/// +/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode +/// `true` as 1 and `false` as 0. +public struct URLEncoding: ParameterEncoding { + + // MARK: Helper Types + + /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the + /// resulting URL request. + /// + /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` + /// requests and sets as the HTTP body for requests with any other HTTP method. + /// - queryString: Sets or appends encoded query string result to existing query string. + /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. + public enum Destination { + case methodDependent, queryString, httpBody + } + + /// Configures how `Array` parameters are encoded. + /// + /// - brackets: An empty set of square brackets is appended to the key for every value. + /// This is the default behavior. + /// - noBrackets: No brackets are appended. The key is encoded as is. + public enum ArrayEncoding { + case brackets, noBrackets + + func encode(key: String) -> String { + switch self { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + } + } + } + + /// Configures how `Bool` parameters are encoded. + /// + /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. + /// - literal: Encode `true` and `false` as string literals. + public enum BoolEncoding { + case numeric, literal + + func encode(value: Bool) -> String { + switch self { + case .numeric: + return value ? "1" : "0" + case .literal: + return value ? "true" : "false" + } + } + } + + // MARK: Properties + + /// Returns a default `URLEncoding` instance. + public static var `default`: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.methodDependent` destination. + public static var methodDependent: URLEncoding { return URLEncoding() } + + /// Returns a `URLEncoding` instance with a `.queryString` destination. + public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } + + /// Returns a `URLEncoding` instance with an `.httpBody` destination. + public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } + + /// The destination defining where the encoded query string is to be applied to the URL request. + public let destination: Destination + + /// The encoding to use for `Array` parameters. + public let arrayEncoding: ArrayEncoding + + /// The encoding to use for `Bool` parameters. + public let boolEncoding: BoolEncoding + + // MARK: Initialization + + /// Creates a `URLEncoding` instance using the specified destination. + /// + /// - parameter destination: The destination defining where the encoded query string is to be applied. + /// - parameter arrayEncoding: The encoding to use for `Array` parameters. + /// - parameter boolEncoding: The encoding to use for `Bool` parameters. + /// + /// - returns: The new `URLEncoding` instance. + public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { + self.destination = destination + self.arrayEncoding = arrayEncoding + self.boolEncoding = boolEncoding + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + guard let url = urlRequest.url else { + throw AFError.parameterEncodingFailed(reason: .missingURL) + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) + urlComponents.percentEncodedQuery = percentEncodedQuery + urlRequest.url = urlComponents.url + } + } else { + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) + } + + return urlRequest + } + + /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. + /// + /// - parameter key: The key of the query component. + /// - parameter value: The value of the query component. + /// + /// - returns: The percent-escaped, URL encoded query string components. + public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { + var components: [(String, String)] = [] + + if let dictionary = value as? [String: Any] { + for (nestedKey, value) in dictionary { + components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) + } + } else if let array = value as? [Any] { + for value in array { + components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) + } + } else if let value = value as? NSNumber { + if value.isBool { + components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) + } else { + components.append((escape(key), escape("\(value)"))) + } + } else if let bool = value as? Bool { + components.append((escape(key), escape(boolEncoding.encode(value: bool)))) + } else { + components.append((escape(key), escape("\(value)"))) + } + + return components + } + + /// 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. + public func escape(_ string: String) -> String { + let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 + let subDelimitersToEncode = "!$&'()*+,;=" + + var allowedCharacterSet = CharacterSet.urlQueryAllowed + allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") + + var escaped = "" + + //========================================================================================================== + // + // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few + // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no + // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more + // info, please refer to: + // + // - https://github.com/Alamofire/Alamofire/issues/206 + // + //========================================================================================================== + + if #available(iOS 8.3, *) { + escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string + } else { + let batchSize = 50 + var index = string.startIndex + + while index != string.endIndex { + let startIndex = index + let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex + let range = startIndex.. String { + var components: [(String, String)] = [] + + for key in parameters.keys.sorted(by: <) { + let value = parameters[key]! + components += queryComponents(fromKey: key, value: value) + } + return components.map { "\($0)=\($1)" }.joined(separator: "&") + } + + private func encodesParametersInURL(with method: HTTPMethod) -> Bool { + switch destination { + case .queryString: + return true + case .httpBody: + return false + default: + break + } + + switch method { + case .get, .head, .delete: + return true + default: + return false + } + } +} + +// MARK: - + +/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the +/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. +public struct JSONEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a `JSONEncoding` instance with default writing options. + public static var `default`: JSONEncoding { return JSONEncoding() } + + /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. + public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } + + /// The options for writing the parameters as JSON data. + public let options: JSONSerialization.WritingOptions + + // MARK: Initialization + + /// Creates a `JSONEncoding` instance using the specified options. + /// + /// - parameter options: The options for writing the parameters as JSON data. + /// + /// - returns: The new `JSONEncoding` instance. + public init(options: JSONSerialization.WritingOptions = []) { + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: parameters, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } + + /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. + /// + /// - parameter urlRequest: The request to apply the JSON object to. + /// - parameter jsonObject: The JSON object to apply to the request. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let jsonObject = jsonObject else { return urlRequest } + + do { + let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the +/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header +/// field of an encoded request is set to `application/x-plist`. +public struct PropertyListEncoding: ParameterEncoding { + + // MARK: Properties + + /// Returns a default `PropertyListEncoding` instance. + public static var `default`: PropertyListEncoding { return PropertyListEncoding() } + + /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. + public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } + + /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. + public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } + + /// The property list serialization format. + public let format: PropertyListSerialization.PropertyListFormat + + /// The options for writing the parameters as plist data. + public let options: PropertyListSerialization.WriteOptions + + // MARK: Initialization + + /// Creates a `PropertyListEncoding` instance using the specified format and options. + /// + /// - parameter format: The property list serialization format. + /// - parameter options: The options for writing the parameters as plist data. + /// + /// - returns: The new `PropertyListEncoding` instance. + public init( + format: PropertyListSerialization.PropertyListFormat = .xml, + options: PropertyListSerialization.WriteOptions = 0) + { + self.format = format + self.options = options + } + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { + var urlRequest = try urlRequest.asURLRequest() + + guard let parameters = parameters else { return urlRequest } + + do { + let data = try PropertyListSerialization.data( + fromPropertyList: parameters, + format: format, + options: options + ) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = data + } catch { + throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) + } + + return urlRequest + } +} + +// MARK: - + +extension NSNumber { + fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } +} diff --git a/Pods/Alamofire/Source/Request.swift b/Pods/Alamofire/Source/Request.swift new file mode 100644 index 0000000..a2efaa0 --- /dev/null +++ b/Pods/Alamofire/Source/Request.swift @@ -0,0 +1,649 @@ +// +// Request.swift +// +// Copyright (c) 2014 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 Foundation + +/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. +public protocol RequestAdapter { + /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. + /// + /// - parameter urlRequest: The URL request to adapt. + /// + /// - throws: An `Error` if the adaptation encounters an error. + /// + /// - returns: The adapted `URLRequest`. + func adapt(_ urlRequest: URLRequest) throws -> URLRequest +} + +// MARK: - + +/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. +public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void + +/// A type that determines whether a request should be retried after being executed by the specified session manager +/// and encountering an error. +public protocol RequestRetrier { + /// Determines whether the `Request` should be retried by calling the `completion` closure. + /// + /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs + /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly + /// cleaned up after. + /// + /// - parameter manager: The session manager the request was executed on. + /// - parameter request: The request that failed due to the encountered error. + /// - parameter error: The error encountered when executing the request. + /// - parameter completion: The completion closure to be executed when retry decision has been determined. + func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) +} + +// MARK: - + +protocol TaskConvertible { + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask +} + +/// A dictionary of headers to apply to a `URLRequest`. +public typealias HTTPHeaders = [String: String] + +// MARK: - + +/// Responsible for sending a request and receiving the response and associated data from the server, as well as +/// managing its underlying `URLSessionTask`. +open class Request { + + // MARK: Helper Types + + /// A closure executed when monitoring upload or download progress of a request. + public typealias ProgressHandler = (Progress) -> Void + + enum RequestTask { + case data(TaskConvertible?, URLSessionTask?) + case download(TaskConvertible?, URLSessionTask?) + case upload(TaskConvertible?, URLSessionTask?) + case stream(TaskConvertible?, URLSessionTask?) + } + + // MARK: Properties + + /// The delegate for the underlying task. + open internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return taskDelegate + } + set { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + taskDelegate = newValue + } + } + + /// The underlying task. + open var task: URLSessionTask? { return delegate.task } + + /// The session belonging to the underlying task. + public let session: URLSession + + /// The request sent or to be sent to the server. + open var request: URLRequest? { return task?.originalRequest } + + /// The response received from the server, if any. + open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } + + /// The number of times the request has been retried. + open internal(set) var retryCount: UInt = 0 + + let originalTask: TaskConvertible? + + var startTime: CFAbsoluteTime? + var endTime: CFAbsoluteTime? + + var validations: [() -> Void] = [] + + private var taskDelegate: TaskDelegate + private var taskDelegateLock = NSLock() + + // MARK: Lifecycle + + init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { + self.session = session + + switch requestTask { + case .data(let originalTask, let task): + taskDelegate = DataTaskDelegate(task: task) + self.originalTask = originalTask + case .download(let originalTask, let task): + taskDelegate = DownloadTaskDelegate(task: task) + self.originalTask = originalTask + case .upload(let originalTask, let task): + taskDelegate = UploadTaskDelegate(task: task) + self.originalTask = originalTask + case .stream(let originalTask, let task): + taskDelegate = TaskDelegate(task: task) + self.originalTask = originalTask + } + + delegate.error = error + delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } + } + + // MARK: Authentication + + /// Associates an HTTP Basic credential with the request. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// - parameter persistence: The URL credential persistence. `.ForSession` by default. + /// + /// - returns: The request. + @discardableResult + open func authenticate( + user: String, + password: String, + persistence: URLCredential.Persistence = .forSession) + -> Self + { + let credential = URLCredential(user: user, password: password, persistence: persistence) + return authenticate(usingCredential: credential) + } + + /// Associates a specified credential with the request. + /// + /// - parameter credential: The credential. + /// + /// - returns: The request. + @discardableResult + open func authenticate(usingCredential credential: URLCredential) -> Self { + delegate.credential = credential + return self + } + + /// Returns a base64 encoded basic authentication credential as an authorization header tuple. + /// + /// - parameter user: The user. + /// - parameter password: The password. + /// + /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. + open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { + guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } + + let credential = data.base64EncodedString(options: []) + + return (key: "Authorization", value: "Basic \(credential)") + } + + // MARK: State + + /// Resumes the request. + open func resume() { + guard let task = task else { delegate.queue.isSuspended = false ; return } + + if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } + + task.resume() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidResume, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Suspends the request. + open func suspend() { + guard let task = task else { return } + + task.suspend() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidSuspend, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } + + /// Cancels the request. + open func cancel() { + guard let task = task else { return } + + task.cancel() + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task] + ) + } +} + +// MARK: - CustomStringConvertible + +extension Request: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as + /// well as the response status code if a response has been received. + open var description: String { + var components: [String] = [] + + if let HTTPMethod = request?.httpMethod { + components.append(HTTPMethod) + } + + if let urlString = request?.url?.absoluteString { + components.append(urlString) + } + + if let response = response { + components.append("(\(response.statusCode))") + } + + return components.joined(separator: " ") + } +} + +// MARK: - CustomDebugStringConvertible + +extension Request: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, in the form of a cURL command. + open var debugDescription: String { + return cURLRepresentation() + } + + func cURLRepresentation() -> String { + var components = ["$ curl -v"] + + guard let request = self.request, + let url = request.url, + let host = url.host + else { + return "$ curl command could not be created" + } + + if let httpMethod = request.httpMethod, httpMethod != "GET" { + components.append("-X \(httpMethod)") + } + + if let credentialStorage = self.session.configuration.urlCredentialStorage { + let protectionSpace = URLProtectionSpace( + host: host, + port: url.port ?? 0, + protocol: url.scheme, + realm: host, + authenticationMethod: NSURLAuthenticationMethodHTTPBasic + ) + + if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { + for credential in credentials { + guard let user = credential.user, let password = credential.password else { continue } + components.append("-u \(user):\(password)") + } + } else { + if let credential = delegate.credential, let user = credential.user, let password = credential.password { + components.append("-u \(user):\(password)") + } + } + } + + if session.configuration.httpShouldSetCookies { + if + let cookieStorage = session.configuration.httpCookieStorage, + let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty + { + let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + + #if swift(>=3.2) + components.append("-b \"\(string[.. URLSessionTask { + do { + let urlRequest = try self.urlRequest.adapt(using: adapter) + return queue.sync { session.dataTask(with: urlRequest) } + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + if let requestable = originalTask as? Requestable { return requestable.urlRequest } + + return nil + } + + /// The progress of fetching the response data from the server for the request. + open var progress: Progress { return dataDelegate.progress } + + var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } + + // MARK: Stream + + /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. + /// + /// This closure returns the bytes most recently received from the server, not including data from previous calls. + /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is + /// also important to note that the server data in any `Response` object will be `nil`. + /// + /// - parameter closure: The code to be executed periodically during the lifecycle of the request. + /// + /// - returns: The request. + @discardableResult + open func stream(closure: ((Data) -> Void)? = nil) -> Self { + dataDelegate.dataStream = closure + return self + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + dataDelegate.progressHandler = (closure, queue) + return self + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. +open class DownloadRequest: Request { + + // MARK: Helper Types + + /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the + /// destination URL. + public struct DownloadOptions: OptionSet { + /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. + public let rawValue: UInt + + /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. + public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) + + /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. + public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) + + /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. + /// + /// - parameter rawValue: The raw bitmask value for the option. + /// + /// - returns: A new log level instance. + public init(rawValue: UInt) { + self.rawValue = rawValue + } + } + + /// A closure executed once a download request has successfully completed in order to determine where to move the + /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL + /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and + /// the options defining how the file should be moved. + public typealias DownloadFileDestination = ( + _ temporaryURL: URL, + _ response: HTTPURLResponse) + -> (destinationURL: URL, options: DownloadOptions) + + enum Downloadable: TaskConvertible { + case request(URLRequest) + case resumeData(Data) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .request(urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.downloadTask(with: urlRequest) } + case let .resumeData(resumeData): + task = queue.sync { session.downloadTask(withResumeData: resumeData) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { + return urlRequest + } + + return nil + } + + /// The resume data of the underlying download task if available after a failure. + open var resumeData: Data? { return downloadDelegate.resumeData } + + /// The progress of downloading the response data from the server for the request. + open var progress: Progress { return downloadDelegate.progress } + + var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } + + // MARK: State + + /// Cancels the request. + open override func cancel() { + downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidCancel, + object: self, + userInfo: [Notification.Key.Task: task as Any] + ) + } + + // MARK: Progress + + /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is read from the server. + /// + /// - returns: The request. + @discardableResult + open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + downloadDelegate.progressHandler = (closure, queue) + return self + } + + // MARK: Destination + + /// Creates a download file destination closure which uses the default file manager to move the temporary file to a + /// file URL in the first available directory with the specified search path directory and search path domain mask. + /// + /// - parameter directory: The search path directory. `.DocumentDirectory` by default. + /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. + /// + /// - returns: A download file destination closure. + open class func suggestedDownloadDestination( + for directory: FileManager.SearchPathDirectory = .documentDirectory, + in domain: FileManager.SearchPathDomainMask = .userDomainMask) + -> DownloadFileDestination + { + return { temporaryURL, response in + let directoryURLs = FileManager.default.urls(for: directory, in: domain) + + if !directoryURLs.isEmpty { + return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) + } + + return (temporaryURL, []) + } + } +} + +// MARK: - + +/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. +open class UploadRequest: DataRequest { + + // MARK: Helper Types + + enum Uploadable: TaskConvertible { + case data(Data, URLRequest) + case file(URL, URLRequest) + case stream(InputStream, URLRequest) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + do { + let task: URLSessionTask + + switch self { + case let .data(data, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, from: data) } + case let .file(url, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } + case let .stream(_, urlRequest): + let urlRequest = try urlRequest.adapt(using: adapter) + task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } + } + + return task + } catch { + throw AdaptError(error: error) + } + } + } + + // MARK: Properties + + /// The request sent or to be sent to the server. + open override var request: URLRequest? { + if let request = super.request { return request } + + guard let uploadable = originalTask as? Uploadable else { return nil } + + switch uploadable { + case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): + return urlRequest + } + } + + /// The progress of uploading the payload to the server for the upload request. + open var uploadProgress: Progress { return uploadDelegate.uploadProgress } + + var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } + + // MARK: Upload Progress + + /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to + /// the server. + /// + /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress + /// of data being read from the server. + /// + /// - parameter queue: The dispatch queue to execute the closure on. + /// - parameter closure: The code to be executed periodically as data is sent to the server. + /// + /// - returns: The request. + @discardableResult + open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { + uploadDelegate.uploadProgressHandler = (closure, queue) + return self + } +} + +// MARK: - + +#if !os(watchOS) + +/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +open class StreamRequest: Request { + enum Streamable: TaskConvertible { + case stream(hostName: String, port: Int) + case netService(NetService) + + func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { + let task: URLSessionTask + + switch self { + case let .stream(hostName, port): + task = queue.sync { session.streamTask(withHostName: hostName, port: port) } + case let .netService(netService): + task = queue.sync { session.streamTask(with: netService) } + } + + return task + } + } +} + +#endif diff --git a/Pods/Alamofire/Source/Response.swift b/Pods/Alamofire/Source/Response.swift new file mode 100644 index 0000000..747a471 --- /dev/null +++ b/Pods/Alamofire/Source/Response.swift @@ -0,0 +1,567 @@ +// +// Response.swift +// +// Copyright (c) 2014 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 Foundation + +/// Used to store all data associated with an non-serialized response of a data or upload request. +public struct DefaultDataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDataResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - data: The data returned by the server. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.data = data + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a data or upload request. +public struct DataResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The data returned by the server. + public let data: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter data: The data returned by the server. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DataResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.data = data + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the server data, the response serialization result and the timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[Data]: \(data?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DataResponse { + /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result + /// value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's + /// result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DataResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DataResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DataResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DataResponse { + var response = DataResponse( + request: request, + response: self.response, + data: data, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +/// Used to store all data associated with an non-serialized response of a download request. +public struct DefaultDownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The error encountered while executing or validating the request. + public let error: Error? + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + var _metrics: AnyObject? + + /// Creates a `DefaultDownloadResponse` instance from the specified parameters. + /// + /// - Parameters: + /// - request: The URL request sent to the server. + /// - response: The server's response to the URL request. + /// - temporaryURL: The temporary destination URL of the data returned from the server. + /// - destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - resumeData: The resume data generated if the request was cancelled. + /// - error: The error encountered while executing or validating the request. + /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. + /// - metrics: The task metrics containing the request / response statistics. `nil` by default. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + error: Error?, + timeline: Timeline = Timeline(), + metrics: AnyObject? = nil) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.error = error + self.timeline = timeline + } +} + +// MARK: - + +/// Used to store all data associated with a serialized response of a download request. +public struct DownloadResponse { + /// The URL request sent to the server. + public let request: URLRequest? + + /// The server's response to the URL request. + public let response: HTTPURLResponse? + + /// The temporary destination URL of the data returned from the server. + public let temporaryURL: URL? + + /// The final destination URL of the data returned from the server if it was moved. + public let destinationURL: URL? + + /// The resume data generated if the request was cancelled. + public let resumeData: Data? + + /// The result of response serialization. + public let result: Result + + /// The timeline of the complete lifecycle of the request. + public let timeline: Timeline + + /// Returns the associated value of the result if it is a success, `nil` otherwise. + public var value: Value? { return result.value } + + /// Returns the associated error value if the result if it is a failure, `nil` otherwise. + public var error: Error? { return result.error } + + var _metrics: AnyObject? + + /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. + /// + /// - parameter request: The URL request sent to the server. + /// - parameter response: The server's response to the URL request. + /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. + /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. + /// - parameter resumeData: The resume data generated if the request was cancelled. + /// - parameter result: The result of response serialization. + /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. + /// + /// - returns: The new `DownloadResponse` instance. + public init( + request: URLRequest?, + response: HTTPURLResponse?, + temporaryURL: URL?, + destinationURL: URL?, + resumeData: Data?, + result: Result, + timeline: Timeline = Timeline()) + { + self.request = request + self.response = response + self.temporaryURL = temporaryURL + self.destinationURL = destinationURL + self.resumeData = resumeData + self.result = result + self.timeline = timeline + } +} + +// MARK: - + +extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + return result.debugDescription + } + + /// The debug textual representation used when written to an output stream, which includes the URL request, the URL + /// response, the temporary and destination URLs, the resume data, the response serialization result and the + /// timeline. + public var debugDescription: String { + var output: [String] = [] + + output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") + output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") + output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") + output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") + output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") + output.append("[Result]: \(result.debugDescription)") + output.append("[Timeline]: \(timeline.debugDescription)") + + return output.joined(separator: "\n") + } +} + +// MARK: - + +extension DownloadResponse { + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleInt = possibleData.map { $0.count } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's + /// result is a failure, returns a response wrapping the same failure. + public func map(_ transform: (Value) -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.map(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped + /// result value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance's result. + /// + /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this + /// instance's result is a failure, returns the same failure. + public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMap(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let withMyError = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func mapError(_ transform: (Error) -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.mapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } + + /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: DownloadResponse = ... + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `DownloadResponse` instance containing the result of the transform. + public func flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { + var response = DownloadResponse( + request: request, + response: self.response, + temporaryURL: temporaryURL, + destinationURL: destinationURL, + resumeData: resumeData, + result: result.flatMapError(transform), + timeline: timeline + ) + + response._metrics = _metrics + + return response + } +} + +// MARK: - + +protocol Response { + /// The task metrics containing the request / response statistics. + var _metrics: AnyObject? { get set } + mutating func add(_ metrics: AnyObject?) +} + +extension Response { + mutating func add(_ metrics: AnyObject?) { + #if !os(watchOS) + guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } + guard let metrics = metrics as? URLSessionTaskMetrics else { return } + + _metrics = metrics + #endif + } +} + +// MARK: - + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DataResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DefaultDownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} + +@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) +extension DownloadResponse: Response { +#if !os(watchOS) + /// The task metrics containing the request / response statistics. + public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } +#endif +} diff --git a/Pods/Alamofire/Source/ResponseSerialization.swift b/Pods/Alamofire/Source/ResponseSerialization.swift new file mode 100644 index 0000000..9cc105a --- /dev/null +++ b/Pods/Alamofire/Source/ResponseSerialization.swift @@ -0,0 +1,715 @@ +// +// ResponseSerialization.swift +// +// Copyright (c) 2014 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 Foundation + +/// The type in which all data response serializers must conform to in order to serialize a response. +public protocol DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DataResponseSerializer: DataResponseSerializerProtocol { + /// The type of serialized object to be created by this `DataResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, data and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - + +/// The type in which all download response serializers must conform to in order to serialize a response. +public protocol DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializerType`. + associatedtype SerializedObject + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } +} + +// MARK: - + +/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. +public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { + /// The type of serialized object to be created by this `DownloadResponseSerializer`. + public typealias SerializedObject = Value + + /// A closure used by response handlers that takes a request, response, url and error and returns a result. + public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result + + /// Initializes the `ResponseSerializer` instance with the given serialize response closure. + /// + /// - parameter serializeResponse: The closure used to serialize the response. + /// + /// - returns: The new generic response serializer instance. + public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { + self.serializeResponse = serializeResponse + } +} + +// MARK: - Timeline + +extension Request { + var timeline: Timeline { + let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() + let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() + let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime + + return Timeline( + requestStartTime: requestStartTime, + initialResponseTime: initialResponseTime, + requestCompletedTime: requestCompletedTime, + serializationCompletedTime: CFAbsoluteTimeGetCurrent() + ) + } +} + +// MARK: - Default + +extension DataRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var dataResponse = DefaultDataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + error: self.delegate.error, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + completionHandler(dataResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.delegate.data, + self.delegate.error + ) + + var dataResponse = DataResponse( + request: self.request, + response: self.response, + data: self.delegate.data, + result: result, + timeline: self.timeline + ) + + dataResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } + } + + return self + } +} + +extension DownloadRequest { + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DefaultDownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + (queue ?? DispatchQueue.main).async { + var downloadResponse = DefaultDownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + error: self.downloadDelegate.error, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + completionHandler(downloadResponse) + } + } + + return self + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter queue: The queue on which the completion handler is dispatched. + /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, + /// and data contained in the destination url. + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func response( + queue: DispatchQueue? = nil, + responseSerializer: T, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + delegate.queue.addOperation { + let result = responseSerializer.serializeResponse( + self.request, + self.response, + self.downloadDelegate.fileURL, + self.downloadDelegate.error + ) + + var downloadResponse = DownloadResponse( + request: self.request, + response: self.response, + temporaryURL: self.downloadDelegate.temporaryURL, + destinationURL: self.downloadDelegate.destinationURL, + resumeData: self.downloadDelegate.resumeData, + result: result, + timeline: self.timeline + ) + + downloadResponse.add(self.delegate.metrics) + + (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } + } + + return self + } +} + +// MARK: - Data + +extension Request { + /// Returns a result data type that contains the response data as-is. + /// + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + return .success(validData) + } +} + +extension DataRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseData(response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns the associated data as-is. + /// + /// - returns: A data response serializer. + public static func dataResponseSerializer() -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseData(response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter completionHandler: The code to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseData( + queue: DispatchQueue? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.dataResponseSerializer(), + completionHandler: completionHandler + ) + } +} + +// MARK: - String + +extension Request { + /// Returns a result string type initialized from the response data with the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseString( + encoding: String.Encoding?, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } + + guard let validData = data else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) + } + + var convertedEncoding = encoding + + if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { + convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( + CFStringConvertIANACharSetNameToEncoding(encodingName)) + ) + } + + let actualEncoding = convertedEncoding ?? .isoLatin1 + + if let string = String(data: validData, encoding: actualEncoding) { + return .success(string) + } else { + return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a result string type initialized from the response data with + /// the specified string encoding. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server + /// response, falling back to the default HTTP default character set, ISO-8859-1. + /// + /// - returns: A string response serializer. + public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the + /// server response, falling back to the default HTTP default character set, + /// ISO-8859-1. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseString( + queue: DispatchQueue? = nil, + encoding: String.Encoding? = nil, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), + completionHandler: completionHandler + ) + } +} + +// MARK: - JSON + +extension Request { + /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` + /// with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponseJSON( + options: JSONSerialization.ReadingOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let json = try JSONSerialization.jsonObject(with: validData, options: options) + return .success(json) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns a JSON object result type constructed from the response data using + /// `JSONSerialization` with the specified reading options. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// + /// - returns: A JSON object response serializer. + public static func jsonResponseSerializer( + options: JSONSerialization.ReadingOptions = .allowFragments) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responseJSON( + queue: DispatchQueue? = nil, + options: JSONSerialization.ReadingOptions = .allowFragments, + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +// MARK: - Property List + +extension Request { + /// Returns a plist object contained in a result type constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter response: The response from the server. + /// - parameter data: The data returned from the server. + /// - parameter error: The error already encountered if it exists. + /// + /// - returns: The result data type. + public static func serializeResponsePropertyList( + options: PropertyListSerialization.ReadOptions, + response: HTTPURLResponse?, + data: Data?, + error: Error?) + -> Result + { + guard error == nil else { return .failure(error!) } + + if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } + + guard let validData = data, validData.count > 0 else { + return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) + } + + do { + let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) + return .success(plist) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) + } + } +} + +extension DataRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DataResponseSerializer + { + return DataResponseSerializer { _, response, data, error in + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DataResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DataRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +extension DownloadRequest { + /// Creates a response serializer that returns an object constructed from the response data using + /// `PropertyListSerialization` with the specified reading options. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// + /// - returns: A property list object response serializer. + public static func propertyListResponseSerializer( + options: PropertyListSerialization.ReadOptions = []) + -> DownloadResponseSerializer + { + return DownloadResponseSerializer { _, response, fileURL, error in + guard error == nil else { return .failure(error!) } + + guard let fileURL = fileURL else { + return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) + } + + do { + let data = try Data(contentsOf: fileURL) + return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) + } catch { + return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) + } + } + } + + /// Adds a handler to be called once the request has finished. + /// + /// - parameter options: The property list reading options. Defaults to `[]`. + /// - parameter completionHandler: A closure to be executed once the request has finished. + /// + /// - returns: The request. + @discardableResult + public func responsePropertyList( + queue: DispatchQueue? = nil, + options: PropertyListSerialization.ReadOptions = [], + completionHandler: @escaping (DownloadResponse) -> Void) + -> Self + { + return response( + queue: queue, + responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), + completionHandler: completionHandler + ) + } +} + +/// A set of HTTP response status code that do not contain response data. +private let emptyDataStatusCodes: Set = [204, 205] diff --git a/Pods/Alamofire/Source/Result.swift b/Pods/Alamofire/Source/Result.swift new file mode 100644 index 0000000..e092808 --- /dev/null +++ b/Pods/Alamofire/Source/Result.swift @@ -0,0 +1,300 @@ +// +// Result.swift +// +// Copyright (c) 2014 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 Foundation + +/// Used to represent whether a request was successful or encountered an error. +/// +/// - success: The request and all post processing operations were successful resulting in the serialization of the +/// provided associated value. +/// +/// - failure: The request encountered an error resulting in a failure. The associated values are the original data +/// provided by the server as well as the error that caused the failure. +public enum Result { + case success(Value) + case failure(Error) + + /// Returns `true` if the result is a success, `false` otherwise. + public var isSuccess: Bool { + switch self { + case .success: + return true + case .failure: + return false + } + } + + /// Returns `true` if the result is a failure, `false` otherwise. + public var isFailure: Bool { + return !isSuccess + } + + /// Returns the associated value if the result is a success, `nil` otherwise. + public var value: Value? { + switch self { + case .success(let value): + return value + case .failure: + return nil + } + } + + /// Returns the associated error value if the result is a failure, `nil` otherwise. + public var error: Error? { + switch self { + case .success: + return nil + case .failure(let error): + return error + } + } +} + +// MARK: - CustomStringConvertible + +extension Result: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes whether the result was a + /// success or failure. + public var description: String { + switch self { + case .success: + return "SUCCESS" + case .failure: + return "FAILURE" + } + } +} + +// MARK: - CustomDebugStringConvertible + +extension Result: CustomDebugStringConvertible { + /// The debug textual representation used when written to an output stream, which includes whether the result was a + /// success or failure in addition to the value or error. + public var debugDescription: String { + switch self { + case .success(let value): + return "SUCCESS: \(value)" + case .failure(let error): + return "FAILURE: \(error)" + } + } +} + +// MARK: - Functional APIs + +extension Result { + /// Creates a `Result` instance from the result of a closure. + /// + /// A failure result is created when the closure throws, and a success result is created when the closure + /// succeeds without throwing an error. + /// + /// func someString() throws -> String { ... } + /// + /// let result = Result(value: { + /// return try someString() + /// }) + /// + /// // The type of result is Result + /// + /// The trailing closure syntax is also supported: + /// + /// let result = Result { try someString() } + /// + /// - parameter value: The closure to execute and create the result for. + public init(value: () throws -> Value) { + do { + self = try .success(value()) + } catch { + self = .failure(error) + } + } + + /// Returns the success value, or throws the failure error. + /// + /// let possibleString: Result = .success("success") + /// try print(possibleString.unwrap()) + /// // Prints "success" + /// + /// let noString: Result = .failure(error) + /// try print(noString.unwrap()) + /// // Throws error + public func unwrap() throws -> Value { + switch self { + case .success(let value): + return value + case .failure(let error): + throw error + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `map` method with a closure that does not throw. For example: + /// + /// let possibleData: Result = .success(Data()) + /// let possibleInt = possibleData.map { $0.count } + /// try print(possibleInt.unwrap()) + /// // Prints "0" + /// + /// let noData: Result = .failure(error) + /// let noInt = noData.map { $0.count } + /// try print(noInt.unwrap()) + /// // Throws error + /// + /// - parameter transform: A closure that takes the success value of the `Result` instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func map(_ transform: (Value) -> T) -> Result { + switch self { + case .success(let value): + return .success(transform(value)) + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `flatMap` method with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMap { + /// try JSONSerialization.jsonObject(with: $0) + /// } + /// + /// - parameter transform: A closure that takes the success value of the instance. + /// + /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the + /// same failure. + public func flatMap(_ transform: (Value) throws -> T) -> Result { + switch self { + case .success(let value): + do { + return try .success(transform(value)) + } catch { + return .failure(error) + } + case .failure(let error): + return .failure(error) + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `mapError` function with a closure that does not throw. For example: + /// + /// let possibleData: Result = .failure(someError) + /// let withMyError: Result = possibleData.mapError { MyError.error($0) } + /// + /// - Parameter transform: A closure that takes the error of the instance. + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func mapError(_ transform: (Error) -> T) -> Result { + switch self { + case .failure(let error): + return .failure(transform(error)) + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `flatMapError` function with a closure that may throw an error. For example: + /// + /// let possibleData: Result = .success(Data(...)) + /// let possibleObject = possibleData.flatMapError { + /// try someFailableFunction(taking: $0) + /// } + /// + /// - Parameter transform: A throwing closure that takes the error of the instance. + /// + /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns + /// the same instance. + public func flatMapError(_ transform: (Error) throws -> T) -> Result { + switch self { + case .failure(let error): + do { + return try .failure(transform(error)) + } catch { + return .failure(error) + } + case .success: + return self + } + } + + /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. + /// + /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withValue(_ closure: (Value) throws -> Void) rethrows -> Result { + if case let .success(value) = self { try closure(value) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. + /// + /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A closure that takes the success value of this instance. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func withError(_ closure: (Error) throws -> Void) rethrows -> Result { + if case let .failure(error) = self { try closure(error) } + + return self + } + + /// Evaluates the specified closure when the `Result` is a success. + /// + /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifSuccess(_ closure: () throws -> Void) rethrows -> Result { + if isSuccess { try closure() } + + return self + } + + /// Evaluates the specified closure when the `Result` is a failure. + /// + /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. + /// + /// - Parameter closure: A `Void` closure. + /// - Returns: This `Result` instance, unmodified. + @discardableResult + public func ifFailure(_ closure: () throws -> Void) rethrows -> Result { + if isFailure { try closure() } + + return self + } +} diff --git a/Pods/Alamofire/Source/ServerTrustPolicy.swift b/Pods/Alamofire/Source/ServerTrustPolicy.swift new file mode 100644 index 0000000..dea099e --- /dev/null +++ b/Pods/Alamofire/Source/ServerTrustPolicy.swift @@ -0,0 +1,307 @@ +// +// ServerTrustPolicy.swift +// +// Copyright (c) 2014 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 Foundation + +/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. +open class ServerTrustPolicyManager { + /// The dictionary of policies mapped to a particular host. + public let policies: [String: ServerTrustPolicy] + + /// Initializes the `ServerTrustPolicyManager` instance with the given policies. + /// + /// Since different servers and web services can have different leaf certificates, intermediate and even root + /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This + /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key + /// pinning for host3 and disabling evaluation for host4. + /// + /// - parameter policies: A dictionary of all policies mapped to a particular host. + /// + /// - returns: The new `ServerTrustPolicyManager` instance. + public init(policies: [String: ServerTrustPolicy]) { + self.policies = policies + } + + /// Returns the `ServerTrustPolicy` for the given host if applicable. + /// + /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override + /// this method and implement more complex mapping implementations such as wildcards. + /// + /// - parameter host: The host to use when searching for a matching policy. + /// + /// - returns: The server trust policy for the given host if found. + open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { + return policies[host] + } +} + +// MARK: - + +extension URLSession { + private struct AssociatedKeys { + static var managerKey = "URLSession.ServerTrustPolicyManager" + } + + var serverTrustPolicyManager: ServerTrustPolicyManager? { + get { + return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager + } + set (manager) { + objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } +} + +// MARK: - ServerTrustPolicy + +/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when +/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust +/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. +/// +/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) 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 pinning enabled. +/// +/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to +/// validate the host provided by the challenge. Applications are encouraged to always +/// validate the host in production environments to guarantee the validity of the server's +/// certificate chain. +/// +/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to +/// validate the host provided by the challenge as well as specify the revocation flags for +/// testing for revoked certificates. Apple platforms did not start testing for revoked +/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is +/// demonstrated in our TLS tests. Applications are encouraged to always validate the host +/// in production environments to guarantee the validity of the server's certificate chain. +/// +/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is +/// considered valid if one of the pinned certificates match one of the server certificates. +/// By validating both the certificate chain and host, certificate pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered +/// valid if one of the pinned public keys match one of the server certificate public keys. +/// By validating both the certificate chain and host, public key pinning provides a very +/// secure form of server trust validation mitigating most, if not all, MITM attacks. +/// Applications are encouraged to always validate the host and require a valid certificate +/// chain in production environments. +/// +/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. +/// +/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. +public enum ServerTrustPolicy { + case performDefaultEvaluation(validateHost: Bool) + case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) + case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) + case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) + case disableEvaluation + case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) + + // MARK: - Bundle Location + + /// Returns all certificates within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `.cer` files. + /// + /// - returns: All certificates within the given bundle. + public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { + var certificates: [SecCertificate] = [] + + let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in + bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) + }.joined()) + + for path in paths { + if + let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, + let certificate = SecCertificateCreateWithData(nil, certificateData) + { + certificates.append(certificate) + } + } + + return certificates + } + + /// Returns all public keys within the given bundle with a `.cer` file extension. + /// + /// - parameter bundle: The bundle to search for all `*.cer` files. + /// + /// - returns: All public keys within the given bundle. + public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for certificate in certificates(in: bundle) { + if let publicKey = publicKey(for: certificate) { + publicKeys.append(publicKey) + } + } + + return publicKeys + } + + // MARK: - Evaluation + + /// Evaluates whether the server trust is valid for the given host. + /// + /// - parameter serverTrust: The server trust to evaluate. + /// - parameter host: The host of the challenge protection space. + /// + /// - returns: Whether the server trust is valid. + public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { + var serverTrustIsValid = false + + switch self { + case let .performDefaultEvaluation(validateHost): + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .performRevokedEvaluation(validateHost, revocationFlags): + let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) + SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) + + serverTrustIsValid = trustIsValid(serverTrust) + case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) + SecTrustSetAnchorCertificatesOnly(serverTrust, true) + + serverTrustIsValid = trustIsValid(serverTrust) + } else { + let serverCertificatesDataArray = certificateData(for: serverTrust) + let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) + + outerLoop: for serverCertificateData in serverCertificatesDataArray { + for pinnedCertificateData in pinnedCertificatesDataArray { + if serverCertificateData == pinnedCertificateData { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): + var certificateChainEvaluationPassed = true + + if validateCertificateChain { + let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) + SecTrustSetPolicies(serverTrust, policy) + + certificateChainEvaluationPassed = trustIsValid(serverTrust) + } + + if certificateChainEvaluationPassed { + outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { + for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { + if serverPublicKey.isEqual(pinnedPublicKey) { + serverTrustIsValid = true + break outerLoop + } + } + } + } + case .disableEvaluation: + serverTrustIsValid = true + case let .customEvaluation(closure): + serverTrustIsValid = closure(serverTrust, host) + } + + return serverTrustIsValid + } + + // MARK: - Private - Trust Validation + + private func trustIsValid(_ trust: SecTrust) -> Bool { + var isValid = false + + var result = SecTrustResultType.invalid + let status = SecTrustEvaluate(trust, &result) + + if status == errSecSuccess { + let unspecified = SecTrustResultType.unspecified + let proceed = SecTrustResultType.proceed + + + isValid = result == unspecified || result == proceed + } + + return isValid + } + + // MARK: - Private - Certificate Data + + private func certificateData(for trust: SecTrust) -> [Data] { + var certificates: [SecCertificate] = [] + + for index in 0.. [Data] { + return certificates.map { SecCertificateCopyData($0) as Data } + } + + // MARK: - Private - Public Key Extraction + + private static func publicKeys(for trust: SecTrust) -> [SecKey] { + var publicKeys: [SecKey] = [] + + for index in 0.. SecKey? { + var publicKey: SecKey? + + let policy = SecPolicyCreateBasicX509() + var trust: SecTrust? + let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) + + if let trust = trust, trustCreationStatus == errSecSuccess { + publicKey = SecTrustCopyPublicKey(trust) + } + + return publicKey + } +} diff --git a/Pods/Alamofire/Source/SessionDelegate.swift b/Pods/Alamofire/Source/SessionDelegate.swift new file mode 100644 index 0000000..4964f1e --- /dev/null +++ b/Pods/Alamofire/Source/SessionDelegate.swift @@ -0,0 +1,725 @@ +// +// SessionDelegate.swift +// +// Copyright (c) 2014 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 Foundation + +/// Responsible for handling all delegate callbacks for the underlying session. +open class SessionDelegate: NSObject { + + // MARK: URLSessionDelegate Overrides + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. + open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. + open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. + open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. + open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? + + // MARK: URLSessionTaskDelegate Overrides + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. + open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. + open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and + /// requires the caller to call the `completionHandler`. + open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. + open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + + /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and + /// requires the caller to call the `completionHandler`. + open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. + open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. + open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? + + // MARK: URLSessionDataDelegate Overrides + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. + open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. + open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. + open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + + /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. + open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and + /// requires caller to call the `completionHandler`. + open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? + + // MARK: URLSessionDownloadDelegate Overrides + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. + open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. + open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + + /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. + open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + // MARK: URLSessionStreamDelegate Overrides + +#if !os(watchOS) + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskReadClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskWriteClosed = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { + get { + return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void + } + set { + _streamTaskBetterRouteDiscovered = newValue + } + } + + /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { + get { + return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void + } + set { + _streamTaskDidBecomeInputStream = newValue + } + } + + var _streamTaskReadClosed: Any? + var _streamTaskWriteClosed: Any? + var _streamTaskBetterRouteDiscovered: Any? + var _streamTaskDidBecomeInputStream: Any? + +#endif + + // MARK: Properties + + var retrier: RequestRetrier? + weak var sessionManager: SessionManager? + + var requests: [Int: Request] = [:] + private let lock = NSLock() + + /// Access the task delegate for the specified task in a thread-safe manner. + open subscript(task: URLSessionTask) -> Request? { + get { + lock.lock() ; defer { lock.unlock() } + return requests[task.taskIdentifier] + } + set { + lock.lock() ; defer { lock.unlock() } + requests[task.taskIdentifier] = newValue + } + } + + // MARK: Lifecycle + + /// Initializes the `SessionDelegate` instance. + /// + /// - returns: The new `SessionDelegate` instance. + public override init() { + super.init() + } + + // MARK: NSObject Overrides + + /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond + /// to a specified message. + /// + /// - parameter selector: A selector that identifies a message. + /// + /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. + open override func responds(to selector: Selector) -> Bool { + #if !os(macOS) + if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { + return sessionDidFinishEventsForBackgroundURLSession != nil + } + #endif + + #if !os(watchOS) + if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { + switch selector { + case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): + return streamTaskReadClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): + return streamTaskWriteClosed != nil + case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): + return streamTaskBetterRouteDiscovered != nil + case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): + return streamTaskDidBecomeInputAndOutputStreams != nil + default: + break + } + } + #endif + + switch selector { + case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): + return sessionDidBecomeInvalidWithError != nil + case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): + return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) + case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): + return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) + case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): + return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) + default: + return type(of: self).instancesRespond(to: selector) + } + } +} + +// MARK: - URLSessionDelegate + +extension SessionDelegate: URLSessionDelegate { + /// Tells the delegate that the session has been invalidated. + /// + /// - parameter session: The session object that was invalidated. + /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. + open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { + sessionDidBecomeInvalidWithError?(session, error) + } + + /// Requests credentials from the delegate in response to a session-level authentication request from the + /// remote server. + /// + /// - parameter session: The session containing the task that requested authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard sessionDidReceiveChallengeWithCompletion == nil else { + sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) + return + } + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { + (disposition, credential) = sessionDidReceiveChallenge(session, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } + + completionHandler(disposition, credential) + } + +#if !os(macOS) + + /// Tells the delegate that all messages enqueued for a session have been delivered. + /// + /// - parameter session: The session that no longer has any outstanding requests. + open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { + sessionDidFinishEventsForBackgroundURLSession?(session) + } + +#endif +} + +// MARK: - URLSessionTaskDelegate + +extension SessionDelegate: URLSessionTaskDelegate { + /// Tells the delegate that the remote server requested an HTTP redirect. + /// + /// - parameter session: The session containing the task whose request resulted in a redirect. + /// - parameter task: The task whose request resulted in a redirect. + /// - parameter response: An object containing the server’s response to the original request. + /// - parameter request: A URL request object filled out with the new location. + /// - parameter completionHandler: A closure that your handler should call with either the value of the request + /// parameter, a modified URL request object, or NULL to refuse the redirect and + /// return the body of the redirect response. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard taskWillPerformHTTPRedirectionWithCompletion == nil else { + taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) + return + } + + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + /// Requests credentials from the delegate in response to an authentication request from the remote server. + /// + /// - parameter session: The session containing the task whose request requires authentication. + /// - parameter task: The task whose request requires authentication. + /// - parameter challenge: An object that contains the request for authentication. + /// - parameter completionHandler: A handler that your delegate method must call providing the disposition + /// and credential. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + guard taskDidReceiveChallengeWithCompletion == nil else { + taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) + return + } + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + let result = taskDidReceiveChallenge(session, task, challenge) + completionHandler(result.0, result.1) + } else if let delegate = self[task]?.delegate { + delegate.urlSession( + session, + task: task, + didReceive: challenge, + completionHandler: completionHandler + ) + } else { + urlSession(session, didReceive: challenge, completionHandler: completionHandler) + } + } + + /// Tells the delegate when a task requires a new request body stream to send to the remote server. + /// + /// - parameter session: The session containing the task that needs a new body stream. + /// - parameter task: The task that needs a new body stream. + /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + guard taskNeedNewBodyStreamWithCompletion == nil else { + taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) + return + } + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + completionHandler(taskNeedNewBodyStream(session, task)) + } else if let delegate = self[task]?.delegate { + delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) + } + } + + /// Periodically informs the delegate of the progress of sending body content to the server. + /// + /// - parameter session: The session containing the data task. + /// - parameter task: The data task. + /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. + /// - parameter totalBytesSent: The total number of bytes sent so far. + /// - parameter totalBytesExpectedToSend: The expected length of the body data. + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { + delegate.URLSession( + session, + task: task, + didSendBodyData: bytesSent, + totalBytesSent: totalBytesSent, + totalBytesExpectedToSend: totalBytesExpectedToSend + ) + } + } + +#if !os(watchOS) + + /// Tells the delegate that the session finished collecting metrics for the task. + /// + /// - parameter session: The session collecting the metrics. + /// - parameter task: The task whose metrics have been collected. + /// - parameter metrics: The collected metrics. + @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) + @objc(URLSession:task:didFinishCollectingMetrics:) + open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { + self[task]?.delegate.metrics = metrics + } + +#endif + + /// Tells the delegate that the task finished transferring data. + /// + /// - parameter session: The session containing the task whose request finished transferring data. + /// - parameter task: The task whose request finished transferring data. + /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + /// Executed after it is determined that the request is not going to be retried + let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in + guard let strongSelf = self else { return } + + strongSelf.taskDidComplete?(session, task, error) + + strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) + + var userInfo: [String: Any] = [Notification.Key.Task: task] + + if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data { + userInfo[Notification.Key.ResponseData] = data + } + + NotificationCenter.default.post( + name: Notification.Name.Task.DidComplete, + object: strongSelf, + userInfo: userInfo + ) + + strongSelf[task] = nil + } + + guard let request = self[task], let sessionManager = sessionManager else { + completeTask(session, task, error) + return + } + + // Run all validations on the request before checking if an error occurred + request.validations.forEach { $0() } + + // Determine whether an error has occurred + var error: Error? = error + + if request.delegate.error != nil { + error = request.delegate.error + } + + /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request + /// should be retried. Otherwise, complete the task by notifying the task delegate. + if let retrier = retrier, let error = error { + retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in + guard shouldRetry else { completeTask(session, task, error) ; return } + + DispatchQueue.utility.after(timeDelay) { [weak self] in + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false + + if retrySucceeded, let task = request.task { + strongSelf[task] = request + return + } else { + completeTask(session, task, error) + } + } + } + } else { + completeTask(session, task, error) + } + } +} + +// MARK: - URLSessionDataDelegate + +extension SessionDelegate: URLSessionDataDelegate { + /// Tells the delegate that the data task received the initial reply (headers) from the server. + /// + /// - parameter session: The session containing the data task that received an initial reply. + /// - parameter dataTask: The data task that received an initial reply. + /// - parameter response: A URL response object populated with headers. + /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a + /// constant to indicate whether the transfer should continue as a data task or + /// should become a download task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard dataTaskDidReceiveResponseWithCompletion == nil else { + dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) + return + } + + var disposition: URLSession.ResponseDisposition = .allow + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + /// Tells the delegate that the data task was changed to a download task. + /// + /// - parameter session: The session containing the task that was replaced by a download task. + /// - parameter dataTask: The data task that was replaced by a download task. + /// - parameter downloadTask: The new download task that replaced the data task. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { + dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) + } else { + self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) + } + } + + /// Tells the delegate that the data task has received some of the expected data. + /// + /// - parameter session: The session containing the data task that provided data. + /// - parameter dataTask: The data task that provided data. + /// - parameter data: A data object containing the transferred data. + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession(session, dataTask: dataTask, didReceive: data) + } + } + + /// Asks the delegate whether the data (or upload) task should store the response in the cache. + /// + /// - parameter session: The session containing the data (or upload) task. + /// - parameter dataTask: The data (or upload) task. + /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current + /// caching policy and the values of certain received headers, such as the Pragma + /// and Cache-Control headers. + /// - parameter completionHandler: A block that your handler must call, providing either the original proposed + /// response, a modified version of that response, or NULL to prevent caching the + /// response. If your delegate implements this method, it must call this completion + /// handler; otherwise, your app leaks memory. + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + guard dataTaskWillCacheResponseWithCompletion == nil else { + dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) + return + } + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) + } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { + delegate.urlSession( + session, + dataTask: dataTask, + willCacheResponse: proposedResponse, + completionHandler: completionHandler + ) + } else { + completionHandler(proposedResponse) + } + } +} + +// MARK: - URLSessionDownloadDelegate + +extension SessionDelegate: URLSessionDownloadDelegate { + /// Tells the delegate that a download task has finished downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that finished. + /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either + /// open the file for reading or move it to a permanent location in your app’s sandbox + /// container directory before returning from this delegate method. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { + downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) + } + } + + /// Periodically informs the delegate about the download’s progress. + /// + /// - parameter session: The session containing the download task. + /// - parameter downloadTask: The download task. + /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate + /// method was called. + /// - parameter totalBytesWritten: The total number of bytes transferred so far. + /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length + /// header. If this header was not provided, the value is + /// `NSURLSessionTransferSizeUnknown`. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didWriteData: bytesWritten, + totalBytesWritten: totalBytesWritten, + totalBytesExpectedToWrite: totalBytesExpectedToWrite + ) + } + } + + /// Tells the delegate that the download task has resumed downloading. + /// + /// - parameter session: The session containing the download task that finished. + /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. + /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the + /// existing content, then this value is zero. Otherwise, this value is an + /// integer representing the number of bytes on disk that do not need to be + /// retrieved again. + /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. + /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. + open func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { + delegate.urlSession( + session, + downloadTask: downloadTask, + didResumeAtOffset: fileOffset, + expectedTotalBytes: expectedTotalBytes + ) + } + } +} + +// MARK: - URLSessionStreamDelegate + +#if !os(watchOS) + +@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) +extension SessionDelegate: URLSessionStreamDelegate { + /// Tells the delegate that the read side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { + streamTaskReadClosed?(session, streamTask) + } + + /// Tells the delegate that the write side of the connection has been closed. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { + streamTaskWriteClosed?(session, streamTask) + } + + /// Tells the delegate that the system has determined that a better route to the host is available. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { + streamTaskBetterRouteDiscovered?(session, streamTask) + } + + /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. + /// + /// - parameter session: The session. + /// - parameter streamTask: The stream task. + /// - parameter inputStream: The new input stream. + /// - parameter outputStream: The new output stream. + open func urlSession( + _ session: URLSession, + streamTask: URLSessionStreamTask, + didBecome inputStream: InputStream, + outputStream: OutputStream) + { + streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) + } +} + +#endif diff --git a/Pods/Alamofire/Source/SessionManager.swift b/Pods/Alamofire/Source/SessionManager.swift new file mode 100644 index 0000000..02c36a7 --- /dev/null +++ b/Pods/Alamofire/Source/SessionManager.swift @@ -0,0 +1,899 @@ +// +// SessionManager.swift +// +// Copyright (c) 2014 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 Foundation + +/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. +open class SessionManager { + + // MARK: - Helper Types + + /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as + /// associated values. + /// + /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with + /// streaming information. + /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding + /// error. + public enum MultipartFormDataEncodingResult { + case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) + case failure(Error) + } + + // MARK: - Properties + + /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use + /// directly for any ad hoc requests. + public static let `default`: SessionManager = { + let configuration = URLSessionConfiguration.default + configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders + + return SessionManager(configuration: configuration) + }() + + /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. + public static let defaultHTTPHeaders: HTTPHeaders = { + // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 + let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" + + // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in + let quality = 1.0 - (Double(index) * 0.1) + return "\(languageCode);q=\(quality)" + }.joined(separator: ", ") + + // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 + // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` + let userAgent: String = { + if let info = Bundle.main.infoDictionary { + let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" + let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" + let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" + let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" + + let osNameVersion: String = { + let version = ProcessInfo.processInfo.operatingSystemVersion + let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + + let osName: String = { + #if os(iOS) + return "iOS" + #elseif os(watchOS) + return "watchOS" + #elseif os(tvOS) + return "tvOS" + #elseif os(macOS) + return "OS X" + #elseif os(Linux) + return "Linux" + #else + return "Unknown" + #endif + }() + + return "\(osName) \(versionString)" + }() + + let alamofireVersion: String = { + guard + let afInfo = Bundle(for: SessionManager.self).infoDictionary, + let build = afInfo["CFBundleShortVersionString"] + else { return "Unknown" } + + return "Alamofire/\(build)" + }() + + return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" + } + + return "Alamofire" + }() + + return [ + "Accept-Encoding": acceptEncoding, + "Accept-Language": acceptLanguage, + "User-Agent": userAgent + ] + }() + + /// Default memory threshold used when encoding `MultipartFormData` in bytes. + public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 + + /// The underlying session. + public let session: URLSession + + /// The session delegate handling all the task and session delegate callbacks. + public let delegate: SessionDelegate + + /// Whether to start requests immediately after being constructed. `true` by default. + open var startRequestsImmediately: Bool = true + + /// The request adapter called each time a new request is created. + open var adapter: RequestAdapter? + + /// The request retrier called each time a request encounters an error to determine whether to retry the request. + open var retrier: RequestRetrier? { + get { return delegate.retrier } + set { delegate.retrier = newValue } + } + + /// The background completion handler closure provided by the UIApplicationDelegate + /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background + /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation + /// will automatically call the handler. + /// + /// If you need to handle your own events before the handler is called, then you need to override the + /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. + /// + /// `nil` by default. + open var backgroundCompletionHandler: (() -> Void)? + + let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) + + // MARK: - Lifecycle + + /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter configuration: The configuration used to construct the managed session. + /// `URLSessionConfiguration.default` by default. + /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by + /// default. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance. + public init( + configuration: URLSessionConfiguration = URLSessionConfiguration.default, + delegate: SessionDelegate = SessionDelegate(), + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + self.delegate = delegate + self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. + /// + /// - parameter session: The URL session. + /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. + /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust + /// challenges. `nil` by default. + /// + /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. + public init?( + session: URLSession, + delegate: SessionDelegate, + serverTrustPolicyManager: ServerTrustPolicyManager? = nil) + { + guard delegate === session.delegate else { return nil } + + self.delegate = delegate + self.session = session + + commonInit(serverTrustPolicyManager: serverTrustPolicyManager) + } + + private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { + session.serverTrustPolicyManager = serverTrustPolicyManager + + delegate.sessionManager = self + + delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in + guard let strongSelf = self else { return } + DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } + } + } + + deinit { + session.invalidateAndCancel() + } + + // MARK: - Data Request + + /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` + /// and `headers`. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil) + -> DataRequest + { + var originalRequest: URLRequest? + + do { + originalRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) + return request(encodedURLRequest) + } catch { + return request(originalRequest, failedWith: error) + } + } + + /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `DataRequest`. + @discardableResult + open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { + var originalRequest: URLRequest? + + do { + originalRequest = try urlRequest.asURLRequest() + let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) + + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + let request = DataRequest(session: session, requestTask: .data(originalTask, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return request(originalRequest, failedWith: error) + } + } + + // MARK: Private - Request Implementation + + private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { + var requestTask: Request.RequestTask = .data(nil, nil) + + if let urlRequest = urlRequest { + let originalTask = DataRequest.Requestable(urlRequest: urlRequest) + requestTask = .data(originalTask, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: request, with: underlyingError) + } else { + if startRequestsImmediately { request.resume() } + } + + return request + } + + // MARK: - Download Request + + // MARK: URL Request + + /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, + /// `headers` and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.get` by default. + /// - parameter parameters: The parameters. `nil` by default. + /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ url: URLConvertible, + method: HTTPMethod = .get, + parameters: Parameters? = nil, + encoding: ParameterEncoding = URLEncoding.default, + headers: HTTPHeaders? = nil, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) + return download(encodedURLRequest, to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save + /// them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter urlRequest: The URL request + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + _ urlRequest: URLRequestConvertible, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + do { + let urlRequest = try urlRequest.asURLRequest() + return download(.request(urlRequest), to: destination) + } catch { + return download(nil, to: destination, failedWith: error) + } + } + + // MARK: Resume Data + + /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve + /// the contents of the original request and save them to the `destination`. + /// + /// If `destination` is not specified, the contents will remain in the temporary location determined by the + /// underlying URL session. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken + /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the + /// data is written incorrectly and will always fail to resume the download. For more information about the bug and + /// possible workarounds, please refer to the following Stack Overflow post: + /// + /// - http://stackoverflow.com/a/39347461/1342462 + /// + /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` + /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for + /// additional information. + /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. + /// + /// - returns: The created `DownloadRequest`. + @discardableResult + open func download( + resumingWith resumeData: Data, + to destination: DownloadRequest.DownloadFileDestination? = nil) + -> DownloadRequest + { + return download(.resumeData(resumeData), to: destination) + } + + // MARK: Private - Download Implementation + + private func download( + _ downloadable: DownloadRequest.Downloadable, + to destination: DownloadRequest.DownloadFileDestination?) + -> DownloadRequest + { + do { + let task = try downloadable.task(session: session, adapter: adapter, queue: queue) + let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) + + download.downloadDelegate.destination = destination + + delegate[task] = download + + if startRequestsImmediately { download.resume() } + + return download + } catch { + return download(downloadable, to: destination, failedWith: error) + } + } + + private func download( + _ downloadable: DownloadRequest.Downloadable?, + to destination: DownloadRequest.DownloadFileDestination?, + failedWith error: Error) + -> DownloadRequest + { + var downloadTask: Request.RequestTask = .download(nil, nil) + + if let downloadable = downloadable { + downloadTask = .download(downloadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + + let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) + download.downloadDelegate.destination = destination + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: download, with: underlyingError) + } else { + if startRequestsImmediately { download.resume() } + } + + return download + } + + // MARK: - Upload Request + + // MARK: File + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ fileURL: URL, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(fileURL, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter file: The file to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.file(fileURL, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: Data + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ data: Data, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(data, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter data: The data to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.data(data, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: InputStream + + /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload( + _ stream: InputStream, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil) + -> UploadRequest + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + return upload(stream, with: urlRequest) + } catch { + return upload(nil, failedWith: error) + } + } + + /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter stream: The stream to upload. + /// - parameter urlRequest: The URL request. + /// + /// - returns: The created `UploadRequest`. + @discardableResult + open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { + do { + let urlRequest = try urlRequest.asURLRequest() + return upload(.stream(stream, urlRequest)) + } catch { + return upload(nil, failedWith: error) + } + } + + // MARK: MultipartFormData + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `url`, `method` and `headers`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter url: The URL. + /// - parameter method: The HTTP method. `.post` by default. + /// - parameter headers: The HTTP headers. `nil` by default. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + to url: URLConvertible, + method: HTTPMethod = .post, + headers: HTTPHeaders? = nil, + queue: DispatchQueue? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + do { + let urlRequest = try URLRequest(url: url, method: method, headers: headers) + + return upload( + multipartFormData: multipartFormData, + usingThreshold: encodingMemoryThreshold, + with: urlRequest, + queue: queue, + encodingCompletion: encodingCompletion + ) + } catch { + (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } + } + } + + /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new + /// `UploadRequest` using the `urlRequest`. + /// + /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative + /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most + /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to + /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory + /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be + /// used for larger payloads such as video content. + /// + /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory + /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, + /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk + /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding + /// technique was used. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. + /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. + /// `multipartFormDataEncodingMemoryThreshold` by default. + /// - parameter urlRequest: The URL request. + /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. + open func upload( + multipartFormData: @escaping (MultipartFormData) -> Void, + usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, + with urlRequest: URLRequestConvertible, + queue: DispatchQueue? = nil, + encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) + { + DispatchQueue.global(qos: .utility).async { + let formData = MultipartFormData() + multipartFormData(formData) + + var tempFileURL: URL? + + do { + var urlRequestWithContentType = try urlRequest.asURLRequest() + urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") + + let isBackgroundSession = self.session.configuration.identifier != nil + + if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { + let data = try formData.encode() + + let encodingResult = MultipartFormDataEncodingResult.success( + request: self.upload(data, with: urlRequestWithContentType), + streamingFromDisk: false, + streamFileURL: nil + ) + + (queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) } + } else { + let fileManager = FileManager.default + let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) + let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") + let fileName = UUID().uuidString + let fileURL = directoryURL.appendingPathComponent(fileName) + + tempFileURL = fileURL + + var directoryError: Error? + + // Create directory inside serial queue to ensure two threads don't do this in parallel + self.queue.sync { + do { + try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) + } catch { + directoryError = error + } + } + + if let directoryError = directoryError { throw directoryError } + + try formData.writeEncodedData(to: fileURL) + + let upload = self.upload(fileURL, with: urlRequestWithContentType) + + // Cleanup the temp file once the upload is complete + upload.delegate.queue.addOperation { + do { + try FileManager.default.removeItem(at: fileURL) + } catch { + // No-op + } + } + + (queue ?? DispatchQueue.main).async { + let encodingResult = MultipartFormDataEncodingResult.success( + request: upload, + streamingFromDisk: true, + streamFileURL: fileURL + ) + + encodingCompletion?(encodingResult) + } + } + } catch { + // Cleanup the temp file in the event that the multipart form data encoding failed + if let tempFileURL = tempFileURL { + do { + try FileManager.default.removeItem(at: tempFileURL) + } catch { + // No-op + } + } + + (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } + } + } + } + + // MARK: Private - Upload Implementation + + private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { + do { + let task = try uploadable.task(session: session, adapter: adapter, queue: queue) + let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) + + if case let .stream(inputStream, _) = uploadable { + upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } + } + + delegate[task] = upload + + if startRequestsImmediately { upload.resume() } + + return upload + } catch { + return upload(uploadable, failedWith: error) + } + } + + private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { + var uploadTask: Request.RequestTask = .upload(nil, nil) + + if let uploadable = uploadable { + uploadTask = .upload(uploadable, nil) + } + + let underlyingError = error.underlyingAdaptError ?? error + let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) + + if let retrier = retrier, error is AdaptError { + allowRetrier(retrier, toRetry: upload, with: underlyingError) + } else { + if startRequestsImmediately { upload.resume() } + } + + return upload + } + +#if !os(watchOS) + + // MARK: - Stream Request + + // MARK: Hostname and Port + + /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter hostName: The hostname of the server to connect to. + /// - parameter port: The port of the server to connect to. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(withHostName hostName: String, port: Int) -> StreamRequest { + return stream(.stream(hostName: hostName, port: port)) + } + + // MARK: NetService + + /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. + /// + /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. + /// + /// - parameter netService: The net service used to identify the endpoint. + /// + /// - returns: The created `StreamRequest`. + @discardableResult + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + open func stream(with netService: NetService) -> StreamRequest { + return stream(.netService(netService)) + } + + // MARK: Private - Stream Implementation + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { + do { + let task = try streamable.task(session: session, adapter: adapter, queue: queue) + let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) + + delegate[task] = request + + if startRequestsImmediately { request.resume() } + + return request + } catch { + return stream(failedWith: error) + } + } + + @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) + private func stream(failedWith error: Error) -> StreamRequest { + let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) + if startRequestsImmediately { stream.resume() } + return stream + } + +#endif + + // MARK: - Internal - Retry Request + + func retry(_ request: Request) -> Bool { + guard let originalTask = request.originalTask else { return false } + + do { + let task = try originalTask.task(session: session, adapter: adapter, queue: queue) + + if let originalTask = request.task { + delegate[originalTask] = nil // removes the old request to avoid endless growth + } + + request.delegate.task = task // resets all task delegate data + + request.retryCount += 1 + request.startTime = CFAbsoluteTimeGetCurrent() + request.endTime = nil + + task.resume() + + return true + } catch { + request.delegate.error = error.underlyingAdaptError ?? error + return false + } + } + + private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { + DispatchQueue.utility.async { [weak self] in + guard let strongSelf = self else { return } + + retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in + guard let strongSelf = self else { return } + + guard shouldRetry else { + if strongSelf.startRequestsImmediately { request.resume() } + return + } + + DispatchQueue.utility.after(timeDelay) { + guard let strongSelf = self else { return } + + let retrySucceeded = strongSelf.retry(request) + + if retrySucceeded, let task = request.task { + strongSelf.delegate[task] = request + } else { + if strongSelf.startRequestsImmediately { request.resume() } + } + } + } + } + } +} diff --git a/Pods/Alamofire/Source/TaskDelegate.swift b/Pods/Alamofire/Source/TaskDelegate.swift new file mode 100644 index 0000000..5705737 --- /dev/null +++ b/Pods/Alamofire/Source/TaskDelegate.swift @@ -0,0 +1,466 @@ +// +// TaskDelegate.swift +// +// Copyright (c) 2014 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 Foundation + +/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as +/// executing all operations attached to the serial operation queue upon task completion. +open class TaskDelegate: NSObject { + + // MARK: Properties + + /// The serial operation queue used to execute all operations after the task completes. + public let queue: OperationQueue + + /// The data returned by the server. + public var data: Data? { return nil } + + /// The error generated throughout the lifecyle of the task. + public var error: Error? + + var task: URLSessionTask? { + set { + taskLock.lock(); defer { taskLock.unlock() } + _task = newValue + } + get { + taskLock.lock(); defer { taskLock.unlock() } + return _task + } + } + + var initialResponseTime: CFAbsoluteTime? + var credential: URLCredential? + var metrics: AnyObject? // URLSessionTaskMetrics + + private var _task: URLSessionTask? { + didSet { reset() } + } + + private let taskLock = NSLock() + + // MARK: Lifecycle + + init(task: URLSessionTask?) { + _task = task + + self.queue = { + let operationQueue = OperationQueue() + + operationQueue.maxConcurrentOperationCount = 1 + operationQueue.isSuspended = true + operationQueue.qualityOfService = .utility + + return operationQueue + }() + } + + func reset() { + error = nil + initialResponseTime = nil + } + + // MARK: URLSessionTaskDelegate + + var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? + var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? + var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? + var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? + + @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + var redirectRequest: URLRequest? = request + + if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { + redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) + } + + completionHandler(redirectRequest) + } + + @objc(URLSession:task:didReceiveChallenge:completionHandler:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + var credential: URLCredential? + + if let taskDidReceiveChallenge = taskDidReceiveChallenge { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + let host = challenge.protectionSpace.host + + if + let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), + let serverTrust = challenge.protectionSpace.serverTrust + { + if serverTrustPolicy.evaluate(serverTrust, forHost: host) { + disposition = .useCredential + credential = URLCredential(trust: serverTrust) + } else { + disposition = .cancelAuthenticationChallenge + } + } + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } + + @objc(URLSession:task:needNewBodyStream:) + func urlSession( + _ session: URLSession, + task: URLSessionTask, + needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) + { + var bodyStream: InputStream? + + if let taskNeedNewBodyStream = taskNeedNewBodyStream { + bodyStream = taskNeedNewBodyStream(session, task) + } + + completionHandler(bodyStream) + } + + @objc(URLSession:task:didCompleteWithError:) + func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + if let taskDidCompleteWithError = taskDidCompleteWithError { + taskDidCompleteWithError(session, task, error) + } else { + if let error = error { + if self.error == nil { self.error = error } + + if + let downloadDelegate = self as? DownloadTaskDelegate, + let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data + { + downloadDelegate.resumeData = resumeData + } + } + + queue.isSuspended = false + } + } +} + +// MARK: - + +class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { + + // MARK: Properties + + var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } + + override var data: Data? { + if dataStream != nil { + return nil + } else { + return mutableData + } + } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var dataStream: ((_ data: Data) -> Void)? + + private var totalBytesReceived: Int64 = 0 + private var mutableData: Data + + private var expectedContentLength: Int64? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + mutableData = Data() + progress = Progress(totalUnitCount: 0) + + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + totalBytesReceived = 0 + mutableData = Data() + expectedContentLength = nil + } + + // MARK: URLSessionDataDelegate + + var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? + var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? + var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? + var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + var disposition: URLSession.ResponseDisposition = .allow + + expectedContentLength = response.expectedContentLength + + if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { + disposition = dataTaskDidReceiveResponse(session, dataTask, response) + } + + completionHandler(disposition) + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didBecome downloadTask: URLSessionDownloadTask) + { + dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) + } + + func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let dataTaskDidReceiveData = dataTaskDidReceiveData { + dataTaskDidReceiveData(session, dataTask, data) + } else { + if let dataStream = dataStream { + dataStream(data) + } else { + mutableData.append(data) + } + + let bytesReceived = Int64(data.count) + totalBytesReceived += bytesReceived + let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown + + progress.totalUnitCount = totalBytesExpected + progress.completedUnitCount = totalBytesReceived + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + willCacheResponse proposedResponse: CachedURLResponse, + completionHandler: @escaping (CachedURLResponse?) -> Void) + { + var cachedResponse: CachedURLResponse? = proposedResponse + + if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { + cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) + } + + completionHandler(cachedResponse) + } +} + +// MARK: - + +class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { + + // MARK: Properties + + var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } + + var progress: Progress + var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + var resumeData: Data? + override var data: Data? { return resumeData } + + var destination: DownloadRequest.DownloadFileDestination? + + var temporaryURL: URL? + var destinationURL: URL? + + var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + progress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + + progress = Progress(totalUnitCount: 0) + resumeData = nil + } + + // MARK: URLSessionDownloadDelegate + + var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? + var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? + var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didFinishDownloadingTo location: URL) + { + temporaryURL = location + + guard + let destination = destination, + let response = downloadTask.response as? HTTPURLResponse + else { return } + + let result = destination(location, response) + let destinationURL = result.destinationURL + let options = result.options + + self.destinationURL = destinationURL + + do { + if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { + try FileManager.default.removeItem(at: destinationURL) + } + + if options.contains(.createIntermediateDirectories) { + let directory = destinationURL.deletingLastPathComponent() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + try FileManager.default.moveItem(at: location, to: destinationURL) + } catch { + self.error = error + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didWriteData bytesWritten: Int64, + totalBytesWritten: Int64, + totalBytesExpectedToWrite: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let downloadTaskDidWriteData = downloadTaskDidWriteData { + downloadTaskDidWriteData( + session, + downloadTask, + bytesWritten, + totalBytesWritten, + totalBytesExpectedToWrite + ) + } else { + progress.totalUnitCount = totalBytesExpectedToWrite + progress.completedUnitCount = totalBytesWritten + + if let progressHandler = progressHandler { + progressHandler.queue.async { progressHandler.closure(self.progress) } + } + } + } + + func urlSession( + _ session: URLSession, + downloadTask: URLSessionDownloadTask, + didResumeAtOffset fileOffset: Int64, + expectedTotalBytes: Int64) + { + if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { + downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) + } else { + progress.totalUnitCount = expectedTotalBytes + progress.completedUnitCount = fileOffset + } + } +} + +// MARK: - + +class UploadTaskDelegate: DataTaskDelegate { + + // MARK: Properties + + var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } + + var uploadProgress: Progress + var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? + + // MARK: Lifecycle + + override init(task: URLSessionTask?) { + uploadProgress = Progress(totalUnitCount: 0) + super.init(task: task) + } + + override func reset() { + super.reset() + uploadProgress = Progress(totalUnitCount: 0) + } + + // MARK: URLSessionTaskDelegate + + var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? + + func URLSession( + _ session: URLSession, + task: URLSessionTask, + didSendBodyData bytesSent: Int64, + totalBytesSent: Int64, + totalBytesExpectedToSend: Int64) + { + if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } + + if let taskDidSendBodyData = taskDidSendBodyData { + taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) + } else { + uploadProgress.totalUnitCount = totalBytesExpectedToSend + uploadProgress.completedUnitCount = totalBytesSent + + if let uploadProgressHandler = uploadProgressHandler { + uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } + } + } + } +} diff --git a/Pods/Alamofire/Source/Timeline.swift b/Pods/Alamofire/Source/Timeline.swift new file mode 100644 index 0000000..596c1bd --- /dev/null +++ b/Pods/Alamofire/Source/Timeline.swift @@ -0,0 +1,136 @@ +// +// Timeline.swift +// +// Copyright (c) 2014 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 Foundation + +/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. +public struct Timeline { + /// The time the request was initialized. + public let requestStartTime: CFAbsoluteTime + + /// The time the first bytes were received from or sent to the server. + public let initialResponseTime: CFAbsoluteTime + + /// The time when the request was completed. + public let requestCompletedTime: CFAbsoluteTime + + /// The time when the response serialization was completed. + public let serializationCompletedTime: CFAbsoluteTime + + /// The time interval in seconds from the time the request started to the initial response from the server. + public let latency: TimeInterval + + /// The time interval in seconds from the time the request started to the time the request completed. + public let requestDuration: TimeInterval + + /// The time interval in seconds from the time the request completed to the time response serialization completed. + public let serializationDuration: TimeInterval + + /// The time interval in seconds from the time the request started to the time response serialization completed. + public let totalDuration: TimeInterval + + /// Creates a new `Timeline` instance with the specified request times. + /// + /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. + /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. + /// Defaults to `0.0`. + /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. + /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults + /// to `0.0`. + /// + /// - returns: The new `Timeline` instance. + public init( + requestStartTime: CFAbsoluteTime = 0.0, + initialResponseTime: CFAbsoluteTime = 0.0, + requestCompletedTime: CFAbsoluteTime = 0.0, + serializationCompletedTime: CFAbsoluteTime = 0.0) + { + self.requestStartTime = requestStartTime + self.initialResponseTime = initialResponseTime + self.requestCompletedTime = requestCompletedTime + self.serializationCompletedTime = serializationCompletedTime + + self.latency = initialResponseTime - requestStartTime + self.requestDuration = requestCompletedTime - requestStartTime + self.serializationDuration = serializationCompletedTime - requestCompletedTime + self.totalDuration = serializationCompletedTime - requestStartTime + } +} + +// MARK: - CustomStringConvertible + +extension Timeline: CustomStringConvertible { + /// The textual representation used when written to an output stream, which includes the latency, the request + /// duration and the total duration. + public var description: String { + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} + +// MARK: - CustomDebugStringConvertible + +extension Timeline: CustomDebugStringConvertible { + /// The textual representation used when written to an output stream, which includes the request start time, the + /// initial response time, the request completed time, the serialization completed time, the latency, the request + /// duration and the total duration. + public var debugDescription: String { + let requestStartTime = String(format: "%.3f", self.requestStartTime) + let initialResponseTime = String(format: "%.3f", self.initialResponseTime) + let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) + let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) + let latency = String(format: "%.3f", self.latency) + let requestDuration = String(format: "%.3f", self.requestDuration) + let serializationDuration = String(format: "%.3f", self.serializationDuration) + let totalDuration = String(format: "%.3f", self.totalDuration) + + // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is + // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. + let timings = [ + "\"Request Start Time\": " + requestStartTime, + "\"Initial Response Time\": " + initialResponseTime, + "\"Request Completed Time\": " + requestCompletedTime, + "\"Serialization Completed Time\": " + serializationCompletedTime, + "\"Latency\": " + latency + " secs", + "\"Request Duration\": " + requestDuration + " secs", + "\"Serialization Duration\": " + serializationDuration + " secs", + "\"Total Duration\": " + totalDuration + " secs" + ] + + return "Timeline: { " + timings.joined(separator: ", ") + " }" + } +} diff --git a/Pods/Alamofire/Source/Validation.swift b/Pods/Alamofire/Source/Validation.swift new file mode 100644 index 0000000..5640789 --- /dev/null +++ b/Pods/Alamofire/Source/Validation.swift @@ -0,0 +1,315 @@ +// +// Validation.swift +// +// Copyright (c) 2014 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 Foundation + +extension Request { + + // MARK: Helper Types + + fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason + + /// Used to represent whether validation was successful or encountered an error resulting in a failure. + /// + /// - success: The validation was successful. + /// - failure: The validation failed encountering the provided error. + public enum ValidationResult { + case success + case failure(Error) + } + + fileprivate struct MIMEType { + let type: String + let subtype: String + + var isWildcard: Bool { return type == "*" && subtype == "*" } + + init?(_ string: String) { + let components: [String] = { + let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) + + #if swift(>=3.2) + let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] + #else + let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) + #endif + + return split.components(separatedBy: "/") + }() + + if let type = components.first, let subtype = components.last { + self.type = type + self.subtype = subtype + } else { + return nil + } + } + + func matches(_ mime: MIMEType) -> Bool { + switch (type, subtype) { + case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): + return true + default: + return false + } + } + } + + // MARK: Properties + + fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } + + fileprivate var acceptableContentTypes: [String] { + if let accept = request?.value(forHTTPHeaderField: "Accept") { + return accept.components(separatedBy: ",") + } + + return ["*/*"] + } + + // MARK: Status Code + + fileprivate func validate( + statusCode acceptableStatusCodes: S, + response: HTTPURLResponse) + -> ValidationResult + where S.Iterator.Element == Int + { + if acceptableStatusCodes.contains(response.statusCode) { + return .success + } else { + let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) + return .failure(AFError.responseValidationFailed(reason: reason)) + } + } + + // MARK: Content Type + + fileprivate func validate( + contentType acceptableContentTypes: S, + response: HTTPURLResponse, + data: Data?) + -> ValidationResult + where S.Iterator.Element == String + { + guard let data = data, data.count > 0 else { return .success } + + guard + let responseContentType = response.mimeType, + let responseMIMEType = MIMEType(responseContentType) + else { + for contentType in acceptableContentTypes { + if let mimeType = MIMEType(contentType), mimeType.isWildcard { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } + + for contentType in acceptableContentTypes { + if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { + return .success + } + } + + let error: AFError = { + let reason: ErrorReason = .unacceptableContentType( + acceptableContentTypes: Array(acceptableContentTypes), + responseContentType: responseContentType + ) + + return AFError.responseValidationFailed(reason: reason) + }() + + return .failure(error) + } +} + +// MARK: - + +extension DataRequest { + /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the + /// request was valid. + public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(self.request, response, self.delegate.data) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, data in + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} + +// MARK: - + +extension DownloadRequest { + /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a + /// destination URL, and returns whether the request was valid. + public typealias Validation = ( + _ request: URLRequest?, + _ response: HTTPURLResponse, + _ temporaryURL: URL?, + _ destinationURL: URL?) + -> ValidationResult + + /// Validates the request, using the specified closure. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter validation: A closure to validate the request. + /// + /// - returns: The request. + @discardableResult + public func validate(_ validation: @escaping Validation) -> Self { + let validationExecution: () -> Void = { [unowned self] in + let request = self.request + let temporaryURL = self.downloadDelegate.temporaryURL + let destinationURL = self.downloadDelegate.destinationURL + + if + let response = self.response, + self.delegate.error == nil, + case let .failure(error) = validation(request, response, temporaryURL, destinationURL) + { + self.delegate.error = error + } + } + + validations.append(validationExecution) + + return self + } + + /// Validates that the response has a status code in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter range: The range of acceptable status codes. + /// + /// - returns: The request. + @discardableResult + public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { + return validate { [unowned self] _, response, _, _ in + return self.validate(statusCode: acceptableStatusCodes, response: response) + } + } + + /// Validates that the response has a content type in the specified sequence. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. + /// + /// - returns: The request. + @discardableResult + public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { + return validate { [unowned self] _, response, _, _ in + let fileURL = self.downloadDelegate.fileURL + + guard let validFileURL = fileURL else { + return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) + } + + do { + let data = try Data(contentsOf: validFileURL) + return self.validate(contentType: acceptableContentTypes, response: response, data: data) + } catch { + return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) + } + } + } + + /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content + /// type matches any specified in the Accept HTTP header field. + /// + /// If validation fails, subsequent calls to response handlers will have an associated error. + /// + /// - returns: The request. + @discardableResult + public func validate() -> Self { + return validate(statusCode: self.acceptableStatusCodes).validate(contentType: self.acceptableContentTypes) + } +} diff --git a/Pods/Kanna/LICENSE b/Pods/Kanna/LICENSE new file mode 100644 index 0000000..30070be --- /dev/null +++ b/Pods/Kanna/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 - 2015 Atsushi Kiwaki (@_tid_) + +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. \ No newline at end of file diff --git a/Pods/Kanna/Modules/libxml2-kanna.h b/Pods/Kanna/Modules/libxml2-kanna.h new file mode 100644 index 0000000..15dae3f --- /dev/null +++ b/Pods/Kanna/Modules/libxml2-kanna.h @@ -0,0 +1,3 @@ +#import +#import +#import diff --git a/Pods/Kanna/Modules/module.modulemap b/Pods/Kanna/Modules/module.modulemap new file mode 100644 index 0000000..b18b454 --- /dev/null +++ b/Pods/Kanna/Modules/module.modulemap @@ -0,0 +1,6 @@ +module libxmlKanna [system] { + link "xml2" + umbrella header "libxml2-kanna.h" + export * + module * { export * } +} diff --git a/Pods/Kanna/README.md b/Pods/Kanna/README.md new file mode 100644 index 0000000..04fd6d1 --- /dev/null +++ b/Pods/Kanna/README.md @@ -0,0 +1,228 @@ +Kanna(鉋) +================= + +Kanna(鉋) is an XML/HTML parser for cross-platform(macOS, iOS, tvOS, watchOS and Linux!). + +It was inspired by [Nokogiri](https://github.com/sparklemotion/nokogiri)(鋸). + +[![Build Status](https://travis-ci.org/tid-kijyun/Kanna.svg?branch=master)](https://travis-ci.org/tid-kijyun/Kanna) +[![Platform](http://img.shields.io/badge/platform-ios_osx_watchos_tvos_linux-lightgrey.svg?style=flat)](https://developer.apple.com/resources/) +[![Cocoapod](http://img.shields.io/cocoapods/v/Kanna.svg?style=flat)](http://cocoadocs.org/docsets/Kanna/) +[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) +[![Swift Package Manager](https://img.shields.io/badge/Swift%20Package%20Manager-compatible-brightgreen.svg)](https://github.com/apple/swift-package-manager) +[![Reference Status](https://www.versioneye.com/objective-c/kanna/reference_badge.svg?style=flat)](https://www.versioneye.com/objective-c/kanna/references) + +:information_source: [Documentation](http://tid-kijyun.github.io/Kanna/) + + +Features: +================= +- [x] XPath 1.0 support for document searching +- [x] CSS3 selector support for document searching +- [x] Support for namespaces +- [x] Comprehensive test suite + +Installation: +================= + +### Swift 5 +##### CocoaPods +Adding it to your `Podfile`: +```ruby +use_frameworks! +pod 'Kanna', '~> 5.0.0' +``` + +##### Carthage +Adding it to your `Cartfile`: + +```ogdl +github "tid-kijyun/Kanna" ~> 5.0.0 +``` + +1. In the project settings add `$(SDKROOT)/usr/include/libxml2` to the "header search paths" field + +##### Others(Swift PM and manual Installation) +Please refer to the case of Swift 4. + +### Swift 4 +##### CocoaPods +**:warning: CocoaPods (`1.1.0 or later`) is required.** + +Adding it to your `Podfile`: +```ruby +use_frameworks! +pod 'Kanna', '~> 4.0.0' +``` + +##### Carthage +Adding it to your `Cartfile`: + +```ogdl +github "tid-kijyun/Kanna" ~> 4.0.0 +``` + +1. In the project settings add `$(SDKROOT)/usr/include/libxml2` to the "header search paths" field + +##### Swift Package Manager + +Installing libxml2 to your computer: + +```bash +// macOS +$ brew install libxml2 +$ brew link --force libxml2 + +// Linux(Ubuntu) +$ sudo apt-get install libxml2-dev +``` + +Adding it to your `Package.swift`: + +```swift +// swift-tools-version:4.0 +import PackageDescription + +let package = Package( + name: "YourProject", + dependencies: [ + .package(url: "https://github.com/tid-kijyun/Kanna.git", from: "4.0.0") + ], + targets: [ + .target( + name: "YourTarget", + dependencies: ["Kanna"]), + ] +) +``` + +```bash +$ swift build +``` + +*Note: When a build error occurs, please try run the following command:* +```bash +$ sudo apt-get install pkg-config +``` + +##### Manual Installation +1. Add these files to your project: + [Kanna.swift](Source/Kanna.swift) + [CSS.swift](Source/CSS.swift) + [libxmlHTMLDocument.swift](Source/libxml/libxmlHTMLDocument.swift) + [libxmlHTMLNode.swift](Source/libxml/libxmlHTMLNode.swift) + [libxmlParserOption.swift](Source/libxml/libxmlParserOption.swift) + [Modules](Modules) +1. In the target settings add `$(SDKROOT)/usr/include/libxml2` to the `Search Paths > Header Search Paths` field +1. In the target settings add `$(SRCROOT)/Modules` to the `Swift Compiler - Search Paths > Import Paths` field + + +### Swift 3.0 +For now, please use the `feature/v3.0.0` branch. + +##### CocoaPods +**:warning: CocoaPods (`1.1.0 or later`) is required.** + +Adding it to your `Podfile`: +```ruby +use_frameworks! +pod 'Kanna', :git => 'https://github.com/tid-kijyun/Kanna', :branch => 'feature/v3.0.0' +``` + +##### Carthage +Adding it to your `Cartfile`: + +```ogdl +github "tid-kijyun/Kanna" "feature/v3.0.0" +``` + +1. In the project settings add `$(SDKROOT)/usr/include/libxml2` to the "header search paths" field + +##### Swift Package Manager + +Installing libxml2 to your computer: + +```bash +// macOS +$ brew install libxml2 +$ brew link --force libxml2 + +// Linux(Ubuntu) +$ sudo apt-get install libxml2-dev +``` + +Adding it to your `Package.swift`: + +```swift +import PackageDescription + +let package = Package( + name: "YourProject", + + dependencies: [ + .Package(url: "https://github.com/tid-kijyun/Kanna.git", majorVersion: 2) + ] +) +``` + +```bash +$ swift build +``` + +*Note: When a build error occurs, please try run the following command:* +```bash +$ sudo apt-get install pkg-config +``` + +##### Manual Installation +1. Add these files to your project: + [Kanna.swift](Source/Kanna.swift) + [CSS.swift](Source/CSS.swift) + [libxmlHTMLDocument.swift](Source/libxml/libxmlHTMLDocument.swift) + [libxmlHTMLNode.swift](Source/libxml/libxmlHTMLNode.swift) + [libxmlParserOption.swift](Source/libxml/libxmlParserOption.swift) + [Modules](Modules) +1. In the target settings add `$(SDKROOT)/usr/include/libxml2` to the `Search Paths > Header Search Paths` field +1. In the target settings add `$(SRCROOT)/Modules` to the `Swift Compiler - Search Paths > Import Paths` field + +Synopsis: +================= + +```swift +import Kanna + +let html = "..." + +if let doc = try? HTML(html: html, encoding: .utf8) { + print(doc.title) + + // Search for nodes by CSS + for link in doc.css("a, link") { + print(link.text) + print(link["href"]) + } + + // Search for nodes by XPath + for link in doc.xpath("//a | //link") { + print(link.text) + print(link["href"]) + } +} +``` + +```swift +let xml = "..." +if let doc = try? Kanna.XML(xml: xml, encoding: .utf8) { + let namespaces = [ + "o": "urn:schemas-microsoft-com:office:office", + "ss": "urn:schemas-microsoft-com:office:spreadsheet" + ] + if let author = doc.at_xpath("//o:Author", namespaces: namespaces) { + print(author.text) + } +} +``` + +License: +================= +The MIT License. See the LICENSE file for more information. diff --git a/Pods/Kanna/Sources/Kanna/CSS.swift b/Pods/Kanna/Sources/Kanna/CSS.swift new file mode 100755 index 0000000..abefa99 --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/CSS.swift @@ -0,0 +1,366 @@ +/**@file CSS.swift + +Kanna + +Copyright (c) 2015 Atsushi Kiwaki (@_tid_) + +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 Foundation + +import libxmlKanna + +typealias AKRegularExpression = NSRegularExpression +#if os(Linux) && swift(>=4) +typealias AKTextCheckingResult = NSTextCheckingResult +#elseif os(Linux) && swift(>=3) +typealias AKTextCheckingResult = TextCheckingResult +#else +typealias AKTextCheckingResult = NSTextCheckingResult +#endif + +public enum CSSError: Error { + case UnsupportSyntax(String) +} + +/** +CSS +*/ +public enum CSS { + /** + CSS3 selector to XPath + + @param selector CSS3 selector + + @return XPath + */ + public static func toXPath(_ css: String) throws -> String { + let selectorGroups = css.components(separatedBy: ",") + return try selectorGroups + .map { try toXPath(selector: $0) } + .joined(separator: " | ") + } + + private static func toXPath(selector: String) throws -> String { + var xpath = "//" + var str = selector + var prev = str + + while !str.isEmpty { + var attributes: [String] = [] + var combinator: String = "" + + str = str.trimmingCharacters(in: .whitespaces) + + // element + let element = getElement(&str) + + // class / id + while let attr = getClassId(&str) { + attributes.append(attr) + } + + // attribute + while let attr = getAttribute(&str) { + attributes.append(attr) + } + + // matchCombinator + if let combi = genCombinator(&str) { + combinator = combi + } + + // generate xpath phrase + let attr = attributes.joined(separator: " and ") + if attr.isEmpty { + xpath += "\(element)\(combinator)" + } else { + xpath += "\(element)[\(attr)]\(combinator)" + } + + if str == prev { + throw CSSError.UnsupportSyntax(selector) + } + prev = str + } + return xpath + } +} + +private func firstMatch(_ pattern: String) -> (String) -> AKTextCheckingResult? { + return { str in + let length = str.utf16.count + do { + let regex = try AKRegularExpression(pattern: pattern, options: .caseInsensitive) + if let result = regex.firstMatch(in: str, options: .reportProgress, range: NSRange(location: 0, length: length)) { + return result + } + } catch _ { + + } + return nil + } +} + +private func nth(prefix: String, a: Int, b: Int) -> String { + let sibling = "\(prefix)-sibling::*" + if a == 0 { + return "count(\(sibling)) = \(b-1)" + } else if a > 0 { + if b != 0 { + return "((count(\(sibling)) + 1) >= \(b)) and ((((count(\(sibling)) + 1)-\(b)) mod \(a)) = 0)" + } + return "((count(\(sibling)) + 1) mod \(a)) = 0" + } + let a = abs(a) + return "(count(\(sibling)) + 1) <= \(b)" + ((a != 1) ? " and ((((count(\(sibling)) + 1)-\(b)) mod \(a) = 0)" : "") +} + +// a(n) + b | a(n) - b +private func nth_child(a: Int, b: Int) -> String { + return nth(prefix: "preceding", a: a, b: b) +} + +private func nth_last_child(a: Int, b: Int) -> String { + return nth(prefix: "following", a: a, b: b) +} + +private let escapePattern = "(?:\\\\([!\"#\\$%&\'\\(\\)\\*\\+,\\./:;<=>\\?@\\[\\\\\\]\\^`\\{\\|\\}~]))" +private let escapeRepeatPattern = "\(escapePattern)*" +private let matchElement = firstMatch("^((?:[a-z0-9\\*_-]+\(escapeRepeatPattern))+)((\\|)((?:[a-z0-9\\*_-]+\(escapeRepeatPattern))+))?") +private let matchClassId = firstMatch("^([#.])((?:[a-z0-9\\*_-]+\(escapeRepeatPattern))+)") +private let matchAttr1 = firstMatch("^\\[([^\\]]*)\\]") +private let matchAttr2 = firstMatch("^\\[\\s*([^~\\|\\^\\$\\*=\\s]+)\\s*([~\\|\\^\\$\\*]?=)\\s*(.*)\\s*\\]") +private let matchAttrN = firstMatch("^:not\\((.*?\\)?)\\)") +private let matchPseudo = firstMatch("^:([\'\"()a-z0-9_+-]+)") +private let matchCombinator = firstMatch("^\\s*([\\s>+~,])\\s*") +private let matchSubNthChild = firstMatch("^(nth-child|nth-last-child)\\(\\s*(odd|even|\\d+)\\s*\\)") +private let matchSubNthChildN = firstMatch("^(nth-child|nth-last-child)\\(\\s*(-?\\d*)n(\\+\\d+)?\\s*\\)") +private let matchSubNthOfType = firstMatch("nth-of-type\\((odd|even|\\d+)\\)") +private let matchSubContains = firstMatch("contains\\([\"\'](.*?)[\"\']\\)") + +private func substringWithRangeAtIndex(_ result: AKTextCheckingResult, str: String, at: Int) -> String { + if result.numberOfRanges > at { + #if swift(>=4.0) || os(Linux) + let range = result.range(at: at) + #else + let range = result.rangeAt(at) + #endif + if range.length > 0 { + let startIndex = str.index(str.startIndex, offsetBy: range.location) + let endIndex = str.index(startIndex, offsetBy: range.length) + return String(str[startIndex.. String { + return text.replacingOccurrences(of: escapePattern, with: "$1", options: .regularExpression, range: nil) +} + +private func getElement(_ str: inout String, skip: Bool = true) -> String { + if let result = matchElement(str) { + let (text, text2) = (escapeCSS(substringWithRangeAtIndex(result, str: str, at: 1)), + escapeCSS(substringWithRangeAtIndex(result, str: str, at: 5))) + + if skip { + str = String(str[str.index(str.startIndex, offsetBy: result.range.length).. String? { + if let result = matchClassId(str) { + let (attr, text) = (escapeCSS(substringWithRangeAtIndex(result, str: str, at: 1)), + escapeCSS(substringWithRangeAtIndex(result, str: str, at: 2))) + if skip { + str = String(str[str.index(str.startIndex, offsetBy: result.range.length).. String? { + if let result = matchAttr2(str) { + let (attr, expr, text) = (escapeCSS(substringWithRangeAtIndex(result, str: str, at: 1)), + substringWithRangeAtIndex(result, str: str, at: 2), + escapeCSS(substringWithRangeAtIndex(result, str: str, at: 3).replacingOccurrences(of: "[\'\"](.*)[\'\"]", with: "$1", options: .regularExpression, range: nil))) + + if skip { + str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..= 1) and (((position()-1) mod 2) = 0)" + } else if arg1 == "even" { + return "(position() mod 2) = 0" + } else { + return "position() = \(arg1)" + } + } else if let sub = matchSubContains(one) { + let text = substringWithRangeAtIndex(sub, str: one, at: 1) + return "contains(., '\(text)')" + } else { + return nil + } + } + } + return nil +} + +private func getAttrNot(_ str: inout String, skip: Bool = true) -> String? { + if let result = matchAttrN(str) { + var one = substringWithRangeAtIndex(result, str: str, at: 1) + if skip { + str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..=4.0) || os(Linux) + let range = sub.range(at: 1) + #else + let range = sub.rangeAt(1) + #endif + let startIndex = one.index(one.startIndex, offsetBy: range.location) + let endIndex = one.index(startIndex, offsetBy: range.length) + + let elem = one[startIndex ..< endIndex] + return "self::\(elem)" + } else if let attr = getClassId(&one) { + return attr + } + } + return nil +} + +private func genCombinator(_ str: inout String, skip: Bool = true) -> String? { + if let result = matchCombinator(str) { + let one = substringWithRangeAtIndex(result, str: str, at: 1) + if skip { + str = String(str[str.index(str.startIndex, offsetBy: result.range.length)..": + return "/" + case "+": + return "/following-sibling::*[1]/self::" + case "~": + return "/following-sibling::" + default: + return "//" + } + } + return nil +} diff --git a/Pods/Kanna/Sources/Kanna/Deprecated.swift b/Pods/Kanna/Sources/Kanna/Deprecated.swift new file mode 100644 index 0000000..0a2045d --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/Deprecated.swift @@ -0,0 +1,45 @@ +// +// Deprecated.swift +// Kanna +// +// Created by Atsushi Kiwaki on 2017/10/27. +// Copyright © 2017 Atsushi Kiwaki. All rights reserved. +// + +import Foundation + +//------------------------------------------------------------- +// XML +//------------------------------------------------------------- +@available(*, unavailable, message: "Use XML(xml: String, url: String?, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.") +public func XML(xml: String, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { + return nil +} + +@available(*, unavailable, message: "Use XML(xml: Data, url: String?, encoding: String.Encoding, option: ParseOption). The type of the first argument has been changed to Data and the type of the second argument has been changed to String.Encoding from UInt.") +public func XML(xml: NSData, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { + return nil +} + +@available(*, unavailable, message: "Use XML(url: URL, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.") +public func XML(url: URL, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { + return nil +} + +//------------------------------------------------------------- +// HTML +//------------------------------------------------------------- +@available(*, unavailable, message: "Use HTML(html: String, url: String?, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.") +public func HTML(html: String, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { + return nil +} + +@available(*, unavailable, message: "Use HTML(html: Data, url: String?, encoding: String.Encoding, option: ParseOption). The type of the first argument has been changed to Data and the type of the second argument has been changed to String.Encoding from UInt.") +public func HTML(html: NSData, url: String? = nil, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { + return nil +} + +@available(*, unavailable, message: "Use HTML(url: URL, encoding: String.Encoding, option: ParseOption). The type of the second argument has been changed to String.Encoding from UInt.") +public func HTML(url: URL, encoding: UInt, option: ParseOption = kDefaultXmlParseOption) -> XMLDocument? { + return nil +} diff --git a/Pods/Kanna/Sources/Kanna/Kanna.h b/Pods/Kanna/Sources/Kanna/Kanna.h new file mode 100644 index 0000000..9ef687b --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/Kanna.h @@ -0,0 +1,33 @@ +/**@file Kanna.h + +Kanna + +Copyright (c) 2015 Atsushi Kiwaki (@_tid_) + +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 + +//! Project version number for Kanna. +FOUNDATION_EXPORT double KannaVersionNumber; + +//! Project version string for Kanna. +FOUNDATION_EXPORT const unsigned char KannaVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import diff --git a/Pods/Kanna/Sources/Kanna/Kanna.swift b/Pods/Kanna/Sources/Kanna/Kanna.swift new file mode 100755 index 0000000..7808eba --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/Kanna.swift @@ -0,0 +1,381 @@ +/**@file Kanna.swift + +Kanna + +Copyright (c) 2015 Atsushi Kiwaki (@_tid_) + +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 Foundation + +import libxmlKanna + +/* +ParseOption +*/ +public enum ParseOption { + // libxml2 + case xmlParseUseLibxml(Libxml2XMLParserOptions) + case htmlParseUseLibxml(Libxml2HTMLParserOptions) +} + +public let kDefaultXmlParseOption = ParseOption.xmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING]) +public let kDefaultHtmlParseOption = ParseOption.htmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING]) + +public enum ParseError: Error { + case Empty + case EncodingMismatch + case InvalidOptions +} + +/** +Parse XML + +@param xml an XML string +@param url the base URL to use for the document +@param encoding the document encoding +@param options a ParserOption +*/ +public func XML(xml: String, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument { + switch option { + case .xmlParseUseLibxml(let opt): + return try libxmlXMLDocument(xml: xml, url: url, encoding: encoding, option: opt.rawValue) + default: + throw ParseError.InvalidOptions + } +} + +// NSData +public func XML(xml: Data, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument { + guard let xmlStr = String(data: xml, encoding: encoding) else { + throw ParseError.EncodingMismatch + } + return try XML(xml: xmlStr, url: url, encoding: encoding, option: option) +} + +// NSURL +public func XML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument { + guard let data = try? Data(contentsOf: url) else { + throw ParseError.EncodingMismatch + } + return try XML(xml: data, url: url.absoluteString, encoding: encoding, option: option) +} + +/** +Parse HTML + +@param html an HTML string +@param url the base URL to use for the document +@param encoding the document encoding +@param options a ParserOption +*/ +public func HTML(html: String, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument { + switch option { + case .htmlParseUseLibxml(let opt): + return try libxmlHTMLDocument(html: html, url: url, encoding: encoding, option: opt.rawValue) + default: + throw ParseError.InvalidOptions + } +} + +// NSData +public func HTML(html: Data, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument { + guard let htmlStr = String(data: html, encoding: encoding) else { + throw ParseError.EncodingMismatch + } + return try HTML(html: htmlStr, url: url, encoding: encoding, option: option) +} + +// NSURL +public func HTML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument { + guard let data = try? Data(contentsOf: url) else { + throw ParseError.EncodingMismatch + } + return try HTML(html: data, url: url.absoluteString, encoding: encoding, option: option) +} + +/** +Searchable +*/ +public protocol Searchable { + /** + Search for node from current node by XPath. + + @param xpath + */ + func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject + func xpath(_ xpath: String) -> XPathObject + func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? + func at_xpath(_ xpath: String) -> XMLElement? + + /** + Search for node from current node by CSS selector. + + @param selector a CSS selector + */ + func css(_ selector: String, namespaces: [String:String]?) -> XPathObject + func css(_ selector: String) -> XPathObject + func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? + func at_css(_ selector: String) -> XMLElement? +} + +/** +SearchableNode +*/ +public protocol SearchableNode: Searchable { + var text: String? { get } + var toHTML: String? { get } + var toXML: String? { get } + var innerHTML: String? { get } + var className: String? { get } + var tagName: String? { get set } + var content: String? { get set } +} + +/** +XMLElement +*/ +public protocol XMLElement: SearchableNode { + var parent: XMLElement? { get set } + subscript(attr: String) -> String? { get set } + + func addPrevSibling(_ node: XMLElement) + func addNextSibling(_ node: XMLElement) + func removeChild(_ node: XMLElement) + var nextSibling: XMLElement? { get } + var previousSibling: XMLElement? { get } +} + +/** +XMLDocument +*/ +public protocol XMLDocument: class, SearchableNode { +} + +/** +HTMLDocument +*/ +public protocol HTMLDocument: XMLDocument { + var title: String? { get } + var head: XMLElement? { get } + var body: XMLElement? { get } +} + +/** +XMLNodeSet +*/ +public final class XMLNodeSet { + fileprivate var nodes: [XMLElement] = [] + + public var toHTML: String? { + let html = nodes.reduce("") { + if let text = $1.toHTML { + return $0 + text + } + return $0 + } + return html.isEmpty == false ? html : nil + } + + public var innerHTML: String? { + let html = nodes.reduce("") { + if let text = $1.innerHTML { + return $0 + text + } + return $0 + } + return html.isEmpty == false ? html : nil + } + + public var text: String? { + let html = nodes.reduce("") { + if let text = $1.text { + return $0 + text + } + return $0 + } + return html + } + + public subscript(index: Int) -> XMLElement { + return nodes[index] + } + + public var count: Int { + return nodes.count + } + + internal init() { + } + + internal init(nodes: [XMLElement]) { + self.nodes = nodes + } + + public func at(_ index: Int) -> XMLElement? { + return count > index ? nodes[index] : nil + } + + public var first: XMLElement? { + return at(0) + } + + public var last: XMLElement? { + return at(count-1) + } +} + +extension XMLNodeSet: Sequence { + public typealias Iterator = AnyIterator + public func makeIterator() -> Iterator { + var index = 0 + return AnyIterator { + if index < self.nodes.count { + let n = self.nodes[index] + index += 1 + return n + } + return nil + } + } +} + +/** +XPathObject +*/ + +public enum XPathObject { + case none + case NodeSet(nodeset: XMLNodeSet) + case Bool(bool: Swift.Bool) + case Number(num: Double) + case String(text: Swift.String) +} + +extension XPathObject { + internal init(document: XMLDocument?, docPtr: xmlDocPtr, object: xmlXPathObject) { + switch object.type { + case XPATH_NODESET: + let nodeSet = object.nodesetval + if nodeSet == nil || nodeSet?.pointee.nodeNr == 0 || nodeSet?.pointee.nodeTab == nil { + self = .none + return + } + + var nodes : [XMLElement] = [] + let size = Int((nodeSet?.pointee.nodeNr)!) + for i in 0 ..< size { + let node: xmlNodePtr = nodeSet!.pointee.nodeTab[i]! + let htmlNode = libxmlHTMLNode(document: document, docPtr: docPtr, node: node) + nodes.append(htmlNode) + } + self = .NodeSet(nodeset: XMLNodeSet(nodes: nodes)) + return + case XPATH_BOOLEAN: + self = .Bool(bool: object.boolval != 0) + return + case XPATH_NUMBER: + self = .Number(num: object.floatval) + case XPATH_STRING: + guard let str = UnsafeRawPointer(object.stringval)?.assumingMemoryBound(to: CChar.self) else { + self = .String(text: "") + return + } + self = .String(text: Swift.String(cString: str)) + return + default: + self = .none + return + } + } + + public subscript(index: Int) -> XMLElement { + return nodeSet![index] + } + + public var first: XMLElement? { + return nodeSet?.first + } + + public var count: Int { + guard let nodeset = nodeSet else { + return 0 + } + return nodeset.count + } + + var nodeSet: XMLNodeSet? { + if case let .NodeSet(nodeset) = self { + return nodeset + } + return nil + } + + var bool: Swift.Bool? { + if case let .Bool(value) = self { + return value + } + return nil + } + + var number: Double? { + if case let .Number(value) = self { + return value + } + return nil + } + + var string: Swift.String? { + if case let .String(value) = self { + return value + } + return nil + } + + var nodeSetValue: XMLNodeSet { + return nodeSet ?? XMLNodeSet() + } + + var boolValue: Swift.Bool { + return bool ?? false + } + + var numberValue: Double { + return number ?? 0.0 + } + + var stringValue: Swift.String { + return string ?? "" + } +} + +extension XPathObject: Sequence { + public typealias Iterator = AnyIterator + public func makeIterator() -> Iterator { + var index = 0 + return AnyIterator { + if index < self.nodeSetValue.count { + let obj = self.nodeSetValue[index] + index += 1 + return obj + } + return nil + } + } +} diff --git a/Pods/Kanna/Sources/Kanna/libxmlHTMLDocument.swift b/Pods/Kanna/Sources/Kanna/libxmlHTMLDocument.swift new file mode 100755 index 0000000..e711143 --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/libxmlHTMLDocument.swift @@ -0,0 +1,393 @@ +/**@file libxmlHTMLDocument.swift + +Kanna + +Copyright (c) 2015 Atsushi Kiwaki (@_tid_) + +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 Foundation +import CoreFoundation + +import libxmlKanna + +extension String.Encoding { + var IANACharSetName: String? { + #if os(Linux) && swift(>=4) + switch self { + case .ascii: + return "us-ascii" + case .iso2022JP: + return "iso-2022-jp" + case .isoLatin1: + return "iso-8859-1" + case .isoLatin2: + return "iso-8859-2" + case .japaneseEUC: + return "euc-jp" + case .macOSRoman: + return "macintosh" + case .nextstep: + return "x-nextstep" + case .nonLossyASCII: + return nil + case .shiftJIS: + return "cp932" + case .symbol: + return "x-mac-symbol" + case .unicode: + return "utf-16" + case .utf16: + return "utf-16" + case .utf16BigEndian: + return "utf-16be" + case .utf32: + return "utf-32" + case .utf32BigEndian: + return "utf-32be" + case .utf32LittleEndian: + return "utf-32le" + case .utf8: + return "utf-8" + case .windowsCP1250: + return "windows-1250" + case .windowsCP1251: + return "windows-1251" + case .windowsCP1252: + return "windows-1252" + case .windowsCP1253: + return "windows-1253" + case .windowsCP1254: + return "windows-1254" + default: + return nil + } + #elseif os(Linux) && swift(>=3) + switch self { + case String.Encoding.ascii: + return "us-ascii" + case String.Encoding.iso2022JP: + return "iso-2022-jp" + case String.Encoding.isoLatin1: + return "iso-8859-1" + case String.Encoding.isoLatin2: + return "iso-8859-2" + case String.Encoding.japaneseEUC: + return "euc-jp" + case String.Encoding.macOSRoman: + return "macintosh" + case String.Encoding.nextstep: + return "x-nextstep" + case String.Encoding.nonLossyASCII: + return nil + case String.Encoding.shiftJIS: + return "cp932" + case String.Encoding.symbol: + return "x-mac-symbol" + case String.Encoding.unicode: + return "utf-16" + case String.Encoding.utf16: + return "utf-16" + case String.Encoding.utf16BigEndian: + return "utf-16be" + case String.Encoding.utf32: + return "utf-32" + case String.Encoding.utf32BigEndian: + return "utf-32be" + case String.Encoding.utf32LittleEndian: + return "utf-32le" + case String.Encoding.utf8: + return "utf-8" + case String.Encoding.windowsCP1250: + return "windows-1250" + case String.Encoding.windowsCP1251: + return "windows-1251" + case String.Encoding.windowsCP1252: + return "windows-1252" + case String.Encoding.windowsCP1253: + return "windows-1253" + case String.Encoding.windowsCP1254: + return "windows-1254" + default: + return nil + } + #else + let cfenc = CFStringConvertNSStringEncodingToEncoding(self.rawValue) + guard let cfencstr = CFStringConvertEncodingToIANACharSetName(cfenc) else { + return nil + } + return String(describing: cfencstr) + #endif + } +} + +/* +libxmlHTMLDocument +*/ +internal final class libxmlHTMLDocument: HTMLDocument { + fileprivate var docPtr: htmlDocPtr? = nil + fileprivate var rootNode: XMLElement? + fileprivate var html: String + fileprivate var url: String? + fileprivate var encoding: String.Encoding + + var text: String? { + return rootNode?.text + } + + var toHTML: String? { + let buf = xmlBufferCreate() + let outputBuf = xmlOutputBufferCreateBuffer(buf, nil) + defer { + xmlOutputBufferClose(outputBuf) + xmlBufferFree(buf) + } + + htmlDocContentDumpOutput(outputBuf, docPtr, nil) + let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf))) + return html + } + + var toXML: String? { + var buf: UnsafeMutablePointer? = nil + let size: UnsafeMutablePointer? = nil + defer { + xmlFree(buf) + } + + xmlDocDumpMemory(docPtr, &buf, size) + let html = String(cString: UnsafePointer(buf!)) + return html + } + + var innerHTML: String? { + return rootNode?.innerHTML + } + + var className: String? { + return nil + } + + var tagName: String? { + get { + return nil + } + + set { + + } + } + + var content: String? { + get { + return text + } + + set { + rootNode?.content = newValue + } + } + + init(html: String, url: String?, encoding: String.Encoding, option: UInt) throws { + self.html = html + self.url = url + self.encoding = encoding + + guard html.lengthOfBytes(using: encoding) > 0 else { + throw ParseError.Empty + } + + guard let charsetName = encoding.IANACharSetName, + let cur = html.cString(using: encoding) else { + throw ParseError.EncodingMismatch + } + + let url : String = "" + docPtr = htmlReadDoc(UnsafeRawPointer(cur).assumingMemoryBound(to: xmlChar.self), url, charsetName, CInt(option)) + + guard let docPtr = docPtr else { + throw ParseError.EncodingMismatch + } + + rootNode = libxmlHTMLNode(document: self, docPtr: docPtr) + } + + deinit { + xmlFreeDoc(self.docPtr) + } + + var title: String? { return at_xpath("//title")?.text } + var head: XMLElement? { return at_xpath("//head") } + var body: XMLElement? { return at_xpath("//body") } + + func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject { + return rootNode?.xpath(xpath, namespaces: namespaces) ?? XPathObject.none + } + + func xpath(_ xpath: String) -> XPathObject { + return self.xpath(xpath, namespaces: nil) + } + + func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? { + return rootNode?.at_xpath(xpath, namespaces: namespaces) + } + + func at_xpath(_ xpath: String) -> XMLElement? { + return self.at_xpath(xpath, namespaces: nil) + } + + func css(_ selector: String, namespaces: [String:String]?) -> XPathObject { + return rootNode?.css(selector, namespaces: namespaces) ?? XPathObject.none + } + + func css(_ selector: String) -> XPathObject { + return self.css(selector, namespaces: nil) + } + + func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? { + return rootNode?.at_css(selector, namespaces: namespaces) + } + + func at_css(_ selector: String) -> XMLElement? { + return self.at_css(selector, namespaces: nil) + } +} + +/* +libxmlXMLDocument +*/ +internal final class libxmlXMLDocument: XMLDocument { + fileprivate var docPtr: xmlDocPtr? = nil + fileprivate var rootNode: XMLElement? + fileprivate var xml: String + fileprivate var url: String? + fileprivate var encoding: String.Encoding + + var text: String? { + return rootNode?.text + } + + var toHTML: String? { + let buf = xmlBufferCreate() + let outputBuf = xmlOutputBufferCreateBuffer(buf, nil) + defer { + xmlOutputBufferClose(outputBuf) + xmlBufferFree(buf) + } + + htmlDocContentDumpOutput(outputBuf, docPtr, nil) + let html = String(cString: UnsafePointer(xmlOutputBufferGetContent(outputBuf))) + return html + } + + var toXML: String? { + var buf: UnsafeMutablePointer? = nil + let size: UnsafeMutablePointer? = nil + defer { + xmlFree(buf) + } + + xmlDocDumpMemory(docPtr, &buf, size) + let html = String(cString: UnsafePointer(buf!)) + return html + } + + var innerHTML: String? { + return rootNode?.innerHTML + } + + var className: String? { + return nil + } + + var tagName: String? { + get { + return nil + } + + set { + + } + } + + var content: String? { + get { + return text + } + + set { + rootNode?.content = newValue + } + } + + init(xml: String, url: String?, encoding: String.Encoding, option: UInt) throws { + self.xml = xml + self.url = url + self.encoding = encoding + + if xml.isEmpty { + throw ParseError.Empty + } + + + guard let charsetName = encoding.IANACharSetName, + let cur = xml.cString(using: encoding) else { + throw ParseError.EncodingMismatch + } + let url : String = "" + docPtr = xmlReadDoc(UnsafeRawPointer(cur).assumingMemoryBound(to: xmlChar.self), url, charsetName, CInt(option)) + rootNode = libxmlHTMLNode(document: self, docPtr: docPtr!) + } + + deinit { + xmlFreeDoc(self.docPtr) + } + + func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject { + return rootNode?.xpath(xpath, namespaces: namespaces) ?? XPathObject.none + } + + func xpath(_ xpath: String) -> XPathObject { + return self.xpath(xpath, namespaces: nil) + } + + func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? { + return rootNode?.at_xpath(xpath, namespaces: namespaces) + } + + func at_xpath(_ xpath: String) -> XMLElement? { + return self.at_xpath(xpath, namespaces: nil) + } + + func css(_ selector: String, namespaces: [String:String]?) -> XPathObject { + return rootNode?.css(selector, namespaces: namespaces) ?? XPathObject.none + } + + func css(_ selector: String) -> XPathObject { + return self.css(selector, namespaces: nil) + } + + func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? { + return rootNode?.at_css(selector, namespaces: namespaces) + } + + func at_css(_ selector: String) -> XMLElement? { + return self.at_css(selector, namespaces: nil) + } +} diff --git a/Pods/Kanna/Sources/Kanna/libxmlHTMLNode.swift b/Pods/Kanna/Sources/Kanna/libxmlHTMLNode.swift new file mode 100755 index 0000000..699f64d --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/libxmlHTMLNode.swift @@ -0,0 +1,300 @@ +/**@file libxmlHTMLNode.swift + +Kanna + +Copyright (c) 2015 Atsushi Kiwaki (@_tid_) + +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 Foundation + +import libxmlKanna + +/** +libxmlHTMLNode +*/ +internal final class libxmlHTMLNode: XMLElement { + var text: String? { + if nodePtr != nil { + return libxmlGetNodeContent(nodePtr!) + } + return nil + } + + var toHTML: String? { + let buf = xmlBufferCreate() + htmlNodeDump(buf, docPtr, nodePtr) + let html = String(cString: UnsafePointer((buf?.pointee.content)!)) + xmlBufferFree(buf) + return html + } + + var toXML: String? { + let buf = xmlBufferCreate() + xmlNodeDump(buf, docPtr, nodePtr, 0, 0) + let html = String(cString: UnsafePointer((buf?.pointee.content)!)) + xmlBufferFree(buf) + return html + } + + var innerHTML: String? { + if let html = self.toHTML { + let inner = html.replacingOccurrences(of: "]*>$", with: "", options: .regularExpression, range: nil) + .replacingOccurrences(of: "^<[^>]*>", with: "", options: .regularExpression, range: nil) + return inner + } + return nil + } + + var className: String? { + return self["class"] + } + + var tagName: String? { + get { + guard let name = nodePtr?.pointee.name else { + return nil + } + return String(cString: name) + } + + set { + if let newValue = newValue { + xmlNodeSetName(nodePtr, newValue) + } + } + } + + var content: String? { + get { + return text + } + + set { + if let newValue = newValue { + let v = escape(newValue) + xmlNodeSetContent(nodePtr, v) + } + } + } + + var parent: XMLElement? { + get { + return libxmlHTMLNode(document: doc, docPtr: docPtr!, node: (nodePtr?.pointee.parent)!) + } + + set { + if let node = newValue as? libxmlHTMLNode { + node.addChild(self) + } + } + } + + var nextSibling: XMLElement? { + let val = xmlNextElementSibling(self.nodePtr) + return self.node(from: val) + } + + var previousSibling: XMLElement? { + let val = xmlPreviousElementSibling(self.nodePtr) + return self.node(from: val) + } + + fileprivate weak var weakDocument: XMLDocument? + fileprivate var document: XMLDocument? + fileprivate var docPtr: htmlDocPtr? = nil + fileprivate var nodePtr: xmlNodePtr? = nil + fileprivate var isRoot: Bool = false + fileprivate var doc: XMLDocument? { + return weakDocument ?? document + } + + subscript(attributeName: String) -> String? + { + get { + var attr = nodePtr?.pointee.properties + while attr != nil { + let mem = attr?.pointee + if let tagName = String(validatingUTF8: UnsafeRawPointer((mem?.name)!).assumingMemoryBound(to: CChar.self)) { + if attributeName == tagName { + if let children = mem?.children { + return libxmlGetNodeContent(children) + } else { + return "" + } + } + } + attr = attr?.pointee.next + } + return nil + } + + set(newValue) { + if let newValue = newValue { + xmlSetProp(nodePtr, attributeName, newValue) + } else { + xmlUnsetProp(nodePtr, attributeName) + } + } + } + + init(document: XMLDocument?, docPtr: xmlDocPtr) { + self.weakDocument = document + self.docPtr = docPtr + self.nodePtr = xmlDocGetRootElement(docPtr) + self.isRoot = true + } + + init(document: XMLDocument?, docPtr: xmlDocPtr, node: xmlNodePtr) { + self.document = document + self.docPtr = docPtr + self.nodePtr = node + } + + // MARK: Searchable + func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject { + let ctxt = xmlXPathNewContext(docPtr) + if ctxt == nil { + return XPathObject.none + } + ctxt?.pointee.node = nodePtr + + if let nsDictionary = namespaces { + for (ns, name) in nsDictionary { + xmlXPathRegisterNs(ctxt, ns, name) + } + } + + let result = xmlXPathEvalExpression(xpath, ctxt) + defer { + xmlXPathFreeObject(result) + } + xmlXPathFreeContext(ctxt) + if result == nil { + return XPathObject.none + } + + return XPathObject(document: doc, docPtr: docPtr!, object: result!.pointee) + } + + func xpath(_ xpath: String) -> XPathObject { + return self.xpath(xpath, namespaces: nil) + } + + func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? { + return self.xpath(xpath, namespaces: namespaces).nodeSetValue.first + } + + func at_xpath(_ xpath: String) -> XMLElement? { + return self.at_xpath(xpath, namespaces: nil) + } + + func css(_ selector: String, namespaces: [String:String]?) -> XPathObject { + if let xpath = try? CSS.toXPath(selector) { + if isRoot { + return self.xpath(xpath, namespaces: namespaces) + } else { + return self.xpath("." + xpath, namespaces: namespaces) + } + } + return XPathObject.none + } + + func css(_ selector: String) -> XPathObject { + return self.css(selector, namespaces: nil) + } + + func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? { + return self.css(selector, namespaces: namespaces).nodeSetValue.first + } + + func at_css(_ selector: String) -> XMLElement? { + return self.css(selector, namespaces: nil).nodeSetValue.first + } + + func addPrevSibling(_ node: XMLElement) { + guard let node = node as? libxmlHTMLNode else { + return + } + xmlAddPrevSibling(nodePtr, node.nodePtr) + } + + func addNextSibling(_ node: XMLElement) { + guard let node = node as? libxmlHTMLNode else { + return + } + xmlAddNextSibling(nodePtr, node.nodePtr) + } + + func addChild(_ node: XMLElement) { + guard let node = node as? libxmlHTMLNode else { + return + } + xmlUnlinkNode(node.nodePtr) + xmlAddChild(nodePtr, node.nodePtr) + } + + func removeChild(_ node: XMLElement) { + + guard let node = node as? libxmlHTMLNode else { + return + } + xmlUnlinkNode(node.nodePtr) + xmlFree(node.nodePtr) + } + + private func node(from ptr: xmlNodePtr?) -> XMLElement? { + guard let doc = self.doc, let docPtr = self.docPtr, let nodePtr = ptr else { + return nil + } + + let element = libxmlHTMLNode(document: doc, docPtr: docPtr, node: nodePtr) + return element + } +} + +private func libxmlGetNodeContent(_ nodePtr: xmlNodePtr) -> String? { + let content = xmlNodeGetContent(nodePtr) + defer { + #if swift(>=4.1) + content?.deallocate() + #else + content?.deallocate(capacity: 1) + #endif + } + if let result = String(validatingUTF8: UnsafeRawPointer(content!).assumingMemoryBound(to: CChar.self)) { + return result + } + return nil +} + +let entities = [ + "&": "&", + "<" : "<", + ">" : ">", +] + +private func escape(_ str: String) -> String { + var newStr = str + for (unesc, esc) in entities { + newStr = newStr.replacingOccurrences(of: unesc, with: esc, options: .regularExpression, range: nil) + } + return newStr +} + diff --git a/Pods/Kanna/Sources/Kanna/libxmlParserOption.swift b/Pods/Kanna/Sources/Kanna/libxmlParserOption.swift new file mode 100755 index 0000000..7b8d36b --- /dev/null +++ b/Pods/Kanna/Sources/Kanna/libxmlParserOption.swift @@ -0,0 +1,94 @@ +/**@file libxmlParserOption.swift + +Kanna + +Copyright (c) 2015 Atsushi Kiwaki (@_tid_) + +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 Foundation + +import libxmlKanna + +/* +Libxml2HTMLParserOptions +*/ +public struct Libxml2HTMLParserOptions : OptionSet { + public typealias RawValue = UInt + private var value: UInt = 0 + init(_ value: UInt) { self.value = value } + private init(_ opt: htmlParserOption) { self.value = UInt(opt.rawValue) } + public init(rawValue value: UInt) { self.value = value } + public init(nilLiteral: ()) { self.value = 0 } + public static var allZeros: Libxml2HTMLParserOptions { return .init(0) } + static func fromMask(raw: UInt) -> Libxml2HTMLParserOptions { return .init(raw) } + public var rawValue: UInt { return self.value } + + public static let STRICT = Libxml2HTMLParserOptions(0) + public static let RECOVER = Libxml2HTMLParserOptions(HTML_PARSE_RECOVER) + public static let NODEFDTD = Libxml2HTMLParserOptions(HTML_PARSE_NODEFDTD) + public static let NOERROR = Libxml2HTMLParserOptions(HTML_PARSE_NOERROR) + public static let NOWARNING = Libxml2HTMLParserOptions(HTML_PARSE_NOWARNING) + public static let PEDANTIC = Libxml2HTMLParserOptions(HTML_PARSE_PEDANTIC) + public static let NOBLANKS = Libxml2HTMLParserOptions(HTML_PARSE_NOBLANKS) + public static let NONET = Libxml2HTMLParserOptions(HTML_PARSE_NONET) + public static let NOIMPLIED = Libxml2HTMLParserOptions(HTML_PARSE_NOIMPLIED) + public static let COMPACT = Libxml2HTMLParserOptions(HTML_PARSE_COMPACT) + public static let IGNORE_ENC = Libxml2HTMLParserOptions(HTML_PARSE_IGNORE_ENC) +} + +/* +Libxml2XMLParserOptions +*/ +public struct Libxml2XMLParserOptions: OptionSet { + public typealias RawValue = UInt + private var value: UInt = 0 + init(_ value: UInt) { self.value = value } + private init(_ opt: xmlParserOption) { self.value = UInt(opt.rawValue) } + public init(rawValue value: UInt) { self.value = value } + public init(nilLiteral: ()) { self.value = 0 } + public static var allZeros: Libxml2XMLParserOptions { return .init(0) } + static func fromMask(raw: UInt) -> Libxml2XMLParserOptions { return .init(raw) } + public var rawValue: UInt { return self.value } + + public static let STRICT = Libxml2XMLParserOptions(0) + public static let RECOVER = Libxml2XMLParserOptions(XML_PARSE_RECOVER) + public static let NOENT = Libxml2XMLParserOptions(XML_PARSE_NOENT) + public static let DTDLOAD = Libxml2XMLParserOptions(XML_PARSE_DTDLOAD) + public static let DTDATTR = Libxml2XMLParserOptions(XML_PARSE_DTDATTR) + public static let DTDVALID = Libxml2XMLParserOptions(XML_PARSE_DTDVALID) + public static let NOERROR = Libxml2XMLParserOptions(XML_PARSE_NOERROR) + public static let NOWARNING = Libxml2XMLParserOptions(XML_PARSE_NOWARNING) + public static let PEDANTIC = Libxml2XMLParserOptions(XML_PARSE_PEDANTIC) + public static let NOBLANKS = Libxml2XMLParserOptions(XML_PARSE_NOBLANKS) + public static let SAX1 = Libxml2XMLParserOptions(XML_PARSE_SAX1) + public static let XINCLUDE = Libxml2XMLParserOptions(XML_PARSE_XINCLUDE) + public static let NONET = Libxml2XMLParserOptions(XML_PARSE_NONET) + public static let NODICT = Libxml2XMLParserOptions(XML_PARSE_NODICT) + public static let NSCLEAN = Libxml2XMLParserOptions(XML_PARSE_NSCLEAN) + public static let NOCDATA = Libxml2XMLParserOptions(XML_PARSE_NOCDATA) + public static let NOXINCNODE = Libxml2XMLParserOptions(XML_PARSE_NOXINCNODE) + public static let COMPACT = Libxml2XMLParserOptions(XML_PARSE_COMPACT) + public static let OLD10 = Libxml2XMLParserOptions(XML_PARSE_OLD10) + public static let NOBASEFIX = Libxml2XMLParserOptions(XML_PARSE_NOBASEFIX) + public static let HUGE = Libxml2XMLParserOptions(XML_PARSE_HUGE) + public static let OLDSAX = Libxml2XMLParserOptions(XML_PARSE_OLDSAX) + public static let IGNORE_ENC = Libxml2XMLParserOptions(XML_PARSE_IGNORE_ENC) + public static let BIG_LINES = Libxml2XMLParserOptions(XML_PARSE_BIG_LINES) +} diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..2ade6aa --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,24 @@ +PODS: + - Alamofire (4.8.2) + - Kanna (5.0.0) + - SwiftSoup (1.7.4) + +DEPENDENCIES: + - Alamofire + - Kanna + - SwiftSoup + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - Alamofire + - Kanna + - SwiftSoup + +SPEC CHECKSUMS: + Alamofire: ae5c501addb7afdbb13687d7f2f722c78734c2d3 + Kanna: a32875df62975f8f4b871e933b4ea1a5c3b8be0f + SwiftSoup: 92f5b348c131aed8af04f4326db1579ab19fa08c + +PODFILE CHECKSUM: 30581c398549a5f1d7f1c358553c9bcad81e21a6 + +COCOAPODS: 1.6.1 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c77a4fa --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1637 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 059D92B7BBFBEC53E9A3B6E11C5C3B3A /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = 813F9DCF597667D2B2B0342BD936A661 /* Response.swift */; }; + 0A39AF55285A3A4F7CBABB6D822FA4A3 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = B3C00386655406AA69D4A5765CC45BB0 /* Alamofire.swift */; }; + 0CAF0664595506AF6BB5C7593231312F /* XmlDeclaration.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA46035AE77AF1965C070385D4EE3057 /* XmlDeclaration.swift */; }; + 0F25A369168AB40262975F8A3D504DB1 /* Attribute.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7AE2AEDC4F16A81364E2DD13CF55495 /* Attribute.swift */; }; + 103CEB869DD905FF5D5911D97F43EECA /* Document.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53058E1EF4ADF2BD1A08F03E4E3F8E83 /* Document.swift */; }; + 11AB21A7ABD27F1BC0466E5F8884E80A /* Tag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B708E36B4E25ED8DCB0C36F9C0B627D /* Tag.swift */; }; + 1223AE2B7078B8DCB7FFEA942ADF426F /* StructuralEvaluator.swift in Sources */ = {isa = PBXBuildFile; fileRef = BAEF925B85CA3BBB8A2671EC00D40C19 /* StructuralEvaluator.swift */; }; + 15F2142B04D3E5002FB854BCCC64486E /* Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C1DBA28A7D6FED5936AF80D2875E1B5 /* Pattern.swift */; }; + 1656188594E6BEB972A26DE11E53228C /* ParseSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = E43EAA9B724EA33F95A4E3A6F0E80EC5 /* ParseSettings.swift */; }; + 18C070538A56B1099412C67BD2376148 /* Pods-AvH PlanTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 9F0D2376FCDE023107AB552C96848609 /* Pods-AvH PlanTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1AD7ED6B484EF1F4436E5A2E6E52022F /* CharacterReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C8131ABA4308A03318FC44FD7A8CF0E /* CharacterReader.swift */; }; + 1D29D2ACADF961F69D32B06FA6A09E28 /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 360629B9A48DEF6DB5115C0A3F3AD440 /* Notifications.swift */; }; + 208CE2CDC7B395934E38A25A2DB41770 /* CombiningEvaluator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 951C72C89491F4A7D0F70B308D51B2FC /* CombiningEvaluator.swift */; }; + 22E70E6714BC77F340641D9DA29659E4 /* DataNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = A806196AE08404C302927001B8FCEA6F /* DataNode.swift */; }; + 251610D47D00503E406E9ACF67563B83 /* Attributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9FA495A9A78F4662F3E848344C1D73AC /* Attributes.swift */; }; + 25B0532B6B99C426B23C8E06C3A8CBAE /* QueryParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9B952B65F8F3C02B5AC0746EE79DFCA8 /* QueryParser.swift */; }; + 25E20CE8D27125EAB2F0E39961E23288 /* Parser.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4ACE57E279FBB41A3DE7F7BD47E5022 /* Parser.swift */; }; + 2A1904DC73F275715C1EBB2D13FB78F4 /* FormElement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28A0127DE378A14D8904C41FABA21347 /* FormElement.swift */; }; + 2DAC7A6A4DC00202CEDB3860F091C34D /* Kanna-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 58C49157383527E6DAAD841D780911F4 /* Kanna-dummy.m */; }; + 3266A69674686AF78CC156CA7CED343D /* Collector.swift in Sources */ = {isa = PBXBuildFile; fileRef = 495173B15550DB4CC990B2B65BE31337 /* Collector.swift */; }; + 355C18EEC82624A06A6CC93965258E33 /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8FFC90FCBA1F53DA88088798BADC9FCB /* Request.swift */; }; + 363064CB26D7D4019C743BBBD94FD45F /* ParseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24E3E70C79180E6675807A55C667D468 /* ParseError.swift */; }; + 3BD1DAFE1F3E6C9E4EB0F2099B6D6FA2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */; }; + 3E0749AF6C51BCF0E4A41CF1D6A76FED /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7EF8B2FEEAD839EC827E8804FB607C7 /* DispatchQueue+Alamofire.swift */; }; + 3E9EB344FDD25FB9A5B104B1F239D07C /* Cleaner.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5802D6CC422B64A8017907DF048B996A /* Cleaner.swift */; }; + 43EFA44E613A4D15E05C22DF30CBAD88 /* Entities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 576721BA56BEC277E8275B3D04727B96 /* Entities.swift */; }; + 447865DB8B03AF8172EE12B9251A79A8 /* SwiftSoup.swift in Sources */ = {isa = PBXBuildFile; fileRef = 739A071FC6E83235FBEC3822EC54A2CE /* SwiftSoup.swift */; }; + 48EAFB23E51CFB029365640B79EC67B4 /* Kanna.h in Headers */ = {isa = PBXBuildFile; fileRef = E83C929C10ECA7B23C4A16A51E89258C /* Kanna.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4C2DE52019670B533E562CE3F2A6E077 /* Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D0F664C25B120FE1D3CE3F872292BDA /* Deprecated.swift */; }; + 5177AD226881FC34E51C71F3B5856839 /* SimpleDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 501DA38799EFC05493791A93E4EE24FA /* SimpleDictionary.swift */; }; + 52E1A3CF97809055A74BC32BF0B9FBBD /* Pods-AvH PlanTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 366D4051596D87F4F38AE0A38BA83DCB /* Pods-AvH PlanTests-dummy.m */; }; + 56FC20477DD0003E453A216F5604D472 /* Comment.swift in Sources */ = {isa = PBXBuildFile; fileRef = 36D84C7692E79C1948D75D3C7EBE68AE /* Comment.swift */; }; + 57F34AD4C8EFD94C87A59A1CB55B072E /* SerializationException.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0ACCBE5CBCEEF0D91BE70C9E889D3BA2 /* SerializationException.swift */; }; + 59AA0BB8D00F434E5E75611C08739E73 /* Node.swift in Sources */ = {isa = PBXBuildFile; fileRef = 648CEFC31AD08F076E9D832A75740912 /* Node.swift */; }; + 5B32A9E85D43A45FD12CE7E813A2775C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */; }; + 5B716DB5EDCEEA7DC0A18C7CBBC9E441 /* StringUtil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 83698EB29BFAE170C22D2497909C4063 /* StringUtil.swift */; }; + 5E551A1DC393554614C44A1F97F4559F /* SwiftSoup-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B9B8B105EBEE55593D98809A0664FF1D /* SwiftSoup-dummy.m */; }; + 60B6C2A003864AAD3A426448152F67BE /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5B6FA00955A4CB62A17194304037BF7 /* Timeline.swift */; }; + 64717A2C0750385FCF19B7957F95E1D6 /* HtmlTreeBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = C47022DD000B164E2AE665B77CD169BE /* HtmlTreeBuilder.swift */; }; + 649843E6929F5C762479A786D651BC81 /* TokeniserState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9AB2D679050F3A617C2396C5A9752E20 /* TokeniserState.swift */; }; + 658738B369633C5B68332B19052DF80B /* Whitelist.swift in Sources */ = {isa = PBXBuildFile; fileRef = C76EDBC769B8360FE1D1986B078CDA0D /* Whitelist.swift */; }; + 67BE4056B849FCA6068BCBA5233E802E /* Connection.swift in Sources */ = {isa = PBXBuildFile; fileRef = C43F4ABD280AD23016A41BECA82A24E8 /* Connection.swift */; }; + 6921ED8F336C9A8584246C8EA9E05BCD /* CSS.swift in Sources */ = {isa = PBXBuildFile; fileRef = D29F1A4B8F28B48CA9A38AD1FE840809 /* CSS.swift */; }; + 6CFA329909831ED4F353461E66C15F97 /* NodeTraversor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 987F66FED3B9F4D2572FA89B48EFB407 /* NodeTraversor.swift */; }; + 6EFD003458AE7F689DEA720A2030C261 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 946C4CB0FF96FD34FF58E6B3981002E6 /* ResponseSerialization.swift */; }; + 700D3D95AF9520CB227846DFD943A2DA /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0524BFE554CD002DF004DC8F7FEFE753 /* ParameterEncoding.swift */; }; + 73AB05789A4982944AF68DBD013E3EB7 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0487FF389DD58423062E24E548C347F /* NetworkReachabilityManager.swift */; }; + 772911DA6E33D1CBBC30131B7C8BDBB3 /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 4A70789BAB48D8E43B1F89CF4F2E170D /* Alamofire-dummy.m */; }; + 77E8F0EB9FFBE2E3EB0C77095C644606 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B59A00536E5BCD69AE5D5F9F791DB51C /* TaskDelegate.swift */; }; + 7E3538A6992A38276764936A9733493D /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 149B0630A2B0C7036D048DD786C2569F /* AFError.swift */; }; + 7F1AC4413B9962E9A9C96FEF61690D8A /* Exception.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BA92A504E09AD80F699278201FBEA51 /* Exception.swift */; }; + 7F4C28B8411B593BC797F580D97CE33F /* ArrayExt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EE7D2D9B241FD1CD1608EAE3CD4355D /* ArrayExt.swift */; }; + 802A676F51FAC5C7504C72CD990D7CB2 /* Token.swift in Sources */ = {isa = PBXBuildFile; fileRef = A37FD0BD5551170D6A159A0FFD57DB16 /* Token.swift */; }; + 8882470CC4B134F927FB080A510BBE2A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */; }; + 8B0792C397B8CF3C3F7A35285B74CA51 /* Pods-AvH Plan-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = EAFC540C9B7F4F6B987516B859977D5C /* Pods-AvH Plan-dummy.m */; }; + 8D2A6A90A6DDAF75EA52D471258545CC /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB20860CAA019FA52F4A35F83680FD6B /* ServerTrustPolicy.swift */; }; + 8FD9C13DCFAB3EE3EC6ED1A8C0810499 /* Selector.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADC262E4866CDB8D980E87AC0E65F429 /* Selector.swift */; }; + 94704597EBD332197C55E9ACABAACBA0 /* OrderedSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6585A3E24D1551DDFD1F1B4CDAFD52A9 /* OrderedSet.swift */; }; + 96808B52A6EC9CAADF816EB99B2FF3C9 /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D8852ECD0E831F2AE24938F8C89BBF8 /* String.swift */; }; + 9C82FFDD7350CE1A7E0B13024820BFF6 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */; }; + A112207C487E7AE0C5074890F136F8A0 /* TokenQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 481DE5F9C541D05406C45159486A7122 /* TokenQueue.swift */; }; + A1EC41966B261DCE460BCDE5124A1DBE /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B35FB7D228EF72D1AD7BC8B4D3E6F98 /* SessionDelegate.swift */; }; + A20D50BC4E158C5BCF2DDE93B62C6335 /* libxmlParserOption.swift in Sources */ = {isa = PBXBuildFile; fileRef = E85C23AA0E9238CEB29619DC264D429A /* libxmlParserOption.swift */; }; + A626EDD7DC5AD198A921E5951A073314 /* Kanna-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = F7152D164F0AA9227443BA39A6D0F255 /* Kanna-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AA56769D8733D3F3E7976742D5ABA998 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 602308BC2EA0CA138E0247A3A5DDD183 /* Validation.swift */; }; + AEA829AB1A8AF2AD077A808AED6B178A /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9B46B4B433F5B30B3E3EB19499B430F /* MultipartFormData.swift */; }; + B333703DB413ED2C9FE0D9B198D80D9E /* StringBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5042E1B69B7C32F708725A4A123EF1B3 /* StringBuilder.swift */; }; + B6F6E4CC26451E91B59FAE0F6841DC1F /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 4A671A7C76E09DBBBEB477A389F0A393 /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + B9BBB29825647956A2AE19F72A2F7570 /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE57CBB6CC8CAF3FCC9DCD131599E1E8 /* OrderedDictionary.swift */; }; + BB01E5C2361137030EECD341813BA379 /* libxmlHTMLDocument.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93C036AA9F2E7653041EE0096A963C21 /* libxmlHTMLDocument.swift */; }; + BB9D54EA7D2102F5C00D57F51B83E954 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */; }; + BDA6F31CDD0578D70CC73AFD8DC1CAD4 /* ParseErrorList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 28E3F0CE6A49012D88F8838F08F014C3 /* ParseErrorList.swift */; }; + BE6BEB297BABD159FAFA069F8CCB5664 /* DocumentType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2088638F952F0502D15B7AF2E1A3944E /* DocumentType.swift */; }; + C73EC5098AFF72BB9B68A49AB7B5B23D /* libxmlHTMLNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 82D0FB4D859F89BC72D83D3F2A987CA4 /* libxmlHTMLNode.swift */; }; + C86B3245A3635B25274BE8FF7411FF72 /* HtmlTreeBuilderState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 634CE874ED90E51D8C74455B66406A5D /* HtmlTreeBuilderState.swift */; }; + C8AE8D4D4ADFE8EF3E18E28AFD091D56 /* XmlTreeBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40A4164D18BD3AE1F9FC305942C48488 /* XmlTreeBuilder.swift */; }; + CE967A656EE25027598A84474DF5B60A /* SwiftSoup-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8DF87281196264525DB63D825BE9F847 /* SwiftSoup-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CEF05C7D22572C0C79CFE3BFACEEBE98 /* DataUtil.swift in Sources */ = {isa = PBXBuildFile; fileRef = E00A87640D00F37E99EC16C1D3F2ADBE /* DataUtil.swift */; }; + CFC8CCA4FC649E1B2D928C56E2B46F08 /* UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F2D6EB4F89AB32EA574DC71E4DD6D75 /* UnicodeScalar.swift */; }; + D14856B7F1FD47625CE8B641D1DC11FE /* TreeBuilder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72A172D68D212D3E1FE1A01E214FFCB3 /* TreeBuilder.swift */; }; + D15DD84A4FE55D8CE30BC48EB6811C37 /* Pods-AvH PlanUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8A10CB565324867AFF90BC29EC8F60B1 /* Pods-AvH PlanUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D3FA0AA634AAEA99AB3FABC36BB4958C /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = C29F3BA1835573FE373519442DFD3C38 /* SessionManager.swift */; }; + D4FB35AA43AE1101A1617A879D9491B2 /* TextNode.swift in Sources */ = {isa = PBXBuildFile; fileRef = AE58976088B83E8DA3B02BA272D16113 /* TextNode.swift */; }; + D571B248178DC9E8D4593BA1DF8F4AA5 /* Pods-AvH PlanUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = F08DABC90F4CDC9C4F0D028838804A5F /* Pods-AvH PlanUITests-dummy.m */; }; + D710B388140E5EA60BB6BB3DAF420488 /* Elements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A06775A643211AFF7F57D9F533E038E /* Elements.swift */; }; + DD117881AA454D7AF74CA99CE44C9A07 /* NodeVisitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18CA905818E5E2164FBC0988AAE55505 /* NodeVisitor.swift */; }; + DF26AB29242601F1EF844C1F93622769 /* Kanna.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CB9196C245D34CE41C4A4701AA0302B /* Kanna.swift */; }; + E2D63D645F95493AA26C0417EB56521E /* Pods-AvH Plan-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 6CEC85DD03548206AF5B25B90A7DF559 /* Pods-AvH Plan-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E4BAD36591E05E5CCDACE4590670908C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */; }; + E6EB6D85479ED5AE656F9A99F404D0A4 /* HttpStatusException.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE9DAE424BF95138A2817D3EFBA5DD83 /* HttpStatusException.swift */; }; + E7863974D6375997E91385DDF642C217 /* Tokeniser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4367514386F919A94180B8AA301EDD24 /* Tokeniser.swift */; }; + EB0DD8CEA1A69867A30267439C970440 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BF5C705006567A0190712D18BCA038E /* Result.swift */; }; + ED978D1098E3AC1329E914E23E5A91EB /* Element.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E4931291C4148098611896ABCEB738A /* Element.swift */; }; + FB5FE2DC0824590FE956240D6082A0C4 /* CharacterExt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D99D1DA89C6E31B1719886510871D2A /* CharacterExt.swift */; }; + FBCBE3C40DF0145BA279F99CA966D578 /* Validate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CA028FB4D552DE30238DB31F744EFFE /* Validate.swift */; }; + FCB44E745786D701F1EEED3DC51A0DA5 /* BooleanAttribute.swift in Sources */ = {isa = PBXBuildFile; fileRef = A9301218346FA504221D1CA6B5806F98 /* BooleanAttribute.swift */; }; + FF60E537FF282E313D93E8DD7C0D826B /* StreamReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = A3830194B61D10D133E69CD7594886C3 /* StreamReader.swift */; }; + FFF7AAE6F95E911282B1EDC15DEBFC49 /* Evaluator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1FFA93A07A589B5F1A667F688B01CD15 /* Evaluator.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 008CF82A0A677D15C24882B430036B0B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 41AEB266717A3C96C2D1E03D16B79263; + remoteInfo = SwiftSoup; + }; + 6C6EE97F11C73A94EEFB5067BE9702F7 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = B07002B7F076BD4E872BCBC38DFC2EBE; + remoteInfo = "Pods-AvH Plan"; + }; + BFB065CE5D4C9BB3E9DD12F906BD2239 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 3383968E74B5371B20BB519B170DC7FD; + remoteInfo = Alamofire; + }; + D19D300FC068934E83D1F9CF36E3C2D1 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 1E0B9DFE11A3B2711C371DDBBA9BDAA6; + remoteInfo = Kanna; + }; + DB5C79D3AB0D0C0F521F5706607E56E5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = B07002B7F076BD4E872BCBC38DFC2EBE; + remoteInfo = "Pods-AvH Plan"; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0036C112B94117FBFB2A41309C9B6206 /* Pods-AvH PlanTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AvH PlanTests-acknowledgements.plist"; sourceTree = ""; }; + 0524BFE554CD002DF004DC8F7FEFE753 /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; + 0ACCBE5CBCEEF0D91BE70C9E889D3BA2 /* SerializationException.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerializationException.swift; path = Sources/SerializationException.swift; sourceTree = ""; }; + 0BF5C705006567A0190712D18BCA038E /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; + 0ECEDE78DBC16091B8359AE4008CCE77 /* Pods_AvH_Plan.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_AvH_Plan.framework; path = "Pods-AvH Plan.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 149B0630A2B0C7036D048DD786C2569F /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; + 18CA905818E5E2164FBC0988AAE55505 /* NodeVisitor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NodeVisitor.swift; path = Sources/NodeVisitor.swift; sourceTree = ""; }; + 1A06F52E0F27260A1C944ED81BE91FA5 /* Pods-AvH PlanUITests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AvH PlanUITests-Info.plist"; sourceTree = ""; }; + 1CA028FB4D552DE30238DB31F744EFFE /* Validate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validate.swift; path = Sources/Validate.swift; sourceTree = ""; }; + 1D8852ECD0E831F2AE24938F8C89BBF8 /* String.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = String.swift; path = Sources/String.swift; sourceTree = ""; }; + 1E55FD447CACA66A7D11C76DBC1885CC /* Pods-AvH Plan-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-AvH Plan-frameworks.sh"; sourceTree = ""; }; + 1FFA93A07A589B5F1A667F688B01CD15 /* Evaluator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Evaluator.swift; path = Sources/Evaluator.swift; sourceTree = ""; }; + 2088638F952F0502D15B7AF2E1A3944E /* DocumentType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DocumentType.swift; path = Sources/DocumentType.swift; sourceTree = ""; }; + 24E3E70C79180E6675807A55C667D468 /* ParseError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParseError.swift; path = Sources/ParseError.swift; sourceTree = ""; }; + 274B1B047B8EAF22F17BCA40DD88A1A0 /* Kanna.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Kanna.modulemap; sourceTree = ""; }; + 28A0127DE378A14D8904C41FABA21347 /* FormElement.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormElement.swift; path = Sources/FormElement.swift; sourceTree = ""; }; + 28E3F0CE6A49012D88F8838F08F014C3 /* ParseErrorList.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParseErrorList.swift; path = Sources/ParseErrorList.swift; sourceTree = ""; }; + 2C1DBA28A7D6FED5936AF80D2875E1B5 /* Pattern.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Pattern.swift; path = Sources/Pattern.swift; sourceTree = ""; }; + 3191F9B06709BB853AEE2408A1C23B8E /* SwiftSoup-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftSoup-prefix.pch"; sourceTree = ""; }; + 360629B9A48DEF6DB5115C0A3F3AD440 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; + 366D4051596D87F4F38AE0A38BA83DCB /* Pods-AvH PlanTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AvH PlanTests-dummy.m"; sourceTree = ""; }; + 36D84C7692E79C1948D75D3C7EBE68AE /* Comment.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Comment.swift; path = Sources/Comment.swift; sourceTree = ""; }; + 3A06775A643211AFF7F57D9F533E038E /* Elements.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Elements.swift; path = Sources/Elements.swift; sourceTree = ""; }; + 3EE7D2D9B241FD1CD1608EAE3CD4355D /* ArrayExt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ArrayExt.swift; path = Sources/ArrayExt.swift; sourceTree = ""; }; + 40A4164D18BD3AE1F9FC305942C48488 /* XmlTreeBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = XmlTreeBuilder.swift; path = Sources/XmlTreeBuilder.swift; sourceTree = ""; }; + 417E6BC7B7D9DE8F619B982865B03F16 /* SwiftSoup-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "SwiftSoup-Info.plist"; sourceTree = ""; }; + 422009F13AE51638B881729065187542 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; + 4367514386F919A94180B8AA301EDD24 /* Tokeniser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Tokeniser.swift; path = Sources/Tokeniser.swift; sourceTree = ""; }; + 44EF4FD8BDC6E1872450E67A99175333 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 481DE5F9C541D05406C45159486A7122 /* TokenQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TokenQueue.swift; path = Sources/TokenQueue.swift; sourceTree = ""; }; + 494E9A80735C309D8067B345DC8E0DBC /* Pods-AvH Plan-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AvH Plan-acknowledgements.plist"; sourceTree = ""; }; + 495173B15550DB4CC990B2B65BE31337 /* Collector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Collector.swift; path = Sources/Collector.swift; sourceTree = ""; }; + 4A671A7C76E09DBBBEB477A389F0A393 /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; + 4A70789BAB48D8E43B1F89CF4F2E170D /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; + 4BF71198830871F9FA2AAB00103CEAAA /* Kanna.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kanna.xcconfig; sourceTree = ""; }; + 4D0F664C25B120FE1D3CE3F872292BDA /* Deprecated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deprecated.swift; path = Sources/Kanna/Deprecated.swift; sourceTree = ""; }; + 501DA38799EFC05493791A93E4EE24FA /* SimpleDictionary.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SimpleDictionary.swift; path = Sources/SimpleDictionary.swift; sourceTree = ""; }; + 5042E1B69B7C32F708725A4A123EF1B3 /* StringBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringBuilder.swift; path = Sources/StringBuilder.swift; sourceTree = ""; }; + 53058E1EF4ADF2BD1A08F03E4E3F8E83 /* Document.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Document.swift; path = Sources/Document.swift; sourceTree = ""; }; + 5452EE4180B23B4041E9D04C7D714BC2 /* Kanna.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Kanna.framework; path = Kanna.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 576721BA56BEC277E8275B3D04727B96 /* Entities.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Entities.swift; path = Sources/Entities.swift; sourceTree = ""; }; + 5802D6CC422B64A8017907DF048B996A /* Cleaner.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cleaner.swift; path = Sources/Cleaner.swift; sourceTree = ""; }; + 5823F184430B87162A942CAD83746EEA /* Pods-AvH Plan.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AvH Plan.release.xcconfig"; sourceTree = ""; }; + 58C49157383527E6DAAD841D780911F4 /* Kanna-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Kanna-dummy.m"; sourceTree = ""; }; + 5C8131ABA4308A03318FC44FD7A8CF0E /* CharacterReader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CharacterReader.swift; path = Sources/CharacterReader.swift; sourceTree = ""; }; + 5D0916396C74706FDD75CD7AE35EBF2E /* Pods-AvH PlanUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AvH PlanUITests.debug.xcconfig"; sourceTree = ""; }; + 5F2D6EB4F89AB32EA574DC71E4DD6D75 /* UnicodeScalar.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = UnicodeScalar.swift; path = Sources/UnicodeScalar.swift; sourceTree = ""; }; + 602308BC2EA0CA138E0247A3A5DDD183 /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; + 61ADAB0A92B456198464EFD35FF98B4C /* Kanna-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kanna-prefix.pch"; sourceTree = ""; }; + 634CE874ED90E51D8C74455B66406A5D /* HtmlTreeBuilderState.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HtmlTreeBuilderState.swift; path = Sources/HtmlTreeBuilderState.swift; sourceTree = ""; }; + 648CEFC31AD08F076E9D832A75740912 /* Node.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Node.swift; path = Sources/Node.swift; sourceTree = ""; }; + 654AD6A738B5116BAF7E09814F928F71 /* SwiftSoup.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = SwiftSoup.xcconfig; sourceTree = ""; }; + 6585A3E24D1551DDFD1F1B4CDAFD52A9 /* OrderedSet.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OrderedSet.swift; path = Sources/OrderedSet.swift; sourceTree = ""; }; + 6B35FB7D228EF72D1AD7BC8B4D3E6F98 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; + 6C6047943B344E34AD832D857A2286F8 /* SwiftSoup.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = SwiftSoup.framework; path = SwiftSoup.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 6CEC85DD03548206AF5B25B90A7DF559 /* Pods-AvH Plan-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AvH Plan-umbrella.h"; sourceTree = ""; }; + 72A172D68D212D3E1FE1A01E214FFCB3 /* TreeBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TreeBuilder.swift; path = Sources/TreeBuilder.swift; sourceTree = ""; }; + 739A071FC6E83235FBEC3822EC54A2CE /* SwiftSoup.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftSoup.swift; path = Sources/SwiftSoup.swift; sourceTree = ""; }; + 73FB82C1152B4D4D20762D1847ABB196 /* Pods-AvH PlanUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AvH PlanUITests-acknowledgements.plist"; sourceTree = ""; }; + 7BA92A504E09AD80F699278201FBEA51 /* Exception.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Exception.swift; path = Sources/Exception.swift; sourceTree = ""; }; + 7CB9196C245D34CE41C4A4701AA0302B /* Kanna.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Kanna.swift; path = Sources/Kanna/Kanna.swift; sourceTree = ""; }; + 7E0006D460D6D0B8FB8F9DE3947E5CAB /* SwiftSoup.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = SwiftSoup.modulemap; sourceTree = ""; }; + 80CA405FCD2D612456555D5052D1C896 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; + 813F9DCF597667D2B2B0342BD936A661 /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; + 82D0FB4D859F89BC72D83D3F2A987CA4 /* libxmlHTMLNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = libxmlHTMLNode.swift; path = Sources/Kanna/libxmlHTMLNode.swift; sourceTree = ""; }; + 83698EB29BFAE170C22D2497909C4063 /* StringUtil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StringUtil.swift; path = Sources/StringUtil.swift; sourceTree = ""; }; + 8614CA5394836DC77257B1CD7E227C5A /* Pods-AvH Plan.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-AvH Plan.modulemap"; sourceTree = ""; }; + 8A10CB565324867AFF90BC29EC8F60B1 /* Pods-AvH PlanUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AvH PlanUITests-umbrella.h"; sourceTree = ""; }; + 8D99D1DA89C6E31B1719886510871D2A /* CharacterExt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CharacterExt.swift; path = Sources/CharacterExt.swift; sourceTree = ""; }; + 8DF87281196264525DB63D825BE9F847 /* SwiftSoup-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "SwiftSoup-umbrella.h"; sourceTree = ""; }; + 8F24FA5439D5FCDE33E2F8C420EF802D /* Pods-AvH PlanUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AvH PlanUITests.release.xcconfig"; sourceTree = ""; }; + 8FFC90FCBA1F53DA88088798BADC9FCB /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; + 90B5A7A64A51B2E3108644ED8DBF2BB8 /* Pods-AvH Plan-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AvH Plan-acknowledgements.markdown"; sourceTree = ""; }; + 93C036AA9F2E7653041EE0096A963C21 /* libxmlHTMLDocument.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = libxmlHTMLDocument.swift; path = Sources/Kanna/libxmlHTMLDocument.swift; sourceTree = ""; }; + 946C4CB0FF96FD34FF58E6B3981002E6 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; + 951C72C89491F4A7D0F70B308D51B2FC /* CombiningEvaluator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombiningEvaluator.swift; path = Sources/CombiningEvaluator.swift; sourceTree = ""; }; + 979941070BFC250C98E0F5961765E434 /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; + 987F66FED3B9F4D2572FA89B48EFB407 /* NodeTraversor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NodeTraversor.swift; path = Sources/NodeTraversor.swift; sourceTree = ""; }; + 9882F455ADC90B15FC388285839B46E9 /* Pods_AvH_PlanUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_AvH_PlanUITests.framework; path = "Pods-AvH PlanUITests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + 9AB2D679050F3A617C2396C5A9752E20 /* TokeniserState.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TokeniserState.swift; path = Sources/TokeniserState.swift; sourceTree = ""; }; + 9B708E36B4E25ED8DCB0C36F9C0B627D /* Tag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Tag.swift; path = Sources/Tag.swift; sourceTree = ""; }; + 9B952B65F8F3C02B5AC0746EE79DFCA8 /* QueryParser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = QueryParser.swift; path = Sources/QueryParser.swift; sourceTree = ""; }; + 9BCE57BC27B042DC0B52D1D45F4B9D18 /* Pods-AvH PlanTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AvH PlanTests-Info.plist"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9E4931291C4148098611896ABCEB738A /* Element.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Element.swift; path = Sources/Element.swift; sourceTree = ""; }; + 9F0D2376FCDE023107AB552C96848609 /* Pods-AvH PlanTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-AvH PlanTests-umbrella.h"; sourceTree = ""; }; + 9FA495A9A78F4662F3E848344C1D73AC /* Attributes.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Attributes.swift; path = Sources/Attributes.swift; sourceTree = ""; }; + 9FD28D145FEBFD59EA284DA62A934238 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; + A37FD0BD5551170D6A159A0FFD57DB16 /* Token.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Token.swift; path = Sources/Token.swift; sourceTree = ""; }; + A3830194B61D10D133E69CD7594886C3 /* StreamReader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StreamReader.swift; path = Sources/StreamReader.swift; sourceTree = ""; }; + A51B0C00365C4E669915F9759D852315 /* Pods-AvH PlanUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-AvH PlanUITests.modulemap"; sourceTree = ""; }; + A5B6FA00955A4CB62A17194304037BF7 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; + A7AE2AEDC4F16A81364E2DD13CF55495 /* Attribute.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Attribute.swift; path = Sources/Attribute.swift; sourceTree = ""; }; + A7EF8B2FEEAD839EC827E8804FB607C7 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; + A806196AE08404C302927001B8FCEA6F /* DataNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataNode.swift; path = Sources/DataNode.swift; sourceTree = ""; }; + A9301218346FA504221D1CA6B5806F98 /* BooleanAttribute.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanAttribute.swift; path = Sources/BooleanAttribute.swift; sourceTree = ""; }; + ADC262E4866CDB8D980E87AC0E65F429 /* Selector.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Selector.swift; path = Sources/Selector.swift; sourceTree = ""; }; + AE58976088B83E8DA3B02BA272D16113 /* TextNode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextNode.swift; path = Sources/TextNode.swift; sourceTree = ""; }; + AF32B8867E0C18326FB3E2192AF8D922 /* Pods-AvH PlanUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AvH PlanUITests-acknowledgements.markdown"; sourceTree = ""; }; + B0487FF389DD58423062E24E548C347F /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; + B0B0A3D6ADA012D62A82E4799AB3A2D8 /* Pods-AvH PlanTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-AvH PlanTests.modulemap"; sourceTree = ""; }; + B3C00386655406AA69D4A5765CC45BB0 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; + B59A00536E5BCD69AE5D5F9F791DB51C /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; + B9B8B105EBEE55593D98809A0664FF1D /* SwiftSoup-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "SwiftSoup-dummy.m"; sourceTree = ""; }; + BAEF925B85CA3BBB8A2671EC00D40C19 /* StructuralEvaluator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StructuralEvaluator.swift; path = Sources/StructuralEvaluator.swift; sourceTree = ""; }; + BB20860CAA019FA52F4A35F83680FD6B /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; + BC4311D98116FE51975F64E10043D9E6 /* Pods-AvH Plan.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AvH Plan.debug.xcconfig"; sourceTree = ""; }; + BCBF7C1753AF33C39A58753446710278 /* Pods_AvH_PlanTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_AvH_PlanTests.framework; path = "Pods-AvH PlanTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + BE57CBB6CC8CAF3FCC9DCD131599E1E8 /* OrderedDictionary.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OrderedDictionary.swift; path = Sources/OrderedDictionary.swift; sourceTree = ""; }; + C29F3BA1835573FE373519442DFD3C38 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; + C43F4ABD280AD23016A41BECA82A24E8 /* Connection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Connection.swift; path = Sources/Connection.swift; sourceTree = ""; }; + C47022DD000B164E2AE665B77CD169BE /* HtmlTreeBuilder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HtmlTreeBuilder.swift; path = Sources/HtmlTreeBuilder.swift; sourceTree = ""; }; + C48C9769C2A247D71BA1C2218D3CD73E /* Pods-AvH PlanTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AvH PlanTests.release.xcconfig"; sourceTree = ""; }; + C76EDBC769B8360FE1D1986B078CDA0D /* Whitelist.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Whitelist.swift; path = Sources/Whitelist.swift; sourceTree = ""; }; + C98E0A40FFAA294F06BB6E9D60AC2AC0 /* Pods-AvH PlanTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-AvH PlanTests.debug.xcconfig"; sourceTree = ""; }; + CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + CBDCF37BBF7FB4EF18D72AB9DA026F6E /* Kanna-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Kanna-Info.plist"; sourceTree = ""; }; + D29F1A4B8F28B48CA9A38AD1FE840809 /* CSS.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CSS.swift; path = Sources/Kanna/CSS.swift; sourceTree = ""; }; + D4E6F4D3F12A1A1A756E6C0A8980B6F8 /* Pods-AvH Plan-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-AvH Plan-Info.plist"; sourceTree = ""; }; + D9B46B4B433F5B30B3E3EB19499B430F /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; + DA46035AE77AF1965C070385D4EE3057 /* XmlDeclaration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = XmlDeclaration.swift; path = Sources/XmlDeclaration.swift; sourceTree = ""; }; + DF1FEFF7EF658A0AFDF3A6ABA2097AA4 /* Pods-AvH PlanTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-AvH PlanTests-acknowledgements.markdown"; sourceTree = ""; }; + E00A87640D00F37E99EC16C1D3F2ADBE /* DataUtil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DataUtil.swift; path = Sources/DataUtil.swift; sourceTree = ""; }; + E43EAA9B724EA33F95A4E3A6F0E80EC5 /* ParseSettings.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParseSettings.swift; path = Sources/ParseSettings.swift; sourceTree = ""; }; + E4ACE57E279FBB41A3DE7F7BD47E5022 /* Parser.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Parser.swift; path = Sources/Parser.swift; sourceTree = ""; }; + E83C929C10ECA7B23C4A16A51E89258C /* Kanna.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = Kanna.h; path = Sources/Kanna/Kanna.h; sourceTree = ""; }; + E85C23AA0E9238CEB29619DC264D429A /* libxmlParserOption.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = libxmlParserOption.swift; path = Sources/Kanna/libxmlParserOption.swift; sourceTree = ""; }; + EAFC540C9B7F4F6B987516B859977D5C /* Pods-AvH Plan-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AvH Plan-dummy.m"; sourceTree = ""; }; + F08DABC90F4CDC9C4F0D028838804A5F /* Pods-AvH PlanUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-AvH PlanUITests-dummy.m"; sourceTree = ""; }; + F7152D164F0AA9227443BA39A6D0F255 /* Kanna-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kanna-umbrella.h"; sourceTree = ""; }; + FE9DAE424BF95138A2817D3EFBA5DD83 /* HttpStatusException.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HttpStatusException.swift; path = Sources/HttpStatusException.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 3796997A3F16472887E8790402667A7E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E4BAD36591E05E5CCDACE4590670908C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BF3DA677E0385C02F3570246154E6A6A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + BB9D54EA7D2102F5C00D57F51B83E954 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C51182ED4109313DDC62F514CB7F93C8 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 5B32A9E85D43A45FD12CE7E813A2775C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EF1DDF49F4F65B713DAE6A4AAA268558 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 9C82FFDD7350CE1A7E0B13024820BFF6 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F1626ADC3A7EC435D2722B3173355D36 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3BD1DAFE1F3E6C9E4EB0F2099B6D6FA2 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FA5BD55C744892BC037F1AD1537CF79A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 8882470CC4B134F927FB080A510BBE2A /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0EF1C89791FF626594290C1A43CD4533 /* Support Files */ = { + isa = PBXGroup; + children = ( + 80CA405FCD2D612456555D5052D1C896 /* Alamofire.modulemap */, + 9FD28D145FEBFD59EA284DA62A934238 /* Alamofire.xcconfig */, + 4A70789BAB48D8E43B1F89CF4F2E170D /* Alamofire-dummy.m */, + 422009F13AE51638B881729065187542 /* Alamofire-Info.plist */, + 979941070BFC250C98E0F5961765E434 /* Alamofire-prefix.pch */, + 4A671A7C76E09DBBBEB477A389F0A393 /* Alamofire-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Alamofire"; + sourceTree = ""; + }; + 193507AA07A01F54362D558007C15085 /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 79DDEB7AC44EBAA9952D15F966180055 /* Pods-AvH Plan */, + 233CAC8E4D2E68212C3DDF04241ADED6 /* Pods-AvH PlanTests */, + A85A4E79C7E1291EF663F6D86185E034 /* Pods-AvH PlanUITests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + 233CAC8E4D2E68212C3DDF04241ADED6 /* Pods-AvH PlanTests */ = { + isa = PBXGroup; + children = ( + B0B0A3D6ADA012D62A82E4799AB3A2D8 /* Pods-AvH PlanTests.modulemap */, + DF1FEFF7EF658A0AFDF3A6ABA2097AA4 /* Pods-AvH PlanTests-acknowledgements.markdown */, + 0036C112B94117FBFB2A41309C9B6206 /* Pods-AvH PlanTests-acknowledgements.plist */, + 366D4051596D87F4F38AE0A38BA83DCB /* Pods-AvH PlanTests-dummy.m */, + 9BCE57BC27B042DC0B52D1D45F4B9D18 /* Pods-AvH PlanTests-Info.plist */, + 9F0D2376FCDE023107AB552C96848609 /* Pods-AvH PlanTests-umbrella.h */, + C98E0A40FFAA294F06BB6E9D60AC2AC0 /* Pods-AvH PlanTests.debug.xcconfig */, + C48C9769C2A247D71BA1C2218D3CD73E /* Pods-AvH PlanTests.release.xcconfig */, + ); + name = "Pods-AvH PlanTests"; + path = "Target Support Files/Pods-AvH PlanTests"; + sourceTree = ""; + }; + 2417465C5A4B97D9538F5FCC2CBA9D50 /* Support Files */ = { + isa = PBXGroup; + children = ( + 274B1B047B8EAF22F17BCA40DD88A1A0 /* Kanna.modulemap */, + 4BF71198830871F9FA2AAB00103CEAAA /* Kanna.xcconfig */, + 58C49157383527E6DAAD841D780911F4 /* Kanna-dummy.m */, + CBDCF37BBF7FB4EF18D72AB9DA026F6E /* Kanna-Info.plist */, + 61ADAB0A92B456198464EFD35FF98B4C /* Kanna-prefix.pch */, + F7152D164F0AA9227443BA39A6D0F255 /* Kanna-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/Kanna"; + sourceTree = ""; + }; + 468C48A37699BE7174BDC806D76D8412 /* Alamofire */ = { + isa = PBXGroup; + children = ( + 149B0630A2B0C7036D048DD786C2569F /* AFError.swift */, + B3C00386655406AA69D4A5765CC45BB0 /* Alamofire.swift */, + A7EF8B2FEEAD839EC827E8804FB607C7 /* DispatchQueue+Alamofire.swift */, + D9B46B4B433F5B30B3E3EB19499B430F /* MultipartFormData.swift */, + B0487FF389DD58423062E24E548C347F /* NetworkReachabilityManager.swift */, + 360629B9A48DEF6DB5115C0A3F3AD440 /* Notifications.swift */, + 0524BFE554CD002DF004DC8F7FEFE753 /* ParameterEncoding.swift */, + 8FFC90FCBA1F53DA88088798BADC9FCB /* Request.swift */, + 813F9DCF597667D2B2B0342BD936A661 /* Response.swift */, + 946C4CB0FF96FD34FF58E6B3981002E6 /* ResponseSerialization.swift */, + 0BF5C705006567A0190712D18BCA038E /* Result.swift */, + BB20860CAA019FA52F4A35F83680FD6B /* ServerTrustPolicy.swift */, + 6B35FB7D228EF72D1AD7BC8B4D3E6F98 /* SessionDelegate.swift */, + C29F3BA1835573FE373519442DFD3C38 /* SessionManager.swift */, + B59A00536E5BCD69AE5D5F9F791DB51C /* TaskDelegate.swift */, + A5B6FA00955A4CB62A17194304037BF7 /* Timeline.swift */, + 602308BC2EA0CA138E0247A3A5DDD183 /* Validation.swift */, + 0EF1C89791FF626594290C1A43CD4533 /* Support Files */, + ); + name = Alamofire; + path = Alamofire; + sourceTree = ""; + }; + 79DDEB7AC44EBAA9952D15F966180055 /* Pods-AvH Plan */ = { + isa = PBXGroup; + children = ( + 8614CA5394836DC77257B1CD7E227C5A /* Pods-AvH Plan.modulemap */, + 90B5A7A64A51B2E3108644ED8DBF2BB8 /* Pods-AvH Plan-acknowledgements.markdown */, + 494E9A80735C309D8067B345DC8E0DBC /* Pods-AvH Plan-acknowledgements.plist */, + EAFC540C9B7F4F6B987516B859977D5C /* Pods-AvH Plan-dummy.m */, + 1E55FD447CACA66A7D11C76DBC1885CC /* Pods-AvH Plan-frameworks.sh */, + D4E6F4D3F12A1A1A756E6C0A8980B6F8 /* Pods-AvH Plan-Info.plist */, + 6CEC85DD03548206AF5B25B90A7DF559 /* Pods-AvH Plan-umbrella.h */, + BC4311D98116FE51975F64E10043D9E6 /* Pods-AvH Plan.debug.xcconfig */, + 5823F184430B87162A942CAD83746EEA /* Pods-AvH Plan.release.xcconfig */, + ); + name = "Pods-AvH Plan"; + path = "Target Support Files/Pods-AvH Plan"; + sourceTree = ""; + }; + 8FEFFF132F1F4B1562A0FE47BF968B48 /* Support Files */ = { + isa = PBXGroup; + children = ( + 7E0006D460D6D0B8FB8F9DE3947E5CAB /* SwiftSoup.modulemap */, + 654AD6A738B5116BAF7E09814F928F71 /* SwiftSoup.xcconfig */, + B9B8B105EBEE55593D98809A0664FF1D /* SwiftSoup-dummy.m */, + 417E6BC7B7D9DE8F619B982865B03F16 /* SwiftSoup-Info.plist */, + 3191F9B06709BB853AEE2408A1C23B8E /* SwiftSoup-prefix.pch */, + 8DF87281196264525DB63D825BE9F847 /* SwiftSoup-umbrella.h */, + ); + name = "Support Files"; + path = "../Target Support Files/SwiftSoup"; + sourceTree = ""; + }; + 9B055D0CFEA43187E72B03DED11F5662 /* iOS */ = { + isa = PBXGroup; + children = ( + CB4607EFCA7C5F75397649E792E2AFCB /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + A85A4E79C7E1291EF663F6D86185E034 /* Pods-AvH PlanUITests */ = { + isa = PBXGroup; + children = ( + A51B0C00365C4E669915F9759D852315 /* Pods-AvH PlanUITests.modulemap */, + AF32B8867E0C18326FB3E2192AF8D922 /* Pods-AvH PlanUITests-acknowledgements.markdown */, + 73FB82C1152B4D4D20762D1847ABB196 /* Pods-AvH PlanUITests-acknowledgements.plist */, + F08DABC90F4CDC9C4F0D028838804A5F /* Pods-AvH PlanUITests-dummy.m */, + 1A06F52E0F27260A1C944ED81BE91FA5 /* Pods-AvH PlanUITests-Info.plist */, + 8A10CB565324867AFF90BC29EC8F60B1 /* Pods-AvH PlanUITests-umbrella.h */, + 5D0916396C74706FDD75CD7AE35EBF2E /* Pods-AvH PlanUITests.debug.xcconfig */, + 8F24FA5439D5FCDE33E2F8C420EF802D /* Pods-AvH PlanUITests.release.xcconfig */, + ); + name = "Pods-AvH PlanUITests"; + path = "Target Support Files/Pods-AvH PlanUITests"; + sourceTree = ""; + }; + AB1E7FA4FCCA25C6C07B52EF12D5A480 /* Products */ = { + isa = PBXGroup; + children = ( + 44EF4FD8BDC6E1872450E67A99175333 /* Alamofire.framework */, + 5452EE4180B23B4041E9D04C7D714BC2 /* Kanna.framework */, + 0ECEDE78DBC16091B8359AE4008CCE77 /* Pods_AvH_Plan.framework */, + BCBF7C1753AF33C39A58753446710278 /* Pods_AvH_PlanTests.framework */, + 9882F455ADC90B15FC388285839B46E9 /* Pods_AvH_PlanUITests.framework */, + 6C6047943B344E34AD832D857A2286F8 /* SwiftSoup.framework */, + ); + name = Products; + sourceTree = ""; + }; + AB907795CBDDCC875E9A63191B51CC93 /* Pods */ = { + isa = PBXGroup; + children = ( + 468C48A37699BE7174BDC806D76D8412 /* Alamofire */, + F78B774216E65E2E6E1EB3088584C5CC /* Kanna */, + ED39CAF2B373D5BBA725F235C03EBC6B /* SwiftSoup */, + ); + name = Pods; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */, + AB907795CBDDCC875E9A63191B51CC93 /* Pods */, + AB1E7FA4FCCA25C6C07B52EF12D5A480 /* Products */, + 193507AA07A01F54362D558007C15085 /* Targets Support Files */, + ); + sourceTree = ""; + }; + D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 9B055D0CFEA43187E72B03DED11F5662 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + ED39CAF2B373D5BBA725F235C03EBC6B /* SwiftSoup */ = { + isa = PBXGroup; + children = ( + 3EE7D2D9B241FD1CD1608EAE3CD4355D /* ArrayExt.swift */, + A7AE2AEDC4F16A81364E2DD13CF55495 /* Attribute.swift */, + 9FA495A9A78F4662F3E848344C1D73AC /* Attributes.swift */, + A9301218346FA504221D1CA6B5806F98 /* BooleanAttribute.swift */, + 8D99D1DA89C6E31B1719886510871D2A /* CharacterExt.swift */, + 5C8131ABA4308A03318FC44FD7A8CF0E /* CharacterReader.swift */, + 5802D6CC422B64A8017907DF048B996A /* Cleaner.swift */, + 495173B15550DB4CC990B2B65BE31337 /* Collector.swift */, + 951C72C89491F4A7D0F70B308D51B2FC /* CombiningEvaluator.swift */, + 36D84C7692E79C1948D75D3C7EBE68AE /* Comment.swift */, + C43F4ABD280AD23016A41BECA82A24E8 /* Connection.swift */, + A806196AE08404C302927001B8FCEA6F /* DataNode.swift */, + E00A87640D00F37E99EC16C1D3F2ADBE /* DataUtil.swift */, + 53058E1EF4ADF2BD1A08F03E4E3F8E83 /* Document.swift */, + 2088638F952F0502D15B7AF2E1A3944E /* DocumentType.swift */, + 9E4931291C4148098611896ABCEB738A /* Element.swift */, + 3A06775A643211AFF7F57D9F533E038E /* Elements.swift */, + 576721BA56BEC277E8275B3D04727B96 /* Entities.swift */, + 1FFA93A07A589B5F1A667F688B01CD15 /* Evaluator.swift */, + 7BA92A504E09AD80F699278201FBEA51 /* Exception.swift */, + 28A0127DE378A14D8904C41FABA21347 /* FormElement.swift */, + C47022DD000B164E2AE665B77CD169BE /* HtmlTreeBuilder.swift */, + 634CE874ED90E51D8C74455B66406A5D /* HtmlTreeBuilderState.swift */, + FE9DAE424BF95138A2817D3EFBA5DD83 /* HttpStatusException.swift */, + 648CEFC31AD08F076E9D832A75740912 /* Node.swift */, + 987F66FED3B9F4D2572FA89B48EFB407 /* NodeTraversor.swift */, + 18CA905818E5E2164FBC0988AAE55505 /* NodeVisitor.swift */, + BE57CBB6CC8CAF3FCC9DCD131599E1E8 /* OrderedDictionary.swift */, + 6585A3E24D1551DDFD1F1B4CDAFD52A9 /* OrderedSet.swift */, + 24E3E70C79180E6675807A55C667D468 /* ParseError.swift */, + 28E3F0CE6A49012D88F8838F08F014C3 /* ParseErrorList.swift */, + E4ACE57E279FBB41A3DE7F7BD47E5022 /* Parser.swift */, + E43EAA9B724EA33F95A4E3A6F0E80EC5 /* ParseSettings.swift */, + 2C1DBA28A7D6FED5936AF80D2875E1B5 /* Pattern.swift */, + 9B952B65F8F3C02B5AC0746EE79DFCA8 /* QueryParser.swift */, + ADC262E4866CDB8D980E87AC0E65F429 /* Selector.swift */, + 0ACCBE5CBCEEF0D91BE70C9E889D3BA2 /* SerializationException.swift */, + 501DA38799EFC05493791A93E4EE24FA /* SimpleDictionary.swift */, + A3830194B61D10D133E69CD7594886C3 /* StreamReader.swift */, + 1D8852ECD0E831F2AE24938F8C89BBF8 /* String.swift */, + 5042E1B69B7C32F708725A4A123EF1B3 /* StringBuilder.swift */, + 83698EB29BFAE170C22D2497909C4063 /* StringUtil.swift */, + BAEF925B85CA3BBB8A2671EC00D40C19 /* StructuralEvaluator.swift */, + 739A071FC6E83235FBEC3822EC54A2CE /* SwiftSoup.swift */, + 9B708E36B4E25ED8DCB0C36F9C0B627D /* Tag.swift */, + AE58976088B83E8DA3B02BA272D16113 /* TextNode.swift */, + A37FD0BD5551170D6A159A0FFD57DB16 /* Token.swift */, + 4367514386F919A94180B8AA301EDD24 /* Tokeniser.swift */, + 9AB2D679050F3A617C2396C5A9752E20 /* TokeniserState.swift */, + 481DE5F9C541D05406C45159486A7122 /* TokenQueue.swift */, + 72A172D68D212D3E1FE1A01E214FFCB3 /* TreeBuilder.swift */, + 5F2D6EB4F89AB32EA574DC71E4DD6D75 /* UnicodeScalar.swift */, + 1CA028FB4D552DE30238DB31F744EFFE /* Validate.swift */, + C76EDBC769B8360FE1D1986B078CDA0D /* Whitelist.swift */, + DA46035AE77AF1965C070385D4EE3057 /* XmlDeclaration.swift */, + 40A4164D18BD3AE1F9FC305942C48488 /* XmlTreeBuilder.swift */, + 8FEFFF132F1F4B1562A0FE47BF968B48 /* Support Files */, + ); + name = SwiftSoup; + path = SwiftSoup; + sourceTree = ""; + }; + F78B774216E65E2E6E1EB3088584C5CC /* Kanna */ = { + isa = PBXGroup; + children = ( + D29F1A4B8F28B48CA9A38AD1FE840809 /* CSS.swift */, + 4D0F664C25B120FE1D3CE3F872292BDA /* Deprecated.swift */, + E83C929C10ECA7B23C4A16A51E89258C /* Kanna.h */, + 7CB9196C245D34CE41C4A4701AA0302B /* Kanna.swift */, + 93C036AA9F2E7653041EE0096A963C21 /* libxmlHTMLDocument.swift */, + 82D0FB4D859F89BC72D83D3F2A987CA4 /* libxmlHTMLNode.swift */, + E85C23AA0E9238CEB29619DC264D429A /* libxmlParserOption.swift */, + 2417465C5A4B97D9538F5FCC2CBA9D50 /* Support Files */, + ); + name = Kanna; + path = Kanna; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 010B64DAE082E3D3B3F85F9323C8E482 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + D15DD84A4FE55D8CE30BC48EB6811C37 /* Pods-AvH PlanUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 09784831BE8777805A5D589463A0428E /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + A626EDD7DC5AD198A921E5951A073314 /* Kanna-umbrella.h in Headers */, + 48EAFB23E51CFB029365640B79EC67B4 /* Kanna.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 23D70D9651451F43E7E8CC1A87B4B7E9 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + B6F6E4CC26451E91B59FAE0F6841DC1F /* Alamofire-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9A6D6A286C86B31645B88CB3A6BA7926 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 18C070538A56B1099412C67BD2376148 /* Pods-AvH PlanTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + BBCAD5D45F73C409A9B4B5A1EB0B3B09 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + CE967A656EE25027598A84474DF5B60A /* SwiftSoup-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + DD56154FFBFE64B425A2361398D128FB /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + E2D63D645F95493AA26C0417EB56521E /* Pods-AvH Plan-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 1E0B9DFE11A3B2711C371DDBBA9BDAA6 /* Kanna */ = { + isa = PBXNativeTarget; + buildConfigurationList = 298C5DBE2FFB2DE540832BA1BD48B738 /* Build configuration list for PBXNativeTarget "Kanna" */; + buildPhases = ( + 09784831BE8777805A5D589463A0428E /* Headers */, + 0D23CFC99303143CC2318F21F02A96F9 /* Sources */, + C51182ED4109313DDC62F514CB7F93C8 /* Frameworks */, + 988B19C4AA686C4184DDF5197B75E074 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Kanna; + productName = Kanna; + productReference = 5452EE4180B23B4041E9D04C7D714BC2 /* Kanna.framework */; + productType = "com.apple.product-type.framework"; + }; + 3383968E74B5371B20BB519B170DC7FD /* Alamofire */ = { + isa = PBXNativeTarget; + buildConfigurationList = E87124444A44B7DB55208E7FEC21D331 /* Build configuration list for PBXNativeTarget "Alamofire" */; + buildPhases = ( + 23D70D9651451F43E7E8CC1A87B4B7E9 /* Headers */, + A1C8B029F600160149A2404C342F6E50 /* Sources */, + F1626ADC3A7EC435D2722B3173355D36 /* Frameworks */, + 28FF73341543B6F0A7DF3C20CFFEA0AA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Alamofire; + productName = Alamofire; + productReference = 44EF4FD8BDC6E1872450E67A99175333 /* Alamofire.framework */; + productType = "com.apple.product-type.framework"; + }; + 41AEB266717A3C96C2D1E03D16B79263 /* SwiftSoup */ = { + isa = PBXNativeTarget; + buildConfigurationList = A92C2376420206B771B40894A62D5100 /* Build configuration list for PBXNativeTarget "SwiftSoup" */; + buildPhases = ( + BBCAD5D45F73C409A9B4B5A1EB0B3B09 /* Headers */, + D91C247306A283624F04C27EDC4FF533 /* Sources */, + 3796997A3F16472887E8790402667A7E /* Frameworks */, + FF2DF74A529ED2AED03C2D76D521AA0B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = SwiftSoup; + productName = SwiftSoup; + productReference = 6C6047943B344E34AD832D857A2286F8 /* SwiftSoup.framework */; + productType = "com.apple.product-type.framework"; + }; + 4F58E6A326CFE0774A009139A52A7BFF /* Pods-AvH PlanUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = D83EEEDCFA4D6FF7B9C294AA5CC10EAC /* Build configuration list for PBXNativeTarget "Pods-AvH PlanUITests" */; + buildPhases = ( + 010B64DAE082E3D3B3F85F9323C8E482 /* Headers */, + C0D9E1CF20004CE670295A8938F0FB76 /* Sources */, + FA5BD55C744892BC037F1AD1537CF79A /* Frameworks */, + A7C5ADC8C3E932B005846554EC7C2EBA /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 1C60BF514C02D008326F475A2AB43EC9 /* PBXTargetDependency */, + ); + name = "Pods-AvH PlanUITests"; + productName = "Pods-AvH PlanUITests"; + productReference = 9882F455ADC90B15FC388285839B46E9 /* Pods_AvH_PlanUITests.framework */; + productType = "com.apple.product-type.framework"; + }; + B07002B7F076BD4E872BCBC38DFC2EBE /* Pods-AvH Plan */ = { + isa = PBXNativeTarget; + buildConfigurationList = ECD6139BCB471427BA440D532EC8B31C /* Build configuration list for PBXNativeTarget "Pods-AvH Plan" */; + buildPhases = ( + DD56154FFBFE64B425A2361398D128FB /* Headers */, + A5E5629EFB30FCDD2E796C34813D7A0C /* Sources */, + BF3DA677E0385C02F3570246154E6A6A /* Frameworks */, + 54676CBBBD41A9470BD91EB48BAD968A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + FE49D9427AD7B750A11A2B51BA42D61A /* PBXTargetDependency */, + 3C6F078671E93D0441B4B1A123349B62 /* PBXTargetDependency */, + 741A382F7308747D7DC56054F02BB6EB /* PBXTargetDependency */, + ); + name = "Pods-AvH Plan"; + productName = "Pods-AvH Plan"; + productReference = 0ECEDE78DBC16091B8359AE4008CCE77 /* Pods_AvH_Plan.framework */; + productType = "com.apple.product-type.framework"; + }; + B8C6AD5E702222047282C46D5A957F5F /* Pods-AvH PlanTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A152575917A1D5DFD790D77FC4A844B5 /* Build configuration list for PBXNativeTarget "Pods-AvH PlanTests" */; + buildPhases = ( + 9A6D6A286C86B31645B88CB3A6BA7926 /* Headers */, + 0BB1B6B3E567CD488099A4FB7C9EDE60 /* Sources */, + EF1DDF49F4F65B713DAE6A4AAA268558 /* Frameworks */, + C945781B0F70C95F0E4B40F421520368 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + AAE8EAF9E258E20B3E6365F805A7C60B /* PBXTargetDependency */, + ); + name = "Pods-AvH PlanTests"; + productName = "Pods-AvH PlanTests"; + productReference = BCBF7C1753AF33C39A58753446710278 /* Pods_AvH_PlanTests.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0930; + LastUpgradeCheck = 0930; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = AB1E7FA4FCCA25C6C07B52EF12D5A480 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 3383968E74B5371B20BB519B170DC7FD /* Alamofire */, + 1E0B9DFE11A3B2711C371DDBBA9BDAA6 /* Kanna */, + B07002B7F076BD4E872BCBC38DFC2EBE /* Pods-AvH Plan */, + B8C6AD5E702222047282C46D5A957F5F /* Pods-AvH PlanTests */, + 4F58E6A326CFE0774A009139A52A7BFF /* Pods-AvH PlanUITests */, + 41AEB266717A3C96C2D1E03D16B79263 /* SwiftSoup */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 28FF73341543B6F0A7DF3C20CFFEA0AA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 54676CBBBD41A9470BD91EB48BAD968A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 988B19C4AA686C4184DDF5197B75E074 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A7C5ADC8C3E932B005846554EC7C2EBA /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C945781B0F70C95F0E4B40F421520368 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FF2DF74A529ED2AED03C2D76D521AA0B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 0BB1B6B3E567CD488099A4FB7C9EDE60 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 52E1A3CF97809055A74BC32BF0B9FBBD /* Pods-AvH PlanTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0D23CFC99303143CC2318F21F02A96F9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 6921ED8F336C9A8584246C8EA9E05BCD /* CSS.swift in Sources */, + 4C2DE52019670B533E562CE3F2A6E077 /* Deprecated.swift in Sources */, + 2DAC7A6A4DC00202CEDB3860F091C34D /* Kanna-dummy.m in Sources */, + DF26AB29242601F1EF844C1F93622769 /* Kanna.swift in Sources */, + BB01E5C2361137030EECD341813BA379 /* libxmlHTMLDocument.swift in Sources */, + C73EC5098AFF72BB9B68A49AB7B5B23D /* libxmlHTMLNode.swift in Sources */, + A20D50BC4E158C5BCF2DDE93B62C6335 /* libxmlParserOption.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A1C8B029F600160149A2404C342F6E50 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7E3538A6992A38276764936A9733493D /* AFError.swift in Sources */, + 772911DA6E33D1CBBC30131B7C8BDBB3 /* Alamofire-dummy.m in Sources */, + 0A39AF55285A3A4F7CBABB6D822FA4A3 /* Alamofire.swift in Sources */, + 3E0749AF6C51BCF0E4A41CF1D6A76FED /* DispatchQueue+Alamofire.swift in Sources */, + AEA829AB1A8AF2AD077A808AED6B178A /* MultipartFormData.swift in Sources */, + 73AB05789A4982944AF68DBD013E3EB7 /* NetworkReachabilityManager.swift in Sources */, + 1D29D2ACADF961F69D32B06FA6A09E28 /* Notifications.swift in Sources */, + 700D3D95AF9520CB227846DFD943A2DA /* ParameterEncoding.swift in Sources */, + 355C18EEC82624A06A6CC93965258E33 /* Request.swift in Sources */, + 059D92B7BBFBEC53E9A3B6E11C5C3B3A /* Response.swift in Sources */, + 6EFD003458AE7F689DEA720A2030C261 /* ResponseSerialization.swift in Sources */, + EB0DD8CEA1A69867A30267439C970440 /* Result.swift in Sources */, + 8D2A6A90A6DDAF75EA52D471258545CC /* ServerTrustPolicy.swift in Sources */, + A1EC41966B261DCE460BCDE5124A1DBE /* SessionDelegate.swift in Sources */, + D3FA0AA634AAEA99AB3FABC36BB4958C /* SessionManager.swift in Sources */, + 77E8F0EB9FFBE2E3EB0C77095C644606 /* TaskDelegate.swift in Sources */, + 60B6C2A003864AAD3A426448152F67BE /* Timeline.swift in Sources */, + AA56769D8733D3F3E7976742D5ABA998 /* Validation.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A5E5629EFB30FCDD2E796C34813D7A0C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8B0792C397B8CF3C3F7A35285B74CA51 /* Pods-AvH Plan-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C0D9E1CF20004CE670295A8938F0FB76 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + D571B248178DC9E8D4593BA1DF8F4AA5 /* Pods-AvH PlanUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + D91C247306A283624F04C27EDC4FF533 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 7F4C28B8411B593BC797F580D97CE33F /* ArrayExt.swift in Sources */, + 0F25A369168AB40262975F8A3D504DB1 /* Attribute.swift in Sources */, + 251610D47D00503E406E9ACF67563B83 /* Attributes.swift in Sources */, + FCB44E745786D701F1EEED3DC51A0DA5 /* BooleanAttribute.swift in Sources */, + FB5FE2DC0824590FE956240D6082A0C4 /* CharacterExt.swift in Sources */, + 1AD7ED6B484EF1F4436E5A2E6E52022F /* CharacterReader.swift in Sources */, + 3E9EB344FDD25FB9A5B104B1F239D07C /* Cleaner.swift in Sources */, + 3266A69674686AF78CC156CA7CED343D /* Collector.swift in Sources */, + 208CE2CDC7B395934E38A25A2DB41770 /* CombiningEvaluator.swift in Sources */, + 56FC20477DD0003E453A216F5604D472 /* Comment.swift in Sources */, + 67BE4056B849FCA6068BCBA5233E802E /* Connection.swift in Sources */, + 22E70E6714BC77F340641D9DA29659E4 /* DataNode.swift in Sources */, + CEF05C7D22572C0C79CFE3BFACEEBE98 /* DataUtil.swift in Sources */, + 103CEB869DD905FF5D5911D97F43EECA /* Document.swift in Sources */, + BE6BEB297BABD159FAFA069F8CCB5664 /* DocumentType.swift in Sources */, + ED978D1098E3AC1329E914E23E5A91EB /* Element.swift in Sources */, + D710B388140E5EA60BB6BB3DAF420488 /* Elements.swift in Sources */, + 43EFA44E613A4D15E05C22DF30CBAD88 /* Entities.swift in Sources */, + FFF7AAE6F95E911282B1EDC15DEBFC49 /* Evaluator.swift in Sources */, + 7F1AC4413B9962E9A9C96FEF61690D8A /* Exception.swift in Sources */, + 2A1904DC73F275715C1EBB2D13FB78F4 /* FormElement.swift in Sources */, + 64717A2C0750385FCF19B7957F95E1D6 /* HtmlTreeBuilder.swift in Sources */, + C86B3245A3635B25274BE8FF7411FF72 /* HtmlTreeBuilderState.swift in Sources */, + E6EB6D85479ED5AE656F9A99F404D0A4 /* HttpStatusException.swift in Sources */, + 59AA0BB8D00F434E5E75611C08739E73 /* Node.swift in Sources */, + 6CFA329909831ED4F353461E66C15F97 /* NodeTraversor.swift in Sources */, + DD117881AA454D7AF74CA99CE44C9A07 /* NodeVisitor.swift in Sources */, + B9BBB29825647956A2AE19F72A2F7570 /* OrderedDictionary.swift in Sources */, + 94704597EBD332197C55E9ACABAACBA0 /* OrderedSet.swift in Sources */, + 363064CB26D7D4019C743BBBD94FD45F /* ParseError.swift in Sources */, + BDA6F31CDD0578D70CC73AFD8DC1CAD4 /* ParseErrorList.swift in Sources */, + 25E20CE8D27125EAB2F0E39961E23288 /* Parser.swift in Sources */, + 1656188594E6BEB972A26DE11E53228C /* ParseSettings.swift in Sources */, + 15F2142B04D3E5002FB854BCCC64486E /* Pattern.swift in Sources */, + 25B0532B6B99C426B23C8E06C3A8CBAE /* QueryParser.swift in Sources */, + 8FD9C13DCFAB3EE3EC6ED1A8C0810499 /* Selector.swift in Sources */, + 57F34AD4C8EFD94C87A59A1CB55B072E /* SerializationException.swift in Sources */, + 5177AD226881FC34E51C71F3B5856839 /* SimpleDictionary.swift in Sources */, + FF60E537FF282E313D93E8DD7C0D826B /* StreamReader.swift in Sources */, + 96808B52A6EC9CAADF816EB99B2FF3C9 /* String.swift in Sources */, + B333703DB413ED2C9FE0D9B198D80D9E /* StringBuilder.swift in Sources */, + 5B716DB5EDCEEA7DC0A18C7CBBC9E441 /* StringUtil.swift in Sources */, + 1223AE2B7078B8DCB7FFEA942ADF426F /* StructuralEvaluator.swift in Sources */, + 5E551A1DC393554614C44A1F97F4559F /* SwiftSoup-dummy.m in Sources */, + 447865DB8B03AF8172EE12B9251A79A8 /* SwiftSoup.swift in Sources */, + 11AB21A7ABD27F1BC0466E5F8884E80A /* Tag.swift in Sources */, + D4FB35AA43AE1101A1617A879D9491B2 /* TextNode.swift in Sources */, + 802A676F51FAC5C7504C72CD990D7CB2 /* Token.swift in Sources */, + E7863974D6375997E91385DDF642C217 /* Tokeniser.swift in Sources */, + 649843E6929F5C762479A786D651BC81 /* TokeniserState.swift in Sources */, + A112207C487E7AE0C5074890F136F8A0 /* TokenQueue.swift in Sources */, + D14856B7F1FD47625CE8B641D1DC11FE /* TreeBuilder.swift in Sources */, + CFC8CCA4FC649E1B2D928C56E2B46F08 /* UnicodeScalar.swift in Sources */, + FBCBE3C40DF0145BA279F99CA966D578 /* Validate.swift in Sources */, + 658738B369633C5B68332B19052DF80B /* Whitelist.swift in Sources */, + 0CAF0664595506AF6BB5C7593231312F /* XmlDeclaration.swift in Sources */, + C8AE8D4D4ADFE8EF3E18E28AFD091D56 /* XmlTreeBuilder.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 1C60BF514C02D008326F475A2AB43EC9 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-AvH Plan"; + target = B07002B7F076BD4E872BCBC38DFC2EBE /* Pods-AvH Plan */; + targetProxy = DB5C79D3AB0D0C0F521F5706607E56E5 /* PBXContainerItemProxy */; + }; + 3C6F078671E93D0441B4B1A123349B62 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Kanna; + target = 1E0B9DFE11A3B2711C371DDBBA9BDAA6 /* Kanna */; + targetProxy = D19D300FC068934E83D1F9CF36E3C2D1 /* PBXContainerItemProxy */; + }; + 741A382F7308747D7DC56054F02BB6EB /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = SwiftSoup; + target = 41AEB266717A3C96C2D1E03D16B79263 /* SwiftSoup */; + targetProxy = 008CF82A0A677D15C24882B430036B0B /* PBXContainerItemProxy */; + }; + AAE8EAF9E258E20B3E6365F805A7C60B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-AvH Plan"; + target = B07002B7F076BD4E872BCBC38DFC2EBE /* Pods-AvH Plan */; + targetProxy = 6C6EE97F11C73A94EEFB5067BE9702F7 /* PBXContainerItemProxy */; + }; + FE49D9427AD7B750A11A2B51BA42D61A /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Alamofire; + target = 3383968E74B5371B20BB519B170DC7FD /* Alamofire */; + targetProxy = BFB065CE5D4C9BB3E9DD12F906BD2239 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 1D480C6E7F72242663C45B14E4730340 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 654AD6A738B5116BAF7E09814F928F71 /* SwiftSoup.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/SwiftSoup/SwiftSoup-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftSoup/SwiftSoup-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SwiftSoup/SwiftSoup.modulemap"; + PRODUCT_MODULE_NAME = SwiftSoup; + PRODUCT_NAME = SwiftSoup; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 296BC9350A8AC299D7D30E66F638276A /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = BC4311D98116FE51975F64E10043D9E6 /* Pods-AvH Plan.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 2B85893F3EC99EB6622F6D7A080FA3EE /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5D0916396C74706FDD75CD7AE35EBF2E /* Pods-AvH PlanUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 31981DC6B069C7F47A6E4E12B7E08513 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C98E0A40FFAA294F06BB6E9D60AC2AC0 /* Pods-AvH PlanTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 411A87FCDCC75B56AE0FF48F3E7D2EB1 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4BF71198830871F9FA2AAB00103CEAAA /* Kanna.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Kanna/Kanna-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Kanna/Kanna-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Kanna/Kanna.modulemap"; + PRODUCT_MODULE_NAME = Kanna; + PRODUCT_NAME = Kanna; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 533220A7363132F85843031FA4F2AAAB /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9FD28D145FEBFD59EA284DA62A934238 /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 6659166854EB79691B22CE07827C37D9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 4BF71198830871F9FA2AAB00103CEAAA /* Kanna.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Kanna/Kanna-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Kanna/Kanna-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Kanna/Kanna.modulemap"; + PRODUCT_MODULE_NAME = Kanna; + PRODUCT_NAME = Kanna; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 81DF3043057D5288CD4E1F6B658EB942 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 5823F184430B87162A942CAD83746EEA /* Pods-AvH Plan.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AvH Plan/Pods-AvH Plan.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 84A06F28E9E7D9EB0A9B476A8668FD60 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 4.2; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + 8DE836AD0CCAB164918935BE1B727AF9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8F24FA5439D5FCDE33E2F8C420EF802D /* Pods-AvH PlanUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 8EFD864C120CEB2731131FA1C6537EC3 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 654AD6A738B5116BAF7E09814F928F71 /* SwiftSoup.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/SwiftSoup/SwiftSoup-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/SwiftSoup/SwiftSoup-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/SwiftSoup/SwiftSoup.modulemap"; + PRODUCT_MODULE_NAME = SwiftSoup; + PRODUCT_NAME = SwiftSoup; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9838C58BD1AA67DBD29475983CB12D4A /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9FD28D145FEBFD59EA284DA62A934238 /* Alamofire.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; + PRODUCT_MODULE_NAME = Alamofire; + PRODUCT_NAME = Alamofire; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 9DEFB36E2F01092D4FF9BC72025BAD4B /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = C48C9769C2A247D71BA1C2218D3CD73E /* Pods-AvH PlanTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D0FE574C7B3479C6425BC136AA57D8C2 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 12.2; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 298C5DBE2FFB2DE540832BA1BD48B738 /* Build configuration list for PBXNativeTarget "Kanna" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 411A87FCDCC75B56AE0FF48F3E7D2EB1 /* Debug */, + 6659166854EB79691B22CE07827C37D9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D0FE574C7B3479C6425BC136AA57D8C2 /* Debug */, + 84A06F28E9E7D9EB0A9B476A8668FD60 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A152575917A1D5DFD790D77FC4A844B5 /* Build configuration list for PBXNativeTarget "Pods-AvH PlanTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31981DC6B069C7F47A6E4E12B7E08513 /* Debug */, + 9DEFB36E2F01092D4FF9BC72025BAD4B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A92C2376420206B771B40894A62D5100 /* Build configuration list for PBXNativeTarget "SwiftSoup" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 1D480C6E7F72242663C45B14E4730340 /* Debug */, + 8EFD864C120CEB2731131FA1C6537EC3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + D83EEEDCFA4D6FF7B9C294AA5CC10EAC /* Build configuration list for PBXNativeTarget "Pods-AvH PlanUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2B85893F3EC99EB6622F6D7A080FA3EE /* Debug */, + 8DE836AD0CCAB164918935BE1B727AF9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E87124444A44B7DB55208E7FEC21D331 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 533220A7363132F85843031FA4F2AAAB /* Debug */, + 9838C58BD1AA67DBD29475983CB12D4A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + ECD6139BCB471427BA440D532EC8B31C /* Build configuration list for PBXNativeTarget "Pods-AvH Plan" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 296BC9350A8AC299D7D30E66F638276A /* Debug */, + 81DF3043057D5288CD4E1F6B658EB942 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Alamofire.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Alamofire.xcscheme new file mode 100644 index 0000000..0f22983 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Alamofire.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Kanna.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Kanna.xcscheme new file mode 100644 index 0000000..d0bccb0 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Kanna.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH Plan.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH Plan.xcscheme new file mode 100644 index 0000000..6996206 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH Plan.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH PlanTests.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH PlanTests.xcscheme new file mode 100644 index 0000000..3808e4d --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH PlanTests.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH PlanUITests.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH PlanUITests.xcscheme new file mode 100644 index 0000000..0b42b04 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/Pods-AvH PlanUITests.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/SwiftSoup.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/SwiftSoup.xcscheme new file mode 100644 index 0000000..d502396 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/SwiftSoup.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..1900c07 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/kduez.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,53 @@ + + + + + SchemeUserState + + Alamofire.xcscheme + + isShown + + orderHint + 0 + + Kanna.xcscheme + + isShown + + orderHint + 1 + + Pods-AvH Plan.xcscheme + + isShown + + orderHint + 2 + + Pods-AvH PlanTests.xcscheme + + isShown + + orderHint + 3 + + Pods-AvH PlanUITests.xcscheme + + isShown + + orderHint + 4 + + SwiftSoup.xcscheme + + isShown + + orderHint + 5 + + + SuppressBuildableAutocreation + + + diff --git a/Pods/SwiftSoup/LICENSE b/Pods/SwiftSoup/LICENSE new file mode 100644 index 0000000..ddeb6c9 --- /dev/null +++ b/Pods/SwiftSoup/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Nabil Chatbi + +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/SwiftSoup/README.md b/Pods/SwiftSoup/README.md new file mode 100644 index 0000000..56a274b --- /dev/null +++ b/Pods/SwiftSoup/README.md @@ -0,0 +1,592 @@ +

+ SwiftSoup +

+ + +![Platform OS X | iOS | tvOS | watchOS | Linux](https://img.shields.io/badge/platform-Linux%20%7C%20OS%20X%20%7C%20iOS%20%7C%20tvOS%20%7C%20watchOS-orange.svg) +[![SPM compatible](https://img.shields.io/badge/SPM-compatible-4BC51D.svg?style=flat)](https://github.com/apple/swift-package-manager) +![🐧 linux: ready](https://img.shields.io/badge/%F0%9F%90%A7%20linux-ready-red.svg) +![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat) +[![Build Status](https://travis-ci.org/scinfu/SwiftSoup.svg?branch=master)](https://travis-ci.org/scinfu/SwiftSoup) +[![Version](https://img.shields.io/cocoapods/v/SwiftSoup.svg?style=flat)](http://cocoapods.org/pods/SwiftSoup) +[![License](https://img.shields.io/cocoapods/l/SwiftSoup.svg?style=flat)](http://cocoapods.org/pods/SwiftSoup) +[![Twitter](https://img.shields.io/badge/twitter-@scinfu-blue.svg?style=flat)](http://twitter.com/scinfu) + +`SwiftSoup` is a pure Swift library, cross-platform (macOS, iOS, tvOS, watchOS and Linux!), for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jQuery-like methods. +`SwiftSoup` implements the WHATWG HTML5 specification, and parses HTML to the same DOM as modern browsers do. +* Scrape and parse HTML from a URL, file, or string +* Find and extract data, using DOM traversal or CSS selectors +* Manipulate the HTML elements, attributes, and text +* Clean user-submitted content against a safe white-list, to prevent XSS attacks +* Output tidy HTML +`SwiftSoup` is designed to deal with all varieties of HTML found in the wild; from pristine and validating, to invalid tag-soup; `SwiftSoup` will create a sensible parse tree. + + +## Installation + +### Cocoapods +SwiftSoup is available through [CocoaPods](http://cocoapods.org). To install +it, simply add the following line to your Podfile: + +```ruby +pod 'SwiftSoup' +``` +### Carthage +SwiftSoup is also available through [Carthage](https://github.com/Carthage/Carthage). To install +it, simply add the following line to your Cartfile: + +```ruby +github "scinfu/SwiftSoup" +``` +### Swift Package Manager +SwiftSoup is also available through [Swift Package Manager](https://github.com/apple/swift-package-manager). +To install it, simply add the dependency to your Package.Swift file: + +```swift +... +dependencies: [ + .package(url: "https://github.com/scinfu/SwiftSoup.git", from: "1.5.10"), +], +targets: [ + .target( name: "YourTarget", dependencies: ["SwiftSoup"]), +] +... +``` + +## Try +### Try out the simple online CSS selectors site: +[SwiftSoup Test Site](https://swiftsoup.herokuapp.com/) + +### Try out the example project opening Terminal and type: +```shell +pod try SwiftSoup +``` +

+ SwiftSoup + SwiftSoup +

+ +# To parse an HTML document: + +```swift +do { + let html = "First parse" + + "

Parsed HTML into a doc.

" + let doc: Document = try SwiftSoup.parse(html) + return try doc.text() +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` + +* Unclosed tags (e.g. `

Lorem

Ipsum` parses to `

Lorem

Ipsum

`) +* Implicit tags (e.g. a naked `Table data` is wrapped into a `
...`) +* Reliably creating the document structure (`html` containing a `head` and `body`, and only appropriate elements within the head) + + +### The object model of a document +* Documents consist of Elements and TextNodes +* The inheritance chain is: `Document` extends `Element` extends `Node.TextNode` extends `Node`. +* An Element contains a list of children Nodes, and has one parent Element. They also have provide a filtered list of child Elements only. + + + + +# Extract attributes, text, and HTML from elements +### Problem +After parsing a document, and finding some elements, you'll want to get at the data inside those elements. +### Solution +- To get the value of an attribute, use the `Node.attr(_ String key)` method +- For the text on an element (and its combined children), use `Element.text()` +- For HTML, use `Element.html()`, or `Node.outerHtml()` as appropriate + +```swift +do { + let html: String = "

An example link.

"; + let doc: Document = try SwiftSoup.parse(html) + let link: Element = try doc.select("a").first()! + + let text: String = try doc.body()!.text(); // "An example link" + let linkHref: String = try link.attr("href"); // "http://example.com/" + let linkText: String = try link.text(); // "example"" + + let linkOuterH: String = try link.outerHtml(); // "example" + let linkInnerH: String = try link.html(); // "example" +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` + +### Description +The methods above are the core of the element data access methods. There are additional others: +- `Element.id()` +- `Element.tagName()` +- `Element.className()` and `Element.hasClass(_ String className)` + +All of these accessor methods have corresponding setter methods to change the data. + + + + + +# Parse a document from a String +### Problem +You have HTML in a Swift String, and you want to parse that HTML to get at its contents, or to make sure it's well formed, or to modify it. The String may have come from user input, a file, or from the web. +### Solution +Use the static `SwiftSoup.parse(_ html: String)` method, or `SwiftSoup.parse(_ html: String, _ baseUri: String)`. + +```swift +do { + let html = "First parse" + + "

Parsed HTML into a doc.

" + let doc: Document = try SwiftSoup.parse(html) + return try doc.text() +} catch Exception.Error(let type, let message) { + print("") +} catch { + print("") +} +``` +### Description +The `parse(_ html: String, _ baseUri: String)` method parses the input HTML into a new `Document`. The base URI argument is used to resolve relative URLs into absolute URLs, and should be set to the URL where the document was fetched from. If that's not applicable, or if you know the HTML has a base element, you can use the `parse(_ html: String)` method. + +As long as you pass in a non-null string, you're guaranteed to have a successful, sensible parse, with a Document containing (at least) a `head` and a `body` element. + +Once you have a `Document`, you can get at the data using the appropriate methods in `Document` and its supers `Element` and `Node`. + + + +# Parsing a body fragment +### Problem +You have a fragment of body HTML (e.g. `div` containing a couple of p tags; as opposed to a full HTML document) that you want to parse. Perhaps it was provided by a user submitting a comment, or editing the body of a page in a CMS. +### Solution +Use the `SwiftSoup.parseBodyFragment(_ html: String)` method. + +```swift +do { + let html: String = "

Lorem ipsum.

" + let doc: Document = try SwiftSoup.parseBodyFragment(html) + let body: Element? = doc.body() +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` + +### Description +The `parseBodyFragment` method creates an empty shell document, and inserts the parsed HTML into the `body` element. If you used the normal `SwiftSoup(_ html: String)` method, you would generally get the same result, but explicitly treating the input as a body fragment ensures that any bozo HTML provided by the user is parsed into the `body` element. + +The `Document.body()` method retrieves the element children of the document's `body` element; it is equivalent to `doc.getElementsByTag("body")`. + +### Stay safe +If you are going to accept HTML input from a user, you need to be careful to avoid cross-site scripting attacks. See the documentation for the `Whitelist` based cleaner, and clean the input with `clean(String bodyHtml, Whitelist whitelist)`. + + + + + +# Sanitize untrusted HTML (to prevent XSS) +### Problem +You want to allow untrusted users to supply HTML for output on your website (e.g. as comment submission). You need to clean this HTML to avoid [cross-site scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) (XSS) attacks. +### Solution +Use the SwiftSoup HTML `Cleaner` with a configuration specified by a `Whitelist`. + +```swift +do { + let unsafe: String = "

Link

" + let safe: String = try SwiftSoup.clean(unsafe, Whitelist.basic())! + // now:

Link

+} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` + +### Discussion +A cross-site scripting attack against your site can really ruin your day, not to mention your users'. Many sites avoid XSS attacks by not allowing HTML in user submitted content: they enforce plain text only, or use an alternative markup syntax like wiki-text or Markdown. These are seldom optimal solutions for the user, as they lower expressiveness, and force the user to learn a new syntax. + +A better solution may be to use a rich text WYSIWYG editor (like [CKEditor](http://ckeditor.com) or [TinyMCE](https://www.tinymce.com)). These output HTML, and allow the user to work visually. However, their validation is done on the client side: you need to apply a server-side validation to clean up the input and ensure the HTML is safe to place on your site. Otherwise, an attacker can avoid the client-side Javascript validation and inject unsafe HMTL directly into your site + +The SwiftSoup whitelist sanitizer works by parsing the input HTML (in a safe, sand-boxed environment), and then iterating through the parse tree and only allowing known-safe tags and attributes (and values) through into the cleaned output. + +It does not use regular expressions, which are inappropriate for this task. + +SwiftSoup provides a range of `Whitelist` configurations to suit most requirements; they can be modified if necessary, but take care. + +The cleaner is useful not only for avoiding XSS, but also in limiting the range of elements the user can provide: you may be OK with textual `a`, `strong` elements, but not structural `div` or `table` elements. + +### See also +- See the [XSS cheat sheet](http://ha.ckers.org/xss.html) and filter evasion guide, as an example of how regular-expression filters don't work, and why a safe whitelist parser-based sanitizer is the correct approach. +- See the `Cleaner` reference if you want to get a `Document` instead of a String return +- See the `Whitelist` reference for the different canned options, and to create a custom whitelist +- The [nofollow](https://en.wikipedia.org/wiki/Nofollow) link attribute + + + + +# Set attribute values +### Problem +You have a parsed document that you would like to update attribute values on, before saving it out to disk, or sending it on as a HTTP response. + +### Solution +Use the attribute setter methods `Element.attr(_ key: String, _ value: String)`, and `Elements.attr(_ key: String, _ value: String)`. + +If you need to modify the class attribute of an element, use the `Element.addClass(_ className: String)` and `Element.removeClass(_ className: String)` methods. + +The `Elements` collection has bulk attribute and class methods. For example, to add a `rel="nofollow"` attribute to every `a` element inside a div: + +```swift +do { + try doc.select("div.comments a").attr("rel", "nofollow") +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` +### Description +Like the other methods in `Element`, the attr methods return the current `Element` (or `Elements` when working on a collection from a select). This allows convenient method chaining: + +```swift +do { + try doc.select("div.masthead").attr("title", "swiftsoup").addClass("round-box"); +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` + + +# Set the HTML of an element +### Problem +You need to modify the HTML of an element. +### Solution +Use the HTML setter methods in `Element`: +```swift +do { + let doc: Document = try SwiftSoup.parse("
One
One") + let div: Element = try doc.select("div").first()! //
+ try div.html("

lorem ipsum

") //

lorem ipsum

+ try div.prepend("

First

") + try div.append("

Last

") + print(div) + // now div is:

First

lorem ipsum

Last

+ + let span: Element = try doc.select("span").first()! // One + try span.wrap("
  • ") + print(doc) + // now:
  • One
  • +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` +### Discussion +- `Element.html(_ html: String)` clears any existing inner HTML in an element, and replaces it with parsed HTML. +- `Element.prepend(_ first: String)` and `Element.append(_ last: String)` add HTML to the start or end of an element's inner HTML, respectively +- `Element.wrap(_ around: String)` wraps HTML around the outer HTML of an element. + +### See also +You can also use the `Element.prependElement(_ tag: String)` and `Element.appendElement(_ tag: String)` methods to create new elements and insert them into the document flow as a child element. + + + + + +# Setting the text content of elements +### Problem +You need to modify the text content of an HTML document. +# Solution +Use the text setter methods of `Element`: + +```swift +do { + let doc: Document = try SwiftSoup.parse("") + let div: Element = try doc.select("div").first()! //
    + try div.text("five > four") //
    five > four
    + try div.prepend("First ") + try div.append(" Last") + // now:
    First five > four Last
    +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` + +### Discussion +The text setter methods mirror the [[HTML setter|Set the HTML of an element]] methods: +- `Element.text(_ text: String)` clears any existing inner HTML in an element, and replaces it with the supplied text. +- `Element.prepend(_ first: String)` and `Element.append(_ last: String)` add text nodes to the start or end of an element's inner HTML, respectively +The text should be supplied unencoded: characters like `<`, `>` etc will be treated as literals, not HTML. + + + + + +# Use DOM methods to navigate a document +### Problem +You have a HTML document that you want to extract data from. You know generally the structure of the HTML document. + +### Solution +Use the DOM-like methods available after parsing HTML into a `Document`. + +```swift +do { + let html: String = "One Two" + let els: Elements = try SwiftSoup.parse(html).select("a") + for link: Element in els.array() { + let linkHref: String = try link.attr("href") + let linkText: String = try link.text() + } +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` +### Description +Elements provide a range of DOM-like methods to find elements, and extract and manipulate their data. The DOM getters are contextual: called on a parent Document they find matching elements under the document; called on a child element they find elements under that child. In this way you can window in on the data you want. +### Finding elements +* `getElementById(_ id: String)` +* `getElementsByTag(_ tag:String)` +* `getElementsByClass(_ className: String)` +* `getElementsByAttribute(_ key: String)` (and related methods) +* Element siblings: `siblingElements()`, `firstElementSibling()`, `lastElementSibling()`, `nextElementSibling()`, `previousElementSibling()` +* Graph: `parent()`, `children()`, `child(_ index: Int)` + +# Element data +* `attr(_ key: Strin)` to get and `attr(_ key: String, _ value: String)` to set attributes +* `attributes()` to get all attributes +* `id()`, `className()` and `classNames()` +* `text()` to get and `text(_ value: String)` to set the text content +* `html()` to get and `html(_ value: String)` to set the inner HTML content +* `outerHtml()` to get the outer HTML value +* `data()` to get data content (e.g. of script and style tags) +* `tag()` and `tagName()` + +### Manipulating HTML and text +* `append(_ html: String)`, `prepend(html: String)` +* `appendText(text: String)`, `prependText(text: String)` +* `appendElement(tagName: String)`, `prependElement(tagName: String)` +* `html(_ value: String)` + + + + + + + + + + + + +# Use selector syntax to find elements +### Problem +You want to find or manipulate elements using a CSS or jQuery-like selector syntax. +### Solution +Use the `Element.select(_ selector: String)` and `Elements.select(_ selector: String)` methods: + +```swift +do { + let doc: Document = try SwiftSoup.parse("...") + let links: Elements = try doc.select("a[href]") // a with href + let pngs: Elements = try doc.select("img[src$=.png]") + // img with src ending .png + let masthead: Element? = try doc.select("div.masthead").first() + // div with class=masthead + let resultLinks: Elements? = try doc.select("h3.r > a") // direct a after h3 +} catch Exception.Error(let type, let message) { + print(message) +} catch { + print("error") +} +``` +### Description +SwiftSoup elements support a [CSS](https://www.w3.org/TR/2009/PR-css3-selectors-20091215/) (or [jQuery](http://jquery.com)) like selector syntax to find matching elements, that allows very powerful and robust queries. + +The `select` method is available in a `Document`, `Element`, or in `Elements`. It is contextual, so you can filter by selecting from a specific element, or by chaining select calls. + +Select returns a list of `Elements` (as `Elements`), which provides a range of methods to extract and manipulate the results. +### Selector overview +* `tagname`: find elements by tag, e.g. `a` +* `ns|tag`: find elements by tag in a namespace, e.g. `fb|name` finds `` elements +* `#id`: find elements by ID, e.g. `#logo` +* `.class`: find elements by class name, e.g. `.masthead` +* `[attribute]`: elements with attribute, e.g. `[href]` +* `[^attr]`: elements with an attribute name prefix, e.g. `[^data-]` finds elements with HTML5 dataset attributes +* `[attr=value]`: elements with attribute value, e.g. `[width=500]` (also quotable, like `[data-name='launch sequence']`) +* `[attr^=value]`, `[attr$=value]`, `[attr*=value]`: elements with attributes that start with, end with, or contain the value, e.g. `[href*=/path/]` +* `[attr~=regex]`: elements with attribute values that match the regular expression; e.g. `img[src~=(?i)\.(png|jpe?g)]` +* `*`: all elements, e.g. `*` +### Selector combinations +* `el#id`: elements with ID, e.g. `div#logo` +* `el.class`: elements with class, e.g. `div.masthead` +* `el[attr]`: elements with attribute, e.g. `a[href]` +* Any combination, e.g. `a[href].highlight` +* Ancestor `child`: child elements that descend from ancestor, e.g. `.body p` finds `p` elements anywhere under a block with class "body" +* `parent > child`: child elements that descend directly from parent, e.g. `div.content > p` finds p elements; and `body > *` finds the direct children of the body tag +* `siblingA + siblingB`: finds sibling B element immediately preceded by sibling A, e.g. `div.head + div` +* `siblingA ~ siblingX`: finds sibling X element preceded by sibling A, e.g. `h1 ~ p` +* `el`, `el`, `el`: group multiple selectors, find unique elements that match any of the selectors; e.g. `div.masthead`, `div.logo` + +### Pseudo selectors +* `:lt(n)`: find elements whose sibling index (i.e. its position in the DOM tree relative to its parent) is less than n; e.g. `td:lt(3)` +* `:gt(n)`: find elements whose sibling index is greater than n; e.g. `div p:gt(2)` +* `:eq(n)`: find elements whose sibling index is equal to n; e.g. `form input:eq(1)` +* `:has(seletor)`: find elements that contain elements matching the selector; e.g. `div:has(p)` +* `:not(selector)`: find elements that do not match the selector; e.g. `div:not(.logo)` +* `:contains(text)`: find elements that contain the given text. The search is case-insensitive; e.g. `p:contains(swiftsoup)` +* `:containsOwn(text)`: find elements that directly contain the given text +* `:matches(regex)`: find elements whose text matches the specified regular expression; e.g. `div:matches((?i)login)` +* `:matchesOwn(regex)`: find elements whose own text matches the specified regular expression +* Note that the above indexed pseudo-selectors are 0-based, that is, the first element is at index 0, the second at 1, etc + +# Examples +## To parse an HTML document from String: + +```swift +let html = "First parse

    Parsed HTML into a doc.

    " +guard let doc: Document = try? SwiftSoup.parse(html) else { return } +``` + +## Get all text nodes: + +```swift +guard let elements = try? doc.getAllElements() else { return html } +for element in elements { + for textNode in element.textNodes() { + [...] + } +} +``` + +## Set CSS using SwiftSoup: + +```swift +try doc.head()?.append("") +``` + +## Get HTML value +```swift +let html = "
    " + + "
    " + + "
    " + + "
    " + + "" + + "" + + "" + + "
    " + + "" + + "" + + "" + + "" + + "
    " + + "
    " + + "
    " + + "
    " +guard let doc: Document = try? SwiftSoup.parse(html) else { return } // parse html +let elements = try doc.select("[name=transaction_id]") // query +let transaction_id = try elements.get(0) // select first element +let value = try transaction_id.val() // get value +print(value) // 4245 +``` +## How to remove all the html from a string + +```swift +guard let doc: Document = try? SwiftSoup.parse(html) else { return } // parse html +guard let txt = try? doc.text() else { return } +print(txt) +``` + +## How to get and update XML values + +```swift +let xml = "One" +guard let doc = try? SwiftSoup.parse(xml, "", Parser.xmlParser()) else { return } +guard let element = try? doc.getElementsByTag("val").first() // Find first element +element.text("NewValue") // Edit Value +let valueString = element.text() // "NewValue" +``` + +## How to get all `` + +```swift +do { + let doc: Document = try SwiftSoup.parse(html) + let srcs: Elements = try doc.select("img[src]") + let srcsStringArray: [String?] = srcs.array().map { try? $0.attr("src").description } + // do something with srcsStringArray +} catch Exception.Error(_, let message) { + print(message) +} catch { + print("error") +} +``` + +## Get all `href` of `` + +```swift +let html = "One Two" +guard let els: Elements = try? SwiftSoup.parse(html).select("a") else { return } +for element: Element in els.array() { + print(try? element.attr("href")) +} +``` +Output: +``` +"?foo=bar&mid<=true" +"?foo=bar Å å π 新 there ¾ © »" + + +"Hello &<> Å å π 新 there ¾ © »" +"Hello &<> Å å π 新 there ¾ © »" +"Hello &<> Å å π 新 there ¾ © »" +"Hello &<> Å å π 新 there ¾ © »" +"Hello &<> Å å π 新 there ¾ © »" + +``` + + + +## Author + +Nabil Chatbi, scinfu@gmail.com + +## Note +SwiftSoup was ported to Swift from Java [Jsoup](https://jsoup.org/) library. + +## License + +SwiftSoup is available under the MIT license. See the LICENSE file for more info. diff --git a/Pods/SwiftSoup/Sources/ArrayExt.swift b/Pods/SwiftSoup/Sources/ArrayExt.swift new file mode 100644 index 0000000..a3b329f --- /dev/null +++ b/Pods/SwiftSoup/Sources/ArrayExt.swift @@ -0,0 +1,21 @@ +// +// ArrayExt.swift +// SwifSoup +// +// Created by Nabil Chatbi on 05/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +extension Array where Element : Equatable { + func lastIndexOf(_ e: Element) -> Int { + for pos in (0.. String { + return key + } + + /** + Set the attribute key; case is preserved. + @param key the new key; must not be null + */ + open func setKey(key: String) throws { + try Validate.notEmpty(string: key) + self.key = key.trim() + } + + /** + Get the attribute value. + @return the attribute value + */ + open func getValue() -> String { + return value + } + + /** + Set the attribute value. + @param value the new attribute value; must not be null + */ + @discardableResult + open func setValue(value: String) -> String { + let old = self.value + self.value = value + return old + } + + /** + Get the HTML representation of this attribute; e.g. {@code href="index.html"}. + @return HTML + */ + public func html() -> String { + let accum = StringBuilder() + html(accum: accum, out: (Document("")).outputSettings()) + return accum.toString() + } + + public func html(accum: StringBuilder, out: OutputSettings ) { + accum.append(key) + if (!shouldCollapseAttribute(out: out)) { + accum.append("=\"") + Entities.escape(accum, value, out, true, false, false) + accum.append("\"") + } + } + + /** + Get the string representation of this attribute, implemented as {@link #html()}. + @return string + */ + open func toString() -> String { + return html() + } + + /** + * Create a new Attribute from an unencoded key and a HTML attribute encoded value. + * @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars. + * @param encodedValue HTML attribute encoded value + * @return attribute + */ + public static func createFromEncoded(unencodedKey: String, encodedValue: String) throws ->Attribute { + let value = try Entities.unescape(string: encodedValue, strict: true) + return try Attribute(key: unencodedKey, value: value) + } + + public func isDataAttribute() -> Bool { + return key.startsWith(Attributes.dataPrefix) && key.count > Attributes.dataPrefix.count + } + + /** + * Collapsible if it's a boolean attribute and value is empty or same as name + * + * @param out Outputsettings + * @return Returns whether collapsible or not + */ + public final func shouldCollapseAttribute(out: OutputSettings) -> Bool { + return ("" == value || value.equalsIgnoreCase(string: key)) + && out.syntax() == OutputSettings.Syntax.html + && isBooleanAttribute() + } + + public func isBooleanAttribute() -> Bool { + return Attribute.booleanAttributes.contains(key) + } + + public func hashCode() -> Int { + var result = key.hashValue + result = 31 * result + value.hashValue + return result + } + + public func clone() -> Attribute { + do { + return try Attribute(key: key, value: value) + } catch Exception.Error( _, let msg) { + print(msg) + } catch { + + } + return try! Attribute(key: "", value: "") + } +} + +extension Attribute: Equatable { + static public func == (lhs: Attribute, rhs: Attribute) -> Bool { + return lhs.value == rhs.value && lhs.key == rhs.key + } + +} diff --git a/Pods/SwiftSoup/Sources/Attributes.swift b/Pods/SwiftSoup/Sources/Attributes.swift new file mode 100644 index 0000000..46c6098 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Attributes.swift @@ -0,0 +1,264 @@ +// +// Attributes.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * The attributes of an Element. + *

    + * Attributes are treated as a map: there can be only one value associated with an attribute key/name. + *

    + *

    + * Attribute name and value comparisons are case sensitive. By default for HTML, attribute names are + * normalized to lower-case on parsing. That means you should use lower-case strings when referring to attributes by + * name. + *

    + * + * + */ +open class Attributes: NSCopying { + + public static var dataPrefix: String = "data-" + + var attributes: OrderedDictionary = OrderedDictionary() + // linked hash map to preserve insertion order. + // null be default as so many elements have no attributes -- saves a good chunk of memory + + public init() {} + + /** + Get an attribute value by key. + @param key the (case-sensitive) attribute key + @return the attribute value if set; or empty string if not set. + @see #hasKey(String) + */ + open func get(key: String) -> String { + let attr: Attribute? = attributes.get(key: key) + return attr != nil ? attr!.getValue() : "" + } + + /** + * Get an attribute's value by case-insensitive key + * @param key the attribute name + * @return the first matching attribute value if set; or empty string if not set. + */ + open func getIgnoreCase(key: String )throws -> String { + try Validate.notEmpty(string: key) + + for attrKey in (attributes.keySet()) { + if attrKey.equalsIgnoreCase(string: key) { + return attributes.get(key: attrKey)!.getValue() + } + } + return "" + } + + /** + Set a new attribute, or replace an existing one by key. + @param key attribute key + @param value attribute value + */ + open func put(_ key: String, _ value: String) throws { + let attr = try Attribute(key: key, value: value) + put(attribute: attr) + } + + /** + Set a new boolean attribute, remove attribute if value is false. + @param key attribute key + @param value attribute value + */ + open func put(_ key: String, _ value: Bool) throws { + if (value) { + try put(attribute: BooleanAttribute(key: key)) + } else { + try remove(key: key) + } + } + + /** + Set a new attribute, or replace an existing one by key. + @param attribute attribute + */ + open func put(attribute: Attribute) { + attributes.put(value: attribute, forKey: attribute.getKey()) + } + + /** + Remove an attribute by key. Case sensitive. + @param key attribute key to remove + */ + open func remove(key: String)throws { + try Validate.notEmpty(string: key) + attributes.remove(key: key) + } + + /** + Remove an attribute by key. Case insensitive. + @param key attribute key to remove + */ + open func removeIgnoreCase(key: String ) throws { + try Validate.notEmpty(string: key) + for attrKey in attributes.keySet() { + if (attrKey.equalsIgnoreCase(string: key)) { + attributes.remove(key: attrKey) + } + } + } + + /** + Tests if these attributes contain an attribute with this key. + @param key case-sensitive key to check for + @return true if key exists, false otherwise + */ + open func hasKey(key: String) -> Bool { + return attributes.containsKey(key: key) + } + + /** + Tests if these attributes contain an attribute with this key. + @param key key to check for + @return true if key exists, false otherwise + */ + open func hasKeyIgnoreCase(key: String) -> Bool { + for attrKey in attributes.keySet() { + if (attrKey.equalsIgnoreCase(string: key)) { + return true + } + } + return false + } + + /** + Get the number of attributes in this set. + @return size + */ + open func size() -> Int { + return attributes.count//TODO: check retyrn right size + } + + /** + Add all the attributes from the incoming set to this set. + @param incoming attributes to add to these attributes. + */ + open func addAll(incoming: Attributes?) { + guard let incoming = incoming else { + return + } + + if (incoming.size() == 0) { + return + } + attributes.putAll(all: incoming.attributes) + } + +// open func iterator() -> IndexingIterator> { +// if (attributes.isEmpty) { +// let args: [Attribute] = [] +// return args.makeIterator() +// } +// return attributes.orderedValues.makeIterator() +// } + + /** + Get the attributes as a List, for iteration. Do not modify the keys of the attributes via this view, as changes + to keys will not be recognised in the containing set. + @return an view of the attributes as a List. + */ + open func asList() -> Array { + var list: Array = Array(/*attributes.size()*/) + for entry in attributes.orderedValues { + list.append(entry) + } + return list + } + + /** + * Retrieves a filtered view of attributes that are HTML5 custom data attributes; that is, attributes with keys + * starting with {@code data-}. + * @return map of custom data attributes. + */ + //Map + open func dataset() -> Dictionary { + var dataset = Dictionary() + for attribute in attributes { + let attr = attribute.1 + if(attr.isDataAttribute()) { + let key = attr.getKey().substring(Attributes.dataPrefix.count) + dataset[key] = attribute.1.getValue() + } + } + return dataset + } + + /** + Get the HTML representation of these attributes. + @return HTML + @throws SerializationException if the HTML representation of the attributes cannot be constructed. + */ + open func html()throws -> String { + let accum = StringBuilder() + try html(accum: accum, out: Document("").outputSettings()) // output settings a bit funky, but this html() seldom used + return accum.toString() + } + + public func html(accum: StringBuilder, out: OutputSettings ) throws { + for attribute in attributes.orderedValues { + accum.append(" ") + attribute.html(accum: accum, out: out) + } + } + + open func toString()throws -> String { + return try html() + } + + /** + * Checks if these attributes are equal to another set of attributes, by comparing the two sets + * @param o attributes to compare with + * @return if both sets of attributes have the same content + */ + open func equals(o: AnyObject?) -> Bool { + if(o == nil) {return false} + if (self === o.self) {return true} + guard let that: Attributes = o as? Attributes else {return false} + return (attributes == that.attributes) + } + + /** + * Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes. + * @return calculated hashcode + */ + open func hashCode() -> Int { + return attributes.hashCode() + } + + public func copy(with zone: NSZone? = nil) -> Any { + let clone = Attributes() + clone.attributes = attributes.clone() + return clone + } + + open func clone() -> Attributes { + return self.copy() as! Attributes + } + + fileprivate static func dataKey(key: String) -> String { + return dataPrefix + key + } + +} + +extension Attributes: Sequence { + public func makeIterator() -> AnyIterator { + var list = attributes.orderedValues + return AnyIterator { + return list.count > 0 ? list.removeFirst() : nil + } + } +} diff --git a/Pods/SwiftSoup/Sources/BooleanAttribute.swift b/Pods/SwiftSoup/Sources/BooleanAttribute.swift new file mode 100644 index 0000000..793490d --- /dev/null +++ b/Pods/SwiftSoup/Sources/BooleanAttribute.swift @@ -0,0 +1,26 @@ +// +// BooleanAttribute.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * A boolean attribute that is written out without any value. + */ +open class BooleanAttribute: Attribute { + /** + * Create a new boolean attribute from unencoded (raw) key. + * @param key attribute key + */ + init(key: String) throws { + try super.init(key: key, value: "") + } + + override public func isBooleanAttribute() -> Bool { + return true + } +} diff --git a/Pods/SwiftSoup/Sources/CharacterExt.swift b/Pods/SwiftSoup/Sources/CharacterExt.swift new file mode 100644 index 0000000..2cab2b5 --- /dev/null +++ b/Pods/SwiftSoup/Sources/CharacterExt.swift @@ -0,0 +1,81 @@ +// +// CharacterExt.swift +// SwifSoup +// +// Created by Nabil Chatbi on 08/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +extension Character { + + public static let space: Character = " " + public static let BackslashT: Character = "\t" + public static let BackslashN: Character = "\n" + public static let BackslashF: Character = Character(UnicodeScalar(12)) + public static let BackslashR: Character = "\r" + public static let BackshashRBackslashN: Character = "\r\n" + + //http://www.unicode.org/glossary/#supplementary_code_point + public static let MIN_SUPPLEMENTARY_CODE_POINT: UInt32 = 0x010000 + + /// True for any space character, and the control characters \t, \n, \r, \f, \v. + + var isWhitespace: Bool { + switch self { + case Character.space, Character.BackslashT, Character.BackslashN, Character.BackslashF, Character.BackslashR: return true + case Character.BackshashRBackslashN: return true + default: return false + + } + } + + /// `true` if `self` normalized contains a single code unit that is in the category of Decimal Numbers. + var isDigit: Bool { + + return isMemberOfCharacterSet(CharacterSet.decimalDigits) + + } + + /// Lowercase `self`. + var lowercase: Character { + + let str = String(self).lowercased() + return str[str.startIndex] + + } + + /// Return `true` if `self` normalized contains a single code unit that is a member of the supplied character set. + /// + /// - parameter set: The `NSCharacterSet` used to test for membership. + /// - returns: `true` if `self` normalized contains a single code unit that is a member of the supplied character set. + func isMemberOfCharacterSet(_ set: CharacterSet) -> Bool { + + let normalized = String(self).precomposedStringWithCanonicalMapping + let unicodes = normalized.unicodeScalars + + guard unicodes.count == 1 else { return false } + return set.contains(UnicodeScalar(unicodes.first!.value)!) + + } + + static func convertFromIntegerLiteral(value: IntegerLiteralType) -> Character { + return Character(UnicodeScalar(value)!) + } + + static func isLetter(_ char: Character) -> Bool { + return char.isLetter() + } + func isLetter() -> Bool { + return self.isMemberOfCharacterSet(CharacterSet.letters) + } + + static func isLetterOrDigit(_ char: Character) -> Bool { + return char.isLetterOrDigit() + } + func isLetterOrDigit() -> Bool { + if(self.isLetter()) {return true} + return self.isDigit + } +} diff --git a/Pods/SwiftSoup/Sources/CharacterReader.swift b/Pods/SwiftSoup/Sources/CharacterReader.swift new file mode 100644 index 0000000..ff81a80 --- /dev/null +++ b/Pods/SwiftSoup/Sources/CharacterReader.swift @@ -0,0 +1,463 @@ +// +// CharacterReader.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 10/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + CharacterReader consumes tokens off a string. To replace the old TokenQueue. + */ +public final class CharacterReader { + private static let empty = "" + public static let EOF: UnicodeScalar = "\u{FFFF}"//65535 + private let input: [UnicodeScalar] + private let length: Int + private var pos: Int = 0 + private var mark: Int = 0 + //private let stringCache: Array // holds reused strings in this doc, to lessen garbage + + public init(_ input: String) { + self.input = Array(input.unicodeScalars) + self.length = self.input.count + //stringCache = Array(repeating:nil, count:512) + } + + public func getPos() -> Int { + return self.pos + } + + public func isEmpty() -> Bool { + return pos >= length + } + + public func current() -> UnicodeScalar { + return (pos >= length) ? CharacterReader.EOF : input[pos] + } + + @discardableResult + public func consume() -> UnicodeScalar { + let val = (pos >= length) ? CharacterReader.EOF : input[pos] + pos += 1 + return val + } + + public func unconsume() { + pos -= 1 + } + + public func advance() { + pos += 1 + } + + public func markPos() { + mark = pos + } + + public func rewindToMark() { + pos = mark + } + + public func consumeAsString() -> String { + let p = pos + pos+=1 + return String(input[p]) + //return String(input, pos+=1, 1) + } + + /** + * Returns the number of characters between the current position and the next instance of the input char + * @param c scan target + * @return offset between current position and next instance of target. -1 if not found. + */ + public func nextIndexOf(_ c: UnicodeScalar) -> Int { + // doesn't handle scanning for surrogates + for i in pos.. Int { + // doesn't handle scanning for surrogates + if(seq.isEmpty) {return -1} + let startChar: UnicodeScalar = seq.unicodeScalar(0) + for var offset in pos.. String { + let offset = nextIndexOf(c) + if (offset != -1) { + let consumed = cacheString(pos, offset) + pos += offset + return consumed + } else { + return consumeToEnd() + } + } + + public func consumeTo(_ seq: String) -> String { + let offset = nextIndexOf(seq) + if (offset != -1) { + let consumed = cacheString(pos, offset) + pos += offset + return consumed + } else { + return consumeToEnd() + } + } + + public func consumeToAny(_ chars: UnicodeScalar...) -> String { + return consumeToAny(chars) + } + public func consumeToAny(_ chars: [UnicodeScalar]) -> String { + let start: Int = pos + let remaining: Int = length + let val = input + OUTER: while (pos < remaining) { + if chars.contains(val[pos]) { + break OUTER + } +// for c in chars { +// if (val[pos] == c){ +// break OUTER +// } +// } + pos += 1 + } + + return pos > start ? cacheString(start, pos-start) : CharacterReader.empty + } + + public func consumeToAnySorted(_ chars: UnicodeScalar...) -> String { + return consumeToAnySorted(chars) + } + public func consumeToAnySorted(_ chars: [UnicodeScalar]) -> String { + let start = pos + let remaining = length + let val = input + + while (pos < remaining) { + + if chars.contains(val[pos]) { + break + } + pos += 1 + } + + return pos > start ? cacheString(start, pos-start) : CharacterReader.empty + } + + public func consumeData() -> String { + // &, <, null + let start = pos + let remaining = length + let val = input + + while (pos < remaining) { + let c: UnicodeScalar = val[pos] + if (c == UnicodeScalar.Ampersand || c == UnicodeScalar.LessThan || c == TokeniserStateVars.nullScalr) { + break + } + pos += 1 + } + + return pos > start ? cacheString(start, pos-start) : CharacterReader.empty + } + + public func consumeTagName() -> String { + // '\t', '\n', '\r', '\f', ' ', '/', '>', nullChar + let start = pos + let remaining = length + let val = input + + while (pos < remaining) { + let c: UnicodeScalar = val[pos] + if (c == UnicodeScalar.BackslashT || c == UnicodeScalar.BackslashN || c == UnicodeScalar.BackslashR || c == UnicodeScalar.BackslashF || c == UnicodeScalar.Space || c == UnicodeScalar.Slash || c == UnicodeScalar.GreaterThan || c == TokeniserStateVars.nullScalr) { + break + } + pos += 1 + } + return pos > start ? cacheString(start, pos-start) : CharacterReader.empty + } + + public func consumeToEnd() -> String { + let data = cacheString(pos, length-pos) + pos = length + return data + } + + public func consumeLetterSequence() -> String { + let start = pos + while (pos < length) { + let c: UnicodeScalar = input[pos] + if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) { + pos += 1 + } else { + break + } + } + return cacheString(start, pos - start) + } + + public func consumeLetterThenDigitSequence() -> String { + let start = pos + while (pos < length) { + let c = input[pos] + if ((c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters)) { + pos += 1 + } else { + break + } + } + while (!isEmpty()) { + let c = input[pos] + if (c >= "0" && c <= "9") { + pos += 1 + } else { + break + } + } + + return cacheString(start, pos - start) + } + + public func consumeHexSequence() -> String { + let start = pos + while (pos < length) { + let c = input[pos] + if ((c >= "0" && c <= "9") || (c >= "A" && c <= "F") || (c >= "a" && c <= "f")) { + pos+=1 + } else { + break + } + } + return cacheString(start, pos - start) + } + + public func consumeDigitSequence() -> String { + let start = pos + while (pos < length) { + let c = input[pos] + if (c >= "0" && c <= "9") { + pos+=1 + } else { + break + } + } + return cacheString(start, pos - start) + } + + public func matches(_ c: UnicodeScalar) -> Bool { + return !isEmpty() && input[pos] == c + + } + + public func matches(_ seq: String) -> Bool { + let scanLength = seq.unicodeScalars.count + if (scanLength > length - pos) { + return false + } + + for offset in 0.. Bool { + + let scanLength = seq.unicodeScalars.count + if(scanLength == 0) { + return false + } + if (scanLength > length - pos) { + return false + } + + for offset in 0.. Bool { + if (isEmpty()) { + return false + } + + let c: UnicodeScalar = input[pos] + for seek in seq { + if (seek == c) { + return true + } + } + return false + } + + public func matchesAnySorted(_ seq: [UnicodeScalar]) -> Bool { + return !isEmpty() && seq.contains(input[pos]) + } + + public func matchesLetter() -> Bool { + if (isEmpty()) { + return false + } + let c = input[pos] + return (c >= "A" && c <= "Z") || (c >= "a" && c <= "z") || c.isMemberOfCharacterSet(CharacterSet.letters) + } + + public func matchesDigit() -> Bool { + if (isEmpty()) { + return false + } + let c = input[pos] + return (c >= "0" && c <= "9") + } + + @discardableResult + public func matchConsume(_ seq: String) -> Bool { + if (matches(seq)) { + pos += seq.unicodeScalars.count + return true + } else { + return false + } + } + + @discardableResult + public func matchConsumeIgnoreCase(_ seq: String) -> Bool { + if (matchesIgnoreCase(seq)) { + pos += seq.unicodeScalars.count + return true + } else { + return false + } + } + + public func containsIgnoreCase(_ seq: String ) -> Bool { + // used to check presence of , . only finds consistent case. + let loScan = seq.lowercased(with: Locale(identifier: "en")) + let hiScan = seq.uppercased(with: Locale(identifier: "eng")) + return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1) + } + + public func toString() -> String { + return String(input[pos.. + * Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list. + * That saves both having to create objects as hash keys, and running through the entry list, at the expense of + * some more duplicates. + */ + private func cacheString(_ start: Int, _ count: Int) -> String { + return String(input[start.. CharacterReader.maxCacheLen) { +// return String(val[start.. Bool { +// if (count == cached.unicodeScalars.count) { +// var count = count +// let one = input +// var i = start +// var j = 0 +// while (count != 0) { +// count -= 1 +// if (one[i] != cached.unicodeScalar(j) ) { +// return false +// } +// j += 1 +// i += 1 +// } +// return true +// } +// return false +// } +} + +extension CharacterReader: CustomDebugStringConvertible { + public var debugDescription: String { + return self.toString() + } +} diff --git a/Pods/SwiftSoup/Sources/Cleaner.swift b/Pods/SwiftSoup/Sources/Cleaner.swift new file mode 100644 index 0000000..6c16c76 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Cleaner.swift @@ -0,0 +1,150 @@ +// +// Cleaner.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 15/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +open class Cleaner { + fileprivate let whitelist: Whitelist + + /** + Create a new cleaner, that sanitizes documents using the supplied whitelist. + @param whitelist white-list to clean with + */ + public init(_ whitelist: Whitelist) { + self.whitelist = whitelist + } + + /** + Creates a new, clean document, from the original dirty document, containing only elements allowed by the whitelist. + The original document is not modified. Only elements from the dirt document's body are used. + @param dirtyDocument Untrusted base document to clean. + @return cleaned document. + */ + public func clean(_ dirtyDocument: Document)throws->Document { + //Validate.notNull(dirtyDocument) + let clean: Document = Document.createShell(dirtyDocument.getBaseUri()) + if (dirtyDocument.body() != nil && clean.body() != nil) // frameset documents won't have a body. the clean doc will have empty body. + { + try copySafeNodes(dirtyDocument.body()!, clean.body()!) + } + return clean + } + + /** + Determines if the input document is valid, against the whitelist. It is considered valid if all the tags and attributes + in the input HTML are allowed by the whitelist. +

    + This method can be used as a validator for user input forms. An invalid document will still be cleaned successfully + using the {@link #clean(Document)} document. If using as a validator, it is recommended to still clean the document + to ensure enforced attributes are set correctly, and that the output is tidied. +

    + @param dirtyDocument document to test + @return true if no tags or attributes need to be removed; false if they do + */ + public func isValid(_ dirtyDocument: Document)throws->Bool { + //Validate.notNull(dirtyDocument) + let clean: Document = Document.createShell(dirtyDocument.getBaseUri()) + let numDiscarded: Int = try copySafeNodes(dirtyDocument.body()!, clean.body()!) + return numDiscarded == 0 + } + + @discardableResult + fileprivate func copySafeNodes(_ source: Element, _ dest: Element)throws->Int { + let cleaningVisitor: Cleaner.CleaningVisitor = Cleaner.CleaningVisitor(source, dest, self) + let traversor: NodeTraversor = NodeTraversor(cleaningVisitor) + try traversor.traverse(source) + return cleaningVisitor.numDiscarded + } + + fileprivate func createSafeElement(_ sourceEl: Element)throws->ElementMeta { + let sourceTag: String = sourceEl.tagName() + let destAttrs: Attributes = Attributes() + let dest: Element = try Element(Tag.valueOf(sourceTag), sourceEl.getBaseUri(), destAttrs) + var numDiscarded: Int = 0 + + if let sourceAttrs = sourceEl.getAttributes() { + for sourceAttr: Attribute in sourceAttrs { + if (try whitelist.isSafeAttribute(sourceTag, sourceEl, sourceAttr)) { + destAttrs.put(attribute: sourceAttr) + } else { + numDiscarded+=1 + } + } + } + let enforcedAttrs: Attributes = try whitelist.getEnforcedAttributes(sourceTag) + destAttrs.addAll(incoming: enforcedAttrs) + + return ElementMeta(dest, numDiscarded) + } + +} + +extension Cleaner { + fileprivate final class CleaningVisitor: NodeVisitor { + var numDiscarded: Int = 0 + let root: Element + var destination: Element? // current element to append nodes to + + private var cleaner: Cleaner + + public init(_ root: Element, _ destination: Element, _ cleaner: Cleaner) { + self.root = root + self.destination = destination + self.cleaner = cleaner + } + + public func head(_ source: Node, _ depth: Int)throws { + if let sourceEl = (source as? Element) { + if (cleaner.whitelist.isSafeTag(sourceEl.tagName())) { // safe, clone and copy safe attrs + let meta: Cleaner.ElementMeta = try cleaner.createSafeElement(sourceEl) + let destChild: Element = meta.el + try destination?.appendChild(destChild) + + numDiscarded += meta.numAttribsDiscarded + destination = destChild + } else if (source != root) { // not a safe tag, so don't add. don't count root against discarded. + numDiscarded+=1 + } + } else if let sourceText = (source as? TextNode) { + let destText: TextNode = TextNode(sourceText.getWholeText(), source.getBaseUri()) + try destination?.appendChild(destText) + } else if let sourceData = (source as? DataNode) { + if sourceData.parent() != nil && cleaner.whitelist.isSafeTag(sourceData.parent()!.nodeName()) { + //let sourceData: DataNode = (DataNode) source + let destData: DataNode = DataNode(sourceData.getWholeData(), source.getBaseUri()) + try destination?.appendChild(destData) + } else { + numDiscarded+=1 + } + } else { // else, we don't care about comments, xml proc instructions, etc + numDiscarded+=1 + } + } + + public func tail(_ source: Node, _ depth: Int)throws { + if let x = (source as? Element) { + if cleaner.whitelist.isSafeTag(x.nodeName()) { + // would have descended, so pop destination stack + destination = destination?.parent() + } + } + } + } +} + +extension Cleaner { + fileprivate struct ElementMeta { + let el: Element + let numAttribsDiscarded: Int + + init(_ el: Element, _ numAttribsDiscarded: Int) { + self.el = el + self.numAttribsDiscarded = numAttribsDiscarded + } + } +} diff --git a/Pods/SwiftSoup/Sources/Collector.swift b/Pods/SwiftSoup/Sources/Collector.swift new file mode 100644 index 0000000..7bb6feb --- /dev/null +++ b/Pods/SwiftSoup/Sources/Collector.swift @@ -0,0 +1,59 @@ +// +// Collector.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 22/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Collects a list of elements that match the supplied criteria. + * + */ +open class Collector { + + private init() { + } + + /** + Build a list of elements, by visiting root and every descendant of root, and testing it against the evaluator. + @param eval Evaluator to test elements against + @param root root of tree to descend + @return list of matches; empty if none + */ + public static func collect (_ eval: Evaluator, _ root: Element)throws->Elements { + let elements: Elements = Elements() + try NodeTraversor(Accumulator(root, elements, eval)).traverse(root) + return elements + } + +} + +private final class Accumulator: NodeVisitor { + private let root: Element + private let elements: Elements + private let eval: Evaluator + + init(_ root: Element, _ elements: Elements, _ eval: Evaluator) { + self.root = root + self.elements = elements + self.eval = eval + } + + public func head(_ node: Node, _ depth: Int) { + guard let el = node as? Element else { + return + } + do { + if try eval.matches(root, el) { + elements.add(el) + } + } catch {} + } + + public func tail(_ node: Node, _ depth: Int) { + // void + } +} diff --git a/Pods/SwiftSoup/Sources/CombiningEvaluator.swift b/Pods/SwiftSoup/Sources/CombiningEvaluator.swift new file mode 100644 index 0000000..fdeb0ae --- /dev/null +++ b/Pods/SwiftSoup/Sources/CombiningEvaluator.swift @@ -0,0 +1,127 @@ +// +// CombiningEvaluator.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 23/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Base combining (and, or) evaluator. + */ +public class CombiningEvaluator: Evaluator { + + public private(set) var evaluators: Array + var num: Int = 0 + + public override init() { + evaluators = Array() + super.init() + } + + public init(_ evaluators: Array) { + self.evaluators = evaluators + super.init() + updateNumEvaluators() + } + + public init(_ evaluators: Evaluator...) { + self.evaluators = evaluators + super.init() + updateNumEvaluators() + } + + func rightMostEvaluator() -> Evaluator? { + return num > 0 && evaluators.count > 0 ? evaluators[num - 1] : nil + } + + func replaceRightMostEvaluator(_ replacement: Evaluator) { + evaluators[num - 1] = replacement + } + + func updateNumEvaluators() { + // used so we don't need to bash on size() for every match test + num = evaluators.count + } + + public final class And: CombiningEvaluator { + public override init(_ evaluators: [Evaluator]) { + super.init(evaluators) + } + + public override init(_ evaluators: Evaluator...) { + super.init(evaluators) + } + + public override func matches(_ root: Element, _ node: Element) -> Bool { + for index in 0.. String { + let array: [String] = evaluators.map { String($0.toString()) } + return StringUtil.join(array, sep: " ") + } + } + + public final class Or: CombiningEvaluator { + /** + * Create a new Or evaluator. The initial evaluators are ANDed together and used as the first clause of the OR. + * @param evaluators initial OR clause (these are wrapped into an AND evaluator). + */ + public override init(_ evaluators: [Evaluator]) { + super.init() + if num > 1 { + self.evaluators.append(And(evaluators)) + } else { // 0 or 1 + self.evaluators.append(contentsOf: evaluators) + } + updateNumEvaluators() + } + + override init(_ evaluators: Evaluator...) { + super.init() + if num > 1 { + self.evaluators.append(And(evaluators)) + } else { // 0 or 1 + self.evaluators.append(contentsOf: evaluators) + } + updateNumEvaluators() + } + + override init() { + super.init() + } + + public func add(_ evaluator: Evaluator) { + evaluators.append(evaluator) + updateNumEvaluators() + } + + public override func matches(_ root: Element, _ node: Element) -> Bool { + for index in 0.. String { + return ":or\(evaluators.map {String($0.toString())})" + } + } +} diff --git a/Pods/SwiftSoup/Sources/Comment.swift b/Pods/SwiftSoup/Sources/Comment.swift new file mode 100644 index 0000000..0892cad --- /dev/null +++ b/Pods/SwiftSoup/Sources/Comment.swift @@ -0,0 +1,66 @@ +// +// Comment.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 22/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + A comment node. + */ +public class Comment: Node { + private static let COMMENT_KEY: String = "comment" + + /** + Create a new comment node. + @param data The contents of the comment + @param baseUri base URI + */ + public init(_ data: String, _ baseUri: String) { + super.init(baseUri) + do { + try attributes?.put(Comment.COMMENT_KEY, data) + } catch {} + } + + public override func nodeName() -> String { + return "#comment" + } + + /** + Get the contents of the comment. + @return comment content + */ + public func getData() -> String { + return attributes!.get(key: Comment.COMMENT_KEY) + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + if (out.prettyPrint()) { + indent(accum, depth, out) + } + accum + .append("") + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {} + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = Comment(attributes!.get(key: Comment.COMMENT_KEY), baseUri!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = Comment(attributes!.get(key: Comment.COMMENT_KEY), baseUri!) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Pods/SwiftSoup/Sources/Connection.swift b/Pods/SwiftSoup/Sources/Connection.swift new file mode 100644 index 0000000..7b309a5 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Connection.swift @@ -0,0 +1,10 @@ +// +// Connection.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation +//TODO: diff --git a/Pods/SwiftSoup/Sources/DataNode.swift b/Pods/SwiftSoup/Sources/DataNode.swift new file mode 100644 index 0000000..37f7199 --- /dev/null +++ b/Pods/SwiftSoup/Sources/DataNode.swift @@ -0,0 +1,85 @@ +// +// DataNode.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + A data node, for contents of style, script tags etc, where contents should not show in text(). + */ +open class DataNode: Node { + private static let DATA_KEY: String = "data" + + /** + Create a new DataNode. + @param data data contents + @param baseUri base URI + */ + public init(_ data: String, _ baseUri: String) { + super.init(baseUri) + do { + try attributes?.put(DataNode.DATA_KEY, data) + } catch {} + + } + + open override func nodeName() -> String { + return "#data" + } + + /** + Get the data contents of this node. Will be unescaped and with original new lines, space etc. + @return data + */ + open func getWholeData() -> String { + return attributes!.get(key: DataNode.DATA_KEY) + } + + /** + * Set the data contents of this node. + * @param data unencoded data + * @return this node, for chaining + */ + @discardableResult + open func setWholeData(_ data: String) -> DataNode { + do { + try attributes?.put(DataNode.DATA_KEY, data) + } catch {} + return self + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings)throws { + accum.append(getWholeData()) // data is not escaped in return from data nodes, so " in script, style is plain + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {} + + /** + Create a new DataNode from HTML encoded data. + @param encodedData encoded data + @param baseUri bass URI + @return new DataNode + */ + public static func createFromEncoded(_ encodedData: String, _ baseUri: String)throws->DataNode { + let data = try Entities.unescape(encodedData) + return DataNode(data, baseUri) + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = DataNode(attributes!.get(key: DataNode.DATA_KEY), baseUri!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = DataNode(attributes!.get(key: DataNode.DATA_KEY), baseUri!) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Pods/SwiftSoup/Sources/DataUtil.swift b/Pods/SwiftSoup/Sources/DataUtil.swift new file mode 100644 index 0000000..f2d0dee --- /dev/null +++ b/Pods/SwiftSoup/Sources/DataUtil.swift @@ -0,0 +1,24 @@ +// +// DataUtil.swift +// SwifSoup +// +// Created by Nabil Chatbi on 02/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Internal static utilities for handling data. + * + */ +class DataUtil { + + static let charsetPattern = "(?i)\\bcharset=\\s*(?:\"|')?([^\\s,;\"']*)" + static let defaultCharset = "UTF-8" // used if not found in header or meta charset + static let bufferSize = 0x20000 // ~130K. + static let UNICODE_BOM = 0xFEFF + static let mimeBoundaryChars = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + static let boundaryLength = 32 + +} diff --git a/Pods/SwiftSoup/Sources/Document.swift b/Pods/SwiftSoup/Sources/Document.swift new file mode 100644 index 0000000..a47a867 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Document.swift @@ -0,0 +1,562 @@ +// +// Document.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +open class Document: Element { + public enum QuirksMode { + case noQuirks, quirks, limitedQuirks + } + + private var _outputSettings: OutputSettings = OutputSettings() + private var _quirksMode: Document.QuirksMode = QuirksMode.noQuirks + private let _location: String + private var updateMetaCharset: Bool = false + + /** + Create a new, empty Document. + @param baseUri base URI of document + @see org.jsoup.Jsoup#parse + @see #createShell + */ + public init(_ baseUri: String) { + self._location = baseUri + super.init(try! Tag.valueOf("#root", ParseSettings.htmlDefault), baseUri) + } + + /** + Create a valid, empty shell of a document, suitable for adding more elements to. + @param baseUri baseUri of document + @return document with html, head, and body elements. + */ + static public func createShell(_ baseUri: String) -> Document { + let doc: Document = Document(baseUri) + let html: Element = try! doc.appendElement("html") + try! html.appendElement("head") + try! html.appendElement("body") + + return doc + } + + /** + * Get the URL this Document was parsed from. If the starting URL is a redirect, + * this will return the final URL from which the document was served from. + * @return location + */ + public func location() -> String { + return _location + } + + /** + Accessor to the document's {@code head} element. + @return {@code head} + */ + public func head() -> Element? { + return findFirstElementByTagName("head", self) + } + + /** + Accessor to the document's {@code body} element. + @return {@code body} + */ + public func body() -> Element? { + return findFirstElementByTagName("body", self) + } + + /** + Get the string contents of the document's {@code title} element. + @return Trimmed title, or empty string if none set. + */ + public func title()throws->String { + // title is a preserve whitespace tag (for document output), but normalised here + let titleEl: Element? = try getElementsByTag("title").first() + return titleEl != nil ? try StringUtil.normaliseWhitespace(titleEl!.text()).trim() : "" + } + + /** + Set the document's {@code title} element. Updates the existing element, or adds {@code title} to {@code head} if + not present + @param title string to set as title + */ + public func title(_ title: String)throws { + let titleEl: Element? = try getElementsByTag("title").first() + if (titleEl == nil) { // add to head + try head()?.appendElement("title").text(title) + } else { + try titleEl?.text(title) + } + } + + /** + Create a new Element, with this document's base uri. Does not make the new element a child of this document. + @param tagName element tag name (e.g. {@code a}) + @return new element + */ + public func createElement(_ tagName: String)throws->Element { + return try Element(Tag.valueOf(tagName, ParseSettings.preserveCase), self.getBaseUri()) + } + + /** + Normalise the document. This happens after the parse phase so generally does not need to be called. + Moves any text content that is not in the body element into the body. + @return this document after normalisation + */ + @discardableResult + public func normalise()throws->Document { + var htmlE: Element? = findFirstElementByTagName("html", self) + if (htmlE == nil) { + htmlE = try appendElement("html") + } + let htmlEl: Element = htmlE! + + if (head() == nil) { + try htmlEl.prependElement("head") + } + if (body() == nil) { + try htmlEl.appendElement("body") + } + + // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care + // of. do in inverse order to maintain text order. + try normaliseTextNodes(head()!) + try normaliseTextNodes(htmlEl) + try normaliseTextNodes(self) + + try normaliseStructure("head", htmlEl) + try normaliseStructure("body", htmlEl) + + try ensureMetaCharsetElement() + + return self + } + + // does not recurse. + private func normaliseTextNodes(_ element: Element)throws { + var toMove: Array = Array() + for node: Node in element.childNodes { + if let tn = (node as? TextNode) { + if (!tn.isBlank()) { + toMove.append(tn) + } + } + } + + for i in (0.. or contents into one, delete the remainder, and ensure they are owned by + private func normaliseStructure(_ tag: String, _ htmlEl: Element)throws { + let elements: Elements = try self.getElementsByTag(tag) + let master: Element? = elements.first() // will always be available as created above if not existent + if (elements.size() > 1) { // dupes, move contents to master + var toMove: Array = Array() + for i in 1.. + if (!(master != nil && master!.parent() != nil && master!.parent()!.equals(htmlEl))) { + try htmlEl.appendChild(master!) // includes remove() + } + } + + // fast method to get first by tag name, used for html, head, body finders + private func findFirstElementByTagName(_ tag: String, _ node: Node) -> Element? { + if (node.nodeName()==tag) { + return node as? Element + } else { + for child: Node in node.childNodes { + let found: Element? = findFirstElementByTagName(tag, child) + if (found != nil) { + return found + } + } + } + return nil + } + + open override func outerHtml()throws->String { + return try super.html() // no outer wrapper tag + } + + /** + Set the text of the {@code body} of this document. Any existing nodes within the body will be cleared. + @param text unencoded text + @return this document + */ + @discardableResult + public override func text(_ text: String)throws->Element { + try body()?.text(text) // overridden to not nuke doc structure + return self + } + + open override func nodeName() -> String { + return "#document" + } + + /** + * Sets the charset used in this document. This method is equivalent + * to {@link OutputSettings#charset(java.nio.charset.Charset) + * OutputSettings.charset(Charset)} but in addition it updates the + * charset / encoding element within the document. + * + *

    This enables + * {@link #updateMetaCharsetElement(boolean) meta charset update}.

    + * + *

    If there's no element with charset / encoding information yet it will + * be created. Obsolete charset / encoding definitions are removed!

    + * + *

    Elements used:

    + * + *
      + *
    • Html: <meta charset="CHARSET">
    • + *
    • Xml: <?xml version="1.0" encoding="CHARSET">
    • + *
    + * + * @param charset Charset + * + * @see #updateMetaCharsetElement(boolean) + * @see OutputSettings#charset(java.nio.charset.Charset) + */ + public func charset(_ charset: String.Encoding)throws { + updateMetaCharsetElement(true) + _outputSettings.charset(charset) + try ensureMetaCharsetElement() + } + + /** + * Returns the charset used in this document. This method is equivalent + * to {@link OutputSettings#charset()}. + * + * @return Current Charset + * + * @see OutputSettings#charset() + */ + public func charset()->String.Encoding { + return _outputSettings.charset() + } + + /** + * Sets whether the element with charset information in this document is + * updated on changes through {@link #charset(java.nio.charset.Charset) + * Document.charset(Charset)} or not. + * + *

    If set to false (default) there are no elements + * modified.

    + * + * @param update If true the element updated on charset + * changes, false if not + * + * @see #charset(java.nio.charset.Charset) + */ + public func updateMetaCharsetElement(_ update: Bool) { + self.updateMetaCharset = update + } + + /** + * Returns whether the element with charset information in this document is + * updated on changes through {@link #charset(java.nio.charset.Charset) + * Document.charset(Charset)} or not. + * + * @return Returns true if the element is updated on charset + * changes, false if not + */ + public func updateMetaCharsetElement() -> Bool { + return updateMetaCharset + } + + /** + * Ensures a meta charset (html) or xml declaration (xml) with the current + * encoding used. This only applies with + * {@link #updateMetaCharsetElement(boolean) updateMetaCharset} set to + * true, otherwise this method does nothing. + * + *
      + *
    • An exsiting element gets updated with the current charset
    • + *
    • If there's no element yet it will be inserted
    • + *
    • Obsolete elements are removed
    • + *
    + * + *

    Elements used:

    + * + *
      + *
    • Html: <meta charset="CHARSET">
    • + *
    • Xml: <?xml version="1.0" encoding="CHARSET">
    • + *
    + */ + private func ensureMetaCharsetElement()throws { + if (updateMetaCharset) { + let syntax: OutputSettings.Syntax = outputSettings().syntax() + + if (syntax == OutputSettings.Syntax.html) { + let metaCharset: Element? = try select("meta[charset]").first() + + if (metaCharset != nil) { + try metaCharset?.attr("charset", charset().displayName()) + } else { + let head: Element? = self.head() + + if (head != nil) { + try head?.appendElement("meta").attr("charset", charset().displayName()) + } + } + + // Remove obsolete elements + let s = try select("meta[name=charset]") + try s.remove() + + } else if (syntax == OutputSettings.Syntax.xml) { + let node: Node = getChildNodes()[0] + + if let decl = (node as? XmlDeclaration) { + + if (decl.name()=="xml") { + try decl.attr("encoding", charset().displayName()) + + _ = try decl.attr("version") + try decl.attr("version", "1.0") + } else { + try Validate.notNull(obj: baseUri) + let decl = XmlDeclaration("xml", baseUri!, false) + try decl.attr("version", "1.0") + try decl.attr("encoding", charset().displayName()) + + try prependChild(decl) + } + } else { + try Validate.notNull(obj: baseUri) + let decl = XmlDeclaration("xml", baseUri!, false) + try decl.attr("version", "1.0") + try decl.attr("encoding", charset().displayName()) + + try prependChild(decl) + } + } + } + } + + /** + * Get the document's current output settings. + * @return the document's current output settings. + */ + public func outputSettings() -> OutputSettings { + return _outputSettings + } + + /** + * Set the document's output settings. + * @param outputSettings new output settings. + * @return this document, for chaining. + */ + @discardableResult + public func outputSettings(_ outputSettings: OutputSettings) -> Document { + self._outputSettings = outputSettings + return self + } + + public func quirksMode()->Document.QuirksMode { + return _quirksMode + } + + @discardableResult + public func quirksMode(_ quirksMode: Document.QuirksMode) -> Document { + self._quirksMode = quirksMode + return self + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = Document(_location) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = Document(_location) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + let clone = clone as! Document + clone._outputSettings = _outputSettings.copy() as! OutputSettings + clone._quirksMode = _quirksMode + clone.updateMetaCharset = updateMetaCharset + return super.copy(clone: clone, parent: parent) + } + +} + +public class OutputSettings: NSCopying { + /** + * The output serialization syntax. + */ + public enum Syntax {case html, xml} + + private var _escapeMode: Entities.EscapeMode = Entities.EscapeMode.base + private var _encoder: String.Encoding = String.Encoding.utf8 // Charset.forName("UTF-8") + private var _prettyPrint: Bool = true + private var _outline: Bool = false + private var _indentAmount: UInt = 1 + private var _syntax = Syntax.html + + public init() {} + + /** + * Get the document's current HTML escape mode: base, which provides a limited set of named HTML + * entities and escapes other characters as numbered entities for maximum compatibility; or extended, + * which uses the complete set of HTML named entities. + *

    + * The default escape mode is base. + * @return the document's current escape mode + */ + public func escapeMode() -> Entities.EscapeMode { + return _escapeMode + } + + /** + * Set the document's escape mode, which determines how characters are escaped when the output character set + * does not support a given character:- using either a named or a numbered escape. + * @param escapeMode the new escape mode to use + * @return the document's output settings, for chaining + */ + @discardableResult + public func escapeMode(_ escapeMode: Entities.EscapeMode) -> OutputSettings { + self._escapeMode = escapeMode + return self + } + + /** + * Get the document's current output charset, which is used to control which characters are escaped when + * generating HTML (via the html() methods), and which are kept intact. + *

    + * Where possible (when parsing from a URL or File), the document's output charset is automatically set to the + * input charset. Otherwise, it defaults to UTF-8. + * @return the document's current charset. + */ + public func encoder() -> String.Encoding { + return _encoder + } + public func charset() -> String.Encoding { + return _encoder + } + + /** + * Update the document's output charset. + * @param charset the new charset to use. + * @return the document's output settings, for chaining + */ + @discardableResult + public func encoder(_ encoder: String.Encoding) -> OutputSettings { + self._encoder = encoder + return self + } + + @discardableResult + public func charset(_ e: String.Encoding) -> OutputSettings { + return encoder(e) + } + + /** + * Get the document's current output syntax. + * @return current syntax + */ + public func syntax() -> Syntax { + return _syntax + } + + /** + * Set the document's output syntax. Either {@code html}, with empty tags and boolean attributes (etc), or + * {@code xml}, with self-closing tags. + * @param syntax serialization syntax + * @return the document's output settings, for chaining + */ + @discardableResult + public func syntax(syntax: Syntax) -> OutputSettings { + _syntax = syntax + return self + } + + /** + * Get if pretty printing is enabled. Default is true. If disabled, the HTML output methods will not re-format + * the output, and the output will generally look like the input. + * @return if pretty printing is enabled. + */ + public func prettyPrint() -> Bool { + return _prettyPrint + } + + /** + * Enable or disable pretty printing. + * @param pretty new pretty print setting + * @return this, for chaining + */ + @discardableResult + public func prettyPrint(pretty: Bool) -> OutputSettings { + _prettyPrint = pretty + return self + } + + /** + * Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider + * all tags as block. + * @return if outline mode is enabled. + */ + public func outline() -> Bool { + return _outline + } + + /** + * Enable or disable HTML outline mode. + * @param outlineMode new outline setting + * @return this, for chaining + */ + @discardableResult + public func outline(outlineMode: Bool) -> OutputSettings { + _outline = outlineMode + return self + } + + /** + * Get the current tag indent amount, used when pretty printing. + * @return the current indent amount + */ + public func indentAmount() -> UInt { + return _indentAmount + } + + /** + * Set the indent amount for pretty printing + * @param indentAmount number of spaces to use for indenting each level. Must be {@literal >=} 0. + * @return this, for chaining + */ + @discardableResult + public func indentAmount(indentAmount: UInt) -> OutputSettings { + _indentAmount = indentAmount + return self + } + + public func copy(with zone: NSZone? = nil) -> Any { + let clone: OutputSettings = OutputSettings() + clone.charset(_encoder) // new charset and charset encoder + clone._escapeMode = _escapeMode//Entities.EscapeMode.valueOf(escapeMode.name()) + // indentAmount, prettyPrint are primitives so object.clone() will handle + return clone + } + +} diff --git a/Pods/SwiftSoup/Sources/DocumentType.swift b/Pods/SwiftSoup/Sources/DocumentType.swift new file mode 100644 index 0000000..95f9b10 --- /dev/null +++ b/Pods/SwiftSoup/Sources/DocumentType.swift @@ -0,0 +1,129 @@ +// +// DocumentType.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * A {@code } node. + */ +public class DocumentType: Node { + static let PUBLIC_KEY: String = "PUBLIC" + static let SYSTEM_KEY: String = "SYSTEM" + private static let NAME: String = "name" + private static let PUB_SYS_KEY: String = "pubSysKey"; // PUBLIC or SYSTEM + private static let PUBLIC_ID: String = "publicId" + private static let SYSTEM_ID: String = "systemId" + // todo: quirk mode from publicId and systemId + + /** + * Create a new doctype element. + * @param name the doctype's name + * @param publicId the doctype's public ID + * @param systemId the doctype's system ID + * @param baseUri the doctype's base URI + */ + public init(_ name: String, _ publicId: String, _ systemId: String, _ baseUri: String) { + super.init(baseUri) + do { + try attr(DocumentType.NAME, name) + try attr(DocumentType.PUBLIC_ID, publicId) + if (has(DocumentType.PUBLIC_ID)) { + try attr(DocumentType.PUB_SYS_KEY, DocumentType.PUBLIC_KEY) + } + try attr(DocumentType.SYSTEM_ID, systemId) + } catch {} + } + + /** + * Create a new doctype element. + * @param name the doctype's name + * @param publicId the doctype's public ID + * @param systemId the doctype's system ID + * @param baseUri the doctype's base URI + */ + public init(_ name: String, _ pubSysKey: String?, _ publicId: String, _ systemId: String, _ baseUri: String) { + super.init(baseUri) + do { + try attr(DocumentType.NAME, name) + if(pubSysKey != nil) { + try attr(DocumentType.PUB_SYS_KEY, pubSysKey!) + } + try attr(DocumentType.PUBLIC_ID, publicId) + try attr(DocumentType.SYSTEM_ID, systemId) + } catch {} + } + + public override func nodeName() -> String { + return "#doctype" + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + if (out.syntax() == OutputSettings.Syntax.html && !has(DocumentType.PUBLIC_ID) && !has(DocumentType.SYSTEM_ID)) { + // looks like a html5 doctype, go lowercase for aesthetics + accum.append("") + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + } + + private func has(_ attribute: String) -> Bool { + do { + return !StringUtil.isBlank(try attr(attribute)) + } catch {return false} + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = DocumentType(attributes!.get(key: DocumentType.NAME), + attributes!.get(key: DocumentType.PUBLIC_ID), + attributes!.get(key: DocumentType.SYSTEM_ID), + baseUri!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = DocumentType(attributes!.get(key: DocumentType.NAME), + attributes!.get(key: DocumentType.PUBLIC_ID), + attributes!.get(key: DocumentType.SYSTEM_ID), + baseUri!) + return copy(clone: clone, parent: parent) + } + + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } + +} diff --git a/Pods/SwiftSoup/Sources/Element.swift b/Pods/SwiftSoup/Sources/Element.swift new file mode 100644 index 0000000..144acc6 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Element.swift @@ -0,0 +1,1295 @@ +// +// Element.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +open class Element: Node { + var _tag: Tag + + private static let classString = "class" + private static let emptyString = "" + private static let idString = "id" + private static let rootString = "#root" + + //private static let classSplit : Pattern = Pattern("\\s+") + private static let classSplit = "\\s+" + + /** + * Create a new, standalone Element. (Standalone in that is has no parent.) + * + * @param tag tag of this element + * @param baseUri the base URI + * @param attributes initial attributes + * @see #appendChild(Node) + * @see #appendElement(String) + */ + public init(_ tag: Tag, _ baseUri: String, _ attributes: Attributes) { + self._tag = tag + super.init(baseUri, attributes) + } + /** + * Create a new Element from a tag and a base URI. + * + * @param tag element tag + * @param baseUri the base URI of this element. It is acceptable for the base URI to be an empty + * string, but not null. + * @see Tag#valueOf(String, ParseSettings) + */ + public init(_ tag: Tag, _ baseUri: String) { + self._tag = tag + super.init(baseUri, Attributes()) + } + + open override func nodeName() -> String { + return _tag.getName() + } + /** + * Get the name of the tag for this element. E.g. {@code div} + * + * @return the tag name + */ + open func tagName() -> String { + return _tag.getName() + } + open func tagNameNormal() -> String { + return _tag.getNameNormal() + } + + /** + * Change the tag of this element. For example, convert a {@code } to a {@code

    } with + * {@code el.tagName("div")}. + * + * @param tagName new tag name for this element + * @return this element, for chaining + */ + @discardableResult + public func tagName(_ tagName: String)throws->Element { + try Validate.notEmpty(string: tagName, msg: "Tag name must not be empty.") + _tag = try Tag.valueOf(tagName, ParseSettings.preserveCase) // preserve the requested tag case + return self + } + + /** + * Get the Tag for this element. + * + * @return the tag object + */ + open func tag() -> Tag { + return _tag + } + + /** + * Test if this element is a block-level element. (E.g. {@code
    == true} or an inline element + * {@code

    == false}). + * + * @return true if block, false if not (and thus inline) + */ + open func isBlock() -> Bool { + return _tag.isBlock() + } + + /** + * Get the {@code id} attribute of this element. + * + * @return The id attribute, if present, or an empty string if not. + */ + open func id() -> String { + guard let attributes = attributes else {return Element.emptyString} + do { + return try attributes.getIgnoreCase(key: Element.idString) + } catch {} + return Element.emptyString + } + + /** + * Set an attribute value on this element. If this element already has an attribute with the + * key, its value is updated; otherwise, a new attribute is added. + * + * @return this element + */ + @discardableResult + open override func attr(_ attributeKey: String, _ attributeValue: String)throws->Element { + try super.attr(attributeKey, attributeValue) + return self + } + + /** + * Set a boolean attribute value on this element. Setting to true sets the attribute value to "" and + * marks the attribute as boolean so no value is written out. Setting to false removes the attribute + * with the same key if it exists. + * + * @param attributeKey the attribute key + * @param attributeValue the attribute value + * + * @return this element + */ + @discardableResult + open func attr(_ attributeKey: String, _ attributeValue: Bool)throws->Element { + try attributes?.put(attributeKey, attributeValue) + return self + } + + /** + * Get this element's HTML5 custom data attributes. Each attribute in the element that has a key + * starting with "data-" is included the dataset. + *

    + * E.g., the element {@code

    ...} has the dataset + * {@code package=jsoup, language=java}. + *

    + * This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected + * in the other map. + *

    + * You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector. + * @return a map of {@code key=value} custom data attributes. + */ + open func dataset()->Dictionary { + return attributes!.dataset() + } + + open override func parent() -> Element? { + return parentNode as? Element + } + + /** + * Get this element's parent and ancestors, up to the document root. + * @return this element's stack of parents, closest first. + */ + open func parents() -> Elements { + let parents: Elements = Elements() + Element.accumulateParents(self, parents) + return parents + } + + private static func accumulateParents(_ el: Element, _ parents: Elements) { + let parent: Element? = el.parent() + if (parent != nil && !(parent!.tagName() == Element.rootString)) { + parents.add(parent!) + accumulateParents(parent!, parents) + } + } + + /** + * Get a child element of this element, by its 0-based index number. + *

    + * Note that an element can have both mixed Nodes and Elements as children. This method inspects + * a filtered list of children that are elements, and the index is based on that filtered list. + *

    + * + * @param index the index number of the element to retrieve + * @return the child element, if it exists, otherwise throws an {@code IndexOutOfBoundsException} + * @see #childNode(int) + */ + open func child(_ index: Int) -> Element { + return children().get(index) + } + + /** + * Get this element's child elements. + *

    + * This is effectively a filter on {@link #childNodes()} to get Element nodes. + *

    + * @return child elements. If this element has no children, returns an + * empty list. + * @see #childNodes() + */ + open func children() -> Elements { + // create on the fly rather than maintaining two lists. if gets slow, memoize, and mark dirty on change + var elements = Array() + for node in childNodes { + if let n = node as? Element { + elements.append(n) + } + } + return Elements(elements) + } + + /** + * Get this element's child text nodes. The list is unmodifiable but the text nodes may be manipulated. + *

    + * This is effectively a filter on {@link #childNodes()} to get Text nodes. + * @return child text nodes. If this element has no text nodes, returns an + * empty list. + *

    + * For example, with the input HTML: {@code

    One Two Three
    Four

    } with the {@code p} element selected: + *
      + *
    • {@code p.text()} = {@code "One Two Three Four"}
    • + *
    • {@code p.ownText()} = {@code "One Three Four"}
    • + *
    • {@code p.children()} = {@code Elements[,
      ]}
    • + *
    • {@code p.childNodes()} = {@code List["One ", , " Three ",
      , " Four"]}
    • + *
    • {@code p.textNodes()} = {@code List["One ", " Three ", " Four"]}
    • + *
    + */ + open func textNodes()->Array { + var textNodes = Array() + for node in childNodes { + if let n = node as? TextNode { + textNodes.append(n) + } + } + return textNodes + } + + /** + * Get this element's child data nodes. The list is unmodifiable but the data nodes may be manipulated. + *

    + * This is effectively a filter on {@link #childNodes()} to get Data nodes. + *

    + * @return child data nodes. If this element has no data nodes, returns an + * empty list. + * @see #data() + */ + open func dataNodes()->Array { + var dataNodes = Array() + for node in childNodes { + if let n = node as? DataNode { + dataNodes.append(n) + } + } + return dataNodes + } + + /** + * Find elements that match the {@link Selector} CSS query, with this element as the starting context. Matched elements + * may include this element, or any of its children. + *

    + * This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because + * multiple filters can be combined, e.g.: + *

    + *
      + *
    • {@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes) + *
    • {@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely) + *
    + *

    + * See the query syntax documentation in {@link org.jsoup.select.Selector}. + *

    + * + * @param cssQuery a {@link Selector} CSS-like query + * @return elements that match the query (empty if none match) + * @see org.jsoup.select.Selector + * @throws Selector.SelectorParseException (unchecked) on an invalid CSS query. + */ + public func select(_ cssQuery: String)throws->Elements { + return try Selector.select(cssQuery, self) + } + + /** + * Check if this element matches the given {@link Selector} CSS query. + * @param cssQuery a {@link Selector} CSS query + * @return if this element matches the query + */ + public func iS(_ cssQuery: String)throws->Bool { + return try iS(QueryParser.parse(cssQuery)) + } + + /** + * Check if this element matches the given {@link Selector} CSS query. + * @param cssQuery a {@link Selector} CSS query + * @return if this element matches the query + */ + public func iS(_ evaluator: Evaluator)throws->Bool { + guard let od = self.ownerDocument() else { + return false + } + return try evaluator.matches(od, self) + } + + /** + * Add a node child node to this element. + * + * @param child node to add. + * @return this element, so that you can add more child nodes or elements. + */ + @discardableResult + public func appendChild(_ child: Node)throws->Element { + // was - Node#addChildren(child). short-circuits an array create and a loop. + try reparentChild(child) + ensureChildNodes() + childNodes.append(child) + child.setSiblingIndex(childNodes.count - 1) + return self + } + + /** + * Add a node to the start of this element's children. + * + * @param child node to add. + * @return this element, so that you can add more child nodes or elements. + */ + @discardableResult + public func prependChild(_ child: Node)throws->Element { + try addChildren(0, child) + return self + } + + /** + * Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the + * right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first. + * + * @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the + * end + * @param children child nodes to insert + * @return this element, for chaining. + */ + @discardableResult + public func insertChildren(_ index: Int, _ children: Array)throws->Element { + //Validate.notNull(children, "Children collection to be inserted must not be null.") + var index = index + let currentSize: Int = childNodeSize() + if (index < 0) { index += currentSize + 1} // roll around + try Validate.isTrue(val: index >= 0 && index <= currentSize, msg: "Insert position out of bounds.") + + try addChildren(index, children) + return self + } + + /** + * Create a new element by tag name, and add it as the last child. + * + * @param tagName the name of the tag (e.g. {@code div}). + * @return the new element, to allow you to add content to it, e.g.: + * {@code parent.appendElement("h1").attr("id", "header").text("Welcome")} + */ + @discardableResult + public func appendElement(_ tagName: String)throws->Element { + let child: Element = Element(try Tag.valueOf(tagName), getBaseUri()) + try appendChild(child) + return child + } + + /** + * Create a new element by tag name, and add it as the first child. + * + * @param tagName the name of the tag (e.g. {@code div}). + * @return the new element, to allow you to add content to it, e.g.: + * {@code parent.prependElement("h1").attr("id", "header").text("Welcome")} + */ + @discardableResult + public func prependElement(_ tagName: String)throws->Element { + let child: Element = Element(try Tag.valueOf(tagName), getBaseUri()) + try prependChild(child) + return child + } + + /** + * Create and append a new TextNode to this element. + * + * @param text the unencoded text to add + * @return this element + */ + @discardableResult + public func appendText(_ text: String)throws->Element { + let node: TextNode = TextNode(text, getBaseUri()) + try appendChild(node) + return self + } + + /** + * Create and prepend a new TextNode to this element. + * + * @param text the unencoded text to add + * @return this element + */ + @discardableResult + public func prependText(_ text: String)throws->Element { + let node: TextNode = TextNode(text, getBaseUri()) + try prependChild(node) + return self + } + + /** + * Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children. + * @param html HTML to add inside this element, after the existing HTML + * @return this element + * @see #html(String) + */ + @discardableResult + public func append(_ html: String)throws->Element { + let nodes: Array = try Parser.parseFragment(html, self, getBaseUri()) + try addChildren(nodes) + return self + } + + /** + * Add inner HTML into this element. The supplied HTML will be parsed, and each node prepended to the start of the element's children. + * @param html HTML to add inside this element, before the existing HTML + * @return this element + * @see #html(String) + */ + @discardableResult + public func prepend(_ html: String)throws->Element { + let nodes: Array = try Parser.parseFragment(html, self, getBaseUri()) + try addChildren(0, nodes) + return self + } + + /** + * Insert the specified HTML into the DOM before this element (as a preceding sibling). + * + * @param html HTML to add before this element + * @return this element, for chaining + * @see #after(String) + */ + @discardableResult + open override func before(_ html: String)throws->Element { + return try super.before(html) as! Element + } + + /** + * Insert the specified node into the DOM before this node (as a preceding sibling). + * @param node to add before this element + * @return this Element, for chaining + * @see #after(Node) + */ + @discardableResult + open override func before(_ node: Node)throws->Element { + return try super.before(node) as! Element + } + + /** + * Insert the specified HTML into the DOM after this element (as a following sibling). + * + * @param html HTML to add after this element + * @return this element, for chaining + * @see #before(String) + */ + @discardableResult + open override func after(_ html: String)throws->Element { + return try super.after(html) as! Element + } + + /** + * Insert the specified node into the DOM after this node (as a following sibling). + * @param node to add after this element + * @return this element, for chaining + * @see #before(Node) + */ + open override func after(_ node: Node)throws->Element { + return try super.after(node) as! Element + } + + /** + * Remove all of the element's child nodes. Any attributes are left as-is. + * @return this element + */ + @discardableResult + public func empty() -> Element { + childNodes.removeAll() + return self + } + + /** + * Wrap the supplied HTML around this element. + * + * @param html HTML to wrap around this element, e.g. {@code
    }. Can be arbitrarily deep. + * @return this element, for chaining. + */ + @discardableResult + open override func wrap(_ html: String)throws->Element { + return try super.wrap(html) as! Element + } + + /** + * Get a CSS selector that will uniquely select this element. + *

    + * If the element has an ID, returns #id; + * otherwise returns the parent (if any) CSS selector, followed by {@literal '>'}, + * followed by a unique selector for the element (tag.class.class:nth-child(n)). + *

    + * + * @return the CSS Path that can be used to retrieve the element in a selector. + */ + public func cssSelector()throws->String { + let elementId = id() + if (elementId.count > 0) { + return "#" + elementId + } + + // Translate HTML namespace ns:tag to CSS namespace syntax ns|tag + let tagName: String = self.tagName().replacingOccurrences(of: ":", with: "|") + var selector: String = tagName + let cl = try classNames() + let classes: String = cl.joined(separator: ".") + if (classes.count > 0) { + selector.append(".") + selector.append(classes) + } + + if (parent() == nil || ((parent() as? Document) != nil)) // don't add Document to selector, as will always have a html node + { + return selector + } + + selector.insert(contentsOf: " > ", at: selector.startIndex) + if (try parent()!.select(selector).array().count > 1) { + selector.append(":nth-child(\(try elementSiblingIndex() + 1))") + } + + return try parent()!.cssSelector() + (selector) + } + + /** + * Get sibling elements. If the element has no sibling elements, returns an empty list. An element is not a sibling + * of itself, so will not be included in the returned list. + * @return sibling elements + */ + public func siblingElements() -> Elements { + if (parentNode == nil) {return Elements()} + + let elements: Array? = parent()?.children().array() + let siblings: Elements = Elements() + if let elements = elements { + for el: Element in elements { + if (el != self) { + siblings.add(el) + } + } + } + return siblings + } + + /** + * Gets the next sibling element of this element. E.g., if a {@code div} contains two {@code p}s, + * the {@code nextElementSibling} of the first {@code p} is the second {@code p}. + *

    + * This is similar to {@link #nextSibling()}, but specifically finds only Elements + *

    + * @return the next element, or null if there is no next element + * @see #previousElementSibling() + */ + public func nextElementSibling()throws->Element? { + if (parentNode == nil) {return nil} + let siblings: Array? = parent()?.children().array() + let index: Int? = try Element.indexInList(self, siblings) + try Validate.notNull(obj: index) + if let siblings = siblings { + if (siblings.count > index!+1) { + return siblings[index!+1] + } else { + return nil} + } + return nil + } + + /** + * Gets the previous element sibling of this element. + * @return the previous element, or null if there is no previous element + * @see #nextElementSibling() + */ + public func previousElementSibling()throws->Element? { + if (parentNode == nil) {return nil} + let siblings: Array? = parent()?.children().array() + let index: Int? = try Element.indexInList(self, siblings) + try Validate.notNull(obj: index) + if (index! > 0) { + return siblings?[index!-1] + } else { + return nil + } + } + + /** + * Gets the first element sibling of this element. + * @return the first sibling that is an element (aka the parent's first element child) + */ + public func firstElementSibling() -> Element? { + // todo: should firstSibling() exclude this? + let siblings: Array? = parent()?.children().array() + return (siblings != nil && siblings!.count > 1) ? siblings![0] : nil + } + + /* + * Get the list index of this element in its element sibling list. I.e. if this is the first element + * sibling, returns 0. + * @return position in element sibling list + */ + public func elementSiblingIndex()throws->Int { + if (parent() == nil) {return 0} + let x = try Element.indexInList(self, parent()?.children().array()) + return x == nil ? 0 : x! + } + + /** + * Gets the last element sibling of this element + * @return the last sibling that is an element (aka the parent's last element child) + */ + public func lastElementSibling() -> Element? { + let siblings: Array? = parent()?.children().array() + return (siblings != nil && siblings!.count > 1) ? siblings![siblings!.count - 1] : nil + } + + private static func indexInList(_ search: Element, _ elements: Array?)throws->Int? { + try Validate.notNull(obj: elements) + if let elements = elements { + for i in 0..Elements { + try Validate.notEmpty(string: tagName) + let tagName = tagName.lowercased().trim() + + return try Collector.collect(Evaluator.Tag(tagName), self) + } + + /** + * Find an element by ID, including or under this element. + *

    + * Note that this finds the first matching ID, starting with this element. If you search down from a different + * starting point, it is possible to find a different element by ID. For unique element by ID within a Document, + * use {@link Document#getElementById(String)} + * @param id The ID to search for. + * @return The first matching element by ID, starting with this element, or null if none found. + */ + public func getElementById(_ id: String)throws->Element? { + try Validate.notEmpty(string: id) + + let elements: Elements = try Collector.collect(Evaluator.Id(id), self) + if (elements.array().count > 0) { + return elements.get(0) + } else { + return nil + } + } + + /** + * Find elements that have this class, including or under this element. Case insensitive. + *

    + * Elements can have multiple classes (e.g. {@code

    }. This method + * checks each class, so you can find the above with {@code el.getElementsByClass("header")}. + * + * @param className the name of the class to search for. + * @return elements with the supplied class name, empty if none + * @see #hasClass(String) + * @see #classNames() + */ + public func getElementsByClass(_ className: String)throws->Elements { + try Validate.notEmpty(string: className) + + return try Collector.collect(Evaluator.Class(className), self) + } + + /** + * Find elements that have a named attribute set. Case insensitive. + * + * @param key name of the attribute, e.g. {@code href} + * @return elements that have this attribute, empty if none + */ + public func getElementsByAttribute(_ key: String)throws->Elements { + try Validate.notEmpty(string: key) + let key = key.trim() + + return try Collector.collect(Evaluator.Attribute(key), self) + } + + /** + * Find elements that have an attribute name starting with the supplied prefix. Use {@code data-} to find elements + * that have HTML5 datasets. + * @param keyPrefix name prefix of the attribute e.g. {@code data-} + * @return elements that have attribute names that start with with the prefix, empty if none. + */ + public func getElementsByAttributeStarting(_ keyPrefix: String)throws->Elements { + try Validate.notEmpty(string: keyPrefix) + let keyPrefix = keyPrefix.trim() + + return try Collector.collect(Evaluator.AttributeStarting(keyPrefix), self) + } + + /** + * Find elements that have an attribute with the specific value. Case insensitive. + * + * @param key name of the attribute + * @param value value of the attribute + * @return elements that have this attribute with this value, empty if none + */ + public func getElementsByAttributeValue(_ key: String, _ value: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValue(key, value), self) + } + + /** + * Find elements that either do not have this attribute, or have it with a different value. Case insensitive. + * + * @param key name of the attribute + * @param value value of the attribute + * @return elements that do not have a matching attribute + */ + public func getElementsByAttributeValueNot(_ key: String, _ value: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueNot(key, value), self) + } + + /** + * Find elements that have attributes that start with the value prefix. Case insensitive. + * + * @param key name of the attribute + * @param valuePrefix start of attribute value + * @return elements that have attributes that start with the value prefix + */ + public func getElementsByAttributeValueStarting(_ key: String, _ valuePrefix: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueStarting(key, valuePrefix), self) + } + + /** + * Find elements that have attributes that end with the value suffix. Case insensitive. + * + * @param key name of the attribute + * @param valueSuffix end of the attribute value + * @return elements that have attributes that end with the value suffix + */ + public func getElementsByAttributeValueEnding(_ key: String, _ valueSuffix: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueEnding(key, valueSuffix), self) + } + + /** + * Find elements that have attributes whose value contains the match string. Case insensitive. + * + * @param key name of the attribute + * @param match substring of value to search for + * @return elements that have attributes containing this text + */ + public func getElementsByAttributeValueContaining(_ key: String, _ match: String)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueContaining(key, match), self) + } + + /** + * Find elements that have attributes whose values match the supplied regular expression. + * @param key name of the attribute + * @param pattern compiled regular expression to match against attribute values + * @return elements that have attributes matching this regular expression + */ + public func getElementsByAttributeValueMatching(_ key: String, _ pattern: Pattern)throws->Elements { + return try Collector.collect(Evaluator.AttributeWithValueMatching(key, pattern), self) + + } + + /** + * Find elements that have attributes whose values match the supplied regular expression. + * @param key name of the attribute + * @param regex regular expression to match against attribute values. You can use embedded flags (such as (?i) and (?m) to control regex options. + * @return elements that have attributes matching this regular expression + */ + public func getElementsByAttributeValueMatching(_ key: String, _ regex: String)throws->Elements { + var pattern: Pattern + do { + pattern = Pattern.compile(regex) + try pattern.validate() + } catch { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Pattern syntax error: \(regex)") + } + return try getElementsByAttributeValueMatching(key, pattern) + } + + /** + * Find elements whose sibling index is less than the supplied index. + * @param index 0-based index + * @return elements less than index + */ + public func getElementsByIndexLessThan(_ index: Int)throws->Elements { + return try Collector.collect(Evaluator.IndexLessThan(index), self) + } + + /** + * Find elements whose sibling index is greater than the supplied index. + * @param index 0-based index + * @return elements greater than index + */ + public func getElementsByIndexGreaterThan(_ index: Int)throws->Elements { + return try Collector.collect(Evaluator.IndexGreaterThan(index), self) + } + + /** + * Find elements whose sibling index is equal to the supplied index. + * @param index 0-based index + * @return elements equal to index + */ + public func getElementsByIndexEquals(_ index: Int)throws->Elements { + return try Collector.collect(Evaluator.IndexEquals(index), self) + } + + /** + * Find elements that contain the specified string. The search is case insensitive. The text may appear directly + * in the element, or in any of its descendants. + * @param searchText to look for in the element's text + * @return elements that contain the string, case insensitive. + * @see Element#text() + */ + public func getElementsContainingText(_ searchText: String)throws->Elements { + return try Collector.collect(Evaluator.ContainsText(searchText), self) + } + + /** + * Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly + * in the element, not in any of its descendants. + * @param searchText to look for in the element's own text + * @return elements that contain the string, case insensitive. + * @see Element#ownText() + */ + public func getElementsContainingOwnText(_ searchText: String)throws->Elements { + return try Collector.collect(Evaluator.ContainsOwnText(searchText), self) + } + + /** + * Find elements whose text matches the supplied regular expression. + * @param pattern regular expression to match text against + * @return elements matching the supplied regular expression. + * @see Element#text() + */ + public func getElementsMatchingText(_ pattern: Pattern)throws->Elements { + return try Collector.collect(Evaluator.Matches(pattern), self) + } + + /** + * Find elements whose text matches the supplied regular expression. + * @param regex regular expression to match text against. You can use embedded flags (such as (?i) and (?m) to control regex options. + * @return elements matching the supplied regular expression. + * @see Element#text() + */ + public func getElementsMatchingText(_ regex: String)throws->Elements { + let pattern: Pattern + do { + pattern = Pattern.compile(regex) + try pattern.validate() + } catch { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Pattern syntax error: \(regex)") + } + return try getElementsMatchingText(pattern) + } + + /** + * Find elements whose own text matches the supplied regular expression. + * @param pattern regular expression to match text against + * @return elements matching the supplied regular expression. + * @see Element#ownText() + */ + public func getElementsMatchingOwnText(_ pattern: Pattern)throws->Elements { + return try Collector.collect(Evaluator.MatchesOwn(pattern), self) + } + + /** + * Find elements whose text matches the supplied regular expression. + * @param regex regular expression to match text against. You can use embedded flags (such as (?i) and (?m) to control regex options. + * @return elements matching the supplied regular expression. + * @see Element#ownText() + */ + public func getElementsMatchingOwnText(_ regex: String)throws->Elements { + let pattern: Pattern + do { + pattern = Pattern.compile(regex) + try pattern.validate() + } catch { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Pattern syntax error: \(regex)") + } + return try getElementsMatchingOwnText(pattern) + } + + /** + * Find all elements under this element (including self, and children of children). + * + * @return all elements + */ + public func getAllElements()throws->Elements { + return try Collector.collect(Evaluator.AllElements(), self) + } + + /** + * Gets the combined text of this element and all its children. Whitespace is normalized and trimmed. + *

    + * For example, given HTML {@code

    Hello there now!

    }, {@code p.text()} returns {@code "Hello there now!"} + * + * @return unencoded text, or empty string if none. + * @see #ownText() + * @see #textNodes() + */ + class textNodeVisitor: NodeVisitor { + let accum: StringBuilder + init(_ accum: StringBuilder) { + self.accum = accum + } + public func head(_ node: Node, _ depth: Int) { + if let textNode = (node as? TextNode) { + Element.appendNormalisedText(accum, textNode) + } else if let element = (node as? Element) { + if (accum.length > 0 && + (element.isBlock() || element._tag.getName() == "br") && + !TextNode.lastCharIsWhitespace(accum)) { + accum.append(" ") + } + } + } + + public func tail(_ node: Node, _ depth: Int) { + } + } + public func text()throws->String { + let accum: StringBuilder = StringBuilder() + try NodeTraversor(textNodeVisitor(accum)).traverse(self) + return accum.toString().trim() + } + + /** + * Gets the text owned by this element only; does not get the combined text of all children. + *

    + * For example, given HTML {@code

    Hello there now!

    }, {@code p.ownText()} returns {@code "Hello now!"}, + * whereas {@code p.text()} returns {@code "Hello there now!"}. + * Note that the text within the {@code b} element is not returned, as it is not a direct child of the {@code p} element. + * + * @return unencoded text, or empty string if none. + * @see #text() + * @see #textNodes() + */ + public func ownText() -> String { + let sb: StringBuilder = StringBuilder() + ownText(sb) + return sb.toString().trim() + } + + private func ownText(_ accum: StringBuilder) { + for child: Node in childNodes { + if let textNode = (child as? TextNode) { + Element.appendNormalisedText(accum, textNode) + } else if let child = (child as? Element) { + Element.appendWhitespaceIfBr(child, accum) + } + } + } + + private static func appendNormalisedText(_ accum: StringBuilder, _ textNode: TextNode) { + let text: String = textNode.getWholeText() + + if (Element.preserveWhitespace(textNode.parentNode)) { + accum.append(text) + } else { + StringUtil.appendNormalisedWhitespace(accum, string: text, stripLeading: TextNode.lastCharIsWhitespace(accum)) + } + } + + private static func appendWhitespaceIfBr(_ element: Element, _ accum: StringBuilder) { + if (element._tag.getName() == "br" && !TextNode.lastCharIsWhitespace(accum)) { + accum.append(" ") + } + } + + static func preserveWhitespace(_ node: Node?) -> Bool { + // looks only at this element and one level up, to prevent recursion & needless stack searches + if let element = (node as? Element) { + return element._tag.preserveWhitespace() || element.parent() != nil && element.parent()!._tag.preserveWhitespace() + } + return false + } + + /** + * Set the text of this element. Any existing contents (text or elements) will be cleared + * @param text unencoded text + * @return this element + */ + @discardableResult + public func text(_ text: String)throws->Element { + empty() + let textNode: TextNode = TextNode(text, baseUri) + try appendChild(textNode) + return self + } + + /** + Test if this element has any text content (that is not just whitespace). + @return true if element has non-blank text content. + */ + public func hasText() -> Bool { + for child: Node in childNodes { + if let textNode = (child as? TextNode) { + if (!textNode.isBlank()) { + return true + } + } else if let el = (child as? Element) { + if (el.hasText()) { + return true + } + } + } + return false + } + + /** + * Get the combined data of this element. Data is e.g. the inside of a {@code script} tag. + * @return the data, or empty string if none + * + * @see #dataNodes() + */ + public func data() -> String { + let sb: StringBuilder = StringBuilder() + + for childNode: Node in childNodes { + if let data = (childNode as? DataNode) { + sb.append(data.getWholeData()) + } else if let element = (childNode as? Element) { + let elementData: String = element.data() + sb.append(elementData) + } + } + return sb.toString() + } + + /** + * Gets the literal value of this element's "class" attribute, which may include multiple class names, space + * separated. (E.g. on <div class="header gray"> returns, "header gray") + * @return The literal class attribute, or empty string if no class attribute set. + */ + public func className()throws->String { + return try attr(Element.classString).trim() + } + + /** + * Get all of the element's class names. E.g. on element {@code
    }, + * returns a set of two elements {@code "header", "gray"}. Note that modifications to this set are not pushed to + * the backing {@code class} attribute; use the {@link #classNames(java.util.Set)} method to persist them. + * @return set of classnames, empty if no class attribute + */ + public func classNames()throws->OrderedSet { + let fitted = try className().replaceAll(of: Element.classSplit, with: " ", options: .caseInsensitive) + let names: [String] = fitted.components(separatedBy: " ") + let classNames: OrderedSet = OrderedSet(sequence: names) + classNames.remove(Element.emptyString) // if classNames() was empty, would include an empty class + return classNames + } + + /** + Set the element's {@code class} attribute to the supplied class names. + @param classNames set of classes + @return this element, for chaining + */ + @discardableResult + public func classNames(_ classNames: OrderedSet)throws->Element { + try attributes?.put(Element.classString, StringUtil.join(classNames, sep: " ")) + return self + } + + /** + * Tests if this element has a class. Case insensitive. + * @param className name of class to check for + * @return true if it does, false if not + */ + // performance sensitive + public func hasClass(_ className: String) -> Bool { + let classAtt: String? = attributes?.get(key: Element.classString) + let len: Int = (classAtt != nil) ? classAtt!.count : 0 + let wantLen: Int = className.count + + if (len == 0 || len < wantLen) { + return false + } + let classAttr = classAtt! + + // if both lengths are equal, only need compare the className with the attribute + if (len == wantLen) { + return className.equalsIgnoreCase(string: classAttr) + } + + // otherwise, scan for whitespace and compare regions (with no string or arraylist allocations) + var inClass: Bool = false + var start: Int = 0 + for i in 0..Element { + let classes: OrderedSet = try classNames() + classes.append(className) + try classNames(classes) + return self + } + + /** + Remove a class name from this element's {@code class} attribute. + @param className class name to remove + @return this element + */ + @discardableResult + public func removeClass(_ className: String)throws->Element { + let classes: OrderedSet = try classNames() + classes.remove(className) + try classNames(classes) + return self + } + + /** + Toggle a class name on this element's {@code class} attribute: if present, remove it; otherwise add it. + @param className class name to toggle + @return this element + */ + @discardableResult + public func toggleClass(_ className: String)throws->Element { + let classes: OrderedSet = try classNames() + if (classes.contains(className)) {classes.remove(className) + } else { + classes.append(className) + } + try classNames(classes) + + return self + } + + /** + * Get the value of a form element (input, textarea, etc). + * @return the value of the form element, or empty string if not set. + */ + public func val()throws->String { + if (tagName()=="textarea") { + return try text() + } else { + return try attr("value") + } + } + + /** + * Set the value of a form element (input, textarea, etc). + * @param value value to set + * @return this element (for chaining) + */ + @discardableResult + public func val(_ value: String)throws->Element { + if (tagName() == "textarea") { + try text(value) + } else { + try attr("value", value) + } + return self + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings)throws { + if (out.prettyPrint() && (_tag.formatAsBlock() || (parent() != nil && parent()!.tag().formatAsBlock()) || out.outline())) { + if (accum.length > 0) { + indent(accum, depth, out) + } + } + accum + .append("<") + .append(tagName()) + try attributes?.html(accum: accum, out: out) + + // selfclosing includes unknown tags, isEmpty defines tags that are always empty + if (childNodes.isEmpty && _tag.isSelfClosing()) { + if (out.syntax() == OutputSettings.Syntax.html && _tag.isEmpty()) { + accum.append(">") + } else { + accum.append(" />") // in html, in xml + } + } else { + accum.append(">") + } + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + if (!(childNodes.isEmpty && _tag.isSelfClosing())) { + if (out.prettyPrint() && (!childNodes.isEmpty && ( + _tag.formatAsBlock() || (out.outline() && (childNodes.count>1 || (childNodes.count==1 && !(((childNodes[0] as? TextNode) != nil))))) + ))) { + indent(accum, depth, out) + } + accum.append("") + } + } + + /** + * Retrieves the element's inner HTML. E.g. on a {@code
    } with one empty {@code

    }, would return + * {@code

    }. (Whereas {@link #outerHtml()} would return {@code

    }.) + * + * @return String of HTML. + * @see #outerHtml() + */ + public func html()throws->String { + let accum: StringBuilder = StringBuilder() + try html2(accum) + return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString() + } + + private func html2(_ accum: StringBuilder)throws { + for node in childNodes { + try node.outerHtml(accum) + } + } + + /** + * {@inheritDoc} + */ + open override func html(_ appendable: StringBuilder)throws->StringBuilder { + for node in childNodes { + try node.outerHtml(appendable) + } + return appendable + } + + /** + * Set this element's inner HTML. Clears the existing HTML first. + * @param html HTML to parse and set into this element + * @return this element + * @see #append(String) + */ + @discardableResult + public func html(_ html: String)throws->Element { + empty() + try append(html) + return self + } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = Element(_tag, baseUri!, attributes!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = Element(_tag, baseUri!, attributes!) + return copy(clone: clone, parent: parent) + } + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } + + override public var hashValue: Int { + return super.hashValue ^ _tag.hashValue + } + +} diff --git a/Pods/SwiftSoup/Sources/Elements.swift b/Pods/SwiftSoup/Sources/Elements.swift new file mode 100644 index 0000000..e8a3d1e --- /dev/null +++ b/Pods/SwiftSoup/Sources/Elements.swift @@ -0,0 +1,616 @@ +// +// Elements.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 20/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// +/** +A list of {@link Element}s, with methods that act on every element in the list. +

    +To get an {@code Elements} object, use the {@link Element#select(String)} method. +

    +*/ + +import Foundation + +//open typealias Elements = Array +//typealias E = Element +open class Elements: NSCopying { + fileprivate var this: Array = Array() + + ///base init + public init() { + } + ///Initialized with an array + public init(_ a: Array) { + this = a + } + ///Initialized with an order set + public init(_ a: OrderedSet) { + this.append(contentsOf: a) + } + + /** + * Creates a deep copy of these elements. + * @return a deep copy + */ + public func copy(with zone: NSZone? = nil) -> Any { + let clone: Elements = Elements() + for e: Element in this { + clone.add(e.copy() as! Element) + } + return clone + } + + // attribute methods + /** + Get an attribute value from the first matched element that has the attribute. + @param attributeKey The attribute key. + @return The attribute value from the first matched element that has the attribute.. If no elements were matched (isEmpty() == true), + or if the no elements have the attribute, returns empty string. + @see #hasAttr(String) + */ + open func attr(_ attributeKey: String)throws->String { + for element in this { + if (element.hasAttr(attributeKey)) { + return try element.attr(attributeKey) + } + } + return "" + } + + /** + Checks if any of the matched elements have this attribute set. + @param attributeKey attribute key + @return true if any of the elements have the attribute; false if none do. + */ + open func hasAttr(_ attributeKey: String) -> Bool { + for element in this { + if element.hasAttr(attributeKey) {return true} + } + return false + } + + /** + * Set an attribute on all matched elements. + * @param attributeKey attribute key + * @param attributeValue attribute value + * @return this + */ + @discardableResult + open func attr(_ attributeKey: String, _ attributeValue: String)throws->Elements { + for element in this { + try element.attr(attributeKey, attributeValue) + } + return self + } + + /** + * Remove an attribute from every matched element. + * @param attributeKey The attribute to remove. + * @return this (for chaining) + */ + @discardableResult + open func removeAttr(_ attributeKey: String)throws->Elements { + for element in this { + try element.removeAttr(attributeKey) + } + return self + } + + /** + Add the class name to every matched element's {@code class} attribute. + @param className class name to add + @return this + */ + @discardableResult + open func addClass(_ className: String)throws->Elements { + for element in this { + try element.addClass(className) + } + return self + } + + /** + Remove the class name from every matched element's {@code class} attribute, if present. + @param className class name to remove + @return this + */ + @discardableResult + open func removeClass(_ className: String)throws->Elements { + for element: Element in this { + try element.removeClass(className) + } + return self + } + + /** + Toggle the class name on every matched element's {@code class} attribute. + @param className class name to add if missing, or remove if present, from every element. + @return this + */ + @discardableResult + open func toggleClass(_ className: String)throws->Elements { + for element: Element in this { + try element.toggleClass(className) + } + return self + } + + /** + Determine if any of the matched elements have this class name set in their {@code class} attribute. + @param className class name to check for + @return true if any do, false if none do + */ + + open func hasClass(_ className: String) -> Bool { + for element: Element in this { + if (element.hasClass(className)) { + return true + } + } + return false + } + + /** + * Get the form element's value of the first matched element. + * @return The form element's value, or empty if not set. + * @see Element#val() + */ + open func val()throws->String { + if (size() > 0) { + return try first()!.val() + } + return "" + } + + /** + * Set the form element's value in each of the matched elements. + * @param value The value to set into each matched element + * @return this (for chaining) + */ + @discardableResult + open func val(_ value: String)throws->Elements { + for element: Element in this { + try element.val(value) + } + return self + } + + /** + * Get the combined text of all the matched elements. + *

    + * Note that it is possible to get repeats if the matched elements contain both parent elements and their own + * children, as the Element.text() method returns the combined text of a parent and all its children. + * @return string of all text: unescaped and no HTML. + * @see Element#text() + */ + open func text()throws->String { + let sb: StringBuilder = StringBuilder() + for element: Element in this { + if (sb.length != 0) { + sb.append(" ") + } + sb.append(try element.text()) + } + return sb.toString() + } + + /// Check if an element has text + open func hasText() -> Bool { + for element: Element in this { + if (element.hasText()) { + return true + } + } + return false + } + + /** + * Get the combined inner HTML of all matched elements. + * @return string of all element's inner HTML. + * @see #text() + * @see #outerHtml() + */ + open func html()throws->String { + let sb: StringBuilder = StringBuilder() + for element: Element in this { + if (sb.length != 0) { + sb.append("\n") + } + sb.append(try element.html()) + } + return sb.toString() + } + + /** + * Get the combined outer HTML of all matched elements. + * @return string of all element's outer HTML. + * @see #text() + * @see #html() + */ + open func outerHtml()throws->String { + let sb: StringBuilder = StringBuilder() + for element in this { + if (sb.length != 0) { + sb.append("\n") + } + sb.append(try element.outerHtml()) + } + return sb.toString() + } + + /** + * Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}. + * @return string of all element's outer HTML. + * @see #text() + * @see #html() + */ + + open func toString()throws->String { + return try outerHtml() + } + + /** + * Update the tag name of each matched element. For example, to change each {@code } to a {@code }, do + * {@code doc.select("i").tagName("em");} + * @param tagName the new tag name + * @return this, for chaining + * @see Element#tagName(String) + */ + @discardableResult + open func tagName(_ tagName: String)throws->Elements { + for element: Element in this { + try element.tagName(tagName) + } + return self + } + + /** + * Set the inner HTML of each matched element. + * @param html HTML to parse and set into each matched element. + * @return this, for chaining + * @see Element#html(String) + */ + @discardableResult + open func html(_ html: String)throws->Elements { + for element: Element in this { + try element.html(html) + } + return self + } + + /** + * Add the supplied HTML to the start of each matched element's inner HTML. + * @param html HTML to add inside each element, before the existing HTML + * @return this, for chaining + * @see Element#prepend(String) + */ + @discardableResult + open func prepend(_ html: String)throws->Elements { + for element: Element in this { + try element.prepend(html) + } + return self + } + + /** + * Add the supplied HTML to the end of each matched element's inner HTML. + * @param html HTML to add inside each element, after the existing HTML + * @return this, for chaining + * @see Element#append(String) + */ + @discardableResult + open func append(_ html: String)throws->Elements { + for element: Element in this { + try element.append(html) + } + return self + } + + /** + * Insert the supplied HTML before each matched element's outer HTML. + * @param html HTML to insert before each element + * @return this, for chaining + * @see Element#before(String) + */ + @discardableResult + open func before(_ html: String)throws->Elements { + for element: Element in this { + try element.before(html) + } + return self + } + + /** + * Insert the supplied HTML after each matched element's outer HTML. + * @param html HTML to insert after each element + * @return this, for chaining + * @see Element#after(String) + */ + @discardableResult + open func after(_ html: String)throws->Elements { + for element: Element in this { + try element.after(html) + } + return self + } + + /** + Wrap the supplied HTML around each matched elements. For example, with HTML + {@code

    This is Jsoup

    }, + doc.select("b").wrap("<i></i>"); + becomes {@code

    This is jsoup

    } + @param html HTML to wrap around each element, e.g. {@code
    }. Can be arbitrarily deep. + @return this (for chaining) + @see Element#wrap + */ + @discardableResult + open func wrap(_ html: String)throws->Elements { + try Validate.notEmpty(string: html) + for element: Element in this { + try element.wrap(html) + } + return self + } + + /** + * Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of + * dropping the elements but keeping their children. + *

    + * This is useful for e.g removing unwanted formatting elements but keeping their contents. + *

    + * + * E.g. with HTML:

    {@code

    One Two
    }

    + *

    {@code doc.select("font").unwrap();}

    + *

    HTML = {@code

    One Two
    }

    + * + * @return this (for chaining) + * @see Node#unwrap + */ + @discardableResult + open func unwrap()throws->Elements { + for element: Element in this { + try element.unwrap() + } + return self + } + + /** + * Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each + * element to nothing. + *

    + * E.g. HTML: {@code

    Hello there

    now

    }
    + * doc.select("p").empty();
    + * HTML = {@code

    } + * @return this, for chaining + * @see Element#empty() + * @see #remove() + */ + @discardableResult + open func empty() -> Elements { + for element: Element in this { + element.empty() + } + return self + } + + /** + * Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing. + *

    + * E.g. HTML: {@code

    Hello

    there

    }
    + * doc.select("p").remove();
    + * HTML = {@code
    } + *

    + * Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML. + * @return this, for chaining + * @see Element#empty() + * @see #empty() + */ + @discardableResult + open func remove()throws->Elements { + for element in this { + try element.remove() + } + return self + } + + // filters + + /** + * Find matching elements within this element list. + * @param query A {@link Selector} query + * @return the filtered list of elements, or an empty list if none match. + */ + open func select(_ query: String)throws->Elements { + return try Selector.select(query, this) + } + + /** + * Remove elements from this list that match the {@link Selector} query. + *

    + * E.g. HTML: {@code

    Two
    }
    + * Elements divs = doc.select("div").not(".logo");
    + * Result: {@code divs: [
    Two
    ]} + *

    + * @param query the selector query whose results should be removed from these elements + * @return a new elements list that contains only the filtered results + */ + open func not(_ query: String)throws->Elements { + let out: Elements = try Selector.select(query, this) + return Selector.filterOut(this, out.this) + } + + /** + * Get the nth matched element as an Elements object. + *

    + * See also {@link #get(int)} to retrieve an Element. + * @param index the (zero-based) index of the element in the list to retain + * @return Elements containing only the specified element, or, if that element did not exist, an empty list. + */ + open func eq(_ index: Int) -> Elements { + return size() > index ? Elements([get(index)]) : Elements() + } + + /** + * Test if any of the matched elements match the supplied query. + * @param query A selector + * @return true if at least one element in the list matches the query. + */ + open func iS(_ query: String)throws->Bool { + let eval: Evaluator = try QueryParser.parse(query) + for e: Element in this { + if (try e.iS(eval)) { + return true + } + } + return false + + } + + /** + * Get all of the parents and ancestor elements of the matched elements. + * @return all of the parents and ancestor elements of the matched elements + */ + + open func parents() -> Elements { + let combo: OrderedSet = OrderedSet() + for e: Element in this { + combo.append(contentsOf: e.parents().array()) + } + return Elements(combo) + } + + // list-like methods + /** + Get the first matched element. + @return The first matched element, or null if contents is empty. + */ + open func first() -> Element? { + return isEmpty() ? nil : get(0) + } + + /// Check if no element stored + open func isEmpty() -> Bool { + return array().count == 0 + } + + /// Count + open func size() -> Int { + return array().count + } + + /** + Get the last matched element. + @return The last matched element, or null if contents is empty. + */ + open func last() -> Element? { + return isEmpty() ? nil : get(size() - 1) + } + + /** + * Perform a depth-first traversal on each of the selected elements. + * @param nodeVisitor the visitor callbacks to perform on each node + * @return this, for chaining + */ + @discardableResult + open func traverse(_ nodeVisitor: NodeVisitor)throws->Elements { + let traversor: NodeTraversor = NodeTraversor(nodeVisitor) + for el: Element in this { + try traversor.traverse(el) + } + return self + } + + /** + * Get the {@link FormElement} forms from the selected elements, if any. + * @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain + * no forms. + */ + open func forms()->Array { + var forms: Array = Array() + for el: Element in this { + if let el = el as? FormElement { + forms.append(el) + } + } + return forms + } + + /** + * Appends the specified element to the end of this list. + * + * @param e element to be appended to this list + * @return true (as specified by {@link Collection#add}) + */ + open func add(_ e: Element) { + this.append(e) + } + + /** + * Insert the specified element at index. + */ + open func add(_ index: Int, _ element: Element) { + this.insert(element, at: index) + } + + /// Return element at index + open func get(_ i: Int) -> Element { + return this[i] + } + + /// Returns all elements + open func array()->Array { + return this + } +} + +/** +* Elements extension Equatable. +*/ +extension Elements: Equatable { + /// Returns a Boolean value indicating whether two values are equal. + /// + /// Equality is the inverse of inequality. For any values `a` and `b`, + /// `a == b` implies that `a != b` is `false`. + /// + /// - Parameters: + /// - lhs: A value to compare. + /// - rhs: Another value to compare. + public static func ==(lhs: Elements, rhs: Elements) -> Bool { + return lhs.this == rhs.this + } +} + +/** +* Elements IteratorProtocol. +*/ +public struct ElementsIterator: IteratorProtocol { + /// Elements reference + let elements: Elements + //current element index + var index = 0 + + /// Initializer + init(_ countdown: Elements) { + self.elements = countdown + } + + /// Advances to the next element and returns it, or `nil` if no next element + mutating public func next() -> Element? { + let result = index < elements.size() ? elements.get(index) : nil + index += 1 + return result + } +} + +/** +* Elements Extension Sequence. +*/ +extension Elements: Sequence { + /// Returns an iterator over the elements of this sequence. + public func makeIterator() -> ElementsIterator { + return ElementsIterator(self) + } +} diff --git a/Pods/SwiftSoup/Sources/Entities.swift b/Pods/SwiftSoup/Sources/Entities.swift new file mode 100644 index 0000000..0ceb968 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Entities.swift @@ -0,0 +1,382 @@ +// +// Entities.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * HTML entities, and escape routines. + * Source: W3C HTML + * named character references. + */ +public class Entities { + private static let empty = -1 + private static let emptyName = "" + private static let codepointRadix: Int = 36 + + public struct EscapeMode: Equatable { + + /** Restricted entities suitable for XHTML output: lt, gt, amp, and quot only. */ + public static let xhtml: EscapeMode = EscapeMode(string: Entities.xhtml, size: 4, id: 0) + /** Default HTML output entities. */ + public static let base: EscapeMode = EscapeMode(string: Entities.base, size: 106, id: 1) + /** Complete HTML entities. */ + public static let extended: EscapeMode = EscapeMode(string: Entities.full, size: 2125, id: 2) + + fileprivate let value: Int + + // table of named references to their codepoints. sorted so we can binary search. built by BuildEntities. + fileprivate var nameKeys: [String] + fileprivate var codeVals: [Int] // limitation is the few references with multiple characters; those go into multipoints. + + // table of codepoints to named entities. + fileprivate var codeKeys: [Int] // we don' support multicodepoints to single named value currently + fileprivate var nameVals: [String] + + public static func == (left: EscapeMode, right: EscapeMode) -> Bool { + return left.value == right.value + } + + static func != (left: EscapeMode, right: EscapeMode) -> Bool { + return left.value != right.value + } + + private static let codeDelims: [UnicodeScalar] = [",", ";"] + + init(string: String, size: Int, id: Int) { + nameKeys = [String](repeating: "", count: size) + codeVals = [Int](repeating: 0, count: size) + codeKeys = [Int](repeating: 0, count: size) + nameVals = [String](repeating: "", count: size) + value = id + + //Load() + + var i = 0 + + let reader: CharacterReader = CharacterReader(string) + + while (!reader.isEmpty()) { + // NotNestedLessLess=10913,824;1887 + + let name: String = reader.consumeTo("=") + reader.advance() + let cp1: Int = Int(reader.consumeToAny(EscapeMode.codeDelims), radix: codepointRadix) ?? 0 + let codeDelim: UnicodeScalar = reader.current() + reader.advance() + let cp2: Int + if (codeDelim == ",") { + cp2 = Int(reader.consumeTo(";"), radix: codepointRadix) ?? 0 + reader.advance() + } else { + cp2 = empty + } + let index: Int = Int(reader.consumeTo("\n"), radix: codepointRadix) ?? 0 + reader.advance() + + nameKeys[i] = name + codeVals[i] = cp1 + codeKeys[index] = cp1 + nameVals[index] = name + + if (cp2 != empty) { + var s = String() + s.append(Character(UnicodeScalar(cp1)!)) + s.append(Character(UnicodeScalar(cp2)!)) + multipoints[name] = s + } + i = i + 1 + } + } + +// init(string: String, size: Int, id: Int) { +// nameKeys = [String](repeating: "", count: size) +// codeVals = [Int](repeating: 0, count: size) +// codeKeys = [Int](repeating: 0, count: size) +// nameVals = [String](repeating: "", count: size) +// value = id +// +// let components = string.components(separatedBy: "\n") +// +// var i = 0 +// for entry in components { +// let match = Entities.entityPattern.matcher(in: entry) +// if (match.find()) { +// let name = match.group(1)! +// let cp1 = Int(match.group(2)!, radix: codepointRadix) +// //let cp2 = Int(Int.parseInt(s: match.group(3), radix: codepointRadix)) +// let cp2 = match.group(3) != nil ? Int(match.group(3)!, radix: codepointRadix) : empty +// let index = Int(match.group(4)!, radix: codepointRadix) +// +// nameKeys[i] = name +// codeVals[i] = cp1! +// codeKeys[index!] = cp1! +// nameVals[index!] = name +// +// if (cp2 != empty) { +// var s = String() +// s.append(Character(UnicodeScalar(cp1!)!)) +// s.append(Character(UnicodeScalar(cp2!)!)) +// multipoints[name] = s +// } +// i += 1 +// } +// } +// } + + public func codepointForName(_ name: String) -> Int { +// for s in nameKeys { +// if s == name { +// return codeVals[nameKeys.index(of: s)!] +// } +// } + guard let index = nameKeys.index(of: name) else { + return empty + } + return codeVals[index] + } + + public func nameForCodepoint(_ codepoint: Int ) -> String { + //let ss = codeKeys.index(of: codepoint) + + var index = -1 + for s in codeKeys { + if s == codepoint { + index = codeKeys.index(of: codepoint)! + } + } + + if (index >= 0) { + // the results are ordered so lower case versions of same codepoint come after uppercase, and we prefer to emit lower + // (and binary search for same item with multi results is undefined + return (index < nameVals.count-1 && codeKeys[index+1] == codepoint) ? + nameVals[index+1] : nameVals[index] + } + return emptyName + } + + private func size() -> Int { + return nameKeys.count + } + + } + + private static var multipoints: Dictionary = Dictionary() // name -> multiple character references + + private init() { + } + + /** + * Check if the input is a known named entity + * @param name the possible entity name (e.g. "lt" or "amp") + * @return true if a known named entity + */ + public static func isNamedEntity(_ name: String ) -> Bool { + return (EscapeMode.extended.codepointForName(name) != empty) + } + + /** + * Check if the input is a known named entity in the base entity set. + * @param name the possible entity name (e.g. "lt" or "amp") + * @return true if a known named entity in the base set + * @see #isNamedEntity(String) + */ + public static func isBaseNamedEntity(_ name: String) -> Bool { + return EscapeMode.base.codepointForName(name) != empty + } + + /** + * Get the Character value of the named entity + * @param name named entity (e.g. "lt" or "amp") + * @return the Character value of the named entity (e.g. '{@literal <}' or '{@literal &}') + * @deprecated does not support characters outside the BMP or multiple character names + */ + public static func getCharacterByName(name: String) -> Character { + return Character.convertFromIntegerLiteral(value: EscapeMode.extended.codepointForName(name)) + } + + /** + * Get the character(s) represented by the named entitiy + * @param name entity (e.g. "lt" or "amp") + * @return the string value of the character(s) represented by this entity, or "" if not defined + */ + public static func getByName(name: String) -> String { + let val = multipoints[name] + if (val != nil) {return val!} + let codepoint = EscapeMode.extended.codepointForName(name) + if (codepoint != empty) { + return String(Character(UnicodeScalar(codepoint)!)) + } + return emptyName + } + + public static func codepointsForName(_ name: String, codepoints: inout [UnicodeScalar]) -> Int { + + if let val: String = multipoints[name] { + codepoints[0] = val.unicodeScalar(0) + codepoints[1] = val.unicodeScalar(1) + return 2 + } + + let codepoint = EscapeMode.extended.codepointForName(name) + if (codepoint != empty) { + codepoints[0] = UnicodeScalar(codepoint)! + return 1 + } + return 0 + } + + public static func escape(_ string: String, _ encode: String.Encoding = .utf8 ) -> String { + return Entities.escape(string, OutputSettings().charset(encode).escapeMode(Entities.EscapeMode.extended)) + } + + public static func escape(_ string: String, _ out: OutputSettings) -> String { + let accum = StringBuilder()//string.characters.count * 2 + escape(accum, string, out, false, false, false) + // try { + // + // } catch (IOException e) { + // throw new SerializationException(e) // doesn't happen + // } + return accum.toString() + } + + // this method is ugly, and does a lot. but other breakups cause rescanning and stringbuilder generations + static func escape(_ accum: StringBuilder, _ string: String, _ out: OutputSettings, _ inAttribute: Bool, _ normaliseWhite: Bool, _ stripLeadingWhite: Bool ) { + var lastWasWhite = false + var reachedNonWhite = false + let escapeMode: EscapeMode = out.escapeMode() + let encoder: String.Encoding = out.encoder() + //let length = UInt32(string.characters.count) + + var codePoint: UnicodeScalar + for ch in string.unicodeScalars { + codePoint = ch + + if (normaliseWhite) { + if (codePoint.isWhitespace) { + if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite) { + continue + } + accum.append(UnicodeScalar.Space) + lastWasWhite = true + continue + } else { + lastWasWhite = false + reachedNonWhite = true + } + } + + // surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]): + if (codePoint.value < Character.MIN_SUPPLEMENTARY_CODE_POINT) { + let c = codePoint + // html specific and required escapes: + switch (codePoint) { + case UnicodeScalar.Ampersand: + accum.append("&") + break + case UnicodeScalar(UInt32(0xA0))!: + if (escapeMode != EscapeMode.xhtml) { + accum.append(" ") + } else { + accum.append(" ") + } + break + case UnicodeScalar.LessThan: + // escape when in character data or when in a xml attribue val; not needed in html attr val + if (!inAttribute || escapeMode == EscapeMode.xhtml) { + accum.append("<") + } else { + accum.append(c) + } + break + case UnicodeScalar.GreaterThan: + if (!inAttribute) { + accum.append(">") + } else { + accum.append(c)} + break + case "\"": + if (inAttribute) { + accum.append(""") + } else { + accum.append(c) + } + break + default: + if (canEncode(c, encoder)) { + accum.append(c) + } else { + appendEncoded(accum: accum, escapeMode: escapeMode, codePoint: codePoint) + } + } + } else { + if (encoder.canEncode(String(codePoint))) // uses fallback encoder for simplicity + { + accum.append(String(codePoint)) + } else { + appendEncoded(accum: accum, escapeMode: escapeMode, codePoint: codePoint) + } + } + } + } + + private static func appendEncoded(accum: StringBuilder, escapeMode: EscapeMode, codePoint: UnicodeScalar) { + let name = escapeMode.nameForCodepoint(Int(codePoint.value)) + if (name != emptyName) // ok for identity check + {accum.append(UnicodeScalar.Ampersand).append(name).append(";") + } else { + accum.append("&#x").append(String.toHexString(n: Int(codePoint.value)) ).append(";") + } + } + + public static func unescape(_ string: String)throws-> String { + return try unescape(string: string, strict: false) + } + + /** + * Unescape the input string. + * @param string to un-HTML-escape + * @param strict if "strict" (that is, requires trailing ';' char, otherwise that's optional) + * @return unescaped string + */ + public static func unescape(string: String, strict: Bool)throws -> String { + return try Parser.unescapeEntities(string, strict) + } + + /* + * Provides a fast-path for Encoder.canEncode, which drastically improves performance on Android post JellyBean. + * After KitKat, the implementation of canEncode degrades to the point of being useless. For non ASCII or UTF, + * performance may be bad. We can add more encoders for common character sets that are impacted by performance + * issues on Android if required. + * + * Benchmarks: * + * OLD toHtml() impl v New (fastpath) in millis + * Wiki: 1895, 16 + * CNN: 6378, 55 + * Alterslash: 3013, 28 + * Jsoup: 167, 2 + */ + private static func canEncode(_ c: UnicodeScalar, _ fallback: String.Encoding) -> Bool { + // todo add more charset tests if impacted by Android's bad perf in canEncode + switch (fallback) { + case String.Encoding.ascii: + return c.value < 0x80 + case String.Encoding.utf8: + return true // real is:!(Character.isLowSurrogate(c) || Character.isHighSurrogate(c)) - but already check above + default: + return fallback.canEncode(String(Character(c))) + } + } + + static let xhtml: String = "amp=12;1\ngt=1q;3\nlt=1o;2\nquot=y;0" + + static let base: String = "AElig=5i;1c\nAMP=12;2\nAacute=5d;17\nAcirc=5e;18\nAgrave=5c;16\nAring=5h;1b\nAtilde=5f;19\nAuml=5g;1a\nCOPY=4p;h\nCcedil=5j;1d\nETH=5s;1m\nEacute=5l;1f\nEcirc=5m;1g\nEgrave=5k;1e\nEuml=5n;1h\nGT=1q;6\nIacute=5p;1j\nIcirc=5q;1k\nIgrave=5o;1i\nIuml=5r;1l\nLT=1o;4\nNtilde=5t;1n\nOacute=5v;1p\nOcirc=5w;1q\nOgrave=5u;1o\nOslash=60;1u\nOtilde=5x;1r\nOuml=5y;1s\nQUOT=y;0\nREG=4u;n\nTHORN=66;20\nUacute=62;1w\nUcirc=63;1x\nUgrave=61;1v\nUuml=64;1y\nYacute=65;1z\naacute=69;23\nacirc=6a;24\nacute=50;u\naelig=6e;28\nagrave=68;22\namp=12;3\naring=6d;27\natilde=6b;25\nauml=6c;26\nbrvbar=4m;e\nccedil=6f;29\ncedil=54;y\ncent=4i;a\ncopy=4p;i\ncurren=4k;c\ndeg=4w;q\ndivide=6v;2p\neacute=6h;2b\necirc=6i;2c\negrave=6g;2a\neth=6o;2i\neuml=6j;2d\nfrac12=59;13\nfrac14=58;12\nfrac34=5a;14\ngt=1q;7\niacute=6l;2f\nicirc=6m;2g\niexcl=4h;9\nigrave=6k;2e\niquest=5b;15\niuml=6n;2h\nlaquo=4r;k\nlt=1o;5\nmacr=4v;p\nmicro=51;v\nmiddot=53;x\nnbsp=4g;8\nnot=4s;l\nntilde=6p;2j\noacute=6r;2l\nocirc=6s;2m\nograve=6q;2k\nordf=4q;j\nordm=56;10\noslash=6w;2q\notilde=6t;2n\nouml=6u;2o\npara=52;w\nplusmn=4x;r\npound=4j;b\nquot=y;1\nraquo=57;11\nreg=4u;o\nsect=4n;f\nshy=4t;m\nsup1=55;z\nsup2=4y;s\nsup3=4z;t\nszlig=67;21\nthorn=72;2w\ntimes=5z;1t\nuacute=6y;2s\nucirc=6z;2t\nugrave=6x;2r\numl=4o;g\nuuml=70;2u\nyacute=71;2v\nyen=4l;d\nyuml=73;2x" + + static let full: String = "AElig=5i;2v\nAMP=12;8\nAacute=5d;2p\nAbreve=76;4k\nAcirc=5e;2q\nAcy=sw;av\nAfr=2kn8;1kh\nAgrave=5c;2o\nAlpha=pd;8d\nAmacr=74;4i\nAnd=8cz;1e1\nAogon=78;4m\nAopf=2koo;1ls\nApplyFunction=6e9;ew\nAring=5h;2t\nAscr=2kkc;1jc\nAssign=6s4;s6\nAtilde=5f;2r\nAuml=5g;2s\nBackslash=6qe;o1\nBarv=8h3;1it\nBarwed=6x2;120\nBcy=sx;aw\nBecause=6r9;pw\nBernoullis=6jw;gn\nBeta=pe;8e\nBfr=2kn9;1ki\nBopf=2kop;1lt\nBreve=k8;82\nBscr=6jw;gp\nBumpeq=6ry;ro\nCHcy=tj;bi\nCOPY=4p;1q\nCacute=7a;4o\nCap=6vm;zz\nCapitalDifferentialD=6kl;h8\nCayleys=6jx;gq\nCcaron=7g;4u\nCcedil=5j;2w\nCcirc=7c;4q\nCconint=6r4;pn\nCdot=7e;4s\nCedilla=54;2e\nCenterDot=53;2b\nCfr=6jx;gr\nChi=pz;8y\nCircleDot=6u1;x8\nCircleMinus=6ty;x3\nCirclePlus=6tx;x1\nCircleTimes=6tz;x5\nClockwiseContourIntegral=6r6;pp\nCloseCurlyDoubleQuote=6cd;e0\nCloseCurlyQuote=6c9;dt\nColon=6rb;q1\nColone=8dw;1en\nCongruent=6sh;sn\nConint=6r3;pm\nContourIntegral=6r2;pi\nCopf=6iq;f7\nCoproduct=6q8;nq\nCounterClockwiseContourIntegral=6r7;pr\nCross=8bz;1d8\nCscr=2kke;1jd\nCup=6vn;100\nCupCap=6rx;rk\nDD=6kl;h9\nDDotrahd=841;184\nDJcy=si;ai\nDScy=sl;al\nDZcy=sv;au\nDagger=6ch;e7\nDarr=6n5;j5\nDashv=8h0;1ir\nDcaron=7i;4w\nDcy=t0;az\nDel=6pz;n9\nDelta=pg;8g\nDfr=2knb;1kj\nDiacriticalAcute=50;27\nDiacriticalDot=k9;84\nDiacriticalDoubleAcute=kd;8a\nDiacriticalGrave=2o;13\nDiacriticalTilde=kc;88\nDiamond=6v8;za\nDifferentialD=6km;ha\nDopf=2kor;1lu\nDot=4o;1n\nDotDot=6ho;f5\nDotEqual=6s0;rw\nDoubleContourIntegral=6r3;pl\nDoubleDot=4o;1m\nDoubleDownArrow=6oj;m0\nDoubleLeftArrow=6og;lq\nDoubleLeftRightArrow=6ok;m3\nDoubleLeftTee=8h0;1iq\nDoubleLongLeftArrow=7w8;17g\nDoubleLongLeftRightArrow=7wa;17m\nDoubleLongRightArrow=7w9;17j\nDoubleRightArrow=6oi;lw\nDoubleRightTee=6ug;xz\nDoubleUpArrow=6oh;lt\nDoubleUpDownArrow=6ol;m7\nDoubleVerticalBar=6qt;ov\nDownArrow=6mr;i8\nDownArrowBar=843;186\nDownArrowUpArrow=6ph;mn\nDownBreve=lt;8c\nDownLeftRightVector=85s;198\nDownLeftTeeVector=866;19m\nDownLeftVector=6nx;ke\nDownLeftVectorBar=85y;19e\nDownRightTeeVector=867;19n\nDownRightVector=6o1;kq\nDownRightVectorBar=85z;19f\nDownTee=6uc;xs\nDownTeeArrow=6nb;jh\nDownarrow=6oj;m1\nDscr=2kkf;1je\nDstrok=7k;4y\nENG=96;6g\nETH=5s;35\nEacute=5l;2y\nEcaron=7u;56\nEcirc=5m;2z\nEcy=tp;bo\nEdot=7q;52\nEfr=2knc;1kk\nEgrave=5k;2x\nElement=6q0;na\nEmacr=7m;50\nEmptySmallSquare=7i3;15x\nEmptyVerySmallSquare=7fv;150\nEogon=7s;54\nEopf=2kos;1lv\nEpsilon=ph;8h\nEqual=8dx;1eo\nEqualTilde=6rm;qp\nEquilibrium=6oc;li\nEscr=6k0;gu\nEsim=8dv;1em\nEta=pj;8j\nEuml=5n;30\nExists=6pv;mz\nExponentialE=6kn;hc\nFcy=tg;bf\nFfr=2knd;1kl\nFilledSmallSquare=7i4;15y\nFilledVerySmallSquare=7fu;14w\nFopf=2kot;1lw\nForAll=6ps;ms\nFouriertrf=6k1;gv\nFscr=6k1;gw\nGJcy=sj;aj\nGT=1q;r\nGamma=pf;8f\nGammad=rg;a5\nGbreve=7y;5a\nGcedil=82;5e\nGcirc=7w;58\nGcy=sz;ay\nGdot=80;5c\nGfr=2kne;1km\nGg=6vt;10c\nGopf=2kou;1lx\nGreaterEqual=6sl;sv\nGreaterEqualLess=6vv;10i\nGreaterFullEqual=6sn;t6\nGreaterGreater=8f6;1gh\nGreaterLess=6t3;ul\nGreaterSlantEqual=8e6;1f5\nGreaterTilde=6sz;ub\nGscr=2kki;1jf\nGt=6sr;tr\nHARDcy=tm;bl\nHacek=jr;80\nHat=2m;10\nHcirc=84;5f\nHfr=6j0;fe\nHilbertSpace=6iz;fa\nHopf=6j1;fg\nHorizontalLine=7b4;13i\nHscr=6iz;fc\nHstrok=86;5h\nHumpDownHump=6ry;rn\nHumpEqual=6rz;rs\nIEcy=t1;b0\nIJlig=8i;5s\nIOcy=sh;ah\nIacute=5p;32\nIcirc=5q;33\nIcy=t4;b3\nIdot=8g;5p\nIfr=6j5;fq\nIgrave=5o;31\nIm=6j5;fr\nImacr=8a;5l\nImaginaryI=6ko;hf\nImplies=6oi;ly\nInt=6r0;pf\nIntegral=6qz;pd\nIntersection=6v6;z4\nInvisibleComma=6eb;f0\nInvisibleTimes=6ea;ey\nIogon=8e;5n\nIopf=2kow;1ly\nIota=pl;8l\nIscr=6j4;fn\nItilde=88;5j\nIukcy=sm;am\nIuml=5r;34\nJcirc=8k;5u\nJcy=t5;b4\nJfr=2knh;1kn\nJopf=2kox;1lz\nJscr=2kkl;1jg\nJsercy=so;ao\nJukcy=sk;ak\nKHcy=th;bg\nKJcy=ss;as\nKappa=pm;8m\nKcedil=8m;5w\nKcy=t6;b5\nKfr=2kni;1ko\nKopf=2koy;1m0\nKscr=2kkm;1jh\nLJcy=sp;ap\nLT=1o;m\nLacute=8p;5z\nLambda=pn;8n\nLang=7vu;173\nLaplacetrf=6j6;fs\nLarr=6n2;j1\nLcaron=8t;63\nLcedil=8r;61\nLcy=t7;b6\nLeftAngleBracket=7vs;16x\nLeftArrow=6mo;hu\nLeftArrowBar=6p0;mj\nLeftArrowRightArrow=6o6;l3\nLeftCeiling=6x4;121\nLeftDoubleBracket=7vq;16t\nLeftDownTeeVector=869;19p\nLeftDownVector=6o3;kw\nLeftDownVectorBar=861;19h\nLeftFloor=6x6;125\nLeftRightArrow=6ms;ib\nLeftRightVector=85q;196\nLeftTee=6ub;xq\nLeftTeeArrow=6n8;ja\nLeftTeeVector=862;19i\nLeftTriangle=6uq;ya\nLeftTriangleBar=89b;1c0\nLeftTriangleEqual=6us;yg\nLeftUpDownVector=85t;199\nLeftUpTeeVector=868;19o\nLeftUpVector=6nz;kk\nLeftUpVectorBar=860;19g\nLeftVector=6nw;kb\nLeftVectorBar=85u;19a\nLeftarrow=6og;lr\nLeftrightarrow=6ok;m4\nLessEqualGreater=6vu;10e\nLessFullEqual=6sm;t0\nLessGreater=6t2;ui\nLessLess=8f5;1gf\nLessSlantEqual=8e5;1ez\nLessTilde=6sy;u8\nLfr=2knj;1kp\nLl=6vs;109\nLleftarrow=6oq;me\nLmidot=8v;65\nLongLeftArrow=7w5;177\nLongLeftRightArrow=7w7;17d\nLongRightArrow=7w6;17a\nLongleftarrow=7w8;17h\nLongleftrightarrow=7wa;17n\nLongrightarrow=7w9;17k\nLopf=2koz;1m1\nLowerLeftArrow=6mx;iq\nLowerRightArrow=6mw;in\nLscr=6j6;fu\nLsh=6nk;jv\nLstrok=8x;67\nLt=6sq;tl\nMap=83p;17v\nMcy=t8;b7\nMediumSpace=6e7;eu\nMellintrf=6k3;gx\nMfr=2knk;1kq\nMinusPlus=6qb;nv\nMopf=2kp0;1m2\nMscr=6k3;gz\nMu=po;8o\nNJcy=sq;aq\nNacute=8z;69\nNcaron=93;6d\nNcedil=91;6b\nNcy=t9;b8\nNegativeMediumSpace=6bv;dc\nNegativeThickSpace=6bv;dd\nNegativeThinSpace=6bv;de\nNegativeVeryThinSpace=6bv;db\nNestedGreaterGreater=6sr;tq\nNestedLessLess=6sq;tk\nNewLine=a;1\nNfr=2knl;1kr\nNoBreak=6e8;ev\nNonBreakingSpace=4g;1d\nNopf=6j9;fx\nNot=8h8;1ix\nNotCongruent=6si;sp\nNotCupCap=6st;tv\nNotDoubleVerticalBar=6qu;p0\nNotElement=6q1;ne\nNotEqual=6sg;sk\nNotEqualTilde=6rm,mw;qn\nNotExists=6pw;n1\nNotGreater=6sv;tz\nNotGreaterEqual=6sx;u5\nNotGreaterFullEqual=6sn,mw;t3\nNotGreaterGreater=6sr,mw;tn\nNotGreaterLess=6t5;uq\nNotGreaterSlantEqual=8e6,mw;1f2\nNotGreaterTilde=6t1;ug\nNotHumpDownHump=6ry,mw;rl\nNotHumpEqual=6rz,mw;rq\nNotLeftTriangle=6wa;113\nNotLeftTriangleBar=89b,mw;1bz\nNotLeftTriangleEqual=6wc;119\nNotLess=6su;tw\nNotLessEqual=6sw;u2\nNotLessGreater=6t4;uo\nNotLessLess=6sq,mw;th\nNotLessSlantEqual=8e5,mw;1ew\nNotLessTilde=6t0;ue\nNotNestedGreaterGreater=8f6,mw;1gg\nNotNestedLessLess=8f5,mw;1ge\nNotPrecedes=6tc;vb\nNotPrecedesEqual=8fj,mw;1gv\nNotPrecedesSlantEqual=6w0;10p\nNotReverseElement=6q4;nl\nNotRightTriangle=6wb;116\nNotRightTriangleBar=89c,mw;1c1\nNotRightTriangleEqual=6wd;11c\nNotSquareSubset=6tr,mw;wh\nNotSquareSubsetEqual=6w2;10t\nNotSquareSuperset=6ts,mw;wl\nNotSquareSupersetEqual=6w3;10v\nNotSubset=6te,6he;vh\nNotSubsetEqual=6tk;w0\nNotSucceeds=6td;ve\nNotSucceedsEqual=8fk,mw;1h1\nNotSucceedsSlantEqual=6w1;10r\nNotSucceedsTilde=6tb,mw;v7\nNotSuperset=6tf,6he;vm\nNotSupersetEqual=6tl;w3\nNotTilde=6rl;ql\nNotTildeEqual=6ro;qv\nNotTildeFullEqual=6rr;r1\nNotTildeTilde=6rt;r9\nNotVerticalBar=6qs;or\nNscr=2kkp;1ji\nNtilde=5t;36\nNu=pp;8p\nOElig=9e;6m\nOacute=5v;38\nOcirc=5w;39\nOcy=ta;b9\nOdblac=9c;6k\nOfr=2knm;1ks\nOgrave=5u;37\nOmacr=98;6i\nOmega=q1;90\nOmicron=pr;8r\nOopf=2kp2;1m3\nOpenCurlyDoubleQuote=6cc;dy\nOpenCurlyQuote=6c8;dr\nOr=8d0;1e2\nOscr=2kkq;1jj\nOslash=60;3d\nOtilde=5x;3a\nOtimes=8c7;1df\nOuml=5y;3b\nOverBar=6da;em\nOverBrace=732;13b\nOverBracket=71w;134\nOverParenthesis=730;139\nPartialD=6pu;mx\nPcy=tb;ba\nPfr=2knn;1kt\nPhi=py;8x\nPi=ps;8s\nPlusMinus=4x;22\nPoincareplane=6j0;fd\nPopf=6jd;g3\nPr=8fv;1hl\nPrecedes=6t6;us\nPrecedesEqual=8fj;1gy\nPrecedesSlantEqual=6t8;uy\nPrecedesTilde=6ta;v4\nPrime=6cz;eg\nProduct=6q7;no\nProportion=6rb;q0\nProportional=6ql;oa\nPscr=2kkr;1jk\nPsi=q0;8z\nQUOT=y;3\nQfr=2kno;1ku\nQopf=6je;g5\nQscr=2kks;1jl\nRBarr=840;183\nREG=4u;1x\nRacute=9g;6o\nRang=7vv;174\nRarr=6n4;j4\nRarrtl=846;187\nRcaron=9k;6s\nRcedil=9i;6q\nRcy=tc;bb\nRe=6jg;gb\nReverseElement=6q3;nh\nReverseEquilibrium=6ob;le\nReverseUpEquilibrium=86n;1a4\nRfr=6jg;ga\nRho=pt;8t\nRightAngleBracket=7vt;170\nRightArrow=6mq;i3\nRightArrowBar=6p1;ml\nRightArrowLeftArrow=6o4;ky\nRightCeiling=6x5;123\nRightDoubleBracket=7vr;16v\nRightDownTeeVector=865;19l\nRightDownVector=6o2;kt\nRightDownVectorBar=85x;19d\nRightFloor=6x7;127\nRightTee=6ua;xo\nRightTeeArrow=6na;je\nRightTeeVector=863;19j\nRightTriangle=6ur;yd\nRightTriangleBar=89c;1c2\nRightTriangleEqual=6ut;yk\nRightUpDownVector=85r;197\nRightUpTeeVector=864;19k\nRightUpVector=6ny;kh\nRightUpVectorBar=85w;19c\nRightVector=6o0;kn\nRightVectorBar=85v;19b\nRightarrow=6oi;lx\nRopf=6jh;gd\nRoundImplies=86o;1a6\nRrightarrow=6or;mg\nRscr=6jf;g7\nRsh=6nl;jx\nRuleDelayed=8ac;1cb\nSHCHcy=tl;bk\nSHcy=tk;bj\nSOFTcy=to;bn\nSacute=9m;6u\nSc=8fw;1hm\nScaron=9s;70\nScedil=9q;6y\nScirc=9o;6w\nScy=td;bc\nSfr=2knq;1kv\nShortDownArrow=6mr;i7\nShortLeftArrow=6mo;ht\nShortRightArrow=6mq;i2\nShortUpArrow=6mp;hy\nSigma=pv;8u\nSmallCircle=6qg;o6\nSopf=2kp6;1m4\nSqrt=6qi;o9\nSquare=7fl;14t\nSquareIntersection=6tv;ww\nSquareSubset=6tr;wi\nSquareSubsetEqual=6tt;wp\nSquareSuperset=6ts;wm\nSquareSupersetEqual=6tu;ws\nSquareUnion=6tw;wz\nSscr=2kku;1jm\nStar=6va;zf\nSub=6vk;zw\nSubset=6vk;zv\nSubsetEqual=6ti;vu\nSucceeds=6t7;uv\nSucceedsEqual=8fk;1h4\nSucceedsSlantEqual=6t9;v1\nSucceedsTilde=6tb;v8\nSuchThat=6q3;ni\nSum=6q9;ns\nSup=6vl;zy\nSuperset=6tf;vp\nSupersetEqual=6tj;vx\nSupset=6vl;zx\nTHORN=66;3j\nTRADE=6jm;gf\nTSHcy=sr;ar\nTScy=ti;bh\nTab=9;0\nTau=pw;8v\nTcaron=9w;74\nTcedil=9u;72\nTcy=te;bd\nTfr=2knr;1kw\nTherefore=6r8;pt\nTheta=pk;8k\nThickSpace=6e7,6bu;et\nThinSpace=6bt;d7\nTilde=6rg;q9\nTildeEqual=6rn;qs\nTildeFullEqual=6rp;qy\nTildeTilde=6rs;r4\nTopf=2kp7;1m5\nTripleDot=6hn;f3\nTscr=2kkv;1jn\nTstrok=9y;76\nUacute=62;3f\nUarr=6n3;j2\nUarrocir=85l;193\nUbrcy=su;at\nUbreve=a4;7c\nUcirc=63;3g\nUcy=tf;be\nUdblac=a8;7g\nUfr=2kns;1kx\nUgrave=61;3e\nUmacr=a2;7a\nUnderBar=2n;11\nUnderBrace=733;13c\nUnderBracket=71x;136\nUnderParenthesis=731;13a\nUnion=6v7;z8\nUnionPlus=6tq;wf\nUogon=aa;7i\nUopf=2kp8;1m6\nUpArrow=6mp;hz\nUpArrowBar=842;185\nUpArrowDownArrow=6o5;l1\nUpDownArrow=6mt;ie\nUpEquilibrium=86m;1a2\nUpTee=6ud;xv\nUpTeeArrow=6n9;jc\nUparrow=6oh;lu\nUpdownarrow=6ol;m8\nUpperLeftArrow=6mu;ih\nUpperRightArrow=6mv;ik\nUpsi=r6;9z\nUpsilon=px;8w\nUring=a6;7e\nUscr=2kkw;1jo\nUtilde=a0;78\nUuml=64;3h\nVDash=6uj;y3\nVbar=8h7;1iw\nVcy=sy;ax\nVdash=6uh;y1\nVdashl=8h2;1is\nVee=6v5;z3\nVerbar=6c6;dp\nVert=6c6;dq\nVerticalBar=6qr;on\nVerticalLine=3g;18\nVerticalSeparator=7rs;16o\nVerticalTilde=6rk;qi\nVeryThinSpace=6bu;d9\nVfr=2knt;1ky\nVopf=2kp9;1m7\nVscr=2kkx;1jp\nVvdash=6ui;y2\nWcirc=ac;7k\nWedge=6v4;z0\nWfr=2knu;1kz\nWopf=2kpa;1m8\nWscr=2kky;1jq\nXfr=2knv;1l0\nXi=pq;8q\nXopf=2kpb;1m9\nXscr=2kkz;1jr\nYAcy=tr;bq\nYIcy=sn;an\nYUcy=tq;bp\nYacute=65;3i\nYcirc=ae;7m\nYcy=tn;bm\nYfr=2knw;1l1\nYopf=2kpc;1ma\nYscr=2kl0;1js\nYuml=ag;7o\nZHcy=t2;b1\nZacute=ah;7p\nZcaron=al;7t\nZcy=t3;b2\nZdot=aj;7r\nZeroWidthSpace=6bv;df\nZeta=pi;8i\nZfr=6js;gl\nZopf=6jo;gi\nZscr=2kl1;1jt\naacute=69;3m\nabreve=77;4l\nac=6ri;qg\nacE=6ri,mr;qe\nacd=6rj;qh\nacirc=6a;3n\nacute=50;28\nacy=ts;br\naelig=6e;3r\naf=6e9;ex\nafr=2kny;1l2\nagrave=68;3l\nalefsym=6k5;h3\naleph=6k5;h4\nalpha=q9;92\namacr=75;4j\namalg=8cf;1dm\namp=12;9\nand=6qv;p6\nandand=8d1;1e3\nandd=8d8;1e9\nandslope=8d4;1e6\nandv=8d6;1e7\nang=6qo;oj\nange=884;1b1\nangle=6qo;oi\nangmsd=6qp;ol\nangmsdaa=888;1b5\nangmsdab=889;1b6\nangmsdac=88a;1b7\nangmsdad=88b;1b8\nangmsdae=88c;1b9\nangmsdaf=88d;1ba\nangmsdag=88e;1bb\nangmsdah=88f;1bc\nangrt=6qn;og\nangrtvb=6v2;yw\nangrtvbd=87x;1b0\nangsph=6qq;om\nangst=5h;2u\nangzarr=70c;12z\naogon=79;4n\naopf=2kpe;1mb\nap=6rs;r8\napE=8ds;1ej\napacir=8dr;1eh\nape=6ru;rd\napid=6rv;rf\napos=13;a\napprox=6rs;r5\napproxeq=6ru;rc\naring=6d;3q\nascr=2kl2;1ju\nast=16;e\nasymp=6rs;r6\nasympeq=6rx;rj\natilde=6b;3o\nauml=6c;3p\nawconint=6r7;ps\nawint=8b5;1cr\nbNot=8h9;1iy\nbackcong=6rw;rg\nbackepsilon=s6;af\nbackprime=6d1;ei\nbacksim=6rh;qc\nbacksimeq=6vh;zp\nbarvee=6v1;yv\nbarwed=6x1;11y\nbarwedge=6x1;11x\nbbrk=71x;137\nbbrktbrk=71y;138\nbcong=6rw;rh\nbcy=tt;bs\nbdquo=6ce;e4\nbecaus=6r9;py\nbecause=6r9;px\nbemptyv=88g;1bd\nbepsi=s6;ag\nbernou=6jw;go\nbeta=qa;93\nbeth=6k6;h5\nbetween=6ss;tt\nbfr=2knz;1l3\nbigcap=6v6;z5\nbigcirc=7hr;15s\nbigcup=6v7;z7\nbigodot=8ao;1cd\nbigoplus=8ap;1cf\nbigotimes=8aq;1ch\nbigsqcup=8au;1cl\nbigstar=7id;15z\nbigtriangledown=7gd;15e\nbigtriangleup=7g3;154\nbiguplus=8as;1cj\nbigvee=6v5;z1\nbigwedge=6v4;yy\nbkarow=83x;17x\nblacklozenge=8a3;1c9\nblacksquare=7fu;14x\nblacktriangle=7g4;156\nblacktriangledown=7ge;15g\nblacktriangleleft=7gi;15k\nblacktriangleright=7g8;15a\nblank=74z;13f\nblk12=7f6;14r\nblk14=7f5;14q\nblk34=7f7;14s\nblock=7ew;14p\nbne=1p,6hx;o\nbnequiv=6sh,6hx;sm\nbnot=6xc;12d\nbopf=2kpf;1mc\nbot=6ud;xx\nbottom=6ud;xu\nbowtie=6vc;zi\nboxDL=7dj;141\nboxDR=7dg;13y\nboxDl=7di;140\nboxDr=7df;13x\nboxH=7dc;13u\nboxHD=7dy;14g\nboxHU=7e1;14j\nboxHd=7dw;14e\nboxHu=7dz;14h\nboxUL=7dp;147\nboxUR=7dm;144\nboxUl=7do;146\nboxUr=7dl;143\nboxV=7dd;13v\nboxVH=7e4;14m\nboxVL=7dv;14d\nboxVR=7ds;14a\nboxVh=7e3;14l\nboxVl=7du;14c\nboxVr=7dr;149\nboxbox=895;1bw\nboxdL=7dh;13z\nboxdR=7de;13w\nboxdl=7bk;13m\nboxdr=7bg;13l\nboxh=7b4;13j\nboxhD=7dx;14f\nboxhU=7e0;14i\nboxhd=7cc;13r\nboxhu=7ck;13s\nboxminus=6u7;xi\nboxplus=6u6;xg\nboxtimes=6u8;xk\nboxuL=7dn;145\nboxuR=7dk;142\nboxul=7bs;13o\nboxur=7bo;13n\nboxv=7b6;13k\nboxvH=7e2;14k\nboxvL=7dt;14b\nboxvR=7dq;148\nboxvh=7cs;13t\nboxvl=7c4;13q\nboxvr=7bw;13p\nbprime=6d1;ej\nbreve=k8;83\nbrvbar=4m;1k\nbscr=2kl3;1jv\nbsemi=6dr;er\nbsim=6rh;qd\nbsime=6vh;zq\nbsol=2k;x\nbsolb=891;1bv\nbsolhsub=7uw;16r\nbull=6ci;e9\nbullet=6ci;e8\nbump=6ry;rp\nbumpE=8fi;1gu\nbumpe=6rz;ru\nbumpeq=6rz;rt\ncacute=7b;4p\ncap=6qx;pa\ncapand=8ck;1dq\ncapbrcup=8cp;1dv\ncapcap=8cr;1dx\ncapcup=8cn;1dt\ncapdot=8cg;1dn\ncaps=6qx,1e68;p9\ncaret=6dd;eo\ncaron=jr;81\nccaps=8ct;1dz\nccaron=7h;4v\nccedil=6f;3s\nccirc=7d;4r\nccups=8cs;1dy\nccupssm=8cw;1e0\ncdot=7f;4t\ncedil=54;2f\ncemptyv=88i;1bf\ncent=4i;1g\ncenterdot=53;2c\ncfr=2ko0;1l4\nchcy=uf;ce\ncheck=7pv;16j\ncheckmark=7pv;16i\nchi=qv;9s\ncir=7gr;15q\ncirE=88z;1bt\ncirc=jq;7z\ncirceq=6s7;sc\ncirclearrowleft=6nu;k6\ncirclearrowright=6nv;k8\ncircledR=4u;1w\ncircledS=79k;13g\ncircledast=6u3;xc\ncircledcirc=6u2;xa\ncircleddash=6u5;xe\ncire=6s7;sd\ncirfnint=8b4;1cq\ncirmid=8hb;1j0\ncirscir=88y;1bs\nclubs=7kz;168\nclubsuit=7kz;167\ncolon=1m;j\ncolone=6s4;s7\ncoloneq=6s4;s5\ncomma=18;g\ncommat=1s;u\ncomp=6pt;mv\ncompfn=6qg;o7\ncomplement=6pt;mu\ncomplexes=6iq;f6\ncong=6rp;qz\ncongdot=8dp;1ef\nconint=6r2;pj\ncopf=2kpg;1md\ncoprod=6q8;nr\ncopy=4p;1r\ncopysr=6jb;fz\ncrarr=6np;k1\ncross=7pz;16k\ncscr=2kl4;1jw\ncsub=8gf;1id\ncsube=8gh;1if\ncsup=8gg;1ie\ncsupe=8gi;1ig\nctdot=6wf;11g\ncudarrl=854;18x\ncudarrr=851;18u\ncuepr=6vy;10m\ncuesc=6vz;10o\ncularr=6nq;k3\ncularrp=859;190\ncup=6qy;pc\ncupbrcap=8co;1du\ncupcap=8cm;1ds\ncupcup=8cq;1dw\ncupdot=6tp;we\ncupor=8cl;1dr\ncups=6qy,1e68;pb\ncurarr=6nr;k5\ncurarrm=858;18z\ncurlyeqprec=6vy;10l\ncurlyeqsucc=6vz;10n\ncurlyvee=6vi;zr\ncurlywedge=6vj;zt\ncurren=4k;1i\ncurvearrowleft=6nq;k2\ncurvearrowright=6nr;k4\ncuvee=6vi;zs\ncuwed=6vj;zu\ncwconint=6r6;pq\ncwint=6r5;po\ncylcty=6y5;12u\ndArr=6oj;m2\ndHar=86d;19t\ndagger=6cg;e5\ndaleth=6k8;h7\ndarr=6mr;ia\ndash=6c0;dl\ndashv=6ub;xr\ndbkarow=83z;180\ndblac=kd;8b\ndcaron=7j;4x\ndcy=tw;bv\ndd=6km;hb\nddagger=6ch;e6\nddarr=6oa;ld\nddotseq=8dz;1ep\ndeg=4w;21\ndelta=qc;95\ndemptyv=88h;1be\ndfisht=873;1aj\ndfr=2ko1;1l5\ndharl=6o3;kx\ndharr=6o2;ku\ndiam=6v8;zc\ndiamond=6v8;zb\ndiamondsuit=7l2;16b\ndiams=7l2;16c\ndie=4o;1o\ndigamma=rh;a6\ndisin=6wi;11j\ndiv=6v;49\ndivide=6v;48\ndivideontimes=6vb;zg\ndivonx=6vb;zh\ndjcy=uq;co\ndlcorn=6xq;12n\ndlcrop=6x9;12a\ndollar=10;6\ndopf=2kph;1me\ndot=k9;85\ndoteq=6s0;rx\ndoteqdot=6s1;rz\ndotminus=6rc;q2\ndotplus=6qc;ny\ndotsquare=6u9;xm\ndoublebarwedge=6x2;11z\ndownarrow=6mr;i9\ndowndownarrows=6oa;lc\ndownharpoonleft=6o3;kv\ndownharpoonright=6o2;ks\ndrbkarow=840;182\ndrcorn=6xr;12p\ndrcrop=6x8;129\ndscr=2kl5;1jx\ndscy=ut;cr\ndsol=8ae;1cc\ndstrok=7l;4z\ndtdot=6wh;11i\ndtri=7gf;15j\ndtrif=7ge;15h\nduarr=6ph;mo\nduhar=86n;1a5\ndwangle=886;1b3\ndzcy=v3;d0\ndzigrarr=7wf;17r\neDDot=8dz;1eq\neDot=6s1;s0\neacute=6h;3u\neaster=8dq;1eg\necaron=7v;57\necir=6s6;sb\necirc=6i;3v\necolon=6s5;s9\necy=ul;ck\nedot=7r;53\nee=6kn;he\nefDot=6s2;s2\nefr=2ko2;1l6\neg=8ey;1g9\negrave=6g;3t\negs=8eu;1g5\negsdot=8ew;1g7\nel=8ex;1g8\nelinters=73b;13e\nell=6j7;fv\nels=8et;1g3\nelsdot=8ev;1g6\nemacr=7n;51\nempty=6px;n7\nemptyset=6px;n5\nemptyv=6px;n6\nemsp=6bn;d2\nemsp13=6bo;d3\nemsp14=6bp;d4\neng=97;6h\nensp=6bm;d1\neogon=7t;55\neopf=2kpi;1mf\nepar=6vp;103\neparsl=89v;1c6\neplus=8dt;1ek\nepsi=qd;97\nepsilon=qd;96\nepsiv=s5;ae\neqcirc=6s6;sa\neqcolon=6s5;s8\neqsim=6rm;qq\neqslantgtr=8eu;1g4\neqslantless=8et;1g2\nequals=1p;p\nequest=6sf;sj\nequiv=6sh;so\nequivDD=8e0;1er\neqvparsl=89x;1c8\nerDot=6s3;s4\nerarr=86p;1a7\nescr=6jz;gs\nesdot=6s0;ry\nesim=6rm;qr\neta=qf;99\neth=6o;41\neuml=6j;3w\neuro=6gc;f2\nexcl=x;2\nexist=6pv;n0\nexpectation=6k0;gt\nexponentiale=6kn;hd\nfallingdotseq=6s2;s1\nfcy=uc;cb\nfemale=7k0;163\nffilig=1dkz;1ja\nfflig=1dkw;1j7\nffllig=1dl0;1jb\nffr=2ko3;1l7\nfilig=1dkx;1j8\nfjlig=2u,2y;15\nflat=7l9;16e\nfllig=1dky;1j9\nfltns=7g1;153\nfnof=b6;7v\nfopf=2kpj;1mg\nforall=6ps;mt\nfork=6vo;102\nforkv=8gp;1in\nfpartint=8b1;1cp\nfrac12=59;2k\nfrac13=6kz;hh\nfrac14=58;2j\nfrac15=6l1;hj\nfrac16=6l5;hn\nfrac18=6l7;hp\nfrac23=6l0;hi\nfrac25=6l2;hk\nfrac34=5a;2m\nfrac35=6l3;hl\nfrac38=6l8;hq\nfrac45=6l4;hm\nfrac56=6l6;ho\nfrac58=6l9;hr\nfrac78=6la;hs\nfrasl=6dg;eq\nfrown=6xu;12r\nfscr=2kl7;1jy\ngE=6sn;t8\ngEl=8ek;1ft\ngacute=dx;7x\ngamma=qb;94\ngammad=rh;a7\ngap=8ee;1fh\ngbreve=7z;5b\ngcirc=7x;59\ngcy=tv;bu\ngdot=81;5d\nge=6sl;sx\ngel=6vv;10k\ngeq=6sl;sw\ngeqq=6sn;t7\ngeqslant=8e6;1f6\nges=8e6;1f7\ngescc=8fd;1gn\ngesdot=8e8;1f9\ngesdoto=8ea;1fb\ngesdotol=8ec;1fd\ngesl=6vv,1e68;10h\ngesles=8es;1g1\ngfr=2ko4;1l8\ngg=6sr;ts\nggg=6vt;10b\ngimel=6k7;h6\ngjcy=ur;cp\ngl=6t3;un\nglE=8eq;1fz\ngla=8f9;1gj\nglj=8f8;1gi\ngnE=6sp;tg\ngnap=8ei;1fp\ngnapprox=8ei;1fo\ngne=8eg;1fl\ngneq=8eg;1fk\ngneqq=6sp;tf\ngnsim=6w7;10y\ngopf=2kpk;1mh\ngrave=2o;14\ngscr=6iy;f9\ngsim=6sz;ud\ngsime=8em;1fv\ngsiml=8eo;1fx\ngt=1q;s\ngtcc=8fb;1gl\ngtcir=8e2;1et\ngtdot=6vr;107\ngtlPar=87p;1aw\ngtquest=8e4;1ev\ngtrapprox=8ee;1fg\ngtrarr=86w;1ad\ngtrdot=6vr;106\ngtreqless=6vv;10j\ngtreqqless=8ek;1fs\ngtrless=6t3;um\ngtrsim=6sz;uc\ngvertneqq=6sp,1e68;td\ngvnE=6sp,1e68;te\nhArr=6ok;m5\nhairsp=6bu;da\nhalf=59;2l\nhamilt=6iz;fb\nhardcy=ui;ch\nharr=6ms;id\nharrcir=85k;192\nharrw=6nh;js\nhbar=6j3;fl\nhcirc=85;5g\nhearts=7l1;16a\nheartsuit=7l1;169\nhellip=6cm;eb\nhercon=6ux;yr\nhfr=2ko5;1l9\nhksearow=84l;18i\nhkswarow=84m;18k\nhoarr=6pr;mr\nhomtht=6rf;q5\nhookleftarrow=6nd;jj\nhookrightarrow=6ne;jl\nhopf=2kpl;1mi\nhorbar=6c5;do\nhscr=2kl9;1jz\nhslash=6j3;fi\nhstrok=87;5i\nhybull=6df;ep\nhyphen=6c0;dk\niacute=6l;3y\nic=6eb;f1\nicirc=6m;3z\nicy=u0;bz\niecy=tx;bw\niexcl=4h;1f\niff=6ok;m6\nifr=2ko6;1la\nigrave=6k;3x\nii=6ko;hg\niiiint=8b0;1cn\niiint=6r1;pg\niinfin=89o;1c3\niiota=6jt;gm\nijlig=8j;5t\nimacr=8b;5m\nimage=6j5;fp\nimagline=6j4;fm\nimagpart=6j5;fo\nimath=8h;5r\nimof=6uv;yo\nimped=c5;7w\nin=6q0;nd\nincare=6it;f8\ninfin=6qm;of\ninfintie=89p;1c4\ninodot=8h;5q\nint=6qz;pe\nintcal=6uy;yt\nintegers=6jo;gh\nintercal=6uy;ys\nintlarhk=8bb;1cx\nintprod=8cc;1dk\niocy=up;cn\niogon=8f;5o\niopf=2kpm;1mj\niota=qh;9b\niprod=8cc;1dl\niquest=5b;2n\niscr=2kla;1k0\nisin=6q0;nc\nisinE=6wp;11r\nisindot=6wl;11n\nisins=6wk;11l\nisinsv=6wj;11k\nisinv=6q0;nb\nit=6ea;ez\nitilde=89;5k\niukcy=uu;cs\niuml=6n;40\njcirc=8l;5v\njcy=u1;c0\njfr=2ko7;1lb\njmath=fr;7y\njopf=2kpn;1mk\njscr=2klb;1k1\njsercy=uw;cu\njukcy=us;cq\nkappa=qi;9c\nkappav=s0;a9\nkcedil=8n;5x\nkcy=u2;c1\nkfr=2ko8;1lc\nkgreen=8o;5y\nkhcy=ud;cc\nkjcy=v0;cy\nkopf=2kpo;1ml\nkscr=2klc;1k2\nlAarr=6oq;mf\nlArr=6og;ls\nlAtail=84b;18a\nlBarr=83y;17z\nlE=6sm;t2\nlEg=8ej;1fr\nlHar=86a;19q\nlacute=8q;60\nlaemptyv=88k;1bh\nlagran=6j6;ft\nlambda=qj;9d\nlang=7vs;16z\nlangd=87l;1as\nlangle=7vs;16y\nlap=8ed;1ff\nlaquo=4r;1t\nlarr=6mo;hx\nlarrb=6p0;mk\nlarrbfs=84f;18e\nlarrfs=84d;18c\nlarrhk=6nd;jk\nlarrlp=6nf;jo\nlarrpl=855;18y\nlarrsim=86r;1a9\nlarrtl=6n6;j7\nlat=8ff;1gp\nlatail=849;188\nlate=8fh;1gt\nlates=8fh,1e68;1gs\nlbarr=83w;17w\nlbbrk=7si;16p\nlbrace=3f;16\nlbrack=2j;v\nlbrke=87f;1am\nlbrksld=87j;1aq\nlbrkslu=87h;1ao\nlcaron=8u;64\nlcedil=8s;62\nlceil=6x4;122\nlcub=3f;17\nlcy=u3;c2\nldca=852;18v\nldquo=6cc;dz\nldquor=6ce;e3\nldrdhar=86f;19v\nldrushar=85n;195\nldsh=6nm;jz\nle=6sk;st\nleftarrow=6mo;hv\nleftarrowtail=6n6;j6\nleftharpoondown=6nx;kd\nleftharpoonup=6nw;ka\nleftleftarrows=6o7;l6\nleftrightarrow=6ms;ic\nleftrightarrows=6o6;l4\nleftrightharpoons=6ob;lf\nleftrightsquigarrow=6nh;jr\nleftthreetimes=6vf;zl\nleg=6vu;10g\nleq=6sk;ss\nleqq=6sm;t1\nleqslant=8e5;1f0\nles=8e5;1f1\nlescc=8fc;1gm\nlesdot=8e7;1f8\nlesdoto=8e9;1fa\nlesdotor=8eb;1fc\nlesg=6vu,1e68;10d\nlesges=8er;1g0\nlessapprox=8ed;1fe\nlessdot=6vq;104\nlesseqgtr=6vu;10f\nlesseqqgtr=8ej;1fq\nlessgtr=6t2;uj\nlesssim=6sy;u9\nlfisht=870;1ag\nlfloor=6x6;126\nlfr=2ko9;1ld\nlg=6t2;uk\nlgE=8ep;1fy\nlhard=6nx;kf\nlharu=6nw;kc\nlharul=86i;19y\nlhblk=7es;14o\nljcy=ux;cv\nll=6sq;tm\nllarr=6o7;l7\nllcorner=6xq;12m\nllhard=86j;19z\nlltri=7i2;15w\nlmidot=8w;66\nlmoust=71s;131\nlmoustache=71s;130\nlnE=6so;tc\nlnap=8eh;1fn\nlnapprox=8eh;1fm\nlne=8ef;1fj\nlneq=8ef;1fi\nlneqq=6so;tb\nlnsim=6w6;10x\nloang=7vw;175\nloarr=6pp;mp\nlobrk=7vq;16u\nlongleftarrow=7w5;178\nlongleftrightarrow=7w7;17e\nlongmapsto=7wc;17p\nlongrightarrow=7w6;17b\nlooparrowleft=6nf;jn\nlooparrowright=6ng;jp\nlopar=879;1ak\nlopf=2kpp;1mm\nloplus=8bx;1d6\nlotimes=8c4;1dc\nlowast=6qf;o5\nlowbar=2n;12\nloz=7gq;15p\nlozenge=7gq;15o\nlozf=8a3;1ca\nlpar=14;b\nlparlt=87n;1au\nlrarr=6o6;l5\nlrcorner=6xr;12o\nlrhar=6ob;lg\nlrhard=86l;1a1\nlrm=6by;di\nlrtri=6v3;yx\nlsaquo=6d5;ek\nlscr=2kld;1k3\nlsh=6nk;jw\nlsim=6sy;ua\nlsime=8el;1fu\nlsimg=8en;1fw\nlsqb=2j;w\nlsquo=6c8;ds\nlsquor=6ca;dw\nlstrok=8y;68\nlt=1o;n\nltcc=8fa;1gk\nltcir=8e1;1es\nltdot=6vq;105\nlthree=6vf;zm\nltimes=6vd;zj\nltlarr=86u;1ac\nltquest=8e3;1eu\nltrPar=87q;1ax\nltri=7gj;15n\nltrie=6us;yi\nltrif=7gi;15l\nlurdshar=85m;194\nluruhar=86e;19u\nlvertneqq=6so,1e68;t9\nlvnE=6so,1e68;ta\nmDDot=6re;q4\nmacr=4v;20\nmale=7k2;164\nmalt=7q8;16m\nmaltese=7q8;16l\nmap=6na;jg\nmapsto=6na;jf\nmapstodown=6nb;ji\nmapstoleft=6n8;jb\nmapstoup=6n9;jd\nmarker=7fy;152\nmcomma=8bt;1d4\nmcy=u4;c3\nmdash=6c4;dn\nmeasuredangle=6qp;ok\nmfr=2koa;1le\nmho=6jr;gj\nmicro=51;29\nmid=6qr;oq\nmidast=16;d\nmidcir=8hc;1j1\nmiddot=53;2d\nminus=6qa;nu\nminusb=6u7;xj\nminusd=6rc;q3\nminusdu=8bu;1d5\nmlcp=8gr;1ip\nmldr=6cm;ec\nmnplus=6qb;nw\nmodels=6uf;xy\nmopf=2kpq;1mn\nmp=6qb;nx\nmscr=2kle;1k4\nmstpos=6ri;qf\nmu=qk;9e\nmultimap=6uw;yp\nmumap=6uw;yq\nnGg=6vt,mw;10a\nnGt=6sr,6he;tp\nnGtv=6sr,mw;to\nnLeftarrow=6od;lk\nnLeftrightarrow=6oe;lm\nnLl=6vs,mw;108\nnLt=6sq,6he;tj\nnLtv=6sq,mw;ti\nnRightarrow=6of;lo\nnVDash=6un;y7\nnVdash=6um;y6\nnabla=6pz;n8\nnacute=90;6a\nnang=6qo,6he;oh\nnap=6rt;rb\nnapE=8ds,mw;1ei\nnapid=6rv,mw;re\nnapos=95;6f\nnapprox=6rt;ra\nnatur=7la;16g\nnatural=7la;16f\nnaturals=6j9;fw\nnbsp=4g;1e\nnbump=6ry,mw;rm\nnbumpe=6rz,mw;rr\nncap=8cj;1dp\nncaron=94;6e\nncedil=92;6c\nncong=6rr;r2\nncongdot=8dp,mw;1ee\nncup=8ci;1do\nncy=u5;c4\nndash=6c3;dm\nne=6sg;sl\nneArr=6on;mb\nnearhk=84k;18h\nnearr=6mv;im\nnearrow=6mv;il\nnedot=6s0,mw;rv\nnequiv=6si;sq\nnesear=84o;18n\nnesim=6rm,mw;qo\nnexist=6pw;n3\nnexists=6pw;n2\nnfr=2kob;1lf\nngE=6sn,mw;t4\nnge=6sx;u7\nngeq=6sx;u6\nngeqq=6sn,mw;t5\nngeqslant=8e6,mw;1f3\nnges=8e6,mw;1f4\nngsim=6t1;uh\nngt=6sv;u1\nngtr=6sv;u0\nnhArr=6oe;ln\nnharr=6ni;ju\nnhpar=8he;1j3\nni=6q3;nk\nnis=6ws;11u\nnisd=6wq;11s\nniv=6q3;nj\nnjcy=uy;cw\nnlArr=6od;ll\nnlE=6sm,mw;sy\nnlarr=6my;iu\nnldr=6cl;ea\nnle=6sw;u4\nnleftarrow=6my;it\nnleftrightarrow=6ni;jt\nnleq=6sw;u3\nnleqq=6sm,mw;sz\nnleqslant=8e5,mw;1ex\nnles=8e5,mw;1ey\nnless=6su;tx\nnlsim=6t0;uf\nnlt=6su;ty\nnltri=6wa;115\nnltrie=6wc;11b\nnmid=6qs;ou\nnopf=2kpr;1mo\nnot=4s;1u\nnotin=6q1;ng\nnotinE=6wp,mw;11q\nnotindot=6wl,mw;11m\nnotinva=6q1;nf\nnotinvb=6wn;11p\nnotinvc=6wm;11o\nnotni=6q4;nn\nnotniva=6q4;nm\nnotnivb=6wu;11w\nnotnivc=6wt;11v\nnpar=6qu;p4\nnparallel=6qu;p2\nnparsl=8hp,6hx;1j5\nnpart=6pu,mw;mw\nnpolint=8b8;1cu\nnpr=6tc;vd\nnprcue=6w0;10q\nnpre=8fj,mw;1gw\nnprec=6tc;vc\nnpreceq=8fj,mw;1gx\nnrArr=6of;lp\nnrarr=6mz;iw\nnrarrc=84z,mw;18s\nnrarrw=6n1,mw;ix\nnrightarrow=6mz;iv\nnrtri=6wb;118\nnrtrie=6wd;11e\nnsc=6td;vg\nnsccue=6w1;10s\nnsce=8fk,mw;1h2\nnscr=2klf;1k5\nnshortmid=6qs;os\nnshortparallel=6qu;p1\nnsim=6rl;qm\nnsime=6ro;qx\nnsimeq=6ro;qw\nnsmid=6qs;ot\nnspar=6qu;p3\nnsqsube=6w2;10u\nnsqsupe=6w3;10w\nnsub=6tg;vs\nnsubE=8g5,mw;1hv\nnsube=6tk;w2\nnsubset=6te,6he;vi\nnsubseteq=6tk;w1\nnsubseteqq=8g5,mw;1hw\nnsucc=6td;vf\nnsucceq=8fk,mw;1h3\nnsup=6th;vt\nnsupE=8g6,mw;1hz\nnsupe=6tl;w5\nnsupset=6tf,6he;vn\nnsupseteq=6tl;w4\nnsupseteqq=8g6,mw;1i0\nntgl=6t5;ur\nntilde=6p;42\nntlg=6t4;up\nntriangleleft=6wa;114\nntrianglelefteq=6wc;11a\nntriangleright=6wb;117\nntrianglerighteq=6wd;11d\nnu=ql;9f\nnum=z;5\nnumero=6ja;fy\nnumsp=6br;d5\nnvDash=6ul;y5\nnvHarr=83o;17u\nnvap=6rx,6he;ri\nnvdash=6uk;y4\nnvge=6sl,6he;su\nnvgt=1q,6he;q\nnvinfin=89q;1c5\nnvlArr=83m;17s\nnvle=6sk,6he;sr\nnvlt=1o,6he;l\nnvltrie=6us,6he;yf\nnvrArr=83n;17t\nnvrtrie=6ut,6he;yj\nnvsim=6rg,6he;q6\nnwArr=6om;ma\nnwarhk=84j;18g\nnwarr=6mu;ij\nnwarrow=6mu;ii\nnwnear=84n;18m\noS=79k;13h\noacute=6r;44\noast=6u3;xd\nocir=6u2;xb\nocirc=6s;45\nocy=u6;c5\nodash=6u5;xf\nodblac=9d;6l\nodiv=8c8;1dg\nodot=6u1;x9\nodsold=88s;1bn\noelig=9f;6n\nofcir=88v;1bp\nofr=2koc;1lg\nogon=kb;87\nograve=6q;43\nogt=88x;1br\nohbar=88l;1bi\nohm=q1;91\noint=6r2;pk\nolarr=6nu;k7\nolcir=88u;1bo\nolcross=88r;1bm\noline=6da;en\nolt=88w;1bq\nomacr=99;6j\nomega=qx;9u\nomicron=qn;9h\nomid=88m;1bj\nominus=6ty;x4\noopf=2kps;1mp\nopar=88n;1bk\noperp=88p;1bl\noplus=6tx;x2\nor=6qw;p8\norarr=6nv;k9\nord=8d9;1ea\norder=6k4;h1\norderof=6k4;h0\nordf=4q;1s\nordm=56;2h\norigof=6uu;yn\noror=8d2;1e4\norslope=8d3;1e5\norv=8d7;1e8\noscr=6k4;h2\noslash=6w;4a\nosol=6u0;x7\notilde=6t;46\notimes=6tz;x6\notimesas=8c6;1de\nouml=6u;47\novbar=6yl;12x\npar=6qt;oz\npara=52;2a\nparallel=6qt;ox\nparsim=8hf;1j4\nparsl=8hp;1j6\npart=6pu;my\npcy=u7;c6\npercnt=11;7\nperiod=1a;h\npermil=6cw;ed\nperp=6ud;xw\npertenk=6cx;ee\npfr=2kod;1lh\nphi=qu;9r\nphiv=r9;a2\nphmmat=6k3;gy\nphone=7im;162\npi=qo;9i\npitchfork=6vo;101\npiv=ra;a4\nplanck=6j3;fj\nplanckh=6j2;fh\nplankv=6j3;fk\nplus=17;f\nplusacir=8bn;1cz\nplusb=6u6;xh\npluscir=8bm;1cy\nplusdo=6qc;nz\nplusdu=8bp;1d1\npluse=8du;1el\nplusmn=4x;23\nplussim=8bq;1d2\nplustwo=8br;1d3\npm=4x;24\npointint=8b9;1cv\npopf=2kpt;1mq\npound=4j;1h\npr=6t6;uu\nprE=8fn;1h7\nprap=8fr;1he\nprcue=6t8;v0\npre=8fj;1h0\nprec=6t6;ut\nprecapprox=8fr;1hd\npreccurlyeq=6t8;uz\npreceq=8fj;1gz\nprecnapprox=8ft;1hh\nprecneqq=8fp;1h9\nprecnsim=6w8;10z\nprecsim=6ta;v5\nprime=6cy;ef\nprimes=6jd;g2\nprnE=8fp;1ha\nprnap=8ft;1hi\nprnsim=6w8;110\nprod=6q7;np\nprofalar=6y6;12v\nprofline=6xe;12e\nprofsurf=6xf;12f\nprop=6ql;oe\npropto=6ql;oc\nprsim=6ta;v6\nprurel=6uo;y8\npscr=2klh;1k6\npsi=qw;9t\npuncsp=6bs;d6\nqfr=2koe;1li\nqint=8b0;1co\nqopf=2kpu;1mr\nqprime=6dz;es\nqscr=2kli;1k7\nquaternions=6j1;ff\nquatint=8ba;1cw\nquest=1r;t\nquesteq=6sf;si\nquot=y;4\nrAarr=6or;mh\nrArr=6oi;lz\nrAtail=84c;18b\nrBarr=83z;181\nrHar=86c;19s\nrace=6rh,mp;qb\nracute=9h;6p\nradic=6qi;o8\nraemptyv=88j;1bg\nrang=7vt;172\nrangd=87m;1at\nrange=885;1b2\nrangle=7vt;171\nraquo=57;2i\nrarr=6mq;i6\nrarrap=86t;1ab\nrarrb=6p1;mm\nrarrbfs=84g;18f\nrarrc=84z;18t\nrarrfs=84e;18d\nrarrhk=6ne;jm\nrarrlp=6ng;jq\nrarrpl=85h;191\nrarrsim=86s;1aa\nrarrtl=6n7;j9\nrarrw=6n1;iz\nratail=84a;189\nratio=6ra;pz\nrationals=6je;g4\nrbarr=83x;17y\nrbbrk=7sj;16q\nrbrace=3h;1b\nrbrack=2l;y\nrbrke=87g;1an\nrbrksld=87i;1ap\nrbrkslu=87k;1ar\nrcaron=9l;6t\nrcedil=9j;6r\nrceil=6x5;124\nrcub=3h;1c\nrcy=u8;c7\nrdca=853;18w\nrdldhar=86h;19x\nrdquo=6cd;e2\nrdquor=6cd;e1\nrdsh=6nn;k0\nreal=6jg;g9\nrealine=6jf;g6\nrealpart=6jg;g8\nreals=6jh;gc\nrect=7fx;151\nreg=4u;1y\nrfisht=871;1ah\nrfloor=6x7;128\nrfr=2kof;1lj\nrhard=6o1;kr\nrharu=6o0;ko\nrharul=86k;1a0\nrho=qp;9j\nrhov=s1;ab\nrightarrow=6mq;i4\nrightarrowtail=6n7;j8\nrightharpoondown=6o1;kp\nrightharpoonup=6o0;km\nrightleftarrows=6o4;kz\nrightleftharpoons=6oc;lh\nrightrightarrows=6o9;la\nrightsquigarrow=6n1;iy\nrightthreetimes=6vg;zn\nring=ka;86\nrisingdotseq=6s3;s3\nrlarr=6o4;l0\nrlhar=6oc;lj\nrlm=6bz;dj\nrmoust=71t;133\nrmoustache=71t;132\nrnmid=8ha;1iz\nroang=7vx;176\nroarr=6pq;mq\nrobrk=7vr;16w\nropar=87a;1al\nropf=2kpv;1ms\nroplus=8by;1d7\nrotimes=8c5;1dd\nrpar=15;c\nrpargt=87o;1av\nrppolint=8b6;1cs\nrrarr=6o9;lb\nrsaquo=6d6;el\nrscr=2klj;1k8\nrsh=6nl;jy\nrsqb=2l;z\nrsquo=6c9;dv\nrsquor=6c9;du\nrthree=6vg;zo\nrtimes=6ve;zk\nrtri=7g9;15d\nrtrie=6ut;ym\nrtrif=7g8;15b\nrtriltri=89a;1by\nruluhar=86g;19w\nrx=6ji;ge\nsacute=9n;6v\nsbquo=6ca;dx\nsc=6t7;ux\nscE=8fo;1h8\nscap=8fs;1hg\nscaron=9t;71\nsccue=6t9;v3\nsce=8fk;1h6\nscedil=9r;6z\nscirc=9p;6x\nscnE=8fq;1hc\nscnap=8fu;1hk\nscnsim=6w9;112\nscpolint=8b7;1ct\nscsim=6tb;va\nscy=u9;c8\nsdot=6v9;zd\nsdotb=6u9;xn\nsdote=8di;1ec\nseArr=6oo;mc\nsearhk=84l;18j\nsearr=6mw;ip\nsearrow=6mw;io\nsect=4n;1l\nsemi=1n;k\nseswar=84p;18p\nsetminus=6qe;o2\nsetmn=6qe;o4\nsext=7qu;16n\nsfr=2kog;1lk\nsfrown=6xu;12q\nsharp=7lb;16h\nshchcy=uh;cg\nshcy=ug;cf\nshortmid=6qr;oo\nshortparallel=6qt;ow\nshy=4t;1v\nsigma=qr;9n\nsigmaf=qq;9l\nsigmav=qq;9m\nsim=6rg;qa\nsimdot=8dm;1ed\nsime=6rn;qu\nsimeq=6rn;qt\nsimg=8f2;1gb\nsimgE=8f4;1gd\nsiml=8f1;1ga\nsimlE=8f3;1gc\nsimne=6rq;r0\nsimplus=8bo;1d0\nsimrarr=86q;1a8\nslarr=6mo;hw\nsmallsetminus=6qe;o0\nsmashp=8c3;1db\nsmeparsl=89w;1c7\nsmid=6qr;op\nsmile=6xv;12t\nsmt=8fe;1go\nsmte=8fg;1gr\nsmtes=8fg,1e68;1gq\nsoftcy=uk;cj\nsol=1b;i\nsolb=890;1bu\nsolbar=6yn;12y\nsopf=2kpw;1mt\nspades=7kw;166\nspadesuit=7kw;165\nspar=6qt;oy\nsqcap=6tv;wx\nsqcaps=6tv,1e68;wv\nsqcup=6tw;x0\nsqcups=6tw,1e68;wy\nsqsub=6tr;wk\nsqsube=6tt;wr\nsqsubset=6tr;wj\nsqsubseteq=6tt;wq\nsqsup=6ts;wo\nsqsupe=6tu;wu\nsqsupset=6ts;wn\nsqsupseteq=6tu;wt\nsqu=7fl;14v\nsquare=7fl;14u\nsquarf=7fu;14y\nsquf=7fu;14z\nsrarr=6mq;i5\nsscr=2klk;1k9\nssetmn=6qe;o3\nssmile=6xv;12s\nsstarf=6va;ze\nstar=7ie;161\nstarf=7id;160\nstraightepsilon=s5;ac\nstraightphi=r9;a0\nstrns=4v;1z\nsub=6te;vl\nsubE=8g5;1hy\nsubdot=8fx;1hn\nsube=6ti;vw\nsubedot=8g3;1ht\nsubmult=8g1;1hr\nsubnE=8gb;1i8\nsubne=6tm;w9\nsubplus=8fz;1hp\nsubrarr=86x;1ae\nsubset=6te;vk\nsubseteq=6ti;vv\nsubseteqq=8g5;1hx\nsubsetneq=6tm;w8\nsubsetneqq=8gb;1i7\nsubsim=8g7;1i3\nsubsub=8gl;1ij\nsubsup=8gj;1ih\nsucc=6t7;uw\nsuccapprox=8fs;1hf\nsucccurlyeq=6t9;v2\nsucceq=8fk;1h5\nsuccnapprox=8fu;1hj\nsuccneqq=8fq;1hb\nsuccnsim=6w9;111\nsuccsim=6tb;v9\nsum=6q9;nt\nsung=7l6;16d\nsup=6tf;vr\nsup1=55;2g\nsup2=4y;25\nsup3=4z;26\nsupE=8g6;1i2\nsupdot=8fy;1ho\nsupdsub=8go;1im\nsupe=6tj;vz\nsupedot=8g4;1hu\nsuphsol=7ux;16s\nsuphsub=8gn;1il\nsuplarr=86z;1af\nsupmult=8g2;1hs\nsupnE=8gc;1ic\nsupne=6tn;wd\nsupplus=8g0;1hq\nsupset=6tf;vq\nsupseteq=6tj;vy\nsupseteqq=8g6;1i1\nsupsetneq=6tn;wc\nsupsetneqq=8gc;1ib\nsupsim=8g8;1i4\nsupsub=8gk;1ii\nsupsup=8gm;1ik\nswArr=6op;md\nswarhk=84m;18l\nswarr=6mx;is\nswarrow=6mx;ir\nswnwar=84q;18r\nszlig=67;3k\ntarget=6xi;12h\ntau=qs;9o\ntbrk=71w;135\ntcaron=9x;75\ntcedil=9v;73\ntcy=ua;c9\ntdot=6hn;f4\ntelrec=6xh;12g\ntfr=2koh;1ll\nthere4=6r8;pv\ntherefore=6r8;pu\ntheta=qg;9a\nthetasym=r5;9v\nthetav=r5;9x\nthickapprox=6rs;r3\nthicksim=6rg;q7\nthinsp=6bt;d8\nthkap=6rs;r7\nthksim=6rg;q8\nthorn=72;4g\ntilde=kc;89\ntimes=5z;3c\ntimesb=6u8;xl\ntimesbar=8c1;1da\ntimesd=8c0;1d9\ntint=6r1;ph\ntoea=84o;18o\ntop=6uc;xt\ntopbot=6ye;12w\ntopcir=8hd;1j2\ntopf=2kpx;1mu\ntopfork=8gq;1io\ntosa=84p;18q\ntprime=6d0;eh\ntrade=6jm;gg\ntriangle=7g5;158\ntriangledown=7gf;15i\ntriangleleft=7gj;15m\ntrianglelefteq=6us;yh\ntriangleq=6sc;sg\ntriangleright=7g9;15c\ntrianglerighteq=6ut;yl\ntridot=7ho;15r\ntrie=6sc;sh\ntriminus=8ca;1di\ntriplus=8c9;1dh\ntrisb=899;1bx\ntritime=8cb;1dj\ntrpezium=736;13d\ntscr=2kll;1ka\ntscy=ue;cd\ntshcy=uz;cx\ntstrok=9z;77\ntwixt=6ss;tu\ntwoheadleftarrow=6n2;j0\ntwoheadrightarrow=6n4;j3\nuArr=6oh;lv\nuHar=86b;19r\nuacute=6y;4c\nuarr=6mp;i1\nubrcy=v2;cz\nubreve=a5;7d\nucirc=6z;4d\nucy=ub;ca\nudarr=6o5;l2\nudblac=a9;7h\nudhar=86m;1a3\nufisht=872;1ai\nufr=2koi;1lm\nugrave=6x;4b\nuharl=6nz;kl\nuharr=6ny;ki\nuhblk=7eo;14n\nulcorn=6xo;12j\nulcorner=6xo;12i\nulcrop=6xb;12c\nultri=7i0;15u\numacr=a3;7b\numl=4o;1p\nuogon=ab;7j\nuopf=2kpy;1mv\nuparrow=6mp;i0\nupdownarrow=6mt;if\nupharpoonleft=6nz;kj\nupharpoonright=6ny;kg\nuplus=6tq;wg\nupsi=qt;9q\nupsih=r6;9y\nupsilon=qt;9p\nupuparrows=6o8;l8\nurcorn=6xp;12l\nurcorner=6xp;12k\nurcrop=6xa;12b\nuring=a7;7f\nurtri=7i1;15v\nuscr=2klm;1kb\nutdot=6wg;11h\nutilde=a1;79\nutri=7g5;159\nutrif=7g4;157\nuuarr=6o8;l9\nuuml=70;4e\nuwangle=887;1b4\nvArr=6ol;m9\nvBar=8h4;1iu\nvBarv=8h5;1iv\nvDash=6ug;y0\nvangrt=87w;1az\nvarepsilon=s5;ad\nvarkappa=s0;a8\nvarnothing=6px;n4\nvarphi=r9;a1\nvarpi=ra;a3\nvarpropto=6ql;ob\nvarr=6mt;ig\nvarrho=s1;aa\nvarsigma=qq;9k\nvarsubsetneq=6tm,1e68;w6\nvarsubsetneqq=8gb,1e68;1i5\nvarsupsetneq=6tn,1e68;wa\nvarsupsetneqq=8gc,1e68;1i9\nvartheta=r5;9w\nvartriangleleft=6uq;y9\nvartriangleright=6ur;yc\nvcy=tu;bt\nvdash=6ua;xp\nvee=6qw;p7\nveebar=6uz;yu\nveeeq=6sa;sf\nvellip=6we;11f\nverbar=3g;19\nvert=3g;1a\nvfr=2koj;1ln\nvltri=6uq;yb\nvnsub=6te,6he;vj\nvnsup=6tf,6he;vo\nvopf=2kpz;1mw\nvprop=6ql;od\nvrtri=6ur;ye\nvscr=2kln;1kc\nvsubnE=8gb,1e68;1i6\nvsubne=6tm,1e68;w7\nvsupnE=8gc,1e68;1ia\nvsupne=6tn,1e68;wb\nvzigzag=87u;1ay\nwcirc=ad;7l\nwedbar=8db;1eb\nwedge=6qv;p5\nwedgeq=6s9;se\nweierp=6jc;g0\nwfr=2kok;1lo\nwopf=2kq0;1mx\nwp=6jc;g1\nwr=6rk;qk\nwreath=6rk;qj\nwscr=2klo;1kd\nxcap=6v6;z6\nxcirc=7hr;15t\nxcup=6v7;z9\nxdtri=7gd;15f\nxfr=2kol;1lp\nxhArr=7wa;17o\nxharr=7w7;17f\nxi=qm;9g\nxlArr=7w8;17i\nxlarr=7w5;179\nxmap=7wc;17q\nxnis=6wr;11t\nxodot=8ao;1ce\nxopf=2kq1;1my\nxoplus=8ap;1cg\nxotime=8aq;1ci\nxrArr=7w9;17l\nxrarr=7w6;17c\nxscr=2klp;1ke\nxsqcup=8au;1cm\nxuplus=8as;1ck\nxutri=7g3;155\nxvee=6v5;z2\nxwedge=6v4;yz\nyacute=71;4f\nyacy=un;cm\nycirc=af;7n\nycy=uj;ci\nyen=4l;1j\nyfr=2kom;1lq\nyicy=uv;ct\nyopf=2kq2;1mz\nyscr=2klq;1kf\nyucy=um;cl\nyuml=73;4h\nzacute=ai;7q\nzcaron=am;7u\nzcy=tz;by\nzdot=ak;7s\nzeetrf=6js;gk\nzeta=qe;98\nzfr=2kon;1lr\nzhcy=ty;bx\nzigrarr=6ot;mi\nzopf=2kq3;1n0\nzscr=2klr;1kg\nzwj=6bx;dh\nzwnj=6bw;dg" + +} diff --git a/Pods/SwiftSoup/Sources/Evaluator.swift b/Pods/SwiftSoup/Sources/Evaluator.swift new file mode 100644 index 0000000..968bcb2 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Evaluator.swift @@ -0,0 +1,720 @@ +// +// Evaluator.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 22/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Evaluates that an element matches the selector. + */ +public class Evaluator { + init () {} + + /** + * Test if the element meets the evaluator's requirements. + * + * @param root Root of the matching subtree + * @param element tested element + * @return Returns true if the requirements are met or + * false otherwise + */ + open func matches(_ root: Element, _ element: Element)throws->Bool { + preconditionFailure("self method must be overridden") + } + + open func toString() -> String { + preconditionFailure("self method must be overridden") + } + + /** + * Evaluator for tag name + */ + public class Tag: Evaluator { + private let tagName: String + private let tagNameNormal: String + + public init(_ tagName: String) { + self.tagName = tagName + self.tagNameNormal = tagName.lowercased() + } + + open override func matches(_ root: Element, _ element: Element)throws->Bool { + return element.tagNameNormal() == tagNameNormal + } + + open override func toString() -> String { + return String(tagName) + } + } + + /** + * Evaluator for tag name that ends with + */ + public final class TagEndsWith: Evaluator { + private let tagName: String + + public init(_ tagName: String) { + self.tagName = tagName + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (element.tagName().hasSuffix(tagName)) + } + + public override func toString() -> String { + return String(tagName) + } + } + + /** + * Evaluator for element id + */ + public final class Id: Evaluator { + private let id: String + + public init(_ id: String) { + self.id = id + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (id == element.id()) + } + + public override func toString() -> String { + return "#\(id)" + } + + } + + /** + * Evaluator for element class + */ + public final class Class: Evaluator { + private let className: String + + public init(_ className: String) { + self.className = className + } + + public override func matches(_ root: Element, _ element: Element) -> Bool { + return (element.hasClass(className)) + } + + public override func toString() -> String { + return ".\(className)" + } + + } + + /** + * Evaluator for attribute name matching + */ + public final class Attribute: Evaluator { + private let key: String + + public init(_ key: String) { + self.key = key + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return element.hasAttr(key) + } + + public override func toString() -> String { + return "[\(key)]" + } + + } + + /** + * Evaluator for attribute name prefix matching + */ + public final class AttributeStarting: Evaluator { + private let keyPrefix: String + + public init(_ keyPrefix: String)throws { + try Validate.notEmpty(string: keyPrefix) + self.keyPrefix = keyPrefix.lowercased() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if let values = element.getAttributes() { + for attribute in values where attribute.getKey().lowercased().hasPrefix(keyPrefix) { + return true + } + } + return false + } + + public override func toString() -> String { + return "[^\(keyPrefix)]" + } + + } + + /** + * Evaluator for attribute name/value matching + */ + public final class AttributeWithValue: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + let string = try element.attr(key) + return value.equalsIgnoreCase(string: string.trim()) + } + return false + } + + public override func toString() -> String { + return "[\(key)=\(value)]" + } + + } + + /** + * Evaluator for attribute name != value matching + */ + public final class AttributeWithValueNot: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let string = try element.attr(key) + return !value.equalsIgnoreCase(string: string) + } + + public override func toString() -> String { + return "[\(key)!=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value prefix) + */ + public final class AttributeWithValueStarting: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + return try element.attr(key).lowercased().hasPrefix(value) // value is lower case already + } + return false + } + + public override func toString() -> String { + return "[\(key)^=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value ending) + */ + public final class AttributeWithValueEnding: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + return try element.attr(key).lowercased().hasSuffix(value) // value is lower case + } + return false + } + + public override func toString() -> String { + return "[\(key)$=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value containing) + */ + public final class AttributeWithValueContaining: AttributeKeyPair { + public override init(_ key: String, _ value: String)throws { + try super.init(key, value) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + return try element.attr(key).lowercased().contains(value) // value is lower case + } + return false + } + + public override func toString() -> String { + return "[\(key)*=\(value)]" + } + + } + + /** + * Evaluator for attribute name/value matching (value regex matching) + */ + public final class AttributeWithValueMatching: Evaluator { + let key: String + let pattern: Pattern + + public init(_ key: String, _ pattern: Pattern) { + self.key = key.trim().lowercased() + self.pattern = pattern + super.init() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + if element.hasAttr(key) { + let string = try element.attr(key) + return pattern.matcher(in: string).find() + } + return false + } + + public override func toString() -> String { + return "[\(key)~=\(pattern.toString())]" + } + + } + + /** + * Abstract evaluator for attribute name/value matching + */ + public class AttributeKeyPair: Evaluator { + let key: String + var value: String + + public init(_ key: String, _ value2: String)throws { + var value2 = value2 + try Validate.notEmpty(string: key) + try Validate.notEmpty(string: value2) + + self.key = key.trim().lowercased() + if value2.startsWith("\"") && value2.hasSuffix("\"") || value2.startsWith("'") && value2.hasSuffix("'") { + value2 = value2.substring(1, value2.count-2) + } + self.value = value2.trim().lowercased() + } + + open override func matches(_ root: Element, _ element: Element)throws->Bool { + preconditionFailure("self method must be overridden") + } + } + + /** + * Evaluator for any / all element matching + */ + public final class AllElements: Evaluator { + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return true + } + + public override func toString() -> String { + return "*" + } + } + + /** + * Evaluator for matching by sibling index number (e {@literal <} idx) + */ + public final class IndexLessThan: IndexEvaluator { + public override init(_ index: Int) { + super.init(index) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return try element.elementSiblingIndex() < index + } + + public override func toString() -> String { + return ":lt(\(index))" + } + + } + + /** + * Evaluator for matching by sibling index number (e {@literal >} idx) + */ + public final class IndexGreaterThan: IndexEvaluator { + public override init(_ index: Int) { + super.init(index) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return try element.elementSiblingIndex() > index + } + + public override func toString() -> String { + return ":gt(\(index))" + } + + } + + /** + * Evaluator for matching by sibling index number (e = idx) + */ + public final class IndexEquals: IndexEvaluator { + public override init(_ index: Int) { + super.init(index) + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return try element.elementSiblingIndex() == index + } + + public override func toString() -> String { + return ":eq(\(index))" + } + + } + + /** + * Evaluator for matching the last sibling (css :last-child) + */ + public final class IsLastChild: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + + if let parent = element.parent() { + let index = try element.elementSiblingIndex() + return !(parent is Document) && index == (parent.getChildNodes().count - 1) + } + return false + } + + public override func toString() -> String { + return ":last-child" + } + } + + public final class IsFirstOfType: IsNthOfType { + public init() { + super.init(0, 1) + } + public override func toString() -> String { + return ":first-of-type" + } + } + + public final class IsLastOfType: IsNthLastOfType { + public init() { + super.init(0, 1) + } + public override func toString() -> String { + return ":last-of-type" + } + } + + public class CssNthEvaluator: Evaluator { + public let a: Int + public let b: Int + + public init(_ a: Int, _ b: Int) { + self.a = a + self.b = b + } + public init(_ b: Int) { + self.a = 0 + self.b = b + } + + open override func matches(_ root: Element, _ element: Element)throws->Bool { + let p: Element? = element.parent() + if (p == nil || (((p as? Document) != nil))) {return false} + + let pos: Int = try calculatePosition(root, element) + if (a == 0) {return pos == b} + + return (pos-b)*a >= 0 && (pos-b)%a==0 + } + + open override func toString() -> String { + if (a == 0) { + return ":\(getPseudoClass)(\(b))" + } + if (b == 0) { + return ":\(getPseudoClass)(\(a))" + } + return ":\(getPseudoClass)(\(a)\(b))" + } + + open func getPseudoClass() -> String { + preconditionFailure("self method must be overridden") + } + open func calculatePosition(_ root: Element, _ element: Element)throws->Int { + preconditionFailure("self method must be overridden") + } + } + + /** + * css-compatible Evaluator for :eq (css :nth-child) + * + * @see IndexEquals + */ + public final class IsNthChild: CssNthEvaluator { + + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + public override func calculatePosition(_ root: Element, _ element: Element)throws->Int { + return try element.elementSiblingIndex()+1 + } + + public override func getPseudoClass() -> String { + return "nth-child" + } + } + + /** + * css pseudo class :nth-last-child) + * + * @see IndexEquals + */ + public final class IsNthLastChild: CssNthEvaluator { + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + public override func calculatePosition(_ root: Element, _ element: Element)throws->Int { + var i = 0 + + if let l = element.parent() { + i = l.children().array().count + } + return i - (try element.elementSiblingIndex()) + } + + public override func getPseudoClass() -> String { + return "nth-last-child" + } + } + + /** + * css pseudo class nth-of-type + * + */ + public class IsNthOfType: CssNthEvaluator { + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + open override func calculatePosition(_ root: Element, _ element: Element) -> Int { + var pos = 0 + let family: Elements? = element.parent()?.children() + if let array = family?.array() { + for el in array { + if (el.tag() == element.tag()) {pos+=1} + if (el === element) {break} + } + } + + return pos + } + + open override func getPseudoClass() -> String { + return "nth-of-type" + } + } + + public class IsNthLastOfType: CssNthEvaluator { + + public override init(_ a: Int, _ b: Int) { + super.init(a, b) + } + + open override func calculatePosition(_ root: Element, _ element: Element)throws->Int { + var pos = 0 + if let family = element.parent()?.children() { + let x = try element.elementSiblingIndex() + for i in x.. String { + return "nth-last-of-type" + } + } + + /** + * Evaluator for matching the first sibling (css :first-child) + */ + public final class IsFirstChild: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let p = element.parent() + if(p != nil && !(((p as? Document) != nil))) { + return (try element.elementSiblingIndex()) == 0 + } + return false + } + + public override func toString() -> String { + return ":first-child" + } + } + + /** + * css3 pseudo-class :root + * @see :root selector + * + */ + public final class IsRoot: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let r: Element = ((root as? Document) != nil) ? root.child(0) : root + return element === r + } + public override func toString() -> String { + return ":root" + } + } + + public final class IsOnlyChild: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let p = element.parent() + return p != nil && !((p as? Document) != nil) && element.siblingElements().array().count == 0 + } + public override func toString() -> String { + return ":only-child" + } + } + + public final class IsOnlyOfType: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let p = element.parent() + if (p == nil || (p as? Document) != nil) {return false} + + var pos = 0 + if let family = p?.children().array() { + for el in family { + if (el.tag() == element.tag()) {pos+=1} + } + } + return pos == 1 + } + + public override func toString() -> String { + return ":only-of-type" + } + } + + public final class IsEmpty: Evaluator { + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let family: Array = element.getChildNodes() + for n in family { + if (!((n as? Comment) != nil || (n as? XmlDeclaration) != nil || (n as? DocumentType) != nil)) {return false} + } + return true + } + + public override func toString() -> String { + return ":empty" + } + } + + /** + * Abstract evaluator for sibling index matching + * + * @author ant + */ + public class IndexEvaluator: Evaluator { + let index: Int + + public init(_ index: Int) { + self.index = index + } + } + + /** + * Evaluator for matching Element (and its descendants) text + */ + public final class ContainsText: Evaluator { + private let searchText: String + + public init(_ searchText: String) { + self.searchText = searchText.lowercased() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (try element.text().lowercased().contains(searchText)) + } + + public override func toString() -> String { + return ":contains(\(searchText)" + } + } + + /** + * Evaluator for matching Element's own text + */ + public final class ContainsOwnText: Evaluator { + private let searchText: String + + public init(_ searchText: String) { + self.searchText = searchText.lowercased() + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + return (element.ownText().lowercased().contains(searchText)) + } + + public override func toString() -> String { + return ":containsOwn(\(searchText)" + } + } + + /** + * Evaluator for matching Element (and its descendants) text with regex + */ + public final class Matches: Evaluator { + private let pattern: Pattern + + public init(_ pattern: Pattern) { + self.pattern = pattern + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let m = try pattern.matcher(in: element.text()) + return m.find() + } + + public override func toString() -> String { + return ":matches(\(pattern)" + } + } + + /** + * Evaluator for matching Element's own text with regex + */ + public final class MatchesOwn: Evaluator { + private let pattern: Pattern + + public init(_ pattern: Pattern) { + self.pattern = pattern + } + + public override func matches(_ root: Element, _ element: Element)throws->Bool { + let m = pattern.matcher(in: element.ownText()) + return m.find() + } + + public override func toString() -> String { + return ":matchesOwn(\(pattern.toString())" + } + } +} diff --git a/Pods/SwiftSoup/Sources/Exception.swift b/Pods/SwiftSoup/Sources/Exception.swift new file mode 100644 index 0000000..a4ab97a --- /dev/null +++ b/Pods/SwiftSoup/Sources/Exception.swift @@ -0,0 +1,22 @@ +// +// Exception.swift +// SwifSoup +// +// Created by Nabil Chatbi on 02/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +public enum ExceptionType { + case IllegalArgumentException + case IOException + case XmlDeclaration + case MalformedURLException + case CloneNotSupportedException + case SelectorParseException +} + +public enum Exception: Error { + case Error(type:ExceptionType, Message: String) +} diff --git a/Pods/SwiftSoup/Sources/FormElement.swift b/Pods/SwiftSoup/Sources/FormElement.swift new file mode 100644 index 0000000..a15754f --- /dev/null +++ b/Pods/SwiftSoup/Sources/FormElement.swift @@ -0,0 +1,125 @@ +// +// FormElement.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * A HTML Form Element provides ready access to the form fields/controls that are associated with it. It also allows a + * form to easily be submitted. + */ +public class FormElement: Element { + private let _elements: Elements = Elements() + + /** + * Create a new, standalone form element. + * + * @param tag tag of this element + * @param baseUri the base URI + * @param attributes initial attributes + */ + public override init(_ tag: Tag, _ baseUri: String, _ attributes: Attributes) { + super.init(tag, baseUri, attributes) + } + + /** + * Get the list of form control elements associated with this form. + * @return form controls associated with this element. + */ + public func elements() -> Elements { + return _elements + } + + /** + * Add a form control element to this form. + * @param element form control to add + * @return this form element, for chaining + */ + @discardableResult + public func addElement(_ element: Element) -> FormElement { + _elements.add(element) + return self + } + + //todo: + /** + * Prepare to submit this form. A Connection object is created with the request set up from the form values. You + * can then set up other options (like user-agent, timeout, cookies), then execute it. + * @return a connection prepared from the values of this form. + * @throws IllegalArgumentException if the form's absolute action URL cannot be determined. Make sure you pass the + * document's base URI when parsing. + */ +// public func submit()throws->Connection { +// let action: String = hasAttr("action") ? try absUrl("action") : try baseUri() +// Validate.notEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.") +// Connection.Method method = attr("method").toUpperCase().equals("POST") ? +// Connection.Method.POST : Connection.Method.GET +// +// return Jsoup.connect(action) +// .data(formData()) +// .method(method) +// } + + //todo: + /** + * Get the data that this form submits. The returned list is a copy of the data, and changes to the contents of the + * list will not be reflected in the DOM. + * @return a list of key vals + */ +// public List formData() { +// ArrayList data = new ArrayList(); +// +// // iterate the form control elements and accumulate their values +// for (Element el: elements) { +// if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable +// if (el.hasAttr("disabled")) continue; // skip disabled form inputs +// String name = el.attr("name"); +// if (name.length() == 0) continue; +// String type = el.attr("type"); +// +// if ("select".equals(el.tagName())) { +// Elements options = el.select("option[selected]"); +// boolean set = false; +// for (Element option: options) { +// data.add(HttpConnection.KeyVal.create(name, option.val())); +// set = true; +// } +// if (!set) { +// Element option = el.select("option").first(); +// if (option != null) +// data.add(HttpConnection.KeyVal.create(name, option.val())); +// } +// } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { +// // only add checkbox or radio if they have the checked attribute +// if (el.hasAttr("checked")) { +// final String val = el.val().length() > 0 ? el.val() : "on"; +// data.add(HttpConnection.KeyVal.create(name, val)); +// } +// } else { +// data.add(HttpConnection.KeyVal.create(name, el.val())); +// } +// } +// return data; +// } + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = FormElement(_tag, baseUri!, attributes!) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = FormElement(_tag, baseUri!, attributes!) + return copy(clone: clone, parent: parent) + } + public override func copy(clone: Node, parent: Node?) -> Node { + let clone = clone as! FormElement + for att in _elements.array() { + clone._elements.add(att) + } + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Pods/SwiftSoup/Sources/HtmlTreeBuilder.swift b/Pods/SwiftSoup/Sources/HtmlTreeBuilder.swift new file mode 100644 index 0000000..532fe34 --- /dev/null +++ b/Pods/SwiftSoup/Sources/HtmlTreeBuilder.swift @@ -0,0 +1,771 @@ +// +// HtmlTreeBuilder.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 24/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * HTML Tree Builder; creates a DOM from Tokens. + */ +class HtmlTreeBuilder: TreeBuilder { + // tag searches + public static let TagsSearchInScope: [String] = ["applet", "caption", "html", "table", "td", "th", "marquee", "object"] + private static let TagSearchList: [String] = ["ol", "ul"] + private static let TagSearchButton: [String] = ["button"] + private static let TagSearchTableScope: [String] = ["html", "table"] + private static let TagSearchSelectScope: [String] = ["optgroup", "option"] + private static let TagSearchEndTags: [String] = ["dd", "dt", "li", "option", "optgroup", "p", "rp", "rt"] + private static let TagSearchSpecial: [String] = ["address", "applet", "area", "article", "aside", "base", "basefont", "bgsound", + "blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "command", "dd", + "details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form", + "frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html", + "iframe", "img", "input", "isindex", "li", "link", "listing", "marquee", "menu", "meta", "nav", + "noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script", + "section", "select", "style", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", + "title", "tr", "ul", "wbr", "xmp"] + + private var _state: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // the current state + private var _originalState: HtmlTreeBuilderState = HtmlTreeBuilderState.Initial // original / marked state + + private var baseUriSetFromDoc: Bool = false + private var headElement: Element? // the current head element + private var formElement: FormElement? // the current form element + private var contextElement: Element? // fragment parse context -- could be null even if fragment parsing + private var formattingElements: Array = Array() // active (open) formatting elements + private var pendingTableCharacters: Array = Array() // chars in table to be shifted out + private var emptyEnd: Token.EndTag = Token.EndTag() // reused empty end tag + + private var _framesetOk: Bool = true // if ok to go into frameset + private var fosterInserts: Bool = false // if next inserts should be fostered + private var fragmentParsing: Bool = false // if parsing a fragment of html + + public override init() { + super.init() + } + + public override func defaultSettings() -> ParseSettings { + return ParseSettings.htmlDefault + } + + override func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document { + _state = HtmlTreeBuilderState.Initial + baseUriSetFromDoc = false + return try super.parse(input, baseUri, errors, settings) + } + + func parseFragment(_ inputFragment: String, _ context: Element?, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Array { + // context may be null + _state = HtmlTreeBuilderState.Initial + initialiseParse(inputFragment, baseUri, errors, settings) + contextElement = context + fragmentParsing = true + var root: Element? = nil + + if let context = context { + if let d = context.ownerDocument() { // quirks setup: + doc.quirksMode(d.quirksMode()) + } + + // initialise the tokeniser state: + let contextTag: String = context.tagName() + if (StringUtil.inString(contextTag, haystack: "title", "textarea")) { + tokeniser.transition(TokeniserState.Rcdata) + } else if (StringUtil.inString(contextTag, haystack: "iframe", "noembed", "noframes", "style", "xmp")) { + tokeniser.transition(TokeniserState.Rawtext) + } else if (contextTag=="script") { + tokeniser.transition(TokeniserState.ScriptData) + } else if (contextTag==("noscript")) { + tokeniser.transition(TokeniserState.Data) // if scripting enabled, rawtext + } else if (contextTag=="plaintext") { + tokeniser.transition(TokeniserState.Data) + } else { + tokeniser.transition(TokeniserState.Data) // default + } + + root = try Element(Tag.valueOf("html", settings), baseUri) + try Validate.notNull(obj: root) + try doc.appendChild(root!) + stack.append(root!) + resetInsertionMode() + + // setup form element to nearest form on context (up ancestor chain). ensures form controls are associated + // with form correctly + let contextChain: Elements = context.parents() + contextChain.add(0, context) + for parent: Element in contextChain.array() { + if let x = (parent as? FormElement) { + formElement = x + break + } + } + } + + try runParser() + if (context != nil && root != nil) { + return root!.getChildNodes() + } else { + return doc.getChildNodes() + } + } + + @discardableResult + public override func process(_ token: Token)throws->Bool { + currentToken = token + return try self._state.process(token, self) + } + + @discardableResult + func process(_ token: Token, _ state: HtmlTreeBuilderState)throws->Bool { + currentToken = token + return try state.process(token, self) + } + + func transition(_ state: HtmlTreeBuilderState) { + self._state = state + } + + func state() -> HtmlTreeBuilderState { + return _state + } + + func markInsertionMode() { + _originalState = _state + } + + func originalState() -> HtmlTreeBuilderState { + return _originalState + } + + func framesetOk(_ framesetOk: Bool) { + self._framesetOk = framesetOk + } + + func framesetOk() -> Bool { + return _framesetOk + } + + func getDocument() -> Document { + return doc + } + + func getBaseUri() -> String { + return baseUri + } + + func maybeSetBaseUri(_ base: Element)throws { + if (baseUriSetFromDoc) { // only listen to the first in parse + return + } + + let href: String = try base.absUrl("href") + if (href.count != 0) { // ignore etc + baseUri = href + baseUriSetFromDoc = true + try doc.setBaseUri(href) // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants + } + } + + func isFragmentParsing() -> Bool { + return fragmentParsing + } + + func error(_ state: HtmlTreeBuilderState) { + if (errors.canAddError() && currentToken != nil) { + errors.add(ParseError(reader.getPos(), "Unexpected token [\(currentToken!.tokenType())] when in state [\(state.rawValue)]")) + } + } + + @discardableResult + func insert(_ startTag: Token.StartTag)throws->Element { + // handle empty unknown tags + // when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag. + if (startTag.isSelfClosing()) { + let el: Element = try insertEmpty(startTag) + stack.append(el) + tokeniser.transition(TokeniserState.Data) // handles + + var tagPending: Token.Tag = Token.Tag() // tag we are building up + let startPending: Token.StartTag = Token.StartTag() + let endPending: Token.EndTag = Token.EndTag() + let charPending: Token.Char = Token.Char() + let doctypePending: Token.Doctype = Token.Doctype() // doctype building up + let commentPending: Token.Comment = Token.Comment() // comment building up + private var lastStartTag: String? // the last start tag emitted, to test appropriate end tag + private var selfClosingFlagAcknowledged: Bool = true + + init(_ reader: CharacterReader, _ errors: ParseErrorList?) { + self.reader = reader + self.errors = errors + } + + func read()throws->Token { + if (!selfClosingFlagAcknowledged) { + error("Self closing flag not acknowledged") + selfClosingFlagAcknowledged = true + } + + while (!isEmitPending) { + try state.read(self, reader) + } + + // if emit is pending, a non-character token was found: return any chars in buffer, and leave token for next read: + if (charsBuilder.length > 0) { + let str: String = charsBuilder.toString() + charsBuilder.clear() + charsString = nil + return charPending.data(str) + } else if (charsString != nil) { + let token: Token = charPending.data(charsString!) + charsString = nil + return token + } else { + isEmitPending = false + return emitPending! + } + } + + func emit(_ token: Token)throws { + try Validate.isFalse(val: isEmitPending, msg: "There is an unread token pending!") + + emitPending = token + isEmitPending = true + + if (token.type == Token.TokenType.StartTag) { + let startTag: Token.StartTag = token as! Token.StartTag + lastStartTag = startTag._tagName! + if (startTag._selfClosing) { + selfClosingFlagAcknowledged = false + } + } else if (token.type == Token.TokenType.EndTag) { + let endTag: Token.EndTag = token as! Token.EndTag + if (endTag._attributes.size() != 0) { + error("Attributes incorrectly present on end tag") + } + } + } + + func emit(_ str: String ) { + // buffer strings up until last string token found, to emit only one token for a run of character refs etc. + // does not set isEmitPending; read checks that + if (charsString == nil) { + charsString = str + } else { + if (charsBuilder.length == 0) { // switching to string builder as more than one emit before read + charsBuilder.append(charsString!) + } + charsBuilder.append(str) + } + } + + func emit(_ chars: [UnicodeScalar]) { + emit(String(chars.map {Character($0)})) + } + + // func emit(_ codepoints: [Int]) { + // emit(String(codepoints, 0, codepoints.length)); + // } + + func emit(_ c: UnicodeScalar) { + emit(String(c)) + } + + func getState() -> TokeniserState { + return state + } + + func transition(_ state: TokeniserState) { + self.state = state + } + + func advanceTransition(_ state: TokeniserState) { + reader.advance() + self.state = state + } + + func acknowledgeSelfClosingFlag() { + selfClosingFlagAcknowledged = true + } + + private var codepointHolder: [UnicodeScalar] = [UnicodeScalar(0)!] // holder to not have to keep creating arrays + private var multipointHolder: [UnicodeScalar] = [UnicodeScalar(0)!, UnicodeScalar(0)!] + + func consumeCharacterReference(_ additionalAllowedCharacter: UnicodeScalar?, _ inAttribute: Bool)throws->[UnicodeScalar]? { + if (reader.isEmpty()) { + return nil + } + if (additionalAllowedCharacter != nil && additionalAllowedCharacter == reader.current()) { + return nil + } + if (reader.matchesAnySorted(Tokeniser.notCharRefCharsSorted)) { + return nil + } + + var codeRef: [UnicodeScalar] = codepointHolder + reader.markPos() + if (reader.matchConsume("#")) { // numbered + let isHexMode: Bool = reader.matchConsumeIgnoreCase("X") + let numRef: String = isHexMode ? reader.consumeHexSequence() : reader.consumeDigitSequence() + if (numRef.unicodeScalars.count == 0) { // didn't match anything + characterReferenceError("numeric reference with no numerals") + reader.rewindToMark() + return nil + } + if (!reader.matchConsume(";")) { + characterReferenceError("missing semicolon") // missing semi + } + var charval: Int = -1 + + let base: Int = isHexMode ? 16 : 10 + if let num = Int(numRef, radix: base) { + charval = num + } + + if (charval == -1 || (charval >= 0xD800 && charval <= 0xDFFF) || charval > 0x10FFFF) { + characterReferenceError("character outside of valid range") + codeRef[0] = Tokeniser.replacementChar + return codeRef + } else { + // todo: implement number replacement table + // todo: check for extra illegal unicode points as parse errors + codeRef[0] = UnicodeScalar(charval)! + return codeRef + } + } else { // named + // get as many letters as possible, and look for matching entities. + let nameRef: String = reader.consumeLetterThenDigitSequence() + let looksLegit: Bool = reader.matches(";") + // found if a base named entity without a ;, or an extended entity with the ;. + let found: Bool = (Entities.isBaseNamedEntity(nameRef) || (Entities.isNamedEntity(nameRef) && looksLegit)) + + if (!found) { + reader.rewindToMark() + if (looksLegit) { // named with semicolon + characterReferenceError("invalid named referenece '\(nameRef)'") + } + return nil + } + if (inAttribute && (reader.matchesLetter() || reader.matchesDigit() || reader.matchesAny("=", "-", "_"))) { + // don't want that to match + reader.rewindToMark() + return nil + } + if (!reader.matchConsume(";")) { + characterReferenceError("missing semicolon") // missing semi + } + let numChars: Int = Entities.codepointsForName(nameRef, codepoints: &multipointHolder) + if (numChars == 1) { + codeRef[0] = multipointHolder[0] + return codeRef + } else if (numChars == 2) { + return multipointHolder + } else { + try Validate.fail(msg: "Unexpected characters returned for \(nameRef) num: \(numChars)") + return multipointHolder + } + } + } + + @discardableResult + func createTagPending(_ start: Bool)->Token.Tag { + tagPending = start ? startPending.reset() : endPending.reset() + return tagPending + } + + func emitTagPending()throws { + try tagPending.finaliseTag() + try emit(tagPending) + } + + func createCommentPending() { + commentPending.reset() + } + + func emitCommentPending()throws { + try emit(commentPending) + } + + func createDoctypePending() { + doctypePending.reset() + } + + func emitDoctypePending()throws { + try emit(doctypePending) + } + + func createTempBuffer() { + Token.reset(dataBuffer) + } + + func isAppropriateEndTagToken()throws->Bool { + if(lastStartTag != nil) { + let s = try tagPending.name() + return s.equalsIgnoreCase(string: lastStartTag!) + } + return false + } + + func appropriateEndTagName() -> String? { + if (lastStartTag == nil) { + return nil + } + return lastStartTag + } + + func error(_ state: TokeniserState) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), "Unexpected character '\(String(reader.current()))' in input state [\(state.description)]")) + } + } + + func eofError(_ state: TokeniserState) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), "Unexpectedly reached end of file (EOF) in input state [\(state.description)]")) + } + } + + private func characterReferenceError(_ message: String) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), "Invalid character reference: \(message)")) + } + } + + private func error(_ errorMsg: String) { + if (errors != nil && errors!.canAddError()) { + errors?.add(ParseError(reader.getPos(), errorMsg)) + } + } + + func currentNodeInHtmlNS() -> Bool { + // todo: implement namespaces correctly + return true + // Element currentNode = currentNode() + // return currentNode != null && currentNode.namespace().equals("HTML") + } + + /** + * Utility method to consume reader and unescape entities found within. + * @param inAttribute + * @return unescaped string from reader + */ + func unescapeEntities(_ inAttribute: Bool)throws->String { + let builder: StringBuilder = StringBuilder() + while (!reader.isEmpty()) { + builder.append(reader.consumeTo(UnicodeScalar.Ampersand)) + if (reader.matches(UnicodeScalar.Ampersand)) { + reader.consume() + if let c = try consumeCharacterReference(nil, inAttribute) { + if (c.count==0) { + builder.append(UnicodeScalar.Ampersand) + } else { + builder.appendCodePoint(c[0]) + if (c.count == 2) { + builder.appendCodePoint(c[1]) + } + } + } else { + builder.append(UnicodeScalar.Ampersand) + } + } + } + return builder.toString() + } + +} diff --git a/Pods/SwiftSoup/Sources/TokeniserState.swift b/Pods/SwiftSoup/Sources/TokeniserState.swift new file mode 100644 index 0000000..707248a --- /dev/null +++ b/Pods/SwiftSoup/Sources/TokeniserState.swift @@ -0,0 +1,1644 @@ +// +// TokeniserState.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 12/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +protocol TokeniserStateProtocol { + func read(_ t: Tokeniser, _ r: CharacterReader)throws +} + +public class TokeniserStateVars { + public static let nullScalr: UnicodeScalar = "\u{0000}" + + static let attributeSingleValueCharsSorted = ["'", UnicodeScalar.Ampersand, nullScalr].sorted() + static let attributeDoubleValueCharsSorted = ["\"", UnicodeScalar.Ampersand, nullScalr].sorted() + static let attributeNameCharsSorted = [UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ", "/", "=", ">", nullScalr, "\"", "'", UnicodeScalar.LessThan].sorted() + static let attributeValueUnquoted = [UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ", UnicodeScalar.Ampersand, ">", nullScalr, "\"", "'", UnicodeScalar.LessThan, "=", "`"].sorted() + + static let replacementChar: UnicodeScalar = Tokeniser.replacementChar + static let replacementStr: String = String(Tokeniser.replacementChar) + static let eof: UnicodeScalar = CharacterReader.EOF +} + +enum TokeniserState: TokeniserStateProtocol { + case Data + case CharacterReferenceInData + case Rcdata + case CharacterReferenceInRcdata + case Rawtext + case ScriptData + case PLAINTEXT + case TagOpen + case EndTagOpen + case TagName + case RcdataLessthanSign + case RCDATAEndTagOpen + case RCDATAEndTagName + case RawtextLessthanSign + case RawtextEndTagOpen + case RawtextEndTagName + case ScriptDataLessthanSign + case ScriptDataEndTagOpen + case ScriptDataEndTagName + case ScriptDataEscapeStart + case ScriptDataEscapeStartDash + case ScriptDataEscaped + case ScriptDataEscapedDash + case ScriptDataEscapedDashDash + case ScriptDataEscapedLessthanSign + case ScriptDataEscapedEndTagOpen + case ScriptDataEscapedEndTagName + case ScriptDataDoubleEscapeStart + case ScriptDataDoubleEscaped + case ScriptDataDoubleEscapedDash + case ScriptDataDoubleEscapedDashDash + case ScriptDataDoubleEscapedLessthanSign + case ScriptDataDoubleEscapeEnd + case BeforeAttributeName + case AttributeName + case AfterAttributeName + case BeforeAttributeValue + case AttributeValue_doubleQuoted + case AttributeValue_singleQuoted + case AttributeValue_unquoted + case AfterAttributeValue_quoted + case SelfClosingStartTag + case BogusComment + case MarkupDeclarationOpen + case CommentStart + case CommentStartDash + case Comment + case CommentEndDash + case CommentEnd + case CommentEndBang + case Doctype + case BeforeDoctypeName + case DoctypeName + case AfterDoctypeName + case AfterDoctypePublicKeyword + case BeforeDoctypePublicIdentifier + case DoctypePublicIdentifier_doubleQuoted + case DoctypePublicIdentifier_singleQuoted + case AfterDoctypePublicIdentifier + case BetweenDoctypePublicAndSystemIdentifiers + case AfterDoctypeSystemKeyword + case BeforeDoctypeSystemIdentifier + case DoctypeSystemIdentifier_doubleQuoted + case DoctypeSystemIdentifier_singleQuoted + case AfterDoctypeSystemIdentifier + case BogusDoctype + case CdataSection + + internal func read(_ t: Tokeniser, _ r: CharacterReader)throws { + switch self { + case .Data: + switch (r.current()) { + case UnicodeScalar.Ampersand: + t.advanceTransition(.CharacterReferenceInData) + break + case UnicodeScalar.LessThan: + t.advanceTransition(.TagOpen) + break + case TokeniserStateVars.nullScalr: + t.error(self) // NOT replacement character (oddly?) + t.emit(r.consume()) + break + case TokeniserStateVars.eof: + try t.emit(Token.EOF()) + break + default: + let data: String = r.consumeData() + t.emit(data) + break + } + break + case .CharacterReferenceInData: + try TokeniserState.readCharRef(t, .Data) + break + case .Rcdata: + switch (r.current()) { + case UnicodeScalar.Ampersand: + t.advanceTransition(.CharacterReferenceInRcdata) + break + case UnicodeScalar.LessThan: + t.advanceTransition(.RcdataLessthanSign) + break + case TokeniserStateVars.nullScalr: + t.error(self) + r.advance() + t.emit(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + try t.emit(Token.EOF()) + break + default: + let data = r.consumeToAny(UnicodeScalar.Ampersand, UnicodeScalar.LessThan, TokeniserStateVars.nullScalr) + t.emit(data) + break + } + break + case .CharacterReferenceInRcdata: + try TokeniserState.readCharRef(t, .Rcdata) + break + case .Rawtext: + try TokeniserState.readData(t, r, self, .RawtextLessthanSign) + break + case .ScriptData: + try TokeniserState.readData(t, r, self, .ScriptDataLessthanSign) + break + case .PLAINTEXT: + switch (r.current()) { + case TokeniserStateVars.nullScalr: + t.error(self) + r.advance() + t.emit(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + try t.emit(Token.EOF()) + break + default: + let data = r.consumeTo(TokeniserStateVars.nullScalr) + t.emit(data) + break + } + break + case .TagOpen: + // from < in data + switch (r.current()) { + case "!": + t.advanceTransition(.MarkupDeclarationOpen) + break + case "/": + t.advanceTransition(.EndTagOpen) + break + case "?": + t.advanceTransition(.BogusComment) + break + default: + if (r.matchesLetter()) { + t.createTagPending(true) + t.transition(.TagName) + } else { + t.error(self) + t.emit(UnicodeScalar.LessThan) // char that got us here + t.transition(.Data) + } + break + } + break + case .EndTagOpen: + if (r.isEmpty()) { + t.eofError(self) + t.emit("")) { + t.error(self) + t.advanceTransition(.Data) + } else { + t.error(self) + t.advanceTransition(.BogusComment) + } + break + case .TagName: + // from < or ": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: // replacement + t.tagPending.appendTagName(TokeniserStateVars.replacementStr) + break + case TokeniserStateVars.eof: // should emit pending tag? + t.eofError(self) + t.transition(.Data) + // no default, as covered with above consumeToAny + default: + break + } + case .RcdataLessthanSign: + if (r.matches("/")) { + t.createTempBuffer() + t.advanceTransition(.RCDATAEndTagOpen) + } else if (r.matchesLetter() && t.appropriateEndTagName() != nil && !r.containsIgnoreCase("), so rather than + // consuming to EOF break out here + t.tagPending = t.createTagPending(false).name(t.appropriateEndTagName()!) + try t.emitTagPending() + r.unconsume() // undo UnicodeScalar.LessThan + t.transition(.Data) + } else { + t.emit(UnicodeScalar.LessThan) + t.transition(.Rcdata) + } + break + case .RCDATAEndTagOpen: + if (r.matchesLetter()) { + t.createTagPending(false) + t.tagPending.appendTagName(r.current()) + t.dataBuffer.append(r.current()) + t.advanceTransition(.RCDATAEndTagName) + } else { + t.emit("": + if (try t.isAppropriateEndTagToken()) { + try t.emitTagPending() + t.transition(.Data) + } else {anythingElse(t, r)} + break + default: + anythingElse(t, r) + break + } + break + case .RawtextLessthanSign: + if (r.matches("/")) { + t.createTempBuffer() + t.advanceTransition(.RawtextEndTagOpen) + } else { + t.emit(UnicodeScalar.LessThan) + t.transition(.Rawtext) + } + break + case .RawtextEndTagOpen: + TokeniserState.readEndTag(t, r, .RawtextEndTagName, .Rawtext) + break + case .RawtextEndTagName: + try TokeniserState.handleDataEndTag(t, r, .Rawtext) + break + case .ScriptDataLessthanSign: + switch (r.consume()) { + case "/": + t.createTempBuffer() + t.transition(.ScriptDataEndTagOpen) + break + case "!": + t.emit("": + t.emit(c) + t.transition(.ScriptData) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.emit(TokeniserStateVars.replacementChar) + t.transition(.ScriptDataEscaped) + break + default: + t.emit(c) + t.transition(.ScriptDataEscaped) + } + break + case .ScriptDataEscapedLessthanSign: + if (r.matchesLetter()) { + t.createTempBuffer() + t.dataBuffer.append(r.current()) + t.emit("<" + String(r.current())) + t.advanceTransition(.ScriptDataDoubleEscapeStart) + } else if (r.matches("/")) { + t.createTempBuffer() + t.advanceTransition(.ScriptDataEscapedEndTagOpen) + } else { + t.emit(UnicodeScalar.LessThan) + t.transition(.ScriptDataEscaped) + } + break + case .ScriptDataEscapedEndTagOpen: + if (r.matchesLetter()) { + t.createTagPending(false) + t.tagPending.appendTagName(r.current()) + t.dataBuffer.append(r.current()) + t.advanceTransition(.ScriptDataEscapedEndTagName) + } else { + t.emit("": + t.emit(c) + t.transition(.ScriptData) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.emit(TokeniserStateVars.replacementChar) + t.transition(.ScriptDataDoubleEscaped) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + default: + t.emit(c) + t.transition(.ScriptDataDoubleEscaped) + } + break + case .ScriptDataDoubleEscapedLessthanSign: + if (r.matches("/")) { + t.emit("/") + t.createTempBuffer() + t.advanceTransition(.ScriptDataDoubleEscapeEnd) + } else { + t.transition(.ScriptDataDoubleEscaped) + } + break + case .ScriptDataDoubleEscapeEnd: + TokeniserState.handleDataDoubleEscapeTag(t, r, .ScriptDataEscaped, .ScriptDataDoubleEscaped) + break + case .BeforeAttributeName: + // from tagname ": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + try t.tagPending.newAttribute() + r.unconsume() + t.transition(.AttributeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"", "'", UnicodeScalar.LessThan, "=": + t.error(self) + try t.tagPending.newAttribute() + t.tagPending.appendAttributeName(c) + t.transition(.AttributeName) + break + default: // A-Z, anything else + try t.tagPending.newAttribute() + r.unconsume() + t.transition(.AttributeName) + } + break + case .AttributeName: + let name = r.consumeToAnySorted(TokeniserStateVars.attributeNameCharsSorted) + t.tagPending.appendAttributeName(name) + + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT: + t.transition(.AfterAttributeName) + break + case "\n": + t.transition(.AfterAttributeName) + break + case "\r": + t.transition(.AfterAttributeName) + break + case UnicodeScalar.BackslashF: + t.transition(.AfterAttributeName) + break + case " ": + t.transition(.AfterAttributeName) + break + case "/": + t.transition(.SelfClosingStartTag) + break + case "=": + t.transition(.BeforeAttributeValue) + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeName(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"": + t.error(self) + t.tagPending.appendAttributeName(c) + case "'": + t.error(self) + t.tagPending.appendAttributeName(c) + case UnicodeScalar.LessThan: + t.error(self) + t.tagPending.appendAttributeName(c) + // no default, as covered in consumeToAny + default: + break + } + break + case .AfterAttributeName: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + // ignore + break + case "/": + t.transition(.SelfClosingStartTag) + break + case "=": + t.transition(.BeforeAttributeValue) + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeName(TokeniserStateVars.replacementChar) + t.transition(.AttributeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"", "'", UnicodeScalar.LessThan: + t.error(self) + try t.tagPending.newAttribute() + t.tagPending.appendAttributeName(c) + t.transition(.AttributeName) + break + default: // A-Z, anything else + try t.tagPending.newAttribute() + r.unconsume() + t.transition(.AttributeName) + } + break + case .BeforeAttributeValue: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + // ignore + break + case "\"": + t.transition(.AttributeValue_doubleQuoted) + break + case UnicodeScalar.Ampersand: + r.unconsume() + t.transition(.AttributeValue_unquoted) + break + case "'": + t.transition(.AttributeValue_singleQuoted) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + t.transition(.AttributeValue_unquoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitTagPending() + t.transition(.Data) + break + case ">": + t.error(self) + try t.emitTagPending() + t.transition(.Data) + break + case UnicodeScalar.LessThan, "=", "`": + t.error(self) + t.tagPending.appendAttributeValue(c) + t.transition(.AttributeValue_unquoted) + break + default: + r.unconsume() + t.transition(.AttributeValue_unquoted) + } + break + case .AttributeValue_doubleQuoted: + let value = r.consumeToAny(TokeniserStateVars.attributeDoubleValueCharsSorted) + if (value.count > 0) { + t.tagPending.appendAttributeValue(value) + } else { + t.tagPending.setEmptyAttributeValue() + } + + let c = r.consume() + switch (c) { + case "\"": + t.transition(.AfterAttributeValue_quoted) + break + case UnicodeScalar.Ampersand: + + if let ref = try t.consumeCharacterReference("\"", true) { + t.tagPending.appendAttributeValue(ref) + } else { + t.tagPending.appendAttributeValue(UnicodeScalar.Ampersand) + } + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + // no default, handled in consume to any above + default: + break + } + break + case .AttributeValue_singleQuoted: + let value = r.consumeToAny(TokeniserStateVars.attributeSingleValueCharsSorted) + if (value.count > 0) { + t.tagPending.appendAttributeValue(value) + } else { + t.tagPending.setEmptyAttributeValue() + } + + let c = r.consume() + switch (c) { + case "'": + t.transition(.AfterAttributeValue_quoted) + break + case UnicodeScalar.Ampersand: + + if let ref = try t.consumeCharacterReference("'", true) { + t.tagPending.appendAttributeValue(ref) + } else { + t.tagPending.appendAttributeValue(UnicodeScalar.Ampersand) + } + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + // no default, handled in consume to any above + default: + break + } + break + case .AttributeValue_unquoted: + let value = r.consumeToAnySorted(TokeniserStateVars.attributeValueUnquoted) + if (value.count > 0) { + t.tagPending.appendAttributeValue(value) + } + + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeAttributeName) + break + case UnicodeScalar.Ampersand: + if let ref = try t.consumeCharacterReference(">", true) { + t.tagPending.appendAttributeValue(ref) + } else { + t.tagPending.appendAttributeValue(UnicodeScalar.Ampersand) + } + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.tagPending.appendAttributeValue(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + case "\"", "'", UnicodeScalar.LessThan, "=", "`": + t.error(self) + t.tagPending.appendAttributeValue(c) + break + // no default, handled in consume to any above + default: + break + } + break + case .AfterAttributeValue_quoted: + // CharacterReferenceInAttributeValue state handled inline + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeAttributeName) + break + case "/": + t.transition(.SelfClosingStartTag) + break + case ">": + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + default: + t.error(self) + r.unconsume() + t.transition(.BeforeAttributeName) + } + break + case .SelfClosingStartTag: + let c = r.consume() + switch (c) { + case ">": + t.tagPending._selfClosing = true + try t.emitTagPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.transition(.Data) + break + default: + t.error(self) + r.unconsume() + t.transition(.BeforeAttributeName) + } + break + case .BogusComment: + // todo: handle bogus comment starting from eof. when does that trigger? + // rewind to capture character that lead us here + r.unconsume() + let comment: Token.Comment = Token.Comment() + comment.bogus = true + comment.data.append(r.consumeTo(">")) + // todo: replace nullChar with replaceChar + try t.emit(comment) + t.advanceTransition(.Data) + break + case .MarkupDeclarationOpen: + if (r.matchConsume("--")) { + t.createCommentPending() + t.transition(.CommentStart) + } else if (r.matchConsumeIgnoreCase("DOCTYPE")) { + t.transition(.Doctype) + } else if (r.matchConsume("[CDATA[")) { + // todo: should actually check current namepspace, and only non-html allows cdata. until namespace + // is implemented properly, keep handling as cdata + //} else if (!t.currentNodeInHtmlNS() && r.matchConsume("[CDATA[")) { + t.transition(.CdataSection) + } else { + t.error(self) + t.advanceTransition(.BogusComment) // advance so self character gets in bogus comment data's rewind + } + break + case .CommentStart: + let c = r.consume() + switch (c) { + case "-": + t.transition(.CommentStartDash) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case ">": + t.error(self) + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append(c) + t.transition(.Comment) + } + break + case .CommentStartDash: + let c = r.consume() + switch (c) { + case "-": + t.transition(.CommentStartDash) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case ">": + t.error(self) + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append(c) + t.transition(.Comment) + } + break + case .Comment: + let c = r.current() + switch (c) { + case "-": + t.advanceTransition(.CommentEndDash) + break + case TokeniserStateVars.nullScalr: + t.error(self) + r.advance() + t.commentPending.data.append(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append(r.consumeToAny("-", TokeniserStateVars.nullScalr)) + } + break + case .CommentEndDash: + let c = r.consume() + switch (c) { + case "-": + t.transition(.CommentEnd) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append("-").append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append("-").append(c) + t.transition(.Comment) + } + break + case .CommentEnd: + let c = r.consume() + switch (c) { + case ">": + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append("--").append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case "!": + t.error(self) + t.transition(.CommentEndBang) + break + case "-": + t.error(self) + t.commentPending.data.append("-") + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.error(self) + t.commentPending.data.append("--").append(c) + t.transition(.Comment) + } + break + case .CommentEndBang: + let c = r.consume() + switch (c) { + case "-": + t.commentPending.data.append("--!") + t.transition(.CommentEndDash) + break + case ">": + try t.emitCommentPending() + t.transition(.Data) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.commentPending.data.append("--!").append(TokeniserStateVars.replacementChar) + t.transition(.Comment) + break + case TokeniserStateVars.eof: + t.eofError(self) + try t.emitCommentPending() + t.transition(.Data) + break + default: + t.commentPending.data.append("--!").append(c) + t.transition(.Comment) + } + break + case .Doctype: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeDoctypeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + // note: fall through to > case + case ">": // catch invalid + t.error(self) + t.createDoctypePending() + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.transition(.BeforeDoctypeName) + } + break + case .BeforeDoctypeName: + if (r.matchesLetter()) { + t.createDoctypePending() + t.transition(.DoctypeName) + return + } + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break // ignore whitespace + case TokeniserStateVars.nullScalr: + t.error(self) + t.createDoctypePending() + t.doctypePending.name.append(TokeniserStateVars.replacementChar) + t.transition(.DoctypeName) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.createDoctypePending() + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.createDoctypePending() + t.doctypePending.name.append(c) + t.transition(.DoctypeName) + } + break + case .DoctypeName: + if (r.matchesLetter()) { + let name = r.consumeLetterSequence() + t.doctypePending.name.append(name) + return + } + let c = r.consume() + switch (c) { + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.AfterDoctypeName) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.name.append(TokeniserStateVars.replacementChar) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.name.append(c) + } + break + case .AfterDoctypeName: + if (r.isEmpty()) { + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + return + } + if (r.matchesAny(UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ")) { + r.advance() // ignore whitespace + } else if (r.matches(">")) { + try t.emitDoctypePending() + t.advanceTransition(.Data) + } else if (r.matchConsumeIgnoreCase(DocumentType.PUBLIC_KEY)) { + t.doctypePending.pubSysKey = DocumentType.PUBLIC_KEY + t.transition(.AfterDoctypePublicKeyword) + } else if (r.matchConsumeIgnoreCase(DocumentType.SYSTEM_KEY)) { + t.doctypePending.pubSysKey = DocumentType.SYSTEM_KEY + t.transition(.AfterDoctypeSystemKeyword) + } else { + t.error(self) + t.doctypePending.forceQuirks = true + t.advanceTransition(.BogusDoctype) + } + break + case .AfterDoctypePublicKeyword: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeDoctypePublicIdentifier) + break + case "\"": + t.error(self) + // set public id to empty string + t.transition(.DoctypePublicIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // set public id to empty string + t.transition(.DoctypePublicIdentifier_singleQuoted) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .BeforeDoctypePublicIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case "\"": + // set public id to empty string + t.transition(.DoctypePublicIdentifier_doubleQuoted) + break + case "'": + // set public id to empty string + t.transition(.DoctypePublicIdentifier_singleQuoted) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .DoctypePublicIdentifier_doubleQuoted: + let c = r.consume() + switch (c) { + case "\"": + t.transition(.AfterDoctypePublicIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.publicIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.publicIdentifier.append(c) + } + break + case .DoctypePublicIdentifier_singleQuoted: + let c = r.consume() + switch (c) { + case "'": + t.transition(.AfterDoctypePublicIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.publicIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.publicIdentifier.append(c) + } + break + case .AfterDoctypePublicIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BetweenDoctypePublicAndSystemIdentifiers) + break + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case "\"": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .BetweenDoctypePublicAndSystemIdentifiers: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case "\"": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .AfterDoctypeSystemKeyword: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(.BeforeDoctypeSystemIdentifier) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case "\"": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + t.error(self) + // system id empty + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + } + break + case .BeforeDoctypeSystemIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case "\"": + // set system id to empty string + t.transition(.DoctypeSystemIdentifier_doubleQuoted) + break + case "'": + // set public id to empty string + t.transition(.DoctypeSystemIdentifier_singleQuoted) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.doctypePending.forceQuirks = true + t.transition(.BogusDoctype) + } + break + case .DoctypeSystemIdentifier_doubleQuoted: + let c = r.consume() + switch (c) { + case "\"": + t.transition(.AfterDoctypeSystemIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.systemIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.systemIdentifier.append(c) + } + break + case .DoctypeSystemIdentifier_singleQuoted: + let c = r.consume() + switch (c) { + case "'": + t.transition(.AfterDoctypeSystemIdentifier) + break + case TokeniserStateVars.nullScalr: + t.error(self) + t.doctypePending.systemIdentifier.append(TokeniserStateVars.replacementChar) + break + case ">": + t.error(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.doctypePending.systemIdentifier.append(c) + } + break + case .AfterDoctypeSystemIdentifier: + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + break + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + t.eofError(self) + t.doctypePending.forceQuirks = true + try t.emitDoctypePending() + t.transition(.Data) + break + default: + t.error(self) + t.transition(.BogusDoctype) + // NOT force quirks + } + break + case .BogusDoctype: + let c = r.consume() + switch (c) { + case ">": + try t.emitDoctypePending() + t.transition(.Data) + break + case TokeniserStateVars.eof: + try t.emitDoctypePending() + t.transition(.Data) + break + default: + // ignore char + break + } + break + case .CdataSection: + let data = r.consumeTo("]]>") + t.emit(data) + r.matchConsume("]]>") + t.transition(.Data) + break + } + } + + var description: String {return String(describing: type(of: self))} + /** + * Handles RawtextEndTagName, ScriptDataEndTagName, and ScriptDataEscapedEndTagName. Same body impl, just + * different else exit transitions. + */ + private static func handleDataEndTag(_ t: Tokeniser, _ r: CharacterReader, _ elseTransition: TokeniserState)throws { + if (r.matchesLetter()) { + let name = r.consumeLetterSequence() + t.tagPending.appendTagName(name) + t.dataBuffer.append(name) + return + } + + var needsExitTransition = false + if (try t.isAppropriateEndTagToken() && !r.isEmpty()) { + let c = r.consume() + switch (c) { + case UnicodeScalar.BackslashT, "\n", "\r", UnicodeScalar.BackslashF, " ": + t.transition(BeforeAttributeName) + break + case "/": + t.transition(SelfClosingStartTag) + break + case ">": + try t.emitTagPending() + t.transition(Data) + break + default: + t.dataBuffer.append(c) + needsExitTransition = true + } + } else { + needsExitTransition = true + } + + if (needsExitTransition) { + t.emit("": + if (t.dataBuffer.toString() == "script") { + t.transition(primary) + } else { + t.transition(fallback) + } + t.emit(c) + break + default: + r.unconsume() + t.transition(fallback) + } + } + +} diff --git a/Pods/SwiftSoup/Sources/TreeBuilder.swift b/Pods/SwiftSoup/Sources/TreeBuilder.swift new file mode 100644 index 0000000..a8b9ac0 --- /dev/null +++ b/Pods/SwiftSoup/Sources/TreeBuilder.swift @@ -0,0 +1,98 @@ +// +// TreeBuilder.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 24/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +public class TreeBuilder { + public var reader: CharacterReader + var tokeniser: Tokeniser + public var doc: Document // current doc we are building into + public var stack: Array // the stack of open elements + public var baseUri: String // current base uri, for creating new elements + public var currentToken: Token? // currentToken is used only for error tracking. + public var errors: ParseErrorList // null when not tracking errors + public var settings: ParseSettings + + private let start: Token.StartTag = Token.StartTag() // start tag to process + private let end: Token.EndTag = Token.EndTag() + + public func defaultSettings() -> ParseSettings {preconditionFailure("This method must be overridden")} + + public init() { + doc = Document("") + reader = CharacterReader("") + tokeniser = Tokeniser(reader, nil) + stack = Array() + baseUri = "" + errors = ParseErrorList(0, 0) + settings = ParseSettings(false, false) + } + + public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) { + doc = Document(baseUri) + self.settings = settings + reader = CharacterReader(input) + self.errors = errors + tokeniser = Tokeniser(reader, errors) + stack = Array() + self.baseUri = baseUri + } + + func parse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings)throws->Document { + initialiseParse(input, baseUri, errors, settings) + try runParser() + return doc + } + + public func runParser()throws { + while (true) { + let token: Token = try tokeniser.read() + try process(token) + token.reset() + + if (token.type == Token.TokenType.EOF) { + break + } + } + } + + @discardableResult + public func process(_ token: Token)throws->Bool {preconditionFailure("This method must be overridden")} + + @discardableResult + public func processStartTag(_ name: String)throws->Bool { + if (currentToken === start) { // don't recycle an in-use token + return try process(Token.StartTag().name(name)) + } + return try process(start.reset().name(name)) + } + + @discardableResult + public func processStartTag(_ name: String, _ attrs: Attributes)throws->Bool { + if (currentToken === start) { // don't recycle an in-use token + return try process(Token.StartTag().nameAttr(name, attrs)) + } + start.reset() + start.nameAttr(name, attrs) + return try process(start) + } + + @discardableResult + public func processEndTag(_ name: String)throws->Bool { + if (currentToken === end) { // don't recycle an in-use token + return try process(Token.EndTag().name(name)) + } + + return try process(end.reset().name(name)) + } + + public func currentElement() -> Element? { + let size: Int = stack.count + return size > 0 ? stack[size-1] : nil + } +} diff --git a/Pods/SwiftSoup/Sources/UnicodeScalar.swift b/Pods/SwiftSoup/Sources/UnicodeScalar.swift new file mode 100644 index 0000000..0a52709 --- /dev/null +++ b/Pods/SwiftSoup/Sources/UnicodeScalar.swift @@ -0,0 +1,67 @@ +// +// UnicodeScalar.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 14/11/16. +// Copyright © 2016 Nabil Chatbi. All rights reserved. +// + +import Foundation + +private let uppercaseSet = CharacterSet.uppercaseLetters +private let lowercaseSet = CharacterSet.lowercaseLetters +private let alphaSet = CharacterSet.letters +private let alphaNumericSet = CharacterSet.alphanumerics +private let symbolSet = CharacterSet.symbols +private let digitSet = CharacterSet.decimalDigits + +extension UnicodeScalar { + public static let Ampersand: UnicodeScalar = "&" + public static let LessThan: UnicodeScalar = "<" + public static let GreaterThan: UnicodeScalar = ">" + + public static let Space: UnicodeScalar = " " + public static let BackslashF: UnicodeScalar = UnicodeScalar(12) + public static let BackslashT: UnicodeScalar = "\t" + public static let BackslashN: UnicodeScalar = "\n" + public static let BackslashR: UnicodeScalar = "\r" + public static let Slash: UnicodeScalar = "/" + + public static let FormFeed: UnicodeScalar = "\u{000B}"// Form Feed + public static let VerticalTab: UnicodeScalar = "\u{000C}"// vertical tab + + func isMemberOfCharacterSet(_ set: CharacterSet) -> Bool { + return set.contains(self) + } + + /// True for any space character, and the control characters \t, \n, \r, \f, \v. + var isWhitespace: Bool { + + switch self { + + case UnicodeScalar.Space, UnicodeScalar.BackslashT, UnicodeScalar.BackslashN, UnicodeScalar.BackslashR, UnicodeScalar.BackslashF: return true + + case UnicodeScalar.FormFeed, UnicodeScalar.VerticalTab: return true // Form Feed, vertical tab + + default: return false + + } + + } + + /// `true` if `self` normalized contains a single code unit that is in the categories of Uppercase and Titlecase Letters. + var isUppercase: Bool { + return isMemberOfCharacterSet(uppercaseSet) + } + + /// `true` if `self` normalized contains a single code unit that is in the category of Lowercase Letters. + var isLowercase: Bool { + return isMemberOfCharacterSet(lowercaseSet) + + } + + var uppercase: UnicodeScalar { + let str = String(self).uppercased() + return str.unicodeScalar(0) + } +} diff --git a/Pods/SwiftSoup/Sources/Validate.swift b/Pods/SwiftSoup/Sources/Validate.swift new file mode 100644 index 0000000..2e6e864 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Validate.swift @@ -0,0 +1,133 @@ +// +// Validate.swift +// SwifSoup +// +// Created by Nabil Chatbi on 02/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +struct Validate { + + /** + * Validates that the object is not null + * @param obj object to test + */ + public static func notNull(obj: Any?) throws { + if (obj == nil) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Object must not be null") + } + } + + /** + * Validates that the object is not null + * @param obj object to test + * @param msg message to output if validation fails + */ + public static func notNull(obj: AnyObject?, msg: String) throws { + if (obj == nil) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + * Validates that the value is true + * @param val object to test + */ + public static func isTrue(val: Bool) throws { + if (!val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Must be true") + } + } + + /** + * Validates that the value is true + * @param val object to test + * @param msg message to output if validation fails + */ + public static func isTrue(val: Bool, msg: String) throws { + if (!val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + * Validates that the value is false + * @param val object to test + */ + public static func isFalse(val: Bool) throws { + if (val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "Must be false") + } + } + + /** + * Validates that the value is false + * @param val object to test + * @param msg message to output if validation fails + */ + public static func isFalse(val: Bool, msg: String) throws { + if (val) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + * Validates that the array contains no null elements + * @param objects the array to test + */ + public static func noNullElements(objects: [AnyObject?]) throws { + try noNullElements(objects: objects, msg: "Array must not contain any null objects") + } + + /** + * Validates that the array contains no null elements + * @param objects the array to test + * @param msg message to output if validation fails + */ + public static func noNullElements(objects: [AnyObject?], msg: String) throws { + for obj in objects { + if (obj == nil) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + } + + /** + * Validates that the string is not empty + * @param string the string to test + */ + public static func notEmpty(string: String?) throws { + if (string == nil || string?.count == 0) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: "String must not be empty") + } + + } + + /** + * Validates that the string is not empty + * @param string the string to test + * @param msg message to output if validation fails + */ + public static func notEmpty(string: String?, msg: String ) throws { + if (string == nil || string?.count == 0) { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + } + + /** + Cause a failure. + @param msg message to output. + */ + public static func fail(msg: String) throws { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } + + /** + Helper + */ + public static func exception(msg: String) throws { + throw Exception.Error(type: ExceptionType.IllegalArgumentException, Message: msg) + } +} diff --git a/Pods/SwiftSoup/Sources/Whitelist.swift b/Pods/SwiftSoup/Sources/Whitelist.swift new file mode 100644 index 0000000..8c2c432 --- /dev/null +++ b/Pods/SwiftSoup/Sources/Whitelist.swift @@ -0,0 +1,650 @@ +// +// Whitelist.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 14/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +/* + Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired + this whitelist configuration, and the initial defaults. + */ + +/** + Whitelists define what HTML (elements and attributes) to allow through the cleaner. Everything else is removed. +

    + Start with one of the defaults: +

    +
      +
    • {@link #none} +
    • {@link #simpleText} +
    • {@link #basic} +
    • {@link #basicWithImages} +
    • {@link #relaxed} +
    +

    + If you need to allow more through (please be careful!), tweak a base whitelist with: +

    +
      +
    • {@link #addTags} +
    • {@link #addAttributes} +
    • {@link #addEnforcedAttribute} +
    • {@link #addProtocols} +
    +

    + You can remove any setting from an existing whitelist with: +

    +
      +
    • {@link #removeTags} +
    • {@link #removeAttributes} +
    • {@link #removeEnforcedAttribute} +
    • {@link #removeProtocols} +
    + +

    + The cleaner and these whitelists assume that you want to clean a body fragment of HTML (to add user + supplied HTML into a templated page), and not to clean a full HTML document. If the latter is the case, either wrap the + document HTML around the cleaned body HTML, or create a whitelist that allows html and head + elements as appropriate. +

    +

    + If you are going to extend a whitelist, please be very careful. Make sure you understand what attributes may lead to + XSS attack vectors. URL attributes are particularly vulnerable and require careful validation. See + http://ha.ckers.org/xss.html for some XSS attack examples. +

    + */ + +import Foundation + +public class Whitelist { + private var tagNames: Set // tags allowed, lower case. e.g. [p, br, span] + private var attributes: Dictionary> // tag -> attribute[]. allowed attributes [href] for a tag. + private var enforcedAttributes: Dictionary> // always set these attribute values + private var protocols: Dictionary>> // allowed URL protocols for attributes + private var preserveRelativeLinks: Bool // option to preserve relative links + + /** + This whitelist allows only text nodes: all HTML will be stripped. + + @return whitelist + */ + public static func none() -> Whitelist { + return Whitelist() + } + + /** + This whitelist allows only simple text formatting: b, em, i, strong, u. All other HTML (tags and + attributes) will be removed. + + @return whitelist + */ + public static func simpleText()throws ->Whitelist { + return try Whitelist().addTags("b", "em", "i", "strong", "u") + } + + /** +

    + This whitelist allows a fuller range of text nodes: a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li, + ol, p, pre, q, small, span, strike, strong, sub, sup, u, ul, and appropriate attributes. +

    +

    + Links (a elements) can point to http, https, ftp, mailto, and have an enforced + rel=nofollow attribute. +

    +

    + Does not allow images. +

    + + @return whitelist + */ + public static func basic()throws->Whitelist { + return try Whitelist() + .addTags( + "a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em", + "i", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", "sub", + "sup", "u", "ul") + + .addAttributes("a", "href") + .addAttributes("blockquote", "cite") + .addAttributes("q", "cite") + + .addProtocols("a", "href", "ftp", "http", "https", "mailto") + .addProtocols("blockquote", "cite", "http", "https") + .addProtocols("cite", "cite", "http", "https") + + .addEnforcedAttribute("a", "rel", "nofollow") + } + + /** + This whitelist allows the same text tags as {@link #basic}, and also allows img tags, with appropriate + attributes, with src pointing to http or https. + + @return whitelist + */ + public static func basicWithImages()throws->Whitelist { + return try basic() + .addTags("img") + .addAttributes("img", "align", "alt", "height", "src", "title", "width") + .addProtocols("img", "src", "http", "https") + + } + + /** + This whitelist allows a full range of text and structural body HTML: a, b, blockquote, br, caption, cite, + code, col, colgroup, dd, div, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, span, strike, strong, sub, + sup, table, tbody, td, tfoot, th, thead, tr, u, ul +

    + Links do not have an enforced rel=nofollow attribute, but you can add that if desired. +

    + + @return whitelist + */ + public static func relaxed()throws->Whitelist { + return try Whitelist() + .addTags( + "a", "b", "blockquote", "br", "caption", "cite", "code", "col", + "colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", + "i", "img", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", + "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", + "ul") + + .addAttributes("a", "href", "title") + .addAttributes("blockquote", "cite") + .addAttributes("col", "span", "width") + .addAttributes("colgroup", "span", "width") + .addAttributes("img", "align", "alt", "height", "src", "title", "width") + .addAttributes("ol", "start", "type") + .addAttributes("q", "cite") + .addAttributes("table", "summary", "width") + .addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width") + .addAttributes( + "th", "abbr", "axis", "colspan", "rowspan", "scope", + "width") + .addAttributes("ul", "type") + + .addProtocols("a", "href", "ftp", "http", "https", "mailto") + .addProtocols("blockquote", "cite", "http", "https") + .addProtocols("cite", "cite", "http", "https") + .addProtocols("img", "src", "http", "https") + .addProtocols("q", "cite", "http", "https") + } + + /** + Create a new, empty whitelist. Generally it will be better to start with a default prepared whitelist instead. + + @see #basic() + @see #basicWithImages() + @see #simpleText() + @see #relaxed() + */ + init() { + tagNames = Set() + attributes = Dictionary>() + enforcedAttributes = Dictionary>() + protocols = Dictionary>>() + preserveRelativeLinks = false + } + + /** + Add a list of allowed elements to a whitelist. (If a tag is not allowed, it will be removed from the HTML.) + + @param tags tag names to allow + @return this (for chaining) + */ + @discardableResult + open func addTags(_ tags: String...)throws ->Whitelist { + for tagName in tags { + try Validate.notEmpty(string: tagName) + tagNames.insert(TagName.valueOf(tagName)) + } + return self + } + + /** + Remove a list of allowed elements from a whitelist. (If a tag is not allowed, it will be removed from the HTML.) + + @param tags tag names to disallow + @return this (for chaining) + */ + @discardableResult + open func removeTags(_ tags: String...)throws ->Whitelist { + try Validate.notNull(obj: tags) + + for tag in tags { + try Validate.notEmpty(string: tag) + let tagName: TagName = TagName.valueOf(tag) + + if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed + tagNames.remove(tagName) + attributes.removeValue(forKey: tagName) + enforcedAttributes.removeValue(forKey: tagName) + protocols.removeValue(forKey: tagName) + } + } + return self + } + + /** + Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.) +

    + E.g.: addAttributes("a", "href", "class") allows href and class attributes + on a tags. +

    +

    + To make an attribute valid for all tags, use the pseudo tag :all, e.g. + addAttributes(":all", "class"). +

    + + @param tag The tag the attributes are for. The tag will be added to the allowed tag list if necessary. + @param keys List of valid attributes for the tag + @return this (for chaining) + */ + @discardableResult + open func addAttributes(_ tag: String, _ keys: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.") + + let tagName = TagName.valueOf(tag) + if (!tagNames.contains(tagName)) { + tagNames.insert(tagName) + } + var attributeSet = Set() + for key in keys { + try Validate.notEmpty(string: key) + attributeSet.insert(AttributeKey.valueOf(key)) + } + + if var currentSet = attributes[tagName] { + for at in attributeSet { + currentSet.insert(at) + } + attributes[tagName] = currentSet + } else { + attributes[tagName] = attributeSet + } + + return self + } + + /** + Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.) +

    + E.g.: removeAttributes("a", "href", "class") disallows href and class + attributes on a tags. +

    +

    + To make an attribute invalid for all tags, use the pseudo tag :all, e.g. + removeAttributes(":all", "class"). +

    + + @param tag The tag the attributes are for. + @param keys List of invalid attributes for the tag + @return this (for chaining) + */ + @discardableResult + open func removeAttributes(_ tag: String, _ keys: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.isTrue(val: keys.count > 0, msg: "No attributes supplied.") + + let tagName: TagName = TagName.valueOf(tag) + var attributeSet = Set() + for key in keys { + try Validate.notEmpty(string: key) + attributeSet.insert(AttributeKey.valueOf(key)) + } + + if(tagNames.contains(tagName)) { // Only look in sub-maps if tag was allowed + if var currentSet = attributes[tagName] { + for l in attributeSet { + currentSet.remove(l) + } + attributes[tagName] = currentSet + if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag + attributes.removeValue(forKey: tagName) + } + } + + } + + if(tag == ":all") { // Attribute needs to be removed from all individually set tags + for name in attributes.keys { + var currentSet: Set = attributes[name]! + for l in attributeSet { + currentSet.remove(l) + } + attributes[name] = currentSet + if(currentSet.isEmpty) { // Remove tag from attribute map if no attributes are allowed for tag + attributes.removeValue(forKey: name) + } + } + } + return self + } + + /** + Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element + already has the attribute set, it will be overridden. +

    + E.g.: addEnforcedAttribute("a", "rel", "nofollow") will make all a tags output as + <a href="..." rel="nofollow"> +

    + + @param tag The tag the enforced attribute is for. The tag will be added to the allowed tag list if necessary. + @param key The attribute key + @param value The enforced attribute value + @return this (for chaining) + */ + @discardableResult + open func addEnforcedAttribute(_ tag: String, _ key: String, _ value: String)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + try Validate.notEmpty(string: value) + + let tagName: TagName = TagName.valueOf(tag) + if (!tagNames.contains(tagName)) { + tagNames.insert(tagName) + } + let attrKey: AttributeKey = AttributeKey.valueOf(key) + let attrVal: AttributeValue = AttributeValue.valueOf(value) + + if (enforcedAttributes[tagName] != nil) { + enforcedAttributes[tagName]?[attrKey] = attrVal + } else { + var attrMap: Dictionary = Dictionary() + attrMap[attrKey] = attrVal + enforcedAttributes[tagName] = attrMap + } + return self + } + + /** + Remove a previously configured enforced attribute from a tag. + + @param tag The tag the enforced attribute is for. + @param key The attribute key + @return this (for chaining) + */ + @discardableResult + open func removeEnforcedAttribute(_ tag: String, _ key: String)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + + let tagName: TagName = TagName.valueOf(tag) + if(tagNames.contains(tagName) && (enforcedAttributes[tagName] != nil)) { + let attrKey: AttributeKey = AttributeKey.valueOf(key) + var attrMap: Dictionary = enforcedAttributes[tagName]! + attrMap.removeValue(forKey: attrKey) + enforcedAttributes[tagName] = attrMap + + if(attrMap.isEmpty) { // Remove tag from enforced attribute map if no enforced attributes are present + enforcedAttributes.removeValue(forKey: tagName) + } + } + return self + } + + /** + * Configure this Whitelist to preserve relative links in an element's URL attribute, or convert them to absolute + * links. By default, this is false: URLs will be made absolute (e.g. start with an allowed protocol, like + * e.g. {@code http://}. + *

    + * Note that when handling relative links, the input document must have an appropriate {@code base URI} set when + * parsing, so that the link's protocol can be confirmed. Regardless of the setting of the {@code preserve relative + * links} option, the link must be resolvable against the base URI to an allowed protocol; otherwise the attribute + * will be removed. + *

    + * + * @param preserve {@code true} to allow relative links, {@code false} (default) to deny + * @return this Whitelist, for chaining. + * @see #addProtocols + */ + @discardableResult + open func preserveRelativeLinks(_ preserve: Bool) -> Whitelist { + preserveRelativeLinks = preserve + return self + } + + /** + Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to + URLs with the defined protocol. +

    + E.g.: addProtocols("a", "href", "ftp", "http", "https") +

    +

    + To allow a link to an in-page URL anchor (i.e. <a href="#anchor">, add a #:
    + E.g.: addProtocols("a", "href", "#") +

    + + @param tag Tag the URL protocol is for + @param key Attribute key + @param protocols List of valid protocols + @return this, for chaining + */ + @discardableResult + open func addProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + + let tagName: TagName = TagName.valueOf(tag) + let attrKey: AttributeKey = AttributeKey.valueOf(key) + var attrMap: Dictionary> + var protSet: Set + + if (self.protocols[tagName] != nil) { + attrMap = self.protocols[tagName]! + } else { + attrMap = Dictionary>() + self.protocols[tagName] = attrMap + } + + if (attrMap[attrKey] != nil) { + protSet = attrMap[attrKey]! + } else { + protSet = Set() + attrMap[attrKey] = protSet + self.protocols[tagName] = attrMap + } + for ptl in protocols { + try Validate.notEmpty(string: ptl) + let prot: Protocol = Protocol.valueOf(ptl) + protSet.insert(prot) + } + attrMap[attrKey] = protSet + self.protocols[tagName] = attrMap + + return self + } + + /** + Remove allowed URL protocols for an element's URL attribute. +

    + E.g.: removeProtocols("a", "href", "ftp") +

    + + @param tag Tag the URL protocol is for + @param key Attribute key + @param protocols List of invalid protocols + @return this, for chaining + */ + @discardableResult + open func removeProtocols(_ tag: String, _ key: String, _ protocols: String...)throws->Whitelist { + try Validate.notEmpty(string: tag) + try Validate.notEmpty(string: key) + + let tagName: TagName = TagName.valueOf(tag) + let attrKey: AttributeKey = AttributeKey.valueOf(key) + + if(self.protocols[tagName] != nil) { + var attrMap: Dictionary> = self.protocols[tagName]! + if(attrMap[attrKey] != nil) { + var protSet: Set = attrMap[attrKey]! + for ptl in protocols { + try Validate.notEmpty(string: ptl) + let prot: Protocol = Protocol.valueOf(ptl) + protSet.remove(prot) + } + attrMap[attrKey] = protSet + + if(protSet.isEmpty) { // Remove protocol set if empty + attrMap.removeValue(forKey: attrKey) + if(attrMap.isEmpty) { // Remove entry for tag if empty + self.protocols.removeValue(forKey: tagName) + } + + } + } + self.protocols[tagName] = attrMap + } + return self + } + + /** + * Test if the supplied tag is allowed by this whitelist + * @param tag test tag + * @return true if allowed + */ + public func isSafeTag(_ tag: String) -> Bool { + return tagNames.contains(TagName.valueOf(tag)) + } + + /** + * Test if the supplied attribute is allowed by this whitelist for this tag + * @param tagName tag to consider allowing the attribute in + * @param el element under test, to confirm protocol + * @param attr attribute under test + * @return true if allowed + */ + public func isSafeAttribute(_ tagName: String, _ el: Element, _ attr: Attribute)throws -> Bool { + let tag: TagName = TagName.valueOf(tagName) + let key: AttributeKey = AttributeKey.valueOf(attr.getKey()) + + if (attributes[tag] != nil) { + if (attributes[tag]?.contains(key))! { + if (protocols[tag] != nil) { + let attrProts: Dictionary> = protocols[tag]! + // ok if not defined protocol; otherwise test + return try (attrProts[key] == nil) || testValidProtocol(el, attr, attrProts[key]!) + } else { // attribute found, no protocols defined, so OK + return true + } + } + } + // no attributes defined for tag, try :all tag + return try !(tagName == ":all") && isSafeAttribute(":all", el, attr) + } + + private func testValidProtocol(_ el: Element, _ attr: Attribute, _ protocols: Set)throws->Bool { + // try to resolve relative urls to abs, and optionally update the attribute so output html has abs. + // rels without a baseuri get removed + var value: String = try el.absUrl(attr.getKey()) + if (value.count == 0) { + value = attr.getValue() + }// if it could not be made abs, run as-is to allow custom unknown protocols + if (!preserveRelativeLinks) { + attr.setValue(value: value) + } + + for ptl in protocols { + var prot: String = ptl.toString() + + if (prot=="#") { // allows anchor links + if (isValidAnchor(value)) { + return true + } else { + continue + } + } + + prot += ":" + + if (value.lowercased().hasPrefix(prot)) { + return true + } + + } + + return false + } + + private func isValidAnchor(_ value: String) -> Bool { + return value.startsWith("#") && !(Pattern(".*\\s.*").matcher(in: value).count > 0) + } + + public func getEnforcedAttributes(_ tagName: String)throws->Attributes { + let attrs: Attributes = Attributes() + let tag: TagName = TagName.valueOf(tagName) + if let keyVals: Dictionary = enforcedAttributes[tag] { + for entry in keyVals { + try attrs.put(entry.key.toString(), entry.value.toString()) + } + } + return attrs + } + +} + +// named types for config. All just hold strings, but here for my sanity. + +open class TagName: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> TagName { + return TagName(value) + } +} + +open class AttributeKey: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> AttributeKey { + return AttributeKey(value) + } +} + +open class AttributeValue: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> AttributeValue { + return AttributeValue(value) + } +} + +open class Protocol: TypedValue { + override init(_ value: String) { + super.init(value) + } + + static func valueOf(_ value: String) -> Protocol { + return Protocol(value) + } +} + +open class TypedValue { + fileprivate let value: String + + init(_ value: String) { + self.value = value + } + + public func toString() -> String { + return value + } +} + +extension TypedValue: Hashable { + public var hashValue: Int { + return value.hashValue + } +} + +public func == (lhs: TypedValue, rhs: TypedValue) -> Bool { + if(lhs === rhs) {return true} + return lhs.value == rhs.value +} diff --git a/Pods/SwiftSoup/Sources/XmlDeclaration.swift b/Pods/SwiftSoup/Sources/XmlDeclaration.swift new file mode 100644 index 0000000..5f1032b --- /dev/null +++ b/Pods/SwiftSoup/Sources/XmlDeclaration.swift @@ -0,0 +1,77 @@ +// +// XmlDeclaration.swift +// SwifSoup +// +// Created by Nabil Chatbi on 29/09/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + An XML Declaration. + */ +public class XmlDeclaration: Node { + private let _name: String + private let isProcessingInstruction: Bool // String { + return "#declaration" + } + + /** + * Get the name of this declaration. + * @return name of this declaration. + */ + public func name() -> String { + return _name + } + + /** + Get the unencoded XML declaration. + @return XML declaration + */ + public func getWholeDeclaration()throws->String { + return try attributes!.html().trim() // attr html starts with a " " + } + + override func outerHtmlHead(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) { + accum + .append("<") + .append(isProcessingInstruction ? "!" : "?") + .append(_name) + do { + try attributes?.html(accum: accum, out: out) + } catch {} + accum + .append(isProcessingInstruction ? "!" : "?") + .append(">") + } + + override func outerHtmlTail(_ accum: StringBuilder, _ depth: Int, _ out: OutputSettings) {} + + public override func copy(with zone: NSZone? = nil) -> Any { + let clone = XmlDeclaration(_name, baseUri!, isProcessingInstruction) + return copy(clone: clone) + } + + public override func copy(parent: Node?) -> Node { + let clone = XmlDeclaration(_name, baseUri!, isProcessingInstruction) + return copy(clone: clone, parent: parent) + } + public override func copy(clone: Node, parent: Node?) -> Node { + return super.copy(clone: clone, parent: parent) + } +} diff --git a/Pods/SwiftSoup/Sources/XmlTreeBuilder.swift b/Pods/SwiftSoup/Sources/XmlTreeBuilder.swift new file mode 100644 index 0000000..785a68b --- /dev/null +++ b/Pods/SwiftSoup/Sources/XmlTreeBuilder.swift @@ -0,0 +1,146 @@ +// +// XmlTreeBuilder.swift +// SwiftSoup +// +// Created by Nabil Chatbi on 14/10/16. +// Copyright © 2016 Nabil Chatbi.. All rights reserved. +// + +import Foundation + +/** + * Use the {@code XmlTreeBuilder} when you want to parse XML without any of the HTML DOM rules being applied to the + * document. + *

    Usage example: {@code Document xmlDoc = Jsoup.parse(html, baseUrl, Parser.xmlParser())}

    + * + */ +public class XmlTreeBuilder: TreeBuilder { + + public override init() { + super.init() + } + + public override func defaultSettings() -> ParseSettings { + return ParseSettings.preserveCase + } + + public func parse(_ input: String, _ baseUri: String)throws->Document { + return try parse(input, baseUri, ParseErrorList.noTracking(), ParseSettings.preserveCase) + } + + override public func initialiseParse(_ input: String, _ baseUri: String, _ errors: ParseErrorList, _ settings: ParseSettings) { + super.initialiseParse(input, baseUri, errors, settings) + stack.append(doc) // place the document onto the stack. differs from HtmlTreeBuilder (not on stack) + doc.outputSettings().syntax(syntax: OutputSettings.Syntax.xml) + } + + override public func process(_ token: Token)throws->Bool { + // start tag, end tag, doctype, comment, character, eof + switch (token.type) { + case .StartTag: + try insert(token.asStartTag()) + break + case .EndTag: + try popStackToClose(token.asEndTag()) + break + case .Comment: + try insert(token.asComment()) + break + case .Char: + try insert(token.asCharacter()) + break + case .Doctype: + try insert(token.asDoctype()) + break + case .EOF: // could put some normalisation here if desired + break +// default: +// try Validate.fail(msg: "Unexpected token type: " + token.tokenType()) + } + return true + } + + private func insertNode(_ node: Node)throws { + try currentElement()?.appendChild(node) + } + + @discardableResult + func insert(_ startTag: Token.StartTag)throws->Element { + let tag: Tag = try Tag.valueOf(startTag.name(), settings) + // todo: wonder if for xml parsing, should treat all tags as unknown? because it's not html. + let el: Element = try Element(tag, baseUri, settings.normalizeAttributes(startTag._attributes)) + try insertNode(el) + if (startTag.isSelfClosing()) { + tokeniser.acknowledgeSelfClosingFlag() + if (!tag.isKnownTag()) // unknown tag, remember this is self closing for output. see above. + { + tag.setSelfClosing() + } + } else { + stack.append(el) + } + return el + } + + func insert(_ commentToken: Token.Comment)throws { + let comment: Comment = Comment(commentToken.getData(), baseUri) + var insert: Node = comment + if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml) + // so we do a bit of a hack and parse the data as an element to pull the attributes out + let data: String = comment.getData() + if (data.count > 1 && (data.startsWith("!") || data.startsWith("?"))) { + let doc: Document = try SwiftSoup.parse("<" + data.substring(1, data.count - 2) + ">", baseUri, Parser.xmlParser()) + let el: Element = doc.child(0) + insert = XmlDeclaration(settings.normalizeTag(el.tagName()), comment.getBaseUri(), data.startsWith("!")) + insert.getAttributes()?.addAll(incoming: el.getAttributes()) + } + } + try insertNode(insert) + } + + func insert(_ characterToken: Token.Char)throws { + let node: Node = TextNode(characterToken.getData()!, baseUri) + try insertNode(node) + } + + func insert(_ d: Token.Doctype)throws { + let doctypeNode = DocumentType(settings.normalizeTag(d.getName()), d.getPubSysKey(), d.getPublicIdentifier(), d.getSystemIdentifier(), baseUri) + try insertNode(doctypeNode) + } + + /** + * If the stack contains an element with this tag's name, pop up the stack to remove the first occurrence. If not + * found, skips. + * + * @param endTag + */ + private func popStackToClose(_ endTag: Token.EndTag)throws { + let elName: String = try endTag.name() + var firstFound: Element? = nil + + for pos in (0..Array { + initialiseParse(inputFragment, baseUri, errors, settings) + try runParser() + return doc.getChildNodes() + } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/Pods/Target Support Files/Alamofire/Alamofire-Info.plist new file mode 100644 index 0000000..b287f84 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 4.8.2 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m new file mode 100644 index 0000000..a6c4594 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Alamofire : NSObject +@end +@implementation PodsDummy_Alamofire +@end diff --git a/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h new file mode 100644 index 0000000..00014e3 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double AlamofireVersionNumber; +FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; + diff --git a/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/Pods/Target Support Files/Alamofire/Alamofire.modulemap new file mode 100644 index 0000000..d1f125f --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.modulemap @@ -0,0 +1,6 @@ +framework module Alamofire { + umbrella header "Alamofire-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig new file mode 100644 index 0000000..12a1450 --- /dev/null +++ b/Pods/Target Support Files/Alamofire/Alamofire.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Pods/Target Support Files/Kanna/Kanna-Info.plist b/Pods/Target Support Files/Kanna/Kanna-Info.plist new file mode 100644 index 0000000..e2771ff --- /dev/null +++ b/Pods/Target Support Files/Kanna/Kanna-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 5.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Kanna/Kanna-dummy.m b/Pods/Target Support Files/Kanna/Kanna-dummy.m new file mode 100644 index 0000000..f3f60bb --- /dev/null +++ b/Pods/Target Support Files/Kanna/Kanna-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Kanna : NSObject +@end +@implementation PodsDummy_Kanna +@end diff --git a/Pods/Target Support Files/Kanna/Kanna-prefix.pch b/Pods/Target Support Files/Kanna/Kanna-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/Kanna/Kanna-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/Kanna/Kanna-umbrella.h b/Pods/Target Support Files/Kanna/Kanna-umbrella.h new file mode 100644 index 0000000..5d24089 --- /dev/null +++ b/Pods/Target Support Files/Kanna/Kanna-umbrella.h @@ -0,0 +1,17 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "Kanna.h" + +FOUNDATION_EXPORT double KannaVersionNumber; +FOUNDATION_EXPORT const unsigned char KannaVersionString[]; + diff --git a/Pods/Target Support Files/Kanna/Kanna.modulemap b/Pods/Target Support Files/Kanna/Kanna.modulemap new file mode 100644 index 0000000..1ccb2e8 --- /dev/null +++ b/Pods/Target Support Files/Kanna/Kanna.modulemap @@ -0,0 +1,6 @@ +framework module Kanna { + umbrella header "Kanna-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Kanna/Kanna.xcconfig b/Pods/Target Support Files/Kanna/Kanna.xcconfig new file mode 100644 index 0000000..3028867 --- /dev/null +++ b/Pods/Target Support Files/Kanna/Kanna.xcconfig @@ -0,0 +1,11 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Kanna +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(SDKROOT)/usr/include/libxml2 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/Kanna +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-Info.plist b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-acknowledgements.markdown b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-acknowledgements.markdown new file mode 100644 index 0000000..a89b042 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-acknowledgements.markdown @@ -0,0 +1,75 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## Alamofire + +Copyright (c) 2014 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. + + +## Kanna + +The MIT License (MIT) + +Copyright (c) 2014 - 2015 Atsushi Kiwaki (@_tid_) + +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. + +## SwiftSoup + +MIT License + +Copyright (c) 2016 Nabil Chatbi + +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. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-acknowledgements.plist b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-acknowledgements.plist new file mode 100644 index 0000000..2c0878b --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-acknowledgements.plist @@ -0,0 +1,119 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2014 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. + + License + MIT + Title + Alamofire + Type + PSGroupSpecifier + + + FooterText + The MIT License (MIT) + +Copyright (c) 2014 - 2015 Atsushi Kiwaki (@_tid_) + +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. + License + MIT + Title + Kanna + Type + PSGroupSpecifier + + + FooterText + MIT License + +Copyright (c) 2016 Nabil Chatbi + +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. + + License + MIT + Title + SwiftSoup + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-dummy.m b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-dummy.m new file mode 100644 index 0000000..2462b9f --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_AvH_Plan : NSObject +@end +@implementation PodsDummy_Pods_AvH_Plan +@end diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh new file mode 100755 index 0000000..72b80e2 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-frameworks.sh @@ -0,0 +1,167 @@ +#!/bin/sh +set -e +set -u +set -o pipefail + +function on_error { + echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" +} +trap 'on_error $LINENO' ERR + +if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then + # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy + # frameworks to, so exit 0 (signalling the script phase was successful). + exit 0 +fi + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +# Used as a return value for each invocation of `strip_invalid_archs` function. +STRIP_BINARY_RETVAL=0 + +# This protects against multiple targets copying the same framework dependency at the same time. The solution +# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html +RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") + +# Copies and strips a vendored framework +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # Use filter instead of exclude so missing patterns don't throw errors. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + elif [ -L "${binary}" ]; then + echo "Destination binary is symlinked..." + dirname="$(dirname "${binary}")" + binary="${dirname}/$(readlink "${binary}")" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Copies and strips a vendored dSYM +install_dsym() { + local source="$1" + if [ -r "$source" ]; then + # Copy the dSYM into a the targets temp dir. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" + + local basename + basename="$(basename -s .framework.dSYM "$source")" + binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"Mach-O dSYM companion"* ]]; then + strip_invalid_archs "$binary" + fi + + if [[ $STRIP_BINARY_RETVAL == 1 ]]; then + # Move the stripped file into its final destination. + echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" + rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" + else + # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. + touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" + fi + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identity + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current target binary + binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" + # Intersect them with the architectures we are building for + intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" + # If there are no archs supported by this binary then warn the user + if [[ -z "$intersected_archs" ]]; then + echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." + STRIP_BINARY_RETVAL=0 + return + fi + stripped="" + for arch in $binary_archs; do + if ! [[ "${ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi + STRIP_BINARY_RETVAL=1 +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Kanna/Kanna.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftSoup/SwiftSoup.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" + install_framework "${BUILT_PRODUCTS_DIR}/Kanna/Kanna.framework" + install_framework "${BUILT_PRODUCTS_DIR}/SwiftSoup/SwiftSoup.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-umbrella.h b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-umbrella.h new file mode 100644 index 0000000..c0862e4 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_AvH_PlanVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_AvH_PlanVersionString[]; + diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.debug.xcconfig b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.debug.xcconfig new file mode 100644 index 0000000..2908fae --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.debug.xcconfig @@ -0,0 +1,12 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna/Kanna.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup/SwiftSoup.framework/Headers" $(SDKROOT)/usr/include/libxml2 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Kanna" -framework "SwiftSoup" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.modulemap b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.modulemap new file mode 100644 index 0000000..9b861eb --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.modulemap @@ -0,0 +1,6 @@ +framework module Pods_AvH_Plan { + umbrella header "Pods-AvH Plan-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.release.xcconfig b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.release.xcconfig new file mode 100644 index 0000000..2908fae --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH Plan/Pods-AvH Plan.release.xcconfig @@ -0,0 +1,12 @@ +ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna/Kanna.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup/SwiftSoup.framework/Headers" $(SDKROOT)/usr/include/libxml2 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Kanna" -framework "SwiftSoup" +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-Info.plist b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-acknowledgements.markdown b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-acknowledgements.markdown new file mode 100644 index 0000000..102af75 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-acknowledgements.plist b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-acknowledgements.plist new file mode 100644 index 0000000..7acbad1 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-dummy.m b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-dummy.m new file mode 100644 index 0000000..5962bfa --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_AvH_PlanTests : NSObject +@end +@implementation PodsDummy_Pods_AvH_PlanTests +@end diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-umbrella.h b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-umbrella.h new file mode 100644 index 0000000..3cb04da --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_AvH_PlanTestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_AvH_PlanTestsVersionString[]; + diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.debug.xcconfig b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.debug.xcconfig new file mode 100644 index 0000000..7f64e99 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.debug.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna/Kanna.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup/SwiftSoup.framework/Headers" $(SDKROOT)/usr/include/libxml2 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Kanna" -framework "SwiftSoup" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.modulemap b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.modulemap new file mode 100644 index 0000000..04561c2 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_AvH_PlanTests { + umbrella header "Pods-AvH PlanTests-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.release.xcconfig b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.release.xcconfig new file mode 100644 index 0000000..7f64e99 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanTests/Pods-AvH PlanTests.release.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna/Kanna.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup/SwiftSoup.framework/Headers" $(SDKROOT)/usr/include/libxml2 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Kanna" -framework "SwiftSoup" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-Info.plist b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-Info.plist new file mode 100644 index 0000000..2243fe6 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-acknowledgements.markdown b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-acknowledgements.markdown new file mode 100644 index 0000000..102af75 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-acknowledgements.markdown @@ -0,0 +1,3 @@ +# Acknowledgements +This application makes use of the following third party libraries: +Generated by CocoaPods - https://cocoapods.org diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-acknowledgements.plist b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-acknowledgements.plist new file mode 100644 index 0000000..7acbad1 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-acknowledgements.plist @@ -0,0 +1,29 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-dummy.m b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-dummy.m new file mode 100644 index 0000000..d04ec77 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_AvH_PlanUITests : NSObject +@end +@implementation PodsDummy_Pods_AvH_PlanUITests +@end diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-umbrella.h b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-umbrella.h new file mode 100644 index 0000000..986d1f1 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_AvH_PlanUITestsVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_AvH_PlanUITestsVersionString[]; + diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.debug.xcconfig b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.debug.xcconfig new file mode 100644 index 0000000..7f64e99 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.debug.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna/Kanna.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup/SwiftSoup.framework/Headers" $(SDKROOT)/usr/include/libxml2 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Kanna" -framework "SwiftSoup" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.modulemap b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.modulemap new file mode 100644 index 0000000..dca6436 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.modulemap @@ -0,0 +1,6 @@ +framework module Pods_AvH_PlanUITests { + umbrella header "Pods-AvH PlanUITests-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.release.xcconfig b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.release.xcconfig new file mode 100644 index 0000000..7f64e99 --- /dev/null +++ b/Pods/Target Support Files/Pods-AvH PlanUITests/Pods-AvH PlanUITests.release.xcconfig @@ -0,0 +1,10 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/Kanna/Kanna.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup/SwiftSoup.framework/Headers" $(SDKROOT)/usr/include/libxml2 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "Kanna" -framework "SwiftSoup" +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods +SWIFT_INCLUDE_PATHS = $(SRCROOT)/Kanna/Modules diff --git a/Pods/Target Support Files/SwiftSoup/SwiftSoup-Info.plist b/Pods/Target Support Files/SwiftSoup/SwiftSoup-Info.plist new file mode 100644 index 0000000..68269a0 --- /dev/null +++ b/Pods/Target Support Files/SwiftSoup/SwiftSoup-Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.7.4 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Pods/Target Support Files/SwiftSoup/SwiftSoup-dummy.m b/Pods/Target Support Files/SwiftSoup/SwiftSoup-dummy.m new file mode 100644 index 0000000..8b1126f --- /dev/null +++ b/Pods/Target Support Files/SwiftSoup/SwiftSoup-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_SwiftSoup : NSObject +@end +@implementation PodsDummy_SwiftSoup +@end diff --git a/Pods/Target Support Files/SwiftSoup/SwiftSoup-prefix.pch b/Pods/Target Support Files/SwiftSoup/SwiftSoup-prefix.pch new file mode 100644 index 0000000..beb2a24 --- /dev/null +++ b/Pods/Target Support Files/SwiftSoup/SwiftSoup-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Pods/Target Support Files/SwiftSoup/SwiftSoup-umbrella.h b/Pods/Target Support Files/SwiftSoup/SwiftSoup-umbrella.h new file mode 100644 index 0000000..57166c4 --- /dev/null +++ b/Pods/Target Support Files/SwiftSoup/SwiftSoup-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double SwiftSoupVersionNumber; +FOUNDATION_EXPORT const unsigned char SwiftSoupVersionString[]; + diff --git a/Pods/Target Support Files/SwiftSoup/SwiftSoup.modulemap b/Pods/Target Support Files/SwiftSoup/SwiftSoup.modulemap new file mode 100644 index 0000000..bed11d0 --- /dev/null +++ b/Pods/Target Support Files/SwiftSoup/SwiftSoup.modulemap @@ -0,0 +1,6 @@ +framework module SwiftSoup { + umbrella header "SwiftSoup-umbrella.h" + + export * + module * { export * } +} diff --git a/Pods/Target Support Files/SwiftSoup/SwiftSoup.xcconfig b/Pods/Target Support Files/SwiftSoup/SwiftSoup.xcconfig new file mode 100644 index 0000000..41d720b --- /dev/null +++ b/Pods/Target Support Files/SwiftSoup/SwiftSoup.xcconfig @@ -0,0 +1,9 @@ +CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/SwiftSoup +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS +PODS_BUILD_DIR = ${BUILD_DIR} +PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/SwiftSoup +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES