From 0428af763a27a59e4b7cdb5dae4599704bfd5d68 Mon Sep 17 00:00:00 2001 From: Ivan Magda Date: Thu, 26 Mar 2020 14:02:21 +0300 Subject: [PATCH 1/6] Update dependencies 1.118 (#684) * Bump Nuke from 8.3.1 to 8.4.1 Bumps [Nuke](https://github.com/kean/Nuke) from 8.3.1 to 8.4.1 - [Release notes](https://github.com/kean/Nuke/releases/tag/8.4.1) - [Commits](https://github.com/kean/Nuke/compare/8.3.1...8.4.1) * Bump Agrume from 5.6.5 to 5.6.7 Bumps [Agrume](https://github.com/JanGorman/Agrume) from 5.6.5 to 5.6.7 - [Release notes](https://github.com/JanGorman/Agrume/releases/tag/5.6.7) - [Commits](https://github.com/JanGorman/Agrume/compare/5.6.5...5.6.7) * Bump fastlane from 2.143.0 to 2.144.0 Bumps [fastlane](https://github.com/fastlane/fastlane) from 2.143.0 to 2.144.0 - [Release notes](https://github.com/fastlane/fastlane/releases/tag/2.144.0) - [Commits](https://github.com/fastlane/fastlane/compare/2.143.0...2.144.0) * Bump Firebase from 6.19.0 to 6.21.0 Bumps [Firebase](https://github.com/firebase/firebase-ios-sdk) from 6.19.0 to 6.21.0 - [Release notes](https://github.com/firebase/firebase-ios-sdk/releases/tag/6.21.0) - [Commits](https://github.com/firebase/firebase-ios-sdk/compare/6.19.0...6.21.0) --- Gemfile | 2 +- Gemfile.lock | 28 +++++++++------- Podfile | 12 +++---- Podfile.lock | 84 +++++++++++++++++++++++------------------------ fastlane/Fastfile | 2 +- 5 files changed, 67 insertions(+), 61 deletions(-) diff --git a/Gemfile b/Gemfile index d016120e63..2f48903e89 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,7 @@ source "https://rubygems.org" ruby "2.6.5" -gem "fastlane", "2.143.0" +gem "fastlane", "2.144.0" gem "cocoapods", "1.9.1" plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile') diff --git a/Gemfile.lock b/Gemfile.lock index 7f6ffd1230..b0400ab21c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -14,13 +14,19 @@ GEM json (>= 1.5.1) atomos (0.1.3) aws-eventstream (1.0.3) - aws-sdk (2.11.463) - aws-sdk-resources (= 2.11.463) - aws-sdk-core (2.11.463) - aws-sigv4 (~> 1.0) + aws-partitions (1.288.0) + aws-sdk-core (3.92.0) + aws-eventstream (~> 1.0, >= 1.0.2) + aws-partitions (~> 1, >= 1.239.0) + aws-sigv4 (~> 1.1) jmespath (~> 1.0) - aws-sdk-resources (2.11.463) - aws-sdk-core (= 2.11.463) + aws-sdk-kms (1.30.0) + aws-sdk-core (~> 3, >= 3.71.0) + aws-sigv4 (~> 1.1) + aws-sdk-s3 (1.61.1) + aws-sdk-core (~> 3, >= 3.83.0) + aws-sdk-kms (~> 1) + aws-sigv4 (~> 1.1) aws-sigv4 (1.1.1) aws-eventstream (~> 1.0, >= 1.0.2) babosa (1.0.3) @@ -77,7 +83,7 @@ GEM escape (0.0.4) ethon (0.12.0) ffi (>= 1.3.0) - excon (0.72.0) + excon (0.73.0) faraday (0.17.3) multipart-post (>= 1.2, < 3) faraday-cookie_jar (0.0.6) @@ -86,10 +92,10 @@ GEM faraday_middleware (0.13.1) faraday (>= 0.7.4, < 1.0) fastimage (2.1.7) - fastlane (2.143.0) + fastlane (2.144.0) CFPropertyList (>= 2.3, < 4.0.0) addressable (>= 2.3, < 3.0.0) - aws-sdk (~> 2.3) + aws-sdk-s3 (~> 1.0) babosa (>= 1.0.2, < 2.0.0) bundler (>= 1.12.0, < 3.0.0) colored @@ -190,7 +196,7 @@ GEM ruby-macho (1.4.0) rubyzip (1.3.0) security (0.1.3) - signet (0.13.0) + signet (0.13.2) addressable (~> 2.3) faraday (>= 0.17.3, < 2.0) jwt (>= 1.5, < 3.0) @@ -233,7 +239,7 @@ PLATFORMS DEPENDENCIES cocoapods (= 1.9.1) - fastlane (= 2.143.0) + fastlane (= 2.144.0) fastlane-plugin-firebase_app_distribution RUBY VERSION diff --git a/Podfile b/Podfile index ce5394b0ef..9e5cf796f1 100644 --- a/Podfile +++ b/Podfile @@ -29,10 +29,10 @@ def all_pods pod 'SnapKit', '5.0.1' # Firebase - pod 'Firebase/Core', '6.19.0' - pod 'Firebase/Messaging' , '6.19.0' - pod 'Firebase/Analytics' , '6.19.0' - pod 'Firebase/RemoteConfig', '6.19.0' + pod 'Firebase/Core', '6.21.0' + pod 'Firebase/Messaging' , '6.21.0' + pod 'Firebase/Analytics' , '6.21.0' + pod 'Firebase/RemoteConfig', '6.21.0' pod 'YandexMobileMetrica/Dynamic', '3.9.4' pod 'Amplitude-iOS', '4.9.3' @@ -53,7 +53,7 @@ def all_pods pod 'Presentr', '1.9' - pod 'Agrume', '5.6.5' + pod 'Agrume', '5.6.7' pod 'Highlightr', '2.1.0' pod 'TTTAttributedLabel', '2.0.0' pod 'lottie-ios', '2.5.3' @@ -61,7 +61,7 @@ def all_pods pod 'Charts', '3.4.0' pod 'EasyTipView', '2.0.4' pod 'ActionSheetPicker-3.0', '2.4.0' - pod 'Nuke', '8.3.1' + pod 'Nuke', '8.4.1' pod 'STRegex', '2.1.1' pod 'Tabman', '2.8.0' pod 'SwiftDate', '6.1.0' diff --git a/Podfile.lock b/Podfile.lock index f2551a4240..8664b28ec7 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -1,6 +1,6 @@ PODS: - ActionSheetPicker-3.0 (2.4.0) - - Agrume (5.6.5): + - Agrume (5.6.7): - SwiftyGif - Alamofire (4.9.1) - Amplitude-iOS (4.9.3) @@ -32,34 +32,34 @@ PODS: - FBSDKLoginKit/Login (= 5.13.0) - FBSDKLoginKit/Login (5.13.0): - FBSDKCoreKit (~> 5.0) - - Firebase/Analytics (6.19.0): + - Firebase/Analytics (6.21.0): - Firebase/Core - - Firebase/Core (6.19.0): + - Firebase/Core (6.21.0): - Firebase/CoreOnly - - FirebaseAnalytics (= 6.3.1) - - Firebase/CoreOnly (6.19.0): - - FirebaseCore (= 6.6.4) - - Firebase/Messaging (6.19.0): + - FirebaseAnalytics (= 6.4.0) + - Firebase/CoreOnly (6.21.0): + - FirebaseCore (= 6.6.5) + - Firebase/Messaging (6.21.0): - Firebase/CoreOnly - FirebaseMessaging (~> 4.3.0) - - Firebase/RemoteConfig (6.19.0): + - Firebase/RemoteConfig (6.21.0): - Firebase/CoreOnly - FirebaseRemoteConfig (~> 4.4.9) - FirebaseABTesting (3.2.0): - FirebaseAnalyticsInterop (~> 1.3) - FirebaseCore (~> 6.1) - Protobuf (>= 3.9.2, ~> 3.9) - - FirebaseAnalytics (6.3.1): + - FirebaseAnalytics (6.4.0): - FirebaseCore (~> 6.6) - FirebaseInstallations (~> 1.1) - - GoogleAppMeasurement (= 6.3.1) + - GoogleAppMeasurement (= 6.4.0) - GoogleUtilities/AppDelegateSwizzler (~> 6.0) - GoogleUtilities/MethodSwizzler (~> 6.0) - GoogleUtilities/Network (~> 6.0) - "GoogleUtilities/NSData+zlib (~> 6.0)" - nanopb (= 0.3.9011) - FirebaseAnalyticsInterop (1.5.0) - - FirebaseCore (6.6.4): + - FirebaseCore (6.6.5): - FirebaseCoreDiagnostics (~> 1.2) - FirebaseCoreDiagnosticsInterop (~> 1.2) - GoogleUtilities/Environment (~> 6.5) @@ -71,7 +71,7 @@ PODS: - GoogleUtilities/Logger (~> 6.5) - nanopb (~> 0.3.901) - FirebaseCoreDiagnosticsInterop (1.2.0) - - FirebaseInstallations (1.1.0): + - FirebaseInstallations (1.1.1): - FirebaseCore (~> 6.6) - GoogleUtilities/UserDefaults (~> 6.5) - PromisesObjC (~> 1.2) @@ -97,33 +97,33 @@ PODS: - GoogleUtilities/Environment (~> 6.2) - "GoogleUtilities/NSData+zlib (~> 6.2)" - Protobuf (>= 3.9.2, ~> 3.9) - - GoogleAppMeasurement (6.3.1): + - GoogleAppMeasurement (6.4.0): - GoogleUtilities/AppDelegateSwizzler (~> 6.0) - GoogleUtilities/MethodSwizzler (~> 6.0) - GoogleUtilities/Network (~> 6.0) - "GoogleUtilities/NSData+zlib (~> 6.0)" - nanopb (= 0.3.9011) - - GoogleDataTransport (5.0.0) - - GoogleDataTransportCCTSupport (2.0.0): - - GoogleDataTransport (~> 5.0) + - GoogleDataTransport (5.1.0) + - GoogleDataTransportCCTSupport (2.0.1): + - GoogleDataTransport (~> 5.1) - nanopb (~> 0.3.901) - - GoogleUtilities/AppDelegateSwizzler (6.5.1): + - GoogleUtilities/AppDelegateSwizzler (6.5.2): - GoogleUtilities/Environment - GoogleUtilities/Logger - GoogleUtilities/Network - - GoogleUtilities/Environment (6.5.1) - - GoogleUtilities/Logger (6.5.1): + - GoogleUtilities/Environment (6.5.2) + - GoogleUtilities/Logger (6.5.2): - GoogleUtilities/Environment - - GoogleUtilities/MethodSwizzler (6.5.1): + - GoogleUtilities/MethodSwizzler (6.5.2): - GoogleUtilities/Logger - - GoogleUtilities/Network (6.5.1): + - GoogleUtilities/Network (6.5.2): - GoogleUtilities/Logger - "GoogleUtilities/NSData+zlib" - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (6.5.1)" - - GoogleUtilities/Reachability (6.5.1): + - "GoogleUtilities/NSData+zlib (6.5.2)" + - GoogleUtilities/Reachability (6.5.2): - GoogleUtilities/Logger - - GoogleUtilities/UserDefaults (6.5.1): + - GoogleUtilities/UserDefaults (6.5.2): - GoogleUtilities/Logger - HexColors (2.3.0) - Highlightr (2.1.0) @@ -145,7 +145,7 @@ PODS: - nanopb/decode (0.3.9011) - nanopb/encode (0.3.9011) - Nimble (8.0.5) - - Nuke (8.3.1) + - Nuke (8.4.1) - Pageboy (3.5.0) - pop (1.0.12) - Presentr (1.9) @@ -191,7 +191,7 @@ PODS: DEPENDENCIES: - ActionSheetPicker-3.0 (= 2.4.0) - - Agrume (= 5.6.5) + - Agrume (= 5.6.7) - Alamofire (= 4.9.1) - Amplitude-iOS (= 4.9.3) - Atributika (= 4.9.5) @@ -206,10 +206,10 @@ DEPENDENCIES: - Fabric (= 1.10.2) - FBSDKCoreKit (= 5.13.0) - FBSDKLoginKit (= 5.13.0) - - Firebase/Analytics (= 6.19.0) - - Firebase/Core (= 6.19.0) - - Firebase/Messaging (= 6.19.0) - - Firebase/RemoteConfig (= 6.19.0) + - Firebase/Analytics (= 6.21.0) + - Firebase/Core (= 6.21.0) + - Firebase/Messaging (= 6.21.0) + - Firebase/RemoteConfig (= 6.21.0) - Highlightr (= 2.1.0) - IQKeyboardManagerSwift (= 6.5.4) - Kanna (= 5.0.0) @@ -217,7 +217,7 @@ DEPENDENCIES: - lottie-ios (= 2.5.3) - Mockingjay (= 3.0.0-alpha.1) - Nimble (= 8.0.5) - - Nuke (= 8.3.1) + - Nuke (= 8.4.1) - Presentr (= 1.9) - PromiseKit (= 6.13.0) - Quick (= 2.2.0) @@ -321,7 +321,7 @@ CHECKOUT OPTIONS: SPEC CHECKSUMS: ActionSheetPicker-3.0: c68e1f8355828b4e1c823fa87185aacfef5e6fe3 - Agrume: ad8e6428b9e1cb305ff14ee6195cefe2f938d13d + Agrume: 1440351654f1d8669f240b5e7f1c76bafa15cd02 Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18 Amplitude-iOS: 122e026c44db8460e5efcf84859aa290a0ae9786 Atributika: 19429d34013b6d860feb5427c67bdbd219414e1f @@ -337,21 +337,21 @@ SPEC CHECKSUMS: Fabric: 706c8b8098fff96c33c0db69cbf81f9c551d0d74 FBSDKCoreKit: b1645dba3dfdba6102f2d4026fdbfca8114dc229 FBSDKLoginKit: 4aca55e93a63b1ff0cb9446208d49e32c13ab24a - Firebase: d55ddb0e0bb3207166cddc028647833d8a1b5b6f + Firebase: f378c80340dd41c0ad0914af740c021eb282a04b FirebaseABTesting: 821a3a3e4a145987e80fee3657c4de1cb9adf693 - FirebaseAnalytics: 572e467f3d977825266e8ccd52674aa3e6f47eac + FirebaseAnalytics: a1a0b3327ceb5cd5b4bacffdb293f6c909aa087d FirebaseAnalyticsInterop: 3f86269c38ae41f47afeb43ebf32a001f58fcdae - FirebaseCore: ed0a24c758a57c2b88c5efa8e6a8195e868af589 + FirebaseCore: 9f495d3afacb7b558711e6218ebb14b1c51b5802 FirebaseCoreDiagnostics: e9b4cd8ba60dee0f2d13347332e4b7898cca5b61 FirebaseCoreDiagnosticsInterop: 296e2c5f5314500a850ad0b83e9e7c10b011a850 - FirebaseInstallations: 575cd32f2aec0feeb0e44f5d0110a09e5e60b47b + FirebaseInstallations: acb3216eb9784d3b1d2d2d635ff74fa892cc0c44 FirebaseInstanceID: 7ee0d6777013bb952f377b41965bf132b6a075be FirebaseMessaging: 4ec33842d36b3319e062e51fb8b35a74f726950d FirebaseRemoteConfig: 47abf7a04a9082091955ea555aa79cfdd249b19c - GoogleAppMeasurement: c29d405ff76e18551b5d158eaba6753fda8c7542 - GoogleDataTransport: a857c6a002d201b524dd4bc2ed7e7355ed07e785 - GoogleDataTransportCCTSupport: 32f75fbe904c82772fcbb6b6bd4525bfb6f2a862 - GoogleUtilities: 06eb53bb579efe7099152735900dd04bf09e7275 + GoogleAppMeasurement: 6e68a94d0eaeb1d73ef6b0ed4f7334e29d63ae29 + GoogleDataTransport: b29a21d813e906014ca16c00897827e40e4a24ab + GoogleDataTransportCCTSupport: 6f15a89b0ca35d6fa523e1f752ef818588885988 + GoogleUtilities: ad0f3b691c67909d03a3327cc205222ab8f42e0e HexColors: 6ad3947c3447a055a3aa8efa859def096351fe5f Highlightr: 595f3e100737c8de41113385da8bd0b5b65212c6 IQKeyboardManagerSwift: 2dde0fc70110e8eac7ccce2a46fdbec6a850b414 @@ -361,7 +361,7 @@ SPEC CHECKSUMS: Mockingjay: 0f7c5aa49c7f1b95621cee3c79b557141f5a225c nanopb: 18003b5e52dab79db540fe93fe9579f399bd1ccd Nimble: 4ab1aeb9b45553c75b9687196b0fa0713170a332 - Nuke: 85fb80f8df0cb26c28d2f4e0cb7fb93bcd6548d3 + Nuke: d780e3507a86b86c589ab3cc5cd302d5456f06fb Pageboy: 3794c578aae5fcce06e90b3ed4a0ad6b807d75bb pop: d582054913807fd11fd50bfe6a539d91c7e1a55a Presentr: 7078d7eb5d1661ebeaae60c9e42a1e534de1b993 @@ -387,6 +387,6 @@ SPEC CHECKSUMS: VK-ios-sdk: 62a10b6571fbcda0657f455fedce7fedf55b4cd0 YandexMobileMetrica: 1030df2959c886a7be3bc3d274eb54c8e86afd6f -PODFILE CHECKSUM: 862182232c8c138cc30830257ae9f062a08c743c +PODFILE CHECKSUM: bf6b5b0ffb011b1f71f717b264a76aa6ca9c8a73 COCOAPODS: 1.9.1 diff --git a/fastlane/Fastfile b/fastlane/Fastfile index 05cc6a6992..6adde753dc 100644 --- a/fastlane/Fastfile +++ b/fastlane/Fastfile @@ -1,5 +1,5 @@ # This is the minimum version number required. -fastlane_version "2.143.0" +fastlane_version "2.144.0" default_platform :ios From e7d14474341a544a092530b876c153de1c769dec Mon Sep 17 00:00:00 2001 From: Ivan Magda Date: Sun, 29 Mar 2020 14:42:10 +0300 Subject: [PATCH 2/6] Alamofire 5.0 Migration (#656) * Bump Alamofire to 5.0.0 * Rename Sessionmanager -> Session * Bump Alamofire from 5.0.0 to 5.0.4 Bumps [Alamofire](https://github.com/Alamofire/Alamofire) from 5.0.0 to 5.0.4 - [Release notes](https://github.com/Alamofire/Alamofire/releases/tag/5.0.4) - [Commits](https://github.com/Alamofire/Alamofire/compare/5.0.0...5.0.4) * Bump Alamofire from 5.0.4 to 5.0.5 Bumps [Alamofire](https://github.com/Alamofire/Alamofire) from 5.0.4 to 5.0.5 - [Release notes](https://github.com/Alamofire/Alamofire/releases/tag/5.0.5) - [Commits](https://github.com/Alamofire/Alamofire/compare/5.0.4...5.0.5) * Migrate Alamofire-SwiftyJSON * Refactor rename Result -> StepikResult & deprecate * Refactor rename Session -> StepikSession * Migrate ApiRequestRetrier to RequestInterceptor * Migrate API * Update SwiftyJSON response serializer * Clean up --- Alamofire-SwiftyJSON.swift | 121 ++++------ Podfile | 2 +- Podfile.lock | 20 +- Stepic.xcodeproj/project.pbxproj | 36 ++- Stepic/Legacy/AppDelegate.swift | 6 +- .../Extensions/UIImageView+SVGDownload.swift | 56 +++-- .../DeleteDeviceExecutableTask.swift | 4 +- .../Views/PostViewsExecutableTask.swift | 130 ++++++----- .../RemoteVersionManager.swift | 69 +++--- .../InAppVersionControl/UpdateChecker.swift | 22 +- Stepic/Legacy/Model/Network/APIDefaults.swift | 19 +- .../AlamofireDefaultSessionManager.swift | 4 +- .../Network/AlamofireRequestsLogger.swift | 45 +--- Stepic/Legacy/Model/Network/ApiRequest.swift | 4 +- .../Model/Network/ApiRequestRetrier.swift | 34 --- Stepic/Legacy/Model/Network/AuthAPI.swift | 216 +++++++++++++----- .../Model/Network/Endpoints/APIEndpoint.swift | 24 +- .../Endpoints/AdaptiveRatingsAPI.swift | 47 ++-- .../Network/Endpoints/AssignmentsAPI.swift | 5 +- .../Model/Network/Endpoints/AttemptsAPI.swift | 41 +--- .../Network/Endpoints/CertificatesAPI.swift | 2 +- .../Endpoints/CourseReviewSummariesAPI.swift | 4 +- .../Model/Network/Endpoints/CoursesAPI.swift | 8 +- .../Model/Network/Endpoints/DevicesAPI.swift | 33 ++- .../Endpoints/DiscussionProxiesAPI.swift | 13 +- .../Network/Endpoints/EnrollmentsAPI.swift | 66 ++---- .../Network/Endpoints/LastStepsAPI.swift | 4 +- .../Model/Network/Endpoints/LessonsAPI.swift | 6 +- .../Network/Endpoints/NotificationsAPI.swift | 2 +- .../Model/Network/Endpoints/ProfilesAPI.swift | 4 +- .../Network/Endpoints/ProgressesAPI.swift | 10 +- .../Model/Network/Endpoints/QueriesAPI.swift | 30 ++- .../Endpoints/RecommendationsAPI.swift | 8 +- .../Network/Endpoints/SearchResultsAPI.swift | 69 +++--- .../Model/Network/Endpoints/SectionsAPI.swift | 2 +- .../Model/Network/Endpoints/StepicsAPI.swift | 2 +- .../Model/Network/Endpoints/StepsAPI.swift | 6 +- .../Network/Endpoints/SubmissionsAPI.swift | 90 +++----- .../Model/Network/Endpoints/UnitsAPI.swift | 25 +- .../Network/Endpoints/UserActivitiesAPI.swift | 2 +- .../Model/Network/Endpoints/UsersAPI.swift | 6 +- .../Model/Network/Endpoints/ViewsAPI.swift | 49 ++-- .../RequestMakers/CreateRequestMaker.swift | 6 +- .../RequestMakers/DeleteRequestMaker.swift | 2 +- .../RequestMakers/RetrieveRequestMaker.swift | 14 +- .../RequestMakers/UpdateRequestMaker.swift | 4 +- .../Model/Network/StepikRequestAdapter.swift | 17 ++ .../Network/StepikRequestInterceptor.swift | 31 +++ .../Model/Network/StepikRequestRetrier.swift | 24 ++ .../Legacy/Model/StepikSession/AuthInfo.swift | 11 +- .../{Session.swift => StepikSession.swift} | 56 +++-- Stepic/Legacy/Views/AvatarImageView.swift | 53 ++--- Stepic/Sources/Common/Result.swift | 6 - Stepic/Sources/Common/StepikResult.swift | 9 + .../ThirdParty/HTTPHeader+Stepik.swift | 11 + .../CourseInfo/CourseInfoDataFlow.swift | 2 +- .../CourseInfoTabSyllabusDataFlow.swift | 2 +- .../CourseList/CourseListDataFlow.swift | 2 +- .../Discussions/DiscussionsDataFlow.swift | 6 +- .../Modules/EditStep/EditStepDataFlow.swift | 2 +- .../CourseListsCollectionDataFlow.swift | 2 +- .../CourseListsCollectionInteractor.swift | 4 +- .../ExploreSubmodules/Tags/TagsDataFlow.swift | 2 +- .../Modules/Lesson/LessonDataFlow.swift | 2 +- .../Quizzes/BaseQuiz/BaseQuizDataFlow.swift | 2 +- .../CodeQuizFullscreenRunCodeDataFlow.swift | 2 +- .../Modules/Solution/SolutionDataFlow.swift | 2 +- .../Sources/Modules/Step/StepDataFlow.swift | 4 +- .../Submissions/SubmissionsDataFlow.swift | 4 +- .../WriteComment/WriteCommentDataFlow.swift | 2 +- .../Services/NetworkReachabilityService.swift | 2 +- StepicTests/DownloaderTests.swift | 2 +- 72 files changed, 856 insertions(+), 778 deletions(-) delete mode 100644 Stepic/Legacy/Model/Network/ApiRequestRetrier.swift create mode 100644 Stepic/Legacy/Model/Network/StepikRequestAdapter.swift create mode 100644 Stepic/Legacy/Model/Network/StepikRequestInterceptor.swift create mode 100644 Stepic/Legacy/Model/Network/StepikRequestRetrier.swift rename Stepic/Legacy/Model/StepikSession/{Session.swift => StepikSession.swift} (59%) delete mode 100644 Stepic/Sources/Common/Result.swift create mode 100644 Stepic/Sources/Common/StepikResult.swift create mode 100644 Stepic/Sources/Extensions/ThirdParty/HTTPHeader+Stepik.swift diff --git a/Alamofire-SwiftyJSON.swift b/Alamofire-SwiftyJSON.swift index 37330b012d..19768d44ad 100644 --- a/Alamofire-SwiftyJSON.swift +++ b/Alamofire-SwiftyJSON.swift @@ -1,37 +1,46 @@ -// -// AlamofireSwiftyJSON.swift -// AlamofireSwiftyJSON -// -// Created by Hikaru on 2016/01/29. -// Copyright © 2016年 Hikaru. All rights reserved. -// import Alamofire +import Foundation import SwiftyJSON -/// A set of HTTP response status code that do not contain response data. -private let emptyDataStatusCodes: Set = [204, 205] - -// MARK: - Request for SwiftyJSON +// MARK: SwiftyJSON Response Serializer - + +public final class SwiftyJSONResponseSerializer: ResponseSerializer { + private let jsonResponseSerializer: JSONResponseSerializer + + public init( + dataPreprocessor: DataPreprocessor = JSONResponseSerializer.defaultDataPreprocessor, + emptyResponseCodes: Set = JSONResponseSerializer.defaultEmptyResponseCodes, + emptyRequestMethods: Set = JSONResponseSerializer.defaultEmptyRequestMethods, + options: JSONSerialization.ReadingOptions = .allowFragments + ) { + self.jsonResponseSerializer = JSONResponseSerializer( + dataPreprocessor: dataPreprocessor, + emptyResponseCodes: emptyResponseCodes, + emptyRequestMethods: emptyRequestMethods, + options: options + ) + } -extension DataRequest { - /// Creates a response serializer that - /// returns a SwiftyJSON 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 serializeResponseSwiftyJSON( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - Request.serializeResponseSwiftyJSON(options: options, - response: response, - data: data, - error: error) - } + public func serialize( + request: URLRequest?, + response: HTTPURLResponse?, + data: Data?, + error: Error? + ) throws -> JSON { + let json = try self.jsonResponseSerializer.serialize( + request: request, + response: response, + data: data, + error: error + ) + + return JSON(json) } +} + +// MARK: - Request for SwiftyJSON - +extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter options: @@ -41,54 +50,14 @@ extension DataRequest { /// - returns: The request. @discardableResult public func responseSwiftyJSON( - queue: DispatchQueue? = nil, + queue: DispatchQueue = .main, options: JSONSerialization.ReadingOptions = .allowFragments, - _ completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.serializeResponseSwiftyJSON(options: options), - 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 serializeResponseSwiftyJSON( - options: JSONSerialization.ReadingOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Alamofire.Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { - return .success(JSON.null) - } - - guard let validData = data, !validData.isEmpty else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) - } - - do { - let json = try JSONSerialization.jsonObject(with: validData, options: options) - - return .success(JSON(json)) - } catch { - return .failure(AFError.responseSerializationFailed( - reason: .jsonSerializationFailed(error: error))) - } + _ completionHandler: @escaping (AFDataResponse) -> Void + ) -> Self { + self.response( + queue: queue, + responseSerializer: SwiftyJSONResponseSerializer(options: options), + completionHandler: completionHandler + ) } } diff --git a/Podfile b/Podfile index 9e5cf796f1..49faaf556d 100644 --- a/Podfile +++ b/Podfile @@ -5,7 +5,7 @@ inhibit_all_warnings! use_frameworks! def shared_pods - pod 'Alamofire', '4.9.1' + pod 'Alamofire', '5.0.5' pod 'Atributika', '4.9.5' pod 'SwiftyJSON', '5.0.0' pod 'SDWebImage', '5.6.1' diff --git a/Podfile.lock b/Podfile.lock index 8664b28ec7..0b5a9addd3 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -2,7 +2,7 @@ PODS: - ActionSheetPicker-3.0 (2.4.0) - Agrume (5.6.7): - SwiftyGif - - Alamofire (4.9.1) + - Alamofire (5.0.5) - Amplitude-iOS (4.9.3) - Atributika (4.9.5) - BEMCheckBox (1.4.1) @@ -12,9 +12,9 @@ PODS: - Charts (3.4.0): - Charts/Core (= 3.4.0) - Charts/Core (3.4.0) - - CocoaLumberjack (3.6.0): - - CocoaLumberjack/Core (= 3.6.0) - - CocoaLumberjack/Core (3.6.0) + - CocoaLumberjack (3.6.1): + - CocoaLumberjack/Core (= 3.6.1) + - CocoaLumberjack/Core (3.6.1) - Crashlytics (3.14.0): - Fabric (~> 1.10.2) - CRToast (0.0.9) @@ -146,7 +146,7 @@ PODS: - nanopb/encode (0.3.9011) - Nimble (8.0.5) - Nuke (8.4.1) - - Pageboy (3.5.0) + - Pageboy (3.5.1) - pop (1.0.12) - Presentr (1.9) - PromiseKit (6.13.0): @@ -192,7 +192,7 @@ PODS: DEPENDENCIES: - ActionSheetPicker-3.0 (= 2.4.0) - Agrume (= 5.6.7) - - Alamofire (= 4.9.1) + - Alamofire (= 5.0.5) - Amplitude-iOS (= 4.9.3) - Atributika (= 4.9.5) - BEMCheckBox (= 1.4.1) @@ -322,13 +322,13 @@ CHECKOUT OPTIONS: SPEC CHECKSUMS: ActionSheetPicker-3.0: c68e1f8355828b4e1c823fa87185aacfef5e6fe3 Agrume: 1440351654f1d8669f240b5e7f1c76bafa15cd02 - Alamofire: 85e8a02c69d6020a0d734f6054870d7ecb75cf18 + Alamofire: df2f8f826963b08b9a870791ad48e07a10090b2e Amplitude-iOS: 122e026c44db8460e5efcf84859aa290a0ae9786 Atributika: 19429d34013b6d860feb5427c67bdbd219414e1f BEMCheckBox: 5ba6e37ade3d3657b36caecc35c8b75c6c2b1a4e Branch: d2e1611afa9ea9aa36fa1996df7f38ca2c3eb03e Charts: 74c9f256eaf0460c0c416522d1cf8c634ea6b286 - CocoaLumberjack: 78b0c238666f4f58db069738ec176f4519557516 + CocoaLumberjack: b17ae15142558d08bbacf69775fa10c4abbebcc9 Crashlytics: 540b7e5f5da5a042647227a5e3ac51d85eed06df CRToast: 5a78c22b921c5ed3487488af605bc403a9c92fed DeviceKit: fc3c2bd361a8d68d8a91eb715e453aede57317e5 @@ -362,7 +362,7 @@ SPEC CHECKSUMS: nanopb: 18003b5e52dab79db540fe93fe9579f399bd1ccd Nimble: 4ab1aeb9b45553c75b9687196b0fa0713170a332 Nuke: d780e3507a86b86c589ab3cc5cd302d5456f06fb - Pageboy: 3794c578aae5fcce06e90b3ed4a0ad6b807d75bb + Pageboy: 288353d4cc848c24deec2f7542f325089247c136 pop: d582054913807fd11fd50bfe6a539d91c7e1a55a Presentr: 7078d7eb5d1661ebeaae60c9e42a1e534de1b993 PromiseKit: c8668a559f26c98277a543192c51bc38dd2dfc76 @@ -387,6 +387,6 @@ SPEC CHECKSUMS: VK-ios-sdk: 62a10b6571fbcda0657f455fedce7fedf55b4cd0 YandexMobileMetrica: 1030df2959c886a7be3bc3d274eb54c8e86afd6f -PODFILE CHECKSUM: bf6b5b0ffb011b1f71f717b264a76aa6ca9c8a73 +PODFILE CHECKSUM: c953057f067b533f75d6deea72cb3e8b1b04f343 COCOAPODS: 1.9.1 diff --git a/Stepic.xcodeproj/project.pbxproj b/Stepic.xcodeproj/project.pbxproj index bdb07a8d30..505e13c1fb 100644 --- a/Stepic.xcodeproj/project.pbxproj +++ b/Stepic.xcodeproj/project.pbxproj @@ -203,7 +203,6 @@ 088CB1EC1D4BD5ED00C6ED1B /* FreeAnswerDataset.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088CB1EB1D4BD5ED00C6ED1B /* FreeAnswerDataset.swift */; }; 088E58C11DE34E2F0009B9CE /* SocialSDKProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088E58C01DE34E2F0009B9CE /* SocialSDKProvider.swift */; }; 088E58C41DE34ED20009B9CE /* VKSocialSDKProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088E58C31DE34ED20009B9CE /* VKSocialSDKProvider.swift */; }; - 088E73EA2060124B00D458E3 /* ApiRequestRetrier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088E73E92060124B00D458E3 /* ApiRequestRetrier.swift */; }; 088E73ED20614DFC00D458E3 /* UpdateRequestMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088E73EC20614DFC00D458E3 /* UpdateRequestMaker.swift */; }; 088E73F020619C8F00D458E3 /* DeleteRequestMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088E73EF20619C8F00D458E3 /* DeleteRequestMaker.swift */; }; 088E73F220619EEF00D458E3 /* CreateRequestMaker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 088E73F120619EEF00D458E3 /* CreateRequestMaker.swift */; }; @@ -241,7 +240,7 @@ 08A500501F2B73C000140D25 /* FullHeightWebView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A5004F1F2B73C000140D25 /* FullHeightWebView.swift */; }; 08A7B0E81EB340F500C1BA71 /* Auth.plist in Resources */ = {isa = PBXBuildFile; fileRef = 08A7B0E71EB340F500C1BA71 /* Auth.plist */; }; 08AB82351D74926F00FDEADE /* StepicsAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08AB82341D74926F00FDEADE /* StepicsAPI.swift */; }; - 08AB82381D74C44100FDEADE /* Session.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08AB82371D74C44100FDEADE /* Session.swift */; }; + 08AB82381D74C44100FDEADE /* StepikSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08AB82371D74C44100FDEADE /* StepikSession.swift */; }; 08AB823B1D75AA9300FDEADE /* CookieTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08AB823A1D75AA9300FDEADE /* CookieTests.swift */; }; 08AC21391CDD34C300FBB9CD /* Tasks.plist in Resources */ = {isa = PBXBuildFile; fileRef = 08AC21381CDD34C300FBB9CD /* Tasks.plist */; }; 08AC213C1CDD35DF00FBB9CD /* Users.plist in Resources */ = {isa = PBXBuildFile; fileRef = 08AC213B1CDD35DF00FBB9CD /* Users.plist */; }; @@ -419,7 +418,7 @@ 2C295A6A222D8BAB008878B6 /* EnrollmentsAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C8CB0E21FB48F39008CB1AC /* EnrollmentsAPI.swift */; }; 2C2972052147F5FD001502BD /* CourseTag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08A9F71D1FC38C9E00640F1F /* CourseTag.swift */; }; 2C2B626821B1660600E22E88 /* NotificationAlertsAnalytics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0176C02188953700DDB9D0 /* NotificationAlertsAnalytics.swift */; }; - 2C2EA36B212D5FEF002116C9 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2EA36A212D5FEF002116C9 /* Result.swift */; }; + 2C2EA36B212D5FEF002116C9 /* StepikResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2EA36A212D5FEF002116C9 /* StepikResult.swift */; }; 2C2F0BE72186EEB8007DCA0A /* StreakNotificationsRequestAlertDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2F0BE62186EEB8007DCA0A /* StreakNotificationsRequestAlertDataSource.swift */; }; 2C2F0BE92186EF87007DCA0A /* CommonNotificationsRequestAlertDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2F0BE82186EF87007DCA0A /* CommonNotificationsRequestAlertDataSource.swift */; }; 2C2F0BEC2186F0C3007DCA0A /* NotificationsRequestAlertPresenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C2F0BEB2186F0C3007DCA0A /* NotificationsRequestAlertPresenter.swift */; }; @@ -452,6 +451,7 @@ 2C4BE7DE221325FB00AEAC34 /* CourseReview.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4BE7DD221325F400AEAC34 /* CourseReview.swift */; }; 2C4BE7E0221328E700AEAC34 /* CourseReview+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4BE7DF221328E700AEAC34 /* CourseReview+CoreDataProperties.swift */; }; 2C4BE7E22213294700AEAC34 /* CourseReviewSummary+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4BE7E12213294700AEAC34 /* CourseReviewSummary+CoreDataProperties.swift */; }; + 2C4DDADF242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4DDADE242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift */; }; 2C5240D32399257B000DDA13 /* UIStatusBarStyle+DarkContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C5240D22399257B000DDA13 /* UIStatusBarStyle+DarkContent.swift */; }; 2C546C1323DA02AB00352F27 /* String+SafeSubscript.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C546C1223DA02AB00352F27 /* String+SafeSubscript.swift */; }; 2C546C1523DA05F300352F27 /* StringExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C546C1423DA05F300352F27 /* StringExtensionsTests.swift */; }; @@ -638,6 +638,9 @@ 2CE8391120C8101500FE3672 /* AchievementBadgeView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2CE8391020C8101500FE3672 /* AchievementBadgeView.xib */; }; 2CE8391320C8102300FE3672 /* AchievementBadgeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE8391220C8102200FE3672 /* AchievementBadgeView.swift */; }; 2CE8BA9B23D631E500C2EED9 /* ImageStoredFileManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE8BA9A23D631E500C2EED9 /* ImageStoredFileManager.swift */; }; + 2CEBEBF2242F8E9900DBFDF0 /* StepikRequestInterceptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEBEBF1242F8E9900DBFDF0 /* StepikRequestInterceptor.swift */; }; + 2CEBEBF4242F8F9900DBFDF0 /* StepikRequestAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEBEBF3242F8F9900DBFDF0 /* StepikRequestAdapter.swift */; }; + 2CEBEBF6242F8FB200DBFDF0 /* StepikRequestRetrier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CEBEBF5242F8FB200DBFDF0 /* StepikRequestRetrier.swift */; }; 2CF0885A205BEBF500FCB9C0 /* StepikTableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CF08859205BEBF500FCB9C0 /* StepikTableView.swift */; }; 2CF0885D205BED9700FCB9C0 /* StepikPlaceholderView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 2CF0885C205BED9700FCB9C0 /* StepikPlaceholderView.xib */; }; 2CF08861205BEE2C00FCB9C0 /* StepikPlaceholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CF08860205BEE2B00FCB9C0 /* StepikPlaceholder.swift */; }; @@ -1386,7 +1389,6 @@ 088CB1EB1D4BD5ED00C6ED1B /* FreeAnswerDataset.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FreeAnswerDataset.swift; sourceTree = ""; }; 088E58C01DE34E2F0009B9CE /* SocialSDKProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SocialSDKProvider.swift; sourceTree = ""; }; 088E58C31DE34ED20009B9CE /* VKSocialSDKProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = VKSocialSDKProvider.swift; sourceTree = ""; }; - 088E73E92060124B00D458E3 /* ApiRequestRetrier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApiRequestRetrier.swift; sourceTree = ""; }; 088E73EC20614DFC00D458E3 /* UpdateRequestMaker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UpdateRequestMaker.swift; sourceTree = ""; }; 088E73EF20619C8F00D458E3 /* DeleteRequestMaker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeleteRequestMaker.swift; sourceTree = ""; }; 088E73F120619EEF00D458E3 /* CreateRequestMaker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateRequestMaker.swift; sourceTree = ""; }; @@ -1428,7 +1430,7 @@ 08A7B0E71EB340F500C1BA71 /* Auth.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Auth.plist; sourceTree = ""; }; 08A9F71D1FC38C9E00640F1F /* CourseTag.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CourseTag.swift; sourceTree = ""; }; 08AB82341D74926F00FDEADE /* StepicsAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StepicsAPI.swift; sourceTree = ""; }; - 08AB82371D74C44100FDEADE /* Session.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Session.swift; sourceTree = ""; }; + 08AB82371D74C44100FDEADE /* StepikSession.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StepikSession.swift; sourceTree = ""; }; 08AB823A1D75AA9300FDEADE /* CookieTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CookieTests.swift; sourceTree = ""; }; 08AC21381CDD34C300FBB9CD /* Tasks.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Tasks.plist; sourceTree = ""; }; 08AC213B1CDD35DF00FBB9CD /* Users.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Users.plist; sourceTree = ""; }; @@ -1628,7 +1630,7 @@ 2C2485462101D91F006F8858 /* RestorableBackgroundDownloaderProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RestorableBackgroundDownloaderProtocol.swift; sourceTree = ""; }; 2C2485482101EE3E006F8858 /* DownloaderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DownloaderTests.swift; sourceTree = ""; }; 2C26BF09240810A3000EE23C /* AttemptsRepository.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AttemptsRepository.swift; sourceTree = ""; }; - 2C2EA36A212D5FEF002116C9 /* Result.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Result.swift; sourceTree = ""; }; + 2C2EA36A212D5FEF002116C9 /* StepikResult.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepikResult.swift; sourceTree = ""; }; 2C2EBAB92382E3EB00AB1B83 /* Model_lesson_can_edit.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_lesson_can_edit.xcdatamodel; sourceTree = ""; }; 2C2F0BE62186EEB8007DCA0A /* StreakNotificationsRequestAlertDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StreakNotificationsRequestAlertDataSource.swift; sourceTree = ""; }; 2C2F0BE82186EF87007DCA0A /* CommonNotificationsRequestAlertDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonNotificationsRequestAlertDataSource.swift; sourceTree = ""; }; @@ -1670,6 +1672,7 @@ 2C4BE7DD221325F400AEAC34 /* CourseReview.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CourseReview.swift; sourceTree = ""; }; 2C4BE7DF221328E700AEAC34 /* CourseReview+CoreDataProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CourseReview+CoreDataProperties.swift"; sourceTree = ""; }; 2C4BE7E12213294700AEAC34 /* CourseReviewSummary+CoreDataProperties.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CourseReviewSummary+CoreDataProperties.swift"; sourceTree = ""; }; + 2C4DDADE242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HTTPHeader+Stepik.swift"; sourceTree = ""; }; 2C5240D22399257B000DDA13 /* UIStatusBarStyle+DarkContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIStatusBarStyle+DarkContent.swift"; sourceTree = ""; }; 2C546C1223DA02AB00352F27 /* String+SafeSubscript.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+SafeSubscript.swift"; sourceTree = ""; }; 2C546C1423DA05F300352F27 /* StringExtensionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringExtensionsTests.swift; sourceTree = ""; }; @@ -1859,6 +1862,9 @@ 2CE8391020C8101500FE3672 /* AchievementBadgeView.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = AchievementBadgeView.xib; sourceTree = ""; }; 2CE8391220C8102200FE3672 /* AchievementBadgeView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AchievementBadgeView.swift; sourceTree = ""; }; 2CE8BA9A23D631E500C2EED9 /* ImageStoredFileManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageStoredFileManager.swift; sourceTree = ""; }; + 2CEBEBF1242F8E9900DBFDF0 /* StepikRequestInterceptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepikRequestInterceptor.swift; sourceTree = ""; }; + 2CEBEBF3242F8F9900DBFDF0 /* StepikRequestAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepikRequestAdapter.swift; sourceTree = ""; }; + 2CEBEBF5242F8FB200DBFDF0 /* StepikRequestRetrier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepikRequestRetrier.swift; sourceTree = ""; }; 2CEE97B0239123EA005503EF /* Model_step_passed_by_correct_ratio.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_step_passed_by_correct_ratio.xcdatamodel; sourceTree = ""; }; 2CF08859205BEBF500FCB9C0 /* StepikTableView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepikTableView.swift; sourceTree = ""; }; 2CF0885C205BED9700FCB9C0 /* StepikPlaceholderView.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = StepikPlaceholderView.xib; sourceTree = ""; }; @@ -2562,6 +2568,7 @@ isa = PBXGroup; children = ( 2C48D5FB228D865E00739477 /* Guarantee+ThenableWithFallback.swift */, + 2C4DDADE242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift */, ); path = ThirdParty; sourceTree = ""; @@ -3824,8 +3831,8 @@ 62E98CF5FA317BCAFAE433A9 /* ImageDataProvider.swift */, 2C7F78392271D5480089FDD7 /* LayoutInsets.swift */, 2CBBCB9723980EB2006D6C15 /* MulticastDelegate.swift */, - 2C2EA36A212D5FEF002116C9 /* Result.swift */, 2C68B3C723F5292100171F89 /* ScrollViewKeyboardAdjuster.swift */, + 2C2EA36A212D5FEF002116C9 /* StepikResult.swift */, 2CBBCB9923980ED6006D6C15 /* WeakBox.swift */, ); path = Common; @@ -4721,9 +4728,11 @@ 0885F84D1BA837E200F2A188 /* ApiDataDownloader.swift */, 08AEC3A61CCA75F400FFF29E /* APIDefaults.swift */, 086953111D748303003857A2 /* ApiRequest.swift */, - 088E73E92060124B00D458E3 /* ApiRequestRetrier.swift */, 08FCEB631B9ED2AC00FC4F8B /* AuthAPI.swift */, 0885F8531BA9DB5C00F2A188 /* Meta.swift */, + 2CEBEBF3242F8F9900DBFDF0 /* StepikRequestAdapter.swift */, + 2CEBEBF1242F8E9900DBFDF0 /* StepikRequestInterceptor.swift */, + 2CEBEBF5242F8FB200DBFDF0 /* StepikRequestRetrier.swift */, 62E98DC7237B8757A9F58935 /* StepikURLSessionConfiguration.swift */, 2CFF903B242A2A3900FD7311 /* Endpoints */, 2CFF903C242A2A6B00FD7311 /* RequestMakers */, @@ -4834,7 +4843,7 @@ isa = PBXGroup; children = ( 0885F8571BAAD43300F2A188 /* AuthInfo.swift */, - 08AB82371D74C44100FDEADE /* Session.swift */, + 08AB82371D74C44100FDEADE /* StepikSession.swift */, 080F31DC1BA7162C00F356A0 /* StepikToken.swift */, ); path = StepikSession; @@ -7077,7 +7086,6 @@ 0891424B1BCEE4EF0000BCB0 /* VideoURL.swift in Sources */, 080EBA371EA64C0C00C43C93 /* CertificatesPresentationContainer.swift in Sources */, 089877A0214047650065DFA2 /* SplitTestGroupProtocol.swift in Sources */, - 088E73EA2060124B00D458E3 /* ApiRequestRetrier.swift in Sources */, 2CF08864205BEF3C00FCB9C0 /* StepikPlaceholderView.swift in Sources */, 2C6E9CDB1FF27543001821A2 /* AdaptiveStorageManager.swift in Sources */, 08AEC3A71CCA75F400FFF29E /* APIDefaults.swift in Sources */, @@ -7144,7 +7152,7 @@ 2C5F77C41F90FC2500E8E175 /* NotificationsMarkAsReadButton.swift in Sources */, 2CF7E3342417C1A700B9188E /* UseCellularDataForDownloadsStorageManager.swift in Sources */, 086A8B251D21434B00F45C45 /* Vote.swift in Sources */, - 08AB82381D74C44100FDEADE /* Session.swift in Sources */, + 08AB82381D74C44100FDEADE /* StepikSession.swift in Sources */, 08901E6D1CD102DF00D94613 /* UpdatePreferencesContainer.swift in Sources */, 2C10100B239EFAD700440651 /* DiscountingPolicy.swift in Sources */, 082E35B220B5F1E4006E28F9 /* StorageRecordsAPI.swift in Sources */, @@ -7169,6 +7177,7 @@ 08263D701DE5F230002E5B7F /* NotificationTimePickerViewController.swift in Sources */, 08E43E9D214C27B200E3CB50 /* ModalRouterSourceProtocol.swift in Sources */, 0885F8581BAAD43300F2A188 /* AuthInfo.swift in Sources */, + 2CEBEBF2242F8E9900DBFDF0 /* StepikRequestInterceptor.swift in Sources */, 2CF0885A205BEBF500FCB9C0 /* StepikTableView.swift in Sources */, 2CE8391320C8102300FE3672 /* AchievementBadgeView.swift in Sources */, 08F4859A1C57868E000165AA /* TextReply.swift in Sources */, @@ -7251,7 +7260,7 @@ 083749341DE5BC2B00144C14 /* NotificationPreferencesContainer.swift in Sources */, 8622056B2055561F00F14255 /* PinsMapView.swift in Sources */, 08E43EA9214C2F7F00E3CB50 /* TabBarRouter.swift in Sources */, - 2C2EA36B212D5FEF002116C9 /* Result.swift in Sources */, + 2C2EA36B212D5FEF002116C9 /* StepikResult.swift in Sources */, 080CE14C1E9562BF0089A27F /* UsersAPI.swift in Sources */, 080217831F55B1B200186245 /* Menu.swift in Sources */, 08E6BB6B1DC8EB45006622EC /* UserActivity.swift in Sources */, @@ -7453,6 +7462,7 @@ 62E9842EFE40259D56C8CF46 /* CourseInfoTabInfoView.swift in Sources */, 62E981E583006D22B9EE976A /* CourseInfoTabInfoHeaderBlockView.swift in Sources */, 62E98A9A1DDD414A6896FB5A /* CourseInfoTabInfoInstructorsBlockView.swift in Sources */, + 2C4DDADF242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift in Sources */, 62E98A27E5558B7854297D76 /* CourseInfoTabInfoInstructorView.swift in Sources */, 62E983B175FD3A1D51D15ED0 /* CourseInfoTabInfoIntroVideoBlockView.swift in Sources */, 62E9836D08C0097659ABBF39 /* CourseInfoTabInfoTextBlockView.swift in Sources */, @@ -7591,6 +7601,7 @@ 62E98DCE33DED1EB1CC11988 /* CourseListsCollectionProvider.swift in Sources */, 62E989FFBAD20007D816071B /* CourseListsCollectionView.swift in Sources */, 62E987E02EC520C92F15E0B9 /* ExploreCoursesCollectionHeaderView.swift in Sources */, + 2CEBEBF4242F8F9900DBFDF0 /* StepikRequestAdapter.swift in Sources */, 62E98F7CBC091ADD515E1E89 /* GradientCoursesPlaceholderView.swift in Sources */, 62E98E98F2F7FB7925AF2730 /* GradientCoursesPlaceholderViewFactory.swift in Sources */, 62E98C3CA2749DA6E0C98BC9 /* TagsAssembly.swift in Sources */, @@ -7700,6 +7711,7 @@ 62E98F77A66AF9AE781611EF /* NewFreeAnswerQuizInteractor.swift in Sources */, 62E988898D30EFB35E3050DC /* NewFreeAnswerQuizPresenter.swift in Sources */, 62E98D9A7B541ACE9D6CF480 /* NewFreeAnswerQuizView.swift in Sources */, + 2CEBEBF6242F8FB200DBFDF0 /* StepikRequestRetrier.swift in Sources */, 62E98D7DEA0DB85F22C353CC /* NewFreeAnswerQuizViewController.swift in Sources */, 62E98377FC4206342B5DEAD9 /* NewFreeAnswerQuizViewModel.swift in Sources */, 62E9867E94A2DD00EEE119E0 /* NewMatchingQuizAssembly.swift in Sources */, diff --git a/Stepic/Legacy/AppDelegate.swift b/Stepic/Legacy/AppDelegate.swift index f3997d232e..bb39c817bc 100644 --- a/Stepic/Legacy/AppDelegate.swift +++ b/Stepic/Legacy/AppDelegate.swift @@ -29,7 +29,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { private let branchService = BranchService(deepLinkRoutingService: DeepLinkRoutingService()) private let spotlightContinueUserActivityService: SpotlightContinueUserActivityServiceProtocol = SpotlightContinueUserActivityService() private let notificationPermissionStatusSettingsObserver = NotificationPermissionStatusSettingsObserver() - private let alamofireRequestsLogger = AlamofireRequestsLogger() deinit { NotificationCenter.default.removeObserver(self) @@ -55,7 +54,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { SVProgressHUD.setHapticsEnabled(true) ConnectionHelper.shared.instantiate() - self.alamofireRequestsLogger.startIfDebug() if !AudioManager.shared.initAudioSession() { print("Could not initialize audio session") @@ -290,7 +288,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - Private API - private func checkForUpdates() { - UpdateChecker.sharedChecker.checkForUpdatesIfNeeded({ [weak self] newVersion in + UpdateChecker.shared.checkForUpdatesIfNeeded({ [weak self] newVersion in guard let newVersion = newVersion else { return } @@ -304,7 +302,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { self?.window?.rootViewController?.present(alert, animated: true) } }, error: { error in - print("error while checking for updates: \(error.code) \(error.localizedDescription)") + print("error while checking for updates: \(error)") }) } diff --git a/Stepic/Legacy/Extensions/UIImageView+SVGDownload.swift b/Stepic/Legacy/Extensions/UIImageView+SVGDownload.swift index 47fbd31f5b..bd1e002f93 100644 --- a/Stepic/Legacy/Extensions/UIImageView+SVGDownload.swift +++ b/Stepic/Legacy/Extensions/UIImageView+SVGDownload.swift @@ -12,40 +12,48 @@ import SDWebImage import SVGKit extension UIImageView { - func setImageWithURL(url optionalURL: URL?, placeholder: UIImage, completion: (() -> Void)? = nil) { - guard let url = optionalURL else { + func setImageWithURL( + url urlOrNil: URL?, + placeholder: UIImage, + completion: (() -> Void)? = nil + ) { + guard let url = urlOrNil else { self.image = placeholder completion?() return } - guard url.pathExtension != "svg" else { + if url.pathExtension == "svg" { self.image = placeholder - AlamofireDefaultSessionManager.shared.request(url).responseData(completionHandler: { response in - if response.result.error != nil { - return - } - - guard let data = response.result.value else { - return - } - DispatchQueue.global(qos: .userInitiated).async { - let svgImage = SVGKImage(data: data) - if !(svgImage?.hasSize() ?? true) { - svgImage?.size = CGSize(width: 200, height: 200) + AlamofireDefaultSessionManager + .shared + .request(url) + .responseData { dataResponse in + guard let data = dataResponse.data else { + completion?() + return } - let img = svgImage?.uiImage ?? placeholder - DispatchQueue.main.async { - self.image = img + + DispatchQueue.global(qos: .userInitiated).async { + let svgImage = SVGKImage(data: data) + + if !(svgImage?.hasSize() ?? true) { + svgImage?.size = CGSize(width: 200, height: 200) + } + + let image = svgImage?.uiImage ?? placeholder + + DispatchQueue.main.async { + self.image = image + completion?() + } } } - }) - return + } else { + self.sd_setImage(with: urlOrNil, placeholderImage: placeholder, options: .retryFailed) { (_, _, _, _) in + completion?() + } } - - self.sd_setImage(with: optionalURL, placeholderImage: placeholder, options: SDWebImageOptions.retryFailed, completed: { _, _, _, _ in - completion?() - }) } } diff --git a/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/DeleteDevice/DeleteDeviceExecutableTask.swift b/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/DeleteDevice/DeleteDeviceExecutableTask.swift index 027441003f..b20e9bac87 100644 --- a/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/DeleteDevice/DeleteDeviceExecutableTask.swift +++ b/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/DeleteDevice/DeleteDeviceExecutableTask.swift @@ -67,7 +67,7 @@ final class DeleteDeviceExecutableTask: Executable, DictionarySerializable { if let token = recoveryManager.recoverStepicToken(userId: userId) { let device = deviceId let user = userId - ApiDataDownloader.devices.delete(device, headers: APIDefaults.headers.bearer(token.accessToken), success: { + ApiDataDownloader.devices.delete(device, headers: APIDefaults.Headers.bearer(token.accessToken), success: { print("user \(user) successfully deleted device with id \(device)") success() }, error: { @@ -80,7 +80,7 @@ final class DeleteDeviceExecutableTask: Executable, DictionarySerializable { AuthInfo.shared.token = token } recoveryManager.writeStepicToken(token, userId: user) - ApiDataDownloader.devices.delete(device, headers: APIDefaults.headers.bearer(token.accessToken), success: { + ApiDataDownloader.devices.delete(device, headers: APIDefaults.Headers.bearer(token.accessToken), success: { print("user \(user) successfully deleted device with id \(device) after refreshing the token") success() }, error: { diff --git a/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/Views/PostViewsExecutableTask.swift b/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/Views/PostViewsExecutableTask.swift index c25d89e525..dc98bd5610 100644 --- a/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/Views/PostViewsExecutableTask.swift +++ b/Stepic/Legacy/Model/ExecutionQueue/TasksSerializers/Views/PostViewsExecutableTask.swift @@ -12,11 +12,7 @@ import Foundation ExecutableTask for deleting device on the server */ final class PostViewsExecutableTask: Executable, DictionarySerializable { - var id: String { - get { - description - } - } + var id: String { self.description } init(stepId: Int, assignmentId: Int?, userId: Int) { self.userId = userId @@ -28,31 +24,31 @@ final class PostViewsExecutableTask: Executable, DictionarySerializable { guard let taskDict = dict["task"] as? [String: Any] else { return nil } + guard let typeString = dict["type"] as? String, - let user = taskDict["user"] as? Int, - let step = taskDict["step"] as? Int else { + let user = taskDict["user"] as? Int, + let step = taskDict["step"] as? Int else { return nil } + let assignment = taskDict["assignment"] as? Int if ExecutableTaskType(rawValue: typeString) != ExecutableTaskType.postViews { return nil } + self.init(stepId: step, assignmentId: assignment, userId: user) } func serializeToDictionary() -> [String: Any] { - let res: [String: Any] = - [ - "type": type.rawValue, - "task": [ - "user": userId, - "step": stepId, - "assignment": assignmentId - ] + [ + "type": self.type.rawValue, + "task": [ + "user": self.userId, + "step": self.stepId, + "assignment": self.assignmentId ] - print(res) - return res + ] } var type: ExecutableTaskType { .postViews } @@ -67,51 +63,67 @@ final class PostViewsExecutableTask: Executable, DictionarySerializable { func execute(success: @escaping (() -> Void), failure: @escaping ((ExecutionError) -> Void)) { let recoveryManager = PersistentUserTokenRecoveryManager(baseName: "Users") + guard let token = recoveryManager.recoverStepicToken(userId: userId) else { return } - let step = stepId - let assignment = assignmentId - let user = userId - - ApiDataDownloader.views.create(stepId: step, assignment: assignment, headers: APIDefaults.headers.bearer(token.accessToken), success: { - print("user \(user) successfully posted views to step \(step) with assignment \(String(describing: assignment))") - success() - }, error: { - error in - print("error \(error) while posting views, trying to refresh token and retry") - ApiDataDownloader.auth.refreshTokenWith(token.refreshToken, success: { - token in - print("successfully refreshed token") - if AuthInfo.shared.userId == user { - AuthInfo.shared.token = token - } - recoveryManager.writeStepicToken(token, userId: user) - ApiDataDownloader.views.create(stepId: step, assignment: assignment, headers: APIDefaults.headers.bearer(token.accessToken), success: { - print("user \(user) successfully posted views to step \(step) with assignment \(String(describing: assignment)) after refreshing the token") - success() - }, error: { - error in - print("error while posting views with refreshed token") - switch error { - case .notAuthorized: - failure(.remove) - return - case .other(error: let e, code: _, message: let message): - print(message ?? "") - if e != nil { - failure(.retry) - } else { - failure(.remove) - } - return + + let step = self.stepId + let assignment = self.assignmentId + let user = self.userId + + ApiDataDownloader.views.create( + stepId: step, + assignment: assignment, + headers: APIDefaults.Headers.bearer(token.accessToken), + success: { + print("user \(user) successfully posted views to step \(step) with assignment \(String(describing: assignment))") + success() + }, + error: { error in + print("error \(error) while posting views, trying to refresh token and retry") + ApiDataDownloader.auth.refreshTokenWith( + token.refreshToken, + success: { token in + print("successfully refreshed token") + + if AuthInfo.shared.userId == user { + AuthInfo.shared.token = token } - }) - }, failure: { - error in - print("error while refreshing the token :(") - failure(error == .other ? .retry : .remove) - }) - }) + + recoveryManager.writeStepicToken(token, userId: user) + + ApiDataDownloader.views.create( + stepId: step, + assignment: assignment, + headers: APIDefaults.Headers.bearer(token.accessToken), + success: { + print("user \(user) successfully posted views to step \(step) with assignment \(String(describing: assignment)) after refreshing the token") + success() + }, + error: { error in + print("error while posting views with refreshed token") + switch error { + case .notAuthorized: + failure(.remove) + case .other(let error, _, let message): + print(message ?? "") + + if error != nil { + failure(.retry) + } else { + failure(.remove) + } + } + } + ) + }, + failure: { error in + print("error while refreshing the token :(") + failure(error == .other ? .retry : .remove) + } + ) + } + ) } } diff --git a/Stepic/Legacy/Model/Managers/InAppVersionControl/RemoteVersionManager.swift b/Stepic/Legacy/Model/Managers/InAppVersionControl/RemoteVersionManager.swift index 03e2c34361..1df2ef0631 100644 --- a/Stepic/Legacy/Model/Managers/InAppVersionControl/RemoteVersionManager.swift +++ b/Stepic/Legacy/Model/Managers/InAppVersionControl/RemoteVersionManager.swift @@ -14,60 +14,57 @@ import UIKit This class manages remote version change */ final class RemoteVersionManager: NSObject { - override private init() {} - static let sharedManager = RemoteVersionManager() + static let shared = RemoteVersionManager() - private func isVersion(_ v1: String, olderThan v2: String) -> Bool { - v1.compare(v2, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedDescending - } + override private init() {} - func checkRemoteVersionChange(needUpdateHandler update: @escaping (Version?) -> Void, error errorHandler: @escaping (NSError) -> Void) { - let local = getLocalVersion() - _ = getRemoteVersion( - success: { - remote, url in - if self.isVersion(remote, olderThan: local) { + func checkRemoteVersionChange( + needUpdateHandler update: @escaping (Version?) -> Void, + error errorHandler: @escaping (Error) -> Void + ) { + let localVersion = self.getLocalVersion() + self.getRemoteVersion( + success: { remote, url in + if self.isVersion(remote, olderThan: localVersion) { if let correctUrl = URL(string: url) { update(Version(version: remote, url: correctUrl)) return } } update(nil) - return }, - error: { - error in + error: { error in errorHandler(error) - }) + } + ) } private func getLocalVersion() -> String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } - private func getRemoteVersion(success: @escaping (String, String) -> Void, error errorHandler: @escaping (NSError) -> Void) -> Request { - AlamofireDefaultSessionManager.shared.request(StepikApplicationsInfo.versionInfoURL).responseSwiftyJSON({ - response in + private func isVersion(_ v1: String, olderThan v2: String) -> Bool { + v1.compare(v2, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedDescending + } - var error = response.result.error - var json: JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() + @discardableResult + private func getRemoteVersion( + success: @escaping (String, String) -> Void, + error errorHandler: @escaping (Error) -> Void + ) -> Request { + AlamofireDefaultSessionManager + .shared + .request(StepikApplicationsInfo.versionInfoURL) + .responseSwiftyJSON { response in + switch response.result { + case .success(let json): + if let version = json["version"].string, + let url = json["url"].string { + success(version, url) + } + case .failure(let error): + errorHandler(error) } - } else { - json = response.result.value! - } - - if let e = error as NSError? { - errorHandler(e) - return - } - - if let version = json["version"].string, - let url = json["url"].string { - success(version, url) } - }) } } diff --git a/Stepic/Legacy/Model/Managers/InAppVersionControl/UpdateChecker.swift b/Stepic/Legacy/Model/Managers/InAppVersionControl/UpdateChecker.swift index a68840ec20..8cf6a8fbce 100644 --- a/Stepic/Legacy/Model/Managers/InAppVersionControl/UpdateChecker.swift +++ b/Stepic/Legacy/Model/Managers/InAppVersionControl/UpdateChecker.swift @@ -12,20 +12,24 @@ import UIKit This class checks for updates if needed */ final class UpdateChecker: NSObject { + static let shared = UpdateChecker() + override private init() {} - static let sharedChecker = UpdateChecker() + + func checkForUpdatesIfNeeded( + _ needUpdateHandler: @escaping (Version?) -> Void, + error errorHandler: @escaping (Error) -> Void + ) { + if isCheckNeeded() { + RemoteVersionManager + .shared + .checkRemoteVersionChange(needUpdateHandler: needUpdateHandler, error: errorHandler) + } + } private func isCheckNeeded() -> Bool { let lastUpdate = UpdatePreferencesContainer.sharedContainer.lastUpdateCheckTime - let isMoreThanDayBetweenChecks = (Date().timeIntervalSince1970 - lastUpdate) > 86400 - return UpdatePreferencesContainer.sharedContainer.allowsUpdateChecks && isMoreThanDayBetweenChecks } - - func checkForUpdatesIfNeeded(_ needUpdateHandler: @escaping (Version?) -> Void, error errorHandler: @escaping (NSError) -> Void) { - if isCheckNeeded() { - RemoteVersionManager.sharedManager.checkRemoteVersionChange(needUpdateHandler: needUpdateHandler, error: errorHandler) - } - } } diff --git a/Stepic/Legacy/Model/Network/APIDefaults.swift b/Stepic/Legacy/Model/Network/APIDefaults.swift index 0e1d0008e9..646d000910 100644 --- a/Stepic/Legacy/Model/Network/APIDefaults.swift +++ b/Stepic/Legacy/Model/Network/APIDefaults.swift @@ -6,22 +6,23 @@ // Copyright © 2016 Alex Karpov. All rights reserved. // +import Alamofire import Foundation -struct APIDefaults { - struct headers { - static var bearer: [String: String] { - return bearer(AuthInfo.shared.token?.accessToken) +enum APIDefaults { + enum Headers { + static var bearer: HTTPHeaders { + return self.bearer(AuthInfo.shared.token?.accessToken) } - static func bearer(_ accessToken: String?) -> [String: String] { - if let token = accessToken { + static func bearer(_ bearerToken: String?) -> HTTPHeaders { + if let bearerToken = bearerToken { return [ - "Content-Type": "application/json", - "Authorization": "Bearer \(token)" + .contentType("application/json"), + .authorization(bearerToken: bearerToken) ] } else { - return [String: String]() + return .init() } } } diff --git a/Stepic/Legacy/Model/Network/AlamofireDefaultSessionManager.swift b/Stepic/Legacy/Model/Network/AlamofireDefaultSessionManager.swift index c8baf08399..980a412b64 100644 --- a/Stepic/Legacy/Model/Network/AlamofireDefaultSessionManager.swift +++ b/Stepic/Legacy/Model/Network/AlamofireDefaultSessionManager.swift @@ -8,6 +8,6 @@ import Alamofire -final class AlamofireDefaultSessionManager: Alamofire.SessionManager { - static let shared = Alamofire.SessionManager(configuration: StepikURLSessionConfiguration.default) +final class AlamofireDefaultSessionManager: Alamofire.Session { + static let shared = Alamofire.Session(configuration: StepikURLSessionConfiguration.default) } diff --git a/Stepic/Legacy/Model/Network/AlamofireRequestsLogger.swift b/Stepic/Legacy/Model/Network/AlamofireRequestsLogger.swift index d902bdc0ce..a0eb4f38af 100644 --- a/Stepic/Legacy/Model/Network/AlamofireRequestsLogger.swift +++ b/Stepic/Legacy/Model/Network/AlamofireRequestsLogger.swift @@ -1,48 +1,11 @@ import Alamofire import Foundation -final class AlamofireRequestsLogger { - private let queue: DispatchQueue +final class AlamofireRequestsLogger: EventMonitor { + let queue = DispatchQueue(label: "AlamofireRequestsLogger", qos: .background) - init(queue: DispatchQueue = DispatchQueue(label: "AlamofireRequestsLogger", qos: .background)) { - self.queue = queue - } - - deinit { - self.stop() - } - - func startIfDebug() { - #if DEBUG - self.start() - #endif - } - - func start() { - self.stop() - - NotificationCenter.default.addObserver( - self, - selector: #selector(self.networkRequestDidStart(notification:)), - name: Foundation.Notification.Name.Task.DidResume, - object: nil - ) - } - - func stop() { - NotificationCenter.default.removeObserver(self) - } - - @objc - private func networkRequestDidStart(notification: Foundation.Notification) { - self.queue.async { [weak self] in - self?.log(notification: notification) - } - } - - private func log(notification: Foundation.Notification) { - guard let userInfo = notification.userInfo, - let task = userInfo[Foundation.Notification.Key.Task] as? URLSessionTask, + func requestDidResume(_ request: Request) { + guard let task = request.task, let request = task.originalRequest, let httpMethod = request.httpMethod, let requestURL = request.url?.absoluteString.removingPercentEncoding else { diff --git a/Stepic/Legacy/Model/Network/ApiRequest.swift b/Stepic/Legacy/Model/Network/ApiRequest.swift index bbad69f134..c4e7c40115 100644 --- a/Stepic/Legacy/Model/Network/ApiRequest.swift +++ b/Stepic/Legacy/Model/Network/ApiRequest.swift @@ -83,8 +83,8 @@ final class ApiRequestPerformer { private static func performRequestWithAuthorizationCheck(_ completion: @escaping (() -> Void), error errorHandler: ((PerformRequestError) -> Void)? = nil) { // if let user = AuthInfo.shared.user { // print("performing request with user \(user.id)") - if !AuthInfo.shared.isAuthorized && Session.needsRefresh { - _ = Session.refresh(completion: { + if !AuthInfo.shared.isAuthorized && StepikSession.needsRefresh { + _ = StepikSession.refresh(completion: { completion() }, error: { _ in diff --git a/Stepic/Legacy/Model/Network/ApiRequestRetrier.swift b/Stepic/Legacy/Model/Network/ApiRequestRetrier.swift deleted file mode 100644 index 64fa8fa474..0000000000 --- a/Stepic/Legacy/Model/Network/ApiRequestRetrier.swift +++ /dev/null @@ -1,34 +0,0 @@ -// -// ApiRequestRetrier.swift -// Stepic -// -// Created by Ostrenkiy on 18.03.2018. -// Copyright © 2018 Alex Karpov. All rights reserved. -// -import Alamofire -import Foundation -import PromiseKit - -final class ApiRequestRetrier: RequestRetrier, RequestAdapter { - func adapt(_ urlRequest: URLRequest) throws -> URLRequest { - var urlRequest = urlRequest - - for (headerField, value) in AuthInfo.shared.initialHTTPHeaders { - urlRequest.setValue(value, forHTTPHeaderField: headerField) - } - return urlRequest - } - - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) { - if let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 && request.retryCount == 0 { - checkToken().done { - completion(true, 0.0) - }.catch { - _ in - completion(false, 0.0) - } - } else { - completion(false, 0.0) - } - } -} diff --git a/Stepic/Legacy/Model/Network/AuthAPI.swift b/Stepic/Legacy/Model/Network/AuthAPI.swift index a26972e3f1..5ce8110c7c 100644 --- a/Stepic/Legacy/Model/Network/AuthAPI.swift +++ b/Stepic/Legacy/Model/Network/AuthAPI.swift @@ -33,16 +33,18 @@ enum SignUpError: Error { } enum TokenRefreshError: Error { - case noAccess, noAppWithCredentials, other + case noAccess + case noAppWithCredentials + case other } final class AuthAPI { - let manager: Alamofire.SessionManager + let manager: Alamofire.Session init() { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 15 - manager = Alamofire.SessionManager(configuration: configuration) + manager = Alamofire.Session(configuration: configuration) } func signInWithCode(_ code: String) -> Promise<(StepikToken, AuthorizationType)> { @@ -51,9 +53,9 @@ final class AuthAPI { throw SignInError.noAppWithCredentials } - let headers = [ - "Content-Type": "application/x-www-form-urlencoded", - "Authorization": "Basic \(socialInfo.credentials)" + let headers: HTTPHeaders = [ + .stepikAuthContentType, + .authorization("Basic \(socialInfo.credentials)") ] let params = [ @@ -62,17 +64,26 @@ final class AuthAPI { "redirect_uri": socialInfo.redirectUri ] - manager.request("\(StepikApplicationsInfo.oauthURL)/token/", method: .post, parameters: params, headers: headers).responseSwiftyJSON { response in + self.manager.request( + "\(StepikApplicationsInfo.oauthURL)/token/", + method: .post, + parameters: params, + headers: headers + ).responseSwiftyJSON { response in switch response.result { case .failure(let error): - if let typedError = error as? URLError { - switch typedError.code { - case .notConnectedToInternet: - seal.reject(SignInError.badConnection) - default: - seal.reject(SignInError.other(error: typedError, code: nil, message: nil)) + switch error { + case .sessionTaskFailed(let sessionError): + if let urlError = sessionError as? URLError { + if urlError.code == .notConnectedToInternet { + seal.reject(SignInError.badConnection) + } else { + seal.reject(SignInError.other(error: urlError, code: nil, message: nil)) + } + } else { + seal.reject(SignInError.other(error: error, code: nil, message: nil)) } - } else { + default: seal.reject(SignInError.other(error: error, code: nil, message: nil)) } case .success(let json): @@ -89,9 +100,9 @@ final class AuthAPI { throw SignInError.noAppWithCredentials } - let headers = [ - "Content-Type": "application/x-www-form-urlencoded", - "Authorization": "Basic \(passwordInfo.credentials)" + let headers: HTTPHeaders = [ + .stepikAuthContentType, + .authorization("Basic \(passwordInfo.credentials)") ] let params = [ @@ -100,33 +111,49 @@ final class AuthAPI { "username": email ] - manager.request("\(StepikApplicationsInfo.oauthURL)/token/", method: .post, parameters: params, headers: headers).responseSwiftyJSON { response in + self.manager.request( + "\(StepikApplicationsInfo.oauthURL)/token/", + method: .post, + parameters: params, + headers: headers + ).responseSwiftyJSON { response in switch response.result { case .failure(let error): - if let typedError = error as? URLError { - switch typedError.code { - case .notConnectedToInternet: - seal.reject(SignInError.badConnection) - default: - seal.reject(SignInError.other(error: typedError, code: nil, message: nil)) + switch error { + case .sessionTaskFailed(let sessionError): + if let urlError = sessionError as? URLError { + if urlError.code == .notConnectedToInternet { + seal.reject(SignInError.badConnection) + } else { + seal.reject(SignInError.other(error: urlError, code: nil, message: nil)) + } + } else { + seal.reject(SignInError.other(error: error, code: nil, message: nil)) } - } else { + default: seal.reject(SignInError.other(error: error, code: nil, message: nil)) } case .success(let json): - if let r = response.response, - !(200...299 ~= r.statusCode) { - switch r.statusCode { + if let requestResponse = response.response, + !(200...299 ~= requestResponse.statusCode) { + switch requestResponse.statusCode { case 497: seal.reject(SignInError.manyAttempts) case 401: seal.reject(SignInError.invalidEmailAndPassword) default: - seal.reject(SignInError.other(error: nil, code: r.statusCode, message: json["error"].string)) + seal.reject( + SignInError.other( + error: nil, + code: requestResponse.statusCode, + message: json["error"].string + ) + ) } } let token = StepikToken(json: json) + seal.fulfill((token, AuthorizationType.password)) } } @@ -158,9 +185,9 @@ final class AuthAPI { credentials = passwordInfo.credentials } - let headers = [ - "Content-Type": "application/x-www-form-urlencoded", - "Authorization": "Basic \(credentials)" + let headers: HTTPHeaders = [ + .stepikAuthContentType, + .authorization("Basic \(credentials)") ] let params: Parameters = [ @@ -168,15 +195,28 @@ final class AuthAPI { "refresh_token": refresh_token ] - manager.request("\(StepikApplicationsInfo.oauthURL)/token/", method: .post, parameters: params, headers: headers).responseSwiftyJSON { response in + self.manager.request( + "\(StepikApplicationsInfo.oauthURL)/token/", + method: .post, + parameters: params, + headers: headers + ).responseSwiftyJSON { response in switch response.result { case .failure(let error): - logRefreshError(statusCode: response.response?.statusCode, message: "Error \(error.localizedDescription) while refreshing") + logRefreshError( + statusCode: response.response?.statusCode, + message: "Error \(error.localizedDescription) while refreshing" + ) seal.reject(TokenRefreshError.other) case .success(let json): let token = StepikToken(json: json) + if token.accessToken.isEmpty { - logRefreshError(statusCode: response.response?.statusCode, message: "Error after getting empty access token") + logRefreshError( + statusCode: response.response?.statusCode, + message: "Error after getting empty access token" + ) + if response.response?.statusCode == 401 { seal.reject(TokenRefreshError.noAccess) } else { @@ -204,28 +244,49 @@ final class AuthAPI { ] ] - manager.request("\(StepikApplicationsInfo.apiURL)/users", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseSwiftyJSON { response in + manager.request( + "\(StepikApplicationsInfo.apiURL)/users", + method: .post, + parameters: params, + encoding: JSONEncoding.default, + headers: headers + ).responseSwiftyJSON { response in switch response.result { case .failure(let error): seal.reject(SignUpError.other(error: error, code: nil, message: nil)) case .success(let json): - if let r = response.response, - !(200...299 ~= r.statusCode) { - switch r.statusCode { + if let requestResponse = response.response, + !(200...299 ~= requestResponse.statusCode) { + switch requestResponse.statusCode { case 400: - seal.reject(SignUpError.validation(email: json["email"].array?[0].string, firstName: json["first_name"].array?[0].string, lastName: json["last_name"].array?[0].string, password: json["password"].array?[0].string)) + seal.reject( + SignUpError.validation( + email: json["email"].array?[0].string, + firstName: json["first_name"].array?[0].string, + lastName: json["last_name"].array?[0].string, + password: json["password"].array?[0].string + ) + ) default: - seal.reject(SignUpError.other(error: nil, code: r.statusCode, message: json["error"].string)) + seal.reject( + SignUpError.other( + error: nil, + code: requestResponse.statusCode, + message: json["error"].string + ) + ) } } - seal.fulfill(()) } } } } - func signUpWithToken(socialToken: String, email: String?, provider: String) -> Promise<(StepikToken, AuthorizationType)> { + func signUpWithToken( + socialToken: String, + email: String?, provider: String + ) -> Promise<(StepikToken, AuthorizationType)> { Promise { seal in guard let socialInfo = StepikApplicationsInfo.social else { throw SignInError.noAppWithCredentials @@ -239,40 +300,62 @@ final class AuthAPI { "code_type": "access_token" ] - if email != nil { - params["email"] = email! + if let email = email { + params["email"] = email } - let headers = [ - "Authorization": "Basic \(socialInfo.credentials)" + let headers: HTTPHeaders = [ + .authorization("Basic \(socialInfo.credentials)") ] - manager.request("\(StepikApplicationsInfo.oauthURL)/social-token/", method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseSwiftyJSON { response in + self.manager.request( + "\(StepikApplicationsInfo.oauthURL)/social-token/", + method: .post, + parameters: params, + encoding: URLEncoding.default, + headers: headers + ).responseSwiftyJSON { response in switch response.result { case .failure(let error): - if let typedError = error as? URLError { - switch typedError.code { - case .notConnectedToInternet: - seal.reject(SignInError.badConnection) - default: - seal.reject(SignInError.other(error: typedError, code: nil, message: nil)) + switch error { + case .sessionTaskFailed(let sessionError): + if let urlError = sessionError as? URLError { + if urlError.code == .notConnectedToInternet { + seal.reject(SignInError.badConnection) + } else { + seal.reject(SignInError.other(error: urlError, code: nil, message: nil)) + } + } else { + seal.reject(SignInError.other(error: error, code: nil, message: nil)) } - } else { + default: seal.reject(SignInError.other(error: error, code: nil, message: nil)) } case .success(let json): if json["error"] != JSON.null { switch json["error"].stringValue { case "social_signup_with_existing_email": - seal.reject(SignInError.existingEmail(provider: json["provider"].string, email: json["email"].string)) + seal.reject( + SignInError.existingEmail( + provider: json["provider"].string, + email: json["email"].string + ) + ) case "social_signup_without_email": seal.reject(SignInError.noEmail(provider: json["provider"].string)) default: - seal.reject(SignInError.other(error: nil, code: response.response?.statusCode, message: json["error"].string)) + seal.reject( + SignInError.other( + error: nil, + code: response.response?.statusCode, + message: json["error"].string + ) + ) } } let token = StepikToken(json: json) + seal.fulfill((token, AuthorizationType.code)) } } @@ -284,8 +367,14 @@ final class AuthAPI { // TODO: remove this extension after global refactoring extension AuthAPI { @available(*, deprecated, message: "Legacy method with callbacks") - @discardableResult func logInWithUsername(_ username: String, password: String, success : @escaping (_ token: StepikToken) -> Void, failure : @escaping (_ error: SignInError) -> Void) -> Request? { - signInWithAccount(email: username, password: password).done { token, authorizationType in + @discardableResult + func logInWithUsername( + _ username: String, + password: String, + success : @escaping (_ token: StepikToken) -> Void, + failure : @escaping (_ error: SignInError) -> Void + ) -> Request? { + self.signInWithAccount(email: username, password: password).done { token, authorizationType in AuthInfo.shared.authorizationType = authorizationType success(token) }.catch { error in @@ -299,8 +388,13 @@ extension AuthAPI { } @available(*, deprecated, message: "Legacy method with callbacks") - @discardableResult func refreshTokenWith(_ refresh_token: String, success : @escaping (_ token: StepikToken) -> Void, failure : @escaping (_ error: TokenRefreshError) -> Void) -> Request? { - refreshToken(with: refresh_token, authorizationType: AuthInfo.shared.authorizationType).done { token in + @discardableResult + func refreshTokenWith( + _ refresh_token: String, + success : @escaping (_ token: StepikToken) -> Void, + failure : @escaping (_ error: TokenRefreshError) -> Void + ) -> Request? { + self.refreshToken(with: refresh_token, authorizationType: AuthInfo.shared.authorizationType).done { token in success(token) }.catch { error in if let typedError = error as? TokenRefreshError { diff --git a/Stepic/Legacy/Model/Network/Endpoints/APIEndpoint.swift b/Stepic/Legacy/Model/Network/Endpoints/APIEndpoint.swift index 3100e646b9..8b6f56fc5b 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/APIEndpoint.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/APIEndpoint.swift @@ -15,7 +15,7 @@ import SwiftyJSON class APIEndpoint { var name: String { "" } - let manager: Alamofire.SessionManager + let manager: Alamofire.Session var update: UpdateRequestMaker var delete: DeleteRequestMaker @@ -23,15 +23,21 @@ class APIEndpoint { var retrieve: RetrieveRequestMaker init() { - manager = Alamofire.SessionManager(configuration: StepikURLSessionConfiguration.default) - let retrier = ApiRequestRetrier() - manager.retrier = retrier - manager.adapter = retrier + var eventMonitors = [EventMonitor]() + #if DEBUG + eventMonitors = [AlamofireRequestsLogger()] + #endif - update = UpdateRequestMaker() - delete = DeleteRequestMaker() - create = CreateRequestMaker() - retrieve = RetrieveRequestMaker() + self.manager = Alamofire.Session( + configuration: StepikURLSessionConfiguration.default, + interceptor: StepikRequestInterceptor(), + eventMonitors: eventMonitors + ) + + self.update = UpdateRequestMaker() + self.delete = DeleteRequestMaker() + self.create = CreateRequestMaker() + self.retrieve = RetrieveRequestMaker() } func cancelAllTasks() { diff --git a/Stepic/Legacy/Model/Network/Endpoints/AdaptiveRatingsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/AdaptiveRatingsAPI.swift index b551a5219c..e6ae964210 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/AdaptiveRatingsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/AdaptiveRatingsAPI.swift @@ -60,17 +60,32 @@ final class AdaptiveRatingsAPI: APIEndpoint { } return Promise { seal in - manager.request("\(RemoteConfig.shared.adaptiveBackendUrl)/\(name)", method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseSwiftyJSON { response in + self.manager.request( + "\(RemoteConfig.shared.adaptiveBackendUrl)/\(self.name)", + method: .get, + parameters: params, + encoding: URLEncoding.default, + headers: nil + ).validate().responseSwiftyJSON { response in switch response.result { case .failure(let error): seal.reject(error) case .success(let json): - if response.response?.statusCode == 200 { - let leaders = json["users"].arrayValue.map { RatingRecord(userId: $0["user"].intValue, exp: $0["exp"].intValue, rank: $0["rank"].intValue, isFake: !$0["is_not_fake"].boolValue) } - seal.fulfill(Scoreboard(allCount: json["count"].intValue, leaders: leaders)) - } else { - seal.reject(RatingsAPIError.serverError) - } + let leaders = json["users"] + .arrayValue + .map { + RatingRecord( + userId: $0["user"].intValue, + exp: $0["exp"].intValue, + rank: $0["rank"].intValue, + isFake: !$0["is_not_fake"].boolValue + ) + } + let scoreboard = Scoreboard( + allCount: json["count"].intValue, + leaders: leaders + ) + seal.fulfill(scoreboard) } } } @@ -86,18 +101,20 @@ final class AdaptiveRatingsAPI: APIEndpoint { } return Promise { seal in - manager.request("\(RemoteConfig.shared.adaptiveBackendUrl)/\(restoreName)", method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseSwiftyJSON { response in + self.manager.request( + "\(RemoteConfig.shared.adaptiveBackendUrl)/\(self.restoreName)", + method: .get, + parameters: params, + encoding: URLEncoding.default, + headers: nil + ).validate().responseSwiftyJSON { response in switch response.result { case .failure(let error): seal.reject(error) case .success(let json): - if response.response?.statusCode == 200 { - let exp = json["exp"].intValue - let streak = json["streak"].intValue - seal.fulfill((exp: exp, streak: streak)) - } else { - seal.reject(RatingsAPIError.serverError) - } + let exp = json["exp"].intValue + let streak = json["streak"].intValue + seal.fulfill((exp: exp, streak: streak)) } } } diff --git a/Stepic/Legacy/Model/Network/Endpoints/AssignmentsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/AssignmentsAPI.swift index 95f3fe3f14..0891f059f6 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/AssignmentsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/AssignmentsAPI.swift @@ -14,9 +14,10 @@ import SwiftyJSON final class AssignmentsAPI: APIEndpoint { override var name: String { "assignments" } - @discardableResult func retrieve( + @discardableResult + func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Assignment], refreshMode: RefreshMode, success: @escaping (([Assignment]) -> Void), diff --git a/Stepic/Legacy/Model/Network/Endpoints/AttemptsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/AttemptsAPI.swift index dfe109e3ce..6eab8ea2bc 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/AttemptsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/AttemptsAPI.swift @@ -19,7 +19,7 @@ final class AttemptsAPI: APIEndpoint { ids: [Attempt.IdType], stepName: String, page: Int = 1, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<([Attempt], Meta)> { let parameters: Parameters = [ "ids": ids, @@ -84,7 +84,7 @@ final class AttemptsAPI: APIEndpoint { stepName: String, stepID: Int, userID: Int, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping ([Attempt], Meta) -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { @@ -100,35 +100,16 @@ final class AttemptsAPI: APIEndpoint { parameters: params, encoding: URLEncoding.default, headers: headers - ).responseSwiftyJSON { response in - var error = response.result.error - var json: JSON = [:] - - if response.result.value == nil { - if error == nil { - error = NSError() - } - } else { - json = response.result.value! - } - - let response = response.response - - if let error = error { - let description = (error as NSError).localizedDescription - print(description) - errorHandler(description) - return - } - - if response?.statusCode == 200 { + ).validate().responseSwiftyJSON { response in + switch response.result { + case .success(let json): let meta = Meta(json: json["meta"]) - let attempts = json["attempts"].arrayValue.map({ Attempt(json: $0, stepBlockName: stepName) }) + let attempts = json["attempts"] + .arrayValue + .map { Attempt(json: $0, stepBlockName: stepName) } success(attempts, meta) - return - } else { - errorHandler("Response status code is wrong(\(String(describing: response?.statusCode)))") - return + case .failure(let error): + errorHandler(error.localizedDescription) } } } @@ -140,7 +121,7 @@ extension AttemptsAPI { func create( stepName: String, stepID: Int, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (Attempt) -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/CertificatesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/CertificatesAPI.swift index 29cd6cc562..42513ecd7c 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/CertificatesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/CertificatesAPI.swift @@ -25,7 +25,7 @@ final class CertificatesAPI: APIEndpoint { //Cannot move it to extension cause it is used in tests @available(*, deprecated, message: "Legacy method with callbacks") - @discardableResult func retrieve(userId: Int, page: Int = 1, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, success: @escaping (Meta, [Certificate]) -> Void, error errorHandler: @escaping (NetworkError) -> Void) -> Request? { + @discardableResult func retrieve(userId: Int, page: Int = 1, headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (Meta, [Certificate]) -> Void, error errorHandler: @escaping (NetworkError) -> Void) -> Request? { retrieve(userId: userId, page: page).done { certificates, meta in success(meta, certificates) diff --git a/Stepic/Legacy/Model/Network/Endpoints/CourseReviewSummariesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/CourseReviewSummariesAPI.swift index 994303e737..6c1e11e27e 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/CourseReviewSummariesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/CourseReviewSummariesAPI.swift @@ -17,7 +17,7 @@ final class CourseReviewSummariesAPI: APIEndpoint { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [CourseReviewSummary], refreshMode: RefreshMode, success: @escaping (([CourseReviewSummary]) -> Void), @@ -37,7 +37,7 @@ final class CourseReviewSummariesAPI: APIEndpoint { @available(*, deprecated, message: "Legacy with update existing") func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[CourseReviewSummary]> { Promise { seal in CourseReviewSummary.fetchAsync(ids: ids).then { summaries in diff --git a/Stepic/Legacy/Model/Network/Endpoints/CoursesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/CoursesAPI.swift index d2590833e6..9f39ec2bd5 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/CoursesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/CoursesAPI.swift @@ -17,7 +17,7 @@ final class CoursesAPI: APIEndpoint { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Course] ) -> Promise<[Course]> { if ids.isEmpty { @@ -31,7 +31,7 @@ final class CoursesAPI: APIEndpoint { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[Course]> { if ids.isEmpty { return .value([]) @@ -105,7 +105,7 @@ final class CoursesAPI: APIEndpoint { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Course], refreshMode: RefreshMode, success: @escaping (([Course]) -> Void), @@ -141,7 +141,7 @@ extension CoursesAPI { order: String? = nil, language: String? = nil, page: Int = 1, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success successHandler: @escaping ([Course], Meta) -> Void, error errorHandler: @escaping (Error) -> Void ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/DevicesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/DevicesAPI.swift index 11234c23a2..c6d4be9c51 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/DevicesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/DevicesAPI.swift @@ -29,7 +29,7 @@ final class DevicesAPI: APIEndpoint { self.retrieve(params: ["user": userId, "page": page]) } - func retrieve(deviceId: Int, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise { + func retrieve(deviceId: Int, headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise { Promise { seal in self.manager.request( "\(StepikApplicationsInfo.apiURL)/\(self.name)/\(deviceId)", @@ -59,7 +59,7 @@ final class DevicesAPI: APIEndpoint { } //TODO: Update this after errors refactoring. DeviceError is something that should be dealt with - func update(_ device: Device, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise { + func update(_ device: Device, headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise { Promise { seal in guard let deviceId = device.id else { throw DeviceError.notFound @@ -98,11 +98,17 @@ final class DevicesAPI: APIEndpoint { } //TODO: Update this after errors refactoring. DeviceError is something that should be dealt with - func create(_ device: Device, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise { + func create(_ device: Device, headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise { let params = ["device": device.json] return Promise { seal in - manager.request("\(StepikApplicationsInfo.apiURL)/devices", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseSwiftyJSON { response in + manager.request( + "\(StepikApplicationsInfo.apiURL)/devices", + method: .post, + parameters: params, + encoding: JSONEncoding.default, + headers: headers + ).responseSwiftyJSON { response in switch response.result { case .failure(let error): seal.reject(error) @@ -113,10 +119,15 @@ final class DevicesAPI: APIEndpoint { case 404: return seal.reject(DeviceError.notFound) default: - return seal.reject(DeviceError.other(error: nil, code: r.statusCode, message: json.rawString())) + return seal.reject( + DeviceError.other( + error: nil, + code: r.statusCode, + message: json.rawString() + ) + ) } } - seal.fulfill(Device(json: json["devices"].arrayValue[0])) } } @@ -124,7 +135,7 @@ final class DevicesAPI: APIEndpoint { } //TODO: Update this after errors refactoring. DeviceError is something that should be dealt with - func delete(_ deviceId: Int, headers: [String: String] = APIDefaults.headers.bearer) -> Promise { + func delete(_ deviceId: Int, headers: HTTPHeaders = APIDefaults.Headers.bearer) -> Promise { Promise { seal in self.manager.request( "\(StepikApplicationsInfo.apiURL)/devices/\(deviceId)", @@ -154,7 +165,7 @@ final class DevicesAPI: APIEndpoint { private func retrieve( params: Parameters, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<(Meta, [Device])> { Promise { seal in self.manager.request( @@ -198,7 +209,7 @@ extension DevicesAPI { @discardableResult func create( _ device: Device, - headers: [String: String] = APIDefaults.headers.bearer, + headers: HTTPHeaders = APIDefaults.Headers.bearer, success: @escaping ((Device) -> Void), error errorHandler: @escaping ((String) -> Void) ) -> Request? { @@ -209,7 +220,7 @@ extension DevicesAPI { @discardableResult func delete( _ deviceId: Int, - headers: [String: String] = APIDefaults.headers.bearer, + headers: HTTPHeaders = APIDefaults.Headers.bearer, success: @escaping (() -> Void), error errorHandler: @escaping ((DeviceError) -> Void) ) -> Request? { @@ -220,7 +231,7 @@ extension DevicesAPI { @discardableResult func retrieve( _ deviceId: Int, - headers: [String: String] = APIDefaults.headers.bearer, + headers: HTTPHeaders = APIDefaults.Headers.bearer, success: @escaping ((Device) -> Void), error errorHandler: @escaping ((String) -> Void) ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/DiscussionProxiesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/DiscussionProxiesAPI.swift index 8eb46c1038..40a49c2532 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/DiscussionProxiesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/DiscussionProxiesAPI.swift @@ -26,11 +26,16 @@ final class DiscussionProxiesAPI: APIEndpoint { extension DiscussionProxiesAPI { @available(*, deprecated, message: "Legacy method with callbacks") - @discardableResult func retrieve(_ id: String, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, success: @escaping ((DiscussionProxy) -> Void), error errorHandler: @escaping ((String) -> Void)) -> Request? { - retrieve(id: id).done { discussionProxy in + @discardableResult + func retrieve( + _ id: String, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, + success: @escaping ((DiscussionProxy) -> Void), + error errorHandler: @escaping ((String) -> Void) + ) -> Request? { + self.retrieve(id: id).done { discussionProxy in success(discussionProxy) - }.catch { - error in + }.catch { error in errorHandler(error.localizedDescription) } return nil diff --git a/Stepic/Legacy/Model/Network/Endpoints/EnrollmentsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/EnrollmentsAPI.swift index 64a2ca7a7f..90d2bfd46f 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/EnrollmentsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/EnrollmentsAPI.swift @@ -39,7 +39,7 @@ extension EnrollmentsAPI { success : @escaping () -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { - let headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + let headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders let params: Parameters = [ "enrollment": [ "course": "\(course.id)" @@ -48,38 +48,22 @@ extension EnrollmentsAPI { if !delete { return self.manager.request( - "\(StepikApplicationsInfo.apiURL)/\(name)", + "\(StepikApplicationsInfo.apiURL)/\(self.name)", method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers - ).responseSwiftyJSON({ response in - var error = response.result.error - var json: JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() + ).validate().responseSwiftyJSON { response in + switch response.result { + case .success(let json): + if let courseJSON = json["courses"].array?[0] { + course.update(json: courseJSON) } - } else { - json = response.result.value! + success() + case .failure: + errorHandler(NSLocalizedString("Error", comment: "")) } - let response = response.response - - if let r = response { - if r.statusCode >= 200 && r.statusCode <= 299 { - if let courseJSON = json["courses"].array?[0] { - course.update(json: courseJSON) - } - success() - } else { - let s = NSLocalizedString("TryJoinFromWeb", comment: "") - errorHandler(s) - } - } else { - let s = NSLocalizedString("Error", comment: "") - errorHandler(s) - } - }) + } } else { return self.manager.request( "\(StepikApplicationsInfo.apiURL)/enrollments/\(course.id)", @@ -87,28 +71,14 @@ extension EnrollmentsAPI { parameters: params, encoding: URLEncoding.default, headers: headers - ).responseSwiftyJSON({ response in - var error = response.result.error - // var json : JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() - } - } else { - // json = response.result.value! + ).validate().responseSwiftyJSON { response in + switch response.result { + case .success: + success() + case .failure: + errorHandler(NSLocalizedString("Error", comment: "")) } - let response = response.response - - if let r = response { - if r.statusCode >= 200 && r.statusCode <= 299 { - success() - return - } - } - - let s = NSLocalizedString("Error", comment: "") - errorHandler(s) - }) + } } } } diff --git a/Stepic/Legacy/Model/Network/Endpoints/LastStepsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/LastStepsAPI.swift index 3fb2ca72d7..2b3a87e2b9 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/LastStepsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/LastStepsAPI.swift @@ -16,13 +16,13 @@ final class LastStepsAPI: APIEndpoint { @discardableResult func retrieve( ids: [String], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, updatingLastSteps: [LastStep], success: @escaping (([LastStep]) -> Void), error errorHandler: @escaping ((NetworkError) -> Void) ) -> Request? { self.getObjectsByIds( - requestString: name, + requestString: self.name, printOutput: false, ids: ids, deleteObjects: updatingLastSteps, diff --git a/Stepic/Legacy/Model/Network/Endpoints/LessonsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/LessonsAPI.swift index 42cc8afa70..89fd3fe88f 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/LessonsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/LessonsAPI.swift @@ -17,14 +17,14 @@ final class LessonsAPI: APIEndpoint { func retrieve( ids: [Int], existing: [Lesson], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[Lesson]> { self.getObjectsByIds(ids: ids, updating: existing, printOutput: false) } @available(*, deprecated, message: "Legacy: we want to pass existing") @discardableResult - func retrieve(ids: [Int], headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise<[Lesson]> { + func retrieve(ids: [Int], headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise<[Lesson]> { if ids.isEmpty { return .value([]) } @@ -38,7 +38,7 @@ extension LessonsAPI { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Lesson], refreshMode: RefreshMode, success: @escaping (([Lesson]) -> Void), diff --git a/Stepic/Legacy/Model/Network/Endpoints/NotificationsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/NotificationsAPI.swift index 2a77b5cd4c..ddd7cc25f0 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/NotificationsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/NotificationsAPI.swift @@ -42,7 +42,7 @@ final class NotificationsAPI: APIEndpoint { ) } - func markAllAsRead(headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise<()> { + func markAllAsRead(headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise<()> { Promise { seal in checkToken().done { self.manager.request( diff --git a/Stepic/Legacy/Model/Network/Endpoints/ProfilesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/ProfilesAPI.swift index 3ccfab4ae5..72edbc393b 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/ProfilesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/ProfilesAPI.swift @@ -17,12 +17,12 @@ final class ProfilesAPI: APIEndpoint { func retrieve( ids: [Int], existing: [Profile], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[Profile]> { self.getObjectsByIds(ids: ids, updating: existing) } - func retrieve(id: Int, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise<[Profile]> { + func retrieve(id: Int, headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise<[Profile]> { self.getObjectsByIds(ids: [id], updating: Profile.fetchById(id) ?? []) } diff --git a/Stepic/Legacy/Model/Network/Endpoints/ProgressesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/ProgressesAPI.swift index 4f438b985a..d08e07d424 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/ProgressesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/ProgressesAPI.swift @@ -17,7 +17,7 @@ final class ProgressesAPI: APIEndpoint { @discardableResult func retrieve( ids: [Progress.IdType], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Progress], refreshMode: RefreshMode, success: @escaping (([Progress]) -> Void), @@ -29,7 +29,7 @@ final class ProgressesAPI: APIEndpoint { } return getObjectsByIds( - requestString: name, + requestString: self.name, printOutput: false, ids: ids, deleteObjects: existing, @@ -42,7 +42,7 @@ final class ProgressesAPI: APIEndpoint { @available(*, deprecated, message: "Legacy with update existing") func retrieve( ids: [Progress.IdType], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[Progress]> { let ids = self.filterIds(ids) if ids.isEmpty { @@ -60,7 +60,5 @@ final class ProgressesAPI: APIEndpoint { } } - private func filterIds(_ ids: [Progress.IdType]) -> [Progress.IdType] { - ids.filter { !$0.isEmpty } - } + private func filterIds(_ ids: [Progress.IdType]) -> [Progress.IdType] { ids.filter { !$0.isEmpty } } } diff --git a/Stepic/Legacy/Model/Network/Endpoints/QueriesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/QueriesAPI.swift index f1ffcde147..dbde24ea8a 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/QueriesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/QueriesAPI.swift @@ -18,27 +18,35 @@ final class QueriesAPI: APIEndpoint { func retrieve(query: String) -> Promise<[String]> { let params: Parameters = ["query": query] return Promise { seal in - retrieve.request(requestEndpoint: "queries", paramName: "queries", params: params, updatingObjects: [Query](), withManager: manager).done { - queries, _ in + self.retrieve.request( + requestEndpoint: "queries", + paramName: "queries", + params: params, + updatingObjects: [Query](), + withManager: manager + ).done { queries, _ in seal.fulfill(queries.map { $0.text }) - }.catch { - error in + }.catch { error in seal.reject(error) } } } - @discardableResult func retrieve(query: String, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, success: @escaping (([String]) -> Void), error errorHandler: @escaping ((NetworkError) -> Void)) -> Request? { - retrieve(query: query).done { - queries in + @discardableResult + func retrieve( + query: String, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, + success: @escaping (([String]) -> Void), + error errorHandler: @escaping ((NetworkError) -> Void) + ) -> Request? { + self.retrieve(query: query).done { queries in success(queries) - }.catch { - error in - guard let e = error as? NetworkError else { + }.catch { error in + guard let networkError = error as? NetworkError else { errorHandler(NetworkError.other(error)) return } - errorHandler(e) + errorHandler(networkError) } return nil diff --git a/Stepic/Legacy/Model/Network/Endpoints/RecommendationsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/RecommendationsAPI.swift index dfb4d156c9..45fcef9d30 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/RecommendationsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/RecommendationsAPI.swift @@ -20,7 +20,7 @@ final class RecommendationsAPI: APIEndpoint { func retrieve( course courseId: Int, count: Int = 1, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[Int]> { Promise { seal in self.manager.request( @@ -45,7 +45,7 @@ final class RecommendationsAPI: APIEndpoint { user userId: Int, lesson lessonId: Int, reaction: Reaction, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise { let params = [ "recommendationReaction": [ @@ -81,7 +81,7 @@ extension RecommendationsAPI { user userId: Int, lesson lessonId: Int, reaction: Reaction, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (() -> Void), error errorHandler: @escaping ((String) -> Void) ) -> Request? { @@ -103,7 +103,7 @@ extension RecommendationsAPI { func getRecommendedLessonsId( course courseId: Int, count: Int = 1, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (([Int]) -> Void), error errorHandler: @escaping ((String) -> Void) ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/SearchResultsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/SearchResultsAPI.swift index 8300a6660b..f14d37d2ca 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/SearchResultsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/SearchResultsAPI.swift @@ -15,7 +15,16 @@ final class SearchResultsAPI: APIEndpoint { override var name: String { "search-results" } @available(*, deprecated, message: "Use searchCourse() -> Promise<([SearchResult], Meta)> instead") - @discardableResult func search(query: String, type: String?, language: ContentLanguage, page: Int?, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, success: @escaping ([SearchResult], Meta) -> Void, error errorHandler: @escaping (NSError) -> Void) -> Request? { + @discardableResult + func search( + query: String, + type: String?, + language: ContentLanguage, + page: Int?, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, + success: @escaping ([SearchResult], Meta) -> Void, + error errorHandler: @escaping (Error) -> Void + ) -> Request? { var params: Parameters = [ "query": query.lowercased(), "access_token": AuthInfo.shared.token?.accessToken ?? "", @@ -24,43 +33,39 @@ final class SearchResultsAPI: APIEndpoint { "is_public": "true" ] - if let p = page { - params["page"] = p + if let page = page { + params["page"] = page } - if let t = type { - params["type"] = t + if let type = type { + params["type"] = type } - return manager.request("\(StepikApplicationsInfo.apiURL)/search-results", method: .get, parameters: params, encoding: URLEncoding.default, headers: headers).responseSwiftyJSON({ - response in - - var error = response.result.error - var json: JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() - } - } else { - json = response.result.value! - } -// let response = response.response - - if let e = error as NSError? { - errorHandler(e) - return + return self.manager.request( + "\(StepikApplicationsInfo.apiURL)/search-results", + method: .get, + parameters: params, + encoding: URLEncoding.default, + headers: headers + ).responseSwiftyJSON { response in + switch response.result { + case .success(let json): + let meta = Meta(json: json["meta"]) + let searchResults = json["search-results"] + .arrayValue + .map { SearchResult(json: $0) } + success(searchResults, meta) + case .failure(let error): + errorHandler(error) } - - let meta = Meta(json: json["meta"]) - var results = [SearchResult]() - for resultJson in json["search-results"].arrayValue { - results += [SearchResult(json: resultJson)] - } - - success(results, meta) - }) + } } - func searchCourse(query: String, language: ContentLanguage, page: Int, headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise<([SearchResult], Meta)> { + func searchCourse( + query: String, + language: ContentLanguage, + page: Int, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders + ) -> Promise<([SearchResult], Meta)> { Promise<([SearchResult], Meta)> { seal in self.search( query: query, diff --git a/Stepic/Legacy/Model/Network/Endpoints/SectionsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/SectionsAPI.swift index 8de3219965..7b0e567f1d 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/SectionsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/SectionsAPI.swift @@ -31,7 +31,7 @@ final class SectionsAPI: APIEndpoint { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Section], refreshMode: RefreshMode, success: @escaping (([Section]) -> Void), diff --git a/Stepic/Legacy/Model/Network/Endpoints/StepicsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/StepicsAPI.swift index 8841b57d3c..5c3d2292f8 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/StepicsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/StepicsAPI.swift @@ -40,7 +40,7 @@ extension StepicsAPI { @available(*, deprecated, message: "Legacy method with callbacks") @discardableResult func retrieveCurrentUser( - _ headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + _ headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (User) -> Void, error errorHandler: @escaping (Error) -> Void ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/StepsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/StepsAPI.swift index 3aefc6bd2a..676c79c197 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/StepsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/StepsAPI.swift @@ -17,13 +17,13 @@ final class StepsAPI: APIEndpoint { func retrieve( ids: [Int], existing: [Step], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[Step]> { self.getObjectsByIds(ids: ids, updating: existing, printOutput: false) } @available(*, deprecated, message: "Legacy: we want to pass existing") - func retrieve(ids: [Int], headers: [String: String] = AuthInfo.shared.initialHTTPHeaders) -> Promise<[Step]> { + func retrieve(ids: [Int], headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders) -> Promise<[Step]> { if ids.isEmpty { return .value([]) } @@ -37,7 +37,7 @@ extension StepsAPI { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Step], refreshMode: RefreshMode, success: @escaping (([Step]) -> Void), diff --git a/Stepic/Legacy/Model/Network/Endpoints/SubmissionsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/SubmissionsAPI.swift index f6eeb67ac6..90dfa9a5f5 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/SubmissionsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/SubmissionsAPI.swift @@ -22,56 +22,39 @@ final class SubmissionsAPI: APIEndpoint { isDescending: Bool? = true, page: Int? = 1, userId: Int? = nil, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping ([Submission], Meta) -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { var params: Parameters = [:] params[objectName] = objectId - if let desc = isDescending { - params["order"] = desc ? "desc" : "asc" + if let isDescending = isDescending { + params["order"] = isDescending ? "desc" : "asc" } - if let p = page { - params["page"] = p + if let page = page { + params["page"] = page } - if let user = userId { - params["user"] = user + if let userId = userId { + params["user"] = userId } - return manager.request( + return self.manager.request( "\(StepikApplicationsInfo.apiURL)/submissions", method: .get, parameters: params, encoding: URLEncoding.default, headers: headers - ).responseSwiftyJSON { response in - var error = response.result.error - var json: JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() - } - } else { - json = response.result.value! - } - let response = response.response - - if let e = error { - let d = (e as NSError).localizedDescription - print(d) - errorHandler(d) - return - } - - if response?.statusCode == 200 { + ).validate().responseSwiftyJSON { response in + switch response.result { + case .success(let json): let meta = Meta(json: json["meta"]) - let submissions = json["submissions"].arrayValue.map({ Submission(json: $0, stepBlockName: stepName) }) + let submissions = json["submissions"] + .arrayValue + .map { Submission(json: $0, stepBlockName: stepName) } success(submissions, meta) - return - } else { - errorHandler("Response status code is wrong(\(String(describing: response?.statusCode)))") - return + case .failure(let error): + errorHandler(error.localizedDescription) } } } @@ -82,7 +65,7 @@ final class SubmissionsAPI: APIEndpoint { stepName: String, userID: User.IdType, page: Int = 1, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<([Submission], Meta)> { Promise { seal in let parameters: Parameters = [ @@ -118,7 +101,7 @@ final class SubmissionsAPI: APIEndpoint { isDescending: Bool? = true, page: Int? = 1, userId: Int? = nil, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping ([Submission], Meta) -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { @@ -142,7 +125,7 @@ final class SubmissionsAPI: APIEndpoint { isDescending: Bool? = true, page: Int? = 1, userId: Int? = nil, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping ([Submission], Meta) -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { @@ -193,7 +176,7 @@ final class SubmissionsAPI: APIEndpoint { func retrieve( stepName: String, submissionId: Int, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (Submission) -> Void, error errorHandler: @escaping (String) -> Void ) -> Request? { @@ -204,34 +187,15 @@ final class SubmissionsAPI: APIEndpoint { parameters: params, encoding: URLEncoding.default, headers: headers - ).responseSwiftyJSON({ response in - var error = response.result.error - var json: JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() - } - } else { - json = response.result.value! - } - let response = response.response - - if let e = error { - let d = (e as NSError).localizedDescription - print(d) - errorHandler(d) - return - } - - if response?.statusCode == 200 { + ).validate().responseSwiftyJSON { response in + switch response.result { + case .success(let json): let submission = Submission(json: json["submissions"][0], stepBlockName: stepName) success(submission) - return - } else { - errorHandler("Response status code is wrong(\(String(describing: response?.statusCode)))") - return + case .failure(let error): + errorHandler(error.localizedDescription) } - }) + } } func create(stepName: String, attemptId: Int, reply: Reply) -> Promise { @@ -260,7 +224,7 @@ extension SubmissionsAPI { stepName: String, attemptId: Int, reply: Reply, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping (Submission) -> Void, error errorHandler: @escaping (Error) -> Void ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/UnitsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/UnitsAPI.swift index fac8f19922..620eec6c97 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/UnitsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/UnitsAPI.swift @@ -17,16 +17,21 @@ final class UnitsAPI: APIEndpoint { //TODO: Seems like a bug. Fix this when fixing CoreData duplicates func retrieve(lesson lessonId: Int) -> Promise { let params: Parameters = ["lesson": lessonId] + return Promise { seal in - retrieve.request(requestEndpoint: "units", paramName: "units", params: params, updatingObjects: [Unit](), withManager: manager).done { - units, _, _ in - guard let unit: Unit = units.first else { + self.retrieve.request( + requestEndpoint: self.name, + paramName: self.name, + params: params, + updatingObjects: [Unit](), + withManager: self.manager + ).done { units, _, _ in + if let unit = units.first { + seal.fulfill(unit) + } else { seal.reject(UnitRetrieveError.noUnits) - return } - seal.fulfill(unit) - }.catch { - error in + }.catch { error in seal.reject(error) } } @@ -39,13 +44,13 @@ final class UnitsAPI: APIEndpoint { return .value([]) } - return getObjectsByIds(ids: ids, updating: Unit.fetch(ids)) + return self.getObjectsByIds(ids: ids, updating: Unit.fetch(ids)) } @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [Unit], refreshMode: RefreshMode, success: @escaping (([Unit]) -> Void), @@ -68,7 +73,7 @@ extension UnitsAPI { @discardableResult func retrieve( lesson lessonId: Int, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping ((Unit) -> Void), error errorHandler: @escaping ((Error) -> Void) ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/UserActivitiesAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/UserActivitiesAPI.swift index 434ec9e445..5e2cc2ee91 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/UserActivitiesAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/UserActivitiesAPI.swift @@ -30,7 +30,7 @@ extension UserActivitiesAPI { @discardableResult func retrieve( user userId: Int, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping ((UserActivity) -> Void), error errorHandler: @escaping ((Error) -> Void) ) -> Request? { diff --git a/Stepic/Legacy/Model/Network/Endpoints/UsersAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/UsersAPI.swift index f1df35a643..17d960599f 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/UsersAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/UsersAPI.swift @@ -16,7 +16,7 @@ final class UsersAPI: APIEndpoint { func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [User] ) -> Promise<[User]> { self.getObjectsByIds(ids: ids, updating: existing) @@ -26,7 +26,7 @@ final class UsersAPI: APIEndpoint { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders ) -> Promise<[User]> { if ids.isEmpty { return .value([]) @@ -41,7 +41,7 @@ extension UsersAPI { @discardableResult func retrieve( ids: [Int], - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, existing: [User], refreshMode: RefreshMode, success: @escaping (([User]) -> Void), diff --git a/Stepic/Legacy/Model/Network/Endpoints/ViewsAPI.swift b/Stepic/Legacy/Model/Network/Endpoints/ViewsAPI.swift index c2bc128f83..f38711749a 100644 --- a/Stepic/Legacy/Model/Network/Endpoints/ViewsAPI.swift +++ b/Stepic/Legacy/Model/Network/Endpoints/ViewsAPI.swift @@ -32,7 +32,7 @@ final class ViewsAPI: APIEndpoint { func create( stepId id: Int, assignment: Int?, - headers: [String: String] = AuthInfo.shared.initialHTTPHeaders, + headers: HTTPHeaders = AuthInfo.shared.initialHTTPHeaders, success: @escaping () -> Void, error errorHandler: @escaping (ViewsCreateError) -> Void ) -> Request? { @@ -60,40 +60,25 @@ final class ViewsAPI: APIEndpoint { parameters: params, encoding: JSONEncoding.default, headers: headers - ).responseSwiftyJSON({ response in - var error = response.result.error -// var json : JSON = [:] - if response.result.value == nil { - if error == nil { - error = NSError() + ).responseSwiftyJSON { response in + switch response.result { + case .success: + guard let statusCode = response.response?.statusCode else { + return errorHandler(.other(error: nil, code: nil, message: nil)) } - } else { -// json = response.result.value! - } - let response = response.response - - if let e = error { - errorHandler(.other(error: e, code: nil, message: nil)) - return - } - guard let code = response?.statusCode else { - errorHandler(.other(error: nil, code: nil, message: nil)) - return - } - - switch code { - case 200..<300: - success() - return - case 401: - errorHandler(.notAuthorized) - return - default: - errorHandler(.other(error: nil, code: code, message: nil)) - return + switch statusCode { + case 200..<300: + success() + case 401: + errorHandler(.notAuthorized) + default: + errorHandler(.other(error: nil, code: statusCode, message: nil)) + } + case .failure(let error): + errorHandler(.other(error: error, code: nil, message: nil)) } - }) + } } } diff --git a/Stepic/Legacy/Model/Network/RequestMakers/CreateRequestMaker.swift b/Stepic/Legacy/Model/Network/RequestMakers/CreateRequestMaker.swift index 89962c3721..707190bee7 100644 --- a/Stepic/Legacy/Model/Network/RequestMakers/CreateRequestMaker.swift +++ b/Stepic/Legacy/Model/Network/RequestMakers/CreateRequestMaker.swift @@ -16,7 +16,7 @@ final class CreateRequestMaker { requestEndpoint: String, paramName: String, creatingObject: T, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<(T, JSON)> { Promise { seal in let params: Parameters? = [ @@ -48,7 +48,7 @@ final class CreateRequestMaker { requestEndpoint: String, paramName: String, creatingObject: T, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise { Promise { seal in self.request( @@ -68,7 +68,7 @@ final class CreateRequestMaker { requestEndpoint: String, paramName: String, creatingObject: T, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise { Promise { seal in self.request( diff --git a/Stepic/Legacy/Model/Network/RequestMakers/DeleteRequestMaker.swift b/Stepic/Legacy/Model/Network/RequestMakers/DeleteRequestMaker.swift index 718b162622..9498eafb6e 100644 --- a/Stepic/Legacy/Model/Network/RequestMakers/DeleteRequestMaker.swift +++ b/Stepic/Legacy/Model/Network/RequestMakers/DeleteRequestMaker.swift @@ -14,7 +14,7 @@ final class DeleteRequestMaker { func request( requestEndpoint: String, deletingId: Int, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise { Promise { seal in checkToken().done { diff --git a/Stepic/Legacy/Model/Network/RequestMakers/RetrieveRequestMaker.swift b/Stepic/Legacy/Model/Network/RequestMakers/RetrieveRequestMaker.swift index 27f495737f..8342e23914 100644 --- a/Stepic/Legacy/Model/Network/RequestMakers/RetrieveRequestMaker.swift +++ b/Stepic/Legacy/Model/Network/RequestMakers/RetrieveRequestMaker.swift @@ -17,7 +17,7 @@ final class RetrieveRequestMaker { paramName: String, id: T.IdType, updatingObject: T? = nil, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise { Promise { seal in checkToken().done { @@ -48,7 +48,7 @@ final class RetrieveRequestMaker { paramName: String, params: Parameters, updatingObjects: [T] = [], - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<([T], Meta, JSON)> { Promise { seal in checkToken().done { @@ -87,7 +87,7 @@ final class RetrieveRequestMaker { paramName: String, params: Parameters, updatingObjects: [T] = [], - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<([T], Meta)> { Promise { seal in self.request( @@ -108,7 +108,7 @@ final class RetrieveRequestMaker { requestEndpoint: String, paramName: String, params: Parameters, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<([T], Meta, JSON)> { Promise { seal in checkToken().done { @@ -157,7 +157,7 @@ final class RetrieveRequestMaker { requestEndpoint: String, paramName: String, params: Parameters, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<([T], Meta)> { Promise { seal in self.requestWithFetching( @@ -178,7 +178,7 @@ final class RetrieveRequestMaker { paramName: String, ids: [T.IdType], updating: [T], - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<([T], JSON)> { let params: Parameters = [ "ids": ids @@ -221,7 +221,7 @@ final class RetrieveRequestMaker { paramName: String, ids: [T.IdType], updating: [T], - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<[T]> { Promise { seal in self.request( diff --git a/Stepic/Legacy/Model/Network/RequestMakers/UpdateRequestMaker.swift b/Stepic/Legacy/Model/Network/RequestMakers/UpdateRequestMaker.swift index f7cda3a621..72b4f2a639 100644 --- a/Stepic/Legacy/Model/Network/RequestMakers/UpdateRequestMaker.swift +++ b/Stepic/Legacy/Model/Network/RequestMakers/UpdateRequestMaker.swift @@ -16,7 +16,7 @@ final class UpdateRequestMaker { requestEndpoint: String, paramName: String, updatingObject: T, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise<(T, JSON)> { Promise { seal in let params: Parameters? = [ @@ -48,7 +48,7 @@ final class UpdateRequestMaker { requestEndpoint: String, paramName: String, updatingObject: T, - withManager manager: Alamofire.SessionManager + withManager manager: Alamofire.Session ) -> Promise { Promise { seal in self.request( diff --git a/Stepic/Legacy/Model/Network/StepikRequestAdapter.swift b/Stepic/Legacy/Model/Network/StepikRequestAdapter.swift new file mode 100644 index 0000000000..d3d2fc3c1d --- /dev/null +++ b/Stepic/Legacy/Model/Network/StepikRequestAdapter.swift @@ -0,0 +1,17 @@ +import Alamofire + +final class StepikRequestAdapter: RequestAdapter { + func adapt( + _ urlRequest: URLRequest, + for session: Session, + completion: @escaping (Result) -> Void + ) { + var urlRequest = urlRequest + + for (headerField, value) in AuthInfo.shared.initialHTTPHeaders.dictionary { + urlRequest.setValue(value, forHTTPHeaderField: headerField) + } + + completion(.success(urlRequest)) + } +} diff --git a/Stepic/Legacy/Model/Network/StepikRequestInterceptor.swift b/Stepic/Legacy/Model/Network/StepikRequestInterceptor.swift new file mode 100644 index 0000000000..3cf66bf7a5 --- /dev/null +++ b/Stepic/Legacy/Model/Network/StepikRequestInterceptor.swift @@ -0,0 +1,31 @@ +import Alamofire + +final class StepikRequestInterceptor: RequestInterceptor { + private let adapter: RequestAdapter + private let retrier: RequestRetrier + + init( + adapter: RequestAdapter = StepikRequestAdapter(), + retrier: RequestRetrier = StepikRequestRetrier() + ) { + self.adapter = adapter + self.retrier = retrier + } + + func adapt( + _ urlRequest: URLRequest, + for session: Session, + completion: @escaping (Result) -> Void + ) { + self.adapter.adapt(urlRequest, for: session, completion: completion) + } + + func retry( + _ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void + ) { + self.retrier.retry(request, for: session, dueTo: error, completion: completion) + } +} diff --git a/Stepic/Legacy/Model/Network/StepikRequestRetrier.swift b/Stepic/Legacy/Model/Network/StepikRequestRetrier.swift new file mode 100644 index 0000000000..b8c7b0c8ab --- /dev/null +++ b/Stepic/Legacy/Model/Network/StepikRequestRetrier.swift @@ -0,0 +1,24 @@ +import Alamofire +import PromiseKit + +final class StepikRequestRetrier: RequestRetrier { + private static let unauthorizedErrorStatusCode = 401 + + func retry( + _ request: Request, + for session: Session, + dueTo error: Error, + completion: @escaping (RetryResult) -> Void + ) { + if let response = request.task?.response as? HTTPURLResponse, + response.statusCode == Self.unauthorizedErrorStatusCode && request.retryCount == 0 { + checkToken().done { + completion(.retry) + }.catch { error in + completion(.doNotRetryWithError(error)) + } + } else { + completion(.doNotRetryWithError(error)) + } + } +} diff --git a/Stepic/Legacy/Model/StepikSession/AuthInfo.swift b/Stepic/Legacy/Model/StepikSession/AuthInfo.swift index 0d2b90f0b4..b005376ae2 100644 --- a/Stepic/Legacy/Model/StepikSession/AuthInfo.swift +++ b/Stepic/Legacy/Model/StepikSession/AuthInfo.swift @@ -6,7 +6,8 @@ // Copyright (c) 2015 Alex Karpov. All rights reserved. // -import UIKit +import Alamofire +import Foundation extension Foundation.Notification.Name { static let didLogout = Foundation.Notification.Name("didLogout") @@ -84,7 +85,7 @@ final class AuthInfo: NSObject { print("\nsetting new token -> \(newToken!.accessToken)\n") didRefresh = true setTokenValue(newToken) - Session.delete() + StepikSession.delete() if oldToken == nil { // first set, not refresh NotificationCenter.default.post(name: .didLogin, object: nil) @@ -175,11 +176,11 @@ final class AuthInfo: NSObject { } } - var initialHTTPHeaders: [String: String] { + var initialHTTPHeaders: HTTPHeaders { if !AuthInfo.shared.isAuthorized { - return Session.cookieHeaders + return HTTPHeaders(StepikSession.cookieHeaders) } else { - return APIDefaults.headers.bearer + return APIDefaults.Headers.bearer } } } diff --git a/Stepic/Legacy/Model/StepikSession/Session.swift b/Stepic/Legacy/Model/StepikSession/StepikSession.swift similarity index 59% rename from Stepic/Legacy/Model/StepikSession/Session.swift rename to Stepic/Legacy/Model/StepikSession/StepikSession.swift index 3f720bbcf7..dfca3da08f 100644 --- a/Stepic/Legacy/Model/StepikSession/Session.swift +++ b/Stepic/Legacy/Model/StepikSession/StepikSession.swift @@ -9,7 +9,13 @@ import Alamofire import Foundation -final class Session { +final class StepikSession { + static var cookieHeaders = [String: String]() + static var needsRefresh: Bool { self.cookieHeaders.isEmpty } + + static var cookieDict = [String: String]() + static var hasCookies: Bool { !self.cookieDict.isEmpty } + static func delete() { let storage = HTTPCookieStorage.shared for cookie in storage.cookies ?? [] { @@ -17,29 +23,39 @@ final class Session { storage.deleteCookie(cookie) } } - cookieDict = [:] - cookieHeaders = [:] + self.cookieDict = [:] + self.cookieHeaders = [:] } - static func refresh(completion: @escaping (() -> Void), error errorHandler: @escaping ((String) -> Void)) -> Request? { + static func refresh( + completion: @escaping (() -> Void), + error errorHandler: @escaping ((String) -> Void) + ) -> Request? { print("refreshing session") - let stepicURLString = StepikApplicationsInfo.stepikURL - let stepicURL = URL(string: stepicURLString)! - delete() - return AlamofireDefaultSessionManager.shared.request(stepicURLString, parameters: nil, encoding: URLEncoding.default).response { - response in + let stepikURLString = StepikApplicationsInfo.stepikURL + let stepikURL = URL(string: stepikURLString)! + + self.delete() + return AlamofireDefaultSessionManager.shared.request( + stepikURLString, + parameters: nil, + encoding: URLEncoding.default + ).response { response in let error = response.error let response = response.response - if let e = error { - errorHandler((e as NSError).localizedDescription) + if let error = error { + errorHandler((error as NSError).localizedDescription) } - if let r = response { - let cookies = HTTPCookie.cookies(withResponseHeaderFields: r.allHeaderFields as! [String: String], for: stepicURL) - HTTPCookieStorage.shared.setCookies(cookies, for: stepicURL, mainDocumentURL: nil) + if let response = response { + let cookies = HTTPCookie.cookies( + withResponseHeaderFields: response.allHeaderFields as! [String: String], + for: stepikURL + ) + HTTPCookieStorage.shared.setCookies(cookies, for: stepikURL, mainDocumentURL: nil) var cookieDict = [String: String]() for cookie in cookies { @@ -48,11 +64,11 @@ final class Session { print(cookieDict) - Session.cookieDict = cookieDict + StepikSession.cookieDict = cookieDict if let csrftoken = cookieDict["\(StepikApplicationsInfo.cookiePrefix)csrftoken"], - let sessionId = cookieDict["\(StepikApplicationsInfo.cookiePrefix)sessionid"] { - Session.cookieHeaders = [ + let sessionId = cookieDict["\(StepikApplicationsInfo.cookiePrefix)sessionid"] { + self.cookieHeaders = [ "Referer": "\(StepikApplicationsInfo.stepikURL)/", "X-CSRFToken": csrftoken, "Cookie": "csrftoken=\(csrftoken); sessionid=\(sessionId)" @@ -66,10 +82,4 @@ final class Session { } } } - - static var cookieHeaders = [String: String]() - static var needsRefresh: Bool { self.cookieHeaders.isEmpty } - - static var cookieDict = [String: String]() - static var hasCookies: Bool { !self.cookieDict.isEmpty } } diff --git a/Stepic/Legacy/Views/AvatarImageView.swift b/Stepic/Legacy/Views/AvatarImageView.swift index 420f39a781..b52a15c1dc 100644 --- a/Stepic/Legacy/Views/AvatarImageView.swift +++ b/Stepic/Legacy/Views/AvatarImageView.swift @@ -49,37 +49,38 @@ final class AvatarImageView: UIImageView { } func set(with url: URL) { - if url.pathExtension != "svg" { - self.sd_setImage(with: url, placeholderImage: self.image) - } else { - AlamofireDefaultSessionManager.shared.request(url).responseData(completionHandler: { response in - if response.result.error != nil { - return - } + if url.pathExtension == "svg" { + AlamofireDefaultSessionManager + .shared + .request(url) + .responseData { dataResponse in + guard let data = dataResponse.data else { + return + } - guard let data = response.result.value else { - return - } + DispatchQueue.global(qos: .userInitiated).async { + if let svgString = String(data: data, encoding: String.Encoding.utf8), + let letters = self.extractLetters(from: svgString) { + // Draw custom avatar + DispatchQueue.main.async { + self.image = self.renderImage(with: letters) ?? self.image + } + } else { + // Render SVG + let svgImage = SVGKImage(data: data) - DispatchQueue.global(qos: .userInitiated).async { - if let svgString = String(data: data, encoding: String.Encoding.utf8), - let letters = self.extractLetters(from: svgString) { - // Draw custom avatar - DispatchQueue.main.async { - self.image = self.renderImage(with: letters) ?? self.image - } - } else { - // Render SVG - let svgImage = SVGKImage(data: data) - if !(svgImage?.hasSize() ?? true) { - svgImage?.size = CGSize(width: 200, height: 200) - } - DispatchQueue.main.async { - self.image = svgImage?.uiImage ?? self.image + if !(svgImage?.hasSize() ?? true) { + svgImage?.size = CGSize(width: 200, height: 200) + } + + DispatchQueue.main.async { + self.image = svgImage?.uiImage ?? self.image + } } } } - }) + } else { + self.sd_setImage(with: url, placeholderImage: self.image) } } diff --git a/Stepic/Sources/Common/Result.swift b/Stepic/Sources/Common/Result.swift deleted file mode 100644 index fc3df98ad2..0000000000 --- a/Stepic/Sources/Common/Result.swift +++ /dev/null @@ -1,6 +0,0 @@ -import Foundation - -enum Result { - case success(T) - case failure(Error) -} diff --git a/Stepic/Sources/Common/StepikResult.swift b/Stepic/Sources/Common/StepikResult.swift new file mode 100644 index 0000000000..4a1ce75513 --- /dev/null +++ b/Stepic/Sources/Common/StepikResult.swift @@ -0,0 +1,9 @@ +import Foundation + +// TODO: Replace StepikResult type with Swift’s Result type. + +@available(*, deprecated, message: "Use Swift’s Result type.") +enum StepikResult { + case success(T) + case failure(Swift.Error) +} diff --git a/Stepic/Sources/Extensions/ThirdParty/HTTPHeader+Stepik.swift b/Stepic/Sources/Extensions/ThirdParty/HTTPHeader+Stepik.swift new file mode 100644 index 0000000000..3caa4a12d9 --- /dev/null +++ b/Stepic/Sources/Extensions/ThirdParty/HTTPHeader+Stepik.swift @@ -0,0 +1,11 @@ +import Alamofire +import Foundation + +extension HTTPHeader { + /// Returns Stepik's default `Content-Type` header, appropriate for the authorization requests. + /// + /// Field: `Content-Type`. + /// + /// Value: `application/x-www-form-urlencoded`. + static let stepikAuthContentType: HTTPHeader = .contentType("application/x-www-form-urlencoded") +} diff --git a/Stepic/Sources/Modules/CourseInfo/CourseInfoDataFlow.swift b/Stepic/Sources/Modules/CourseInfo/CourseInfoDataFlow.swift index 21b82fb975..3639e13a61 100644 --- a/Stepic/Sources/Modules/CourseInfo/CourseInfoDataFlow.swift +++ b/Stepic/Sources/Modules/CourseInfo/CourseInfoDataFlow.swift @@ -25,7 +25,7 @@ enum CourseInfo { struct Request { } struct Response { - var result: Result + var result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/CourseInfoSubmodules/CourseInfoTabSyllabus/CourseInfoTabSyllabusDataFlow.swift b/Stepic/Sources/Modules/CourseInfoSubmodules/CourseInfoTabSyllabus/CourseInfoTabSyllabusDataFlow.swift index b5b3391c5c..8c0df5e9b4 100644 --- a/Stepic/Sources/Modules/CourseInfoSubmodules/CourseInfoTabSyllabus/CourseInfoTabSyllabusDataFlow.swift +++ b/Stepic/Sources/Modules/CourseInfoSubmodules/CourseInfoTabSyllabus/CourseInfoTabSyllabusDataFlow.swift @@ -31,7 +31,7 @@ enum CourseInfoTabSyllabus { struct Request { } struct Response { - var result: Result + var result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/CourseList/CourseListDataFlow.swift b/Stepic/Sources/Modules/CourseList/CourseListDataFlow.swift index 961296f679..4926393251 100644 --- a/Stepic/Sources/Modules/CourseList/CourseListDataFlow.swift +++ b/Stepic/Sources/Modules/CourseList/CourseListDataFlow.swift @@ -41,7 +41,7 @@ enum CourseList { struct Response { let isAuthorized: Bool - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/Discussions/DiscussionsDataFlow.swift b/Stepic/Sources/Modules/Discussions/DiscussionsDataFlow.swift index 5d3d9de79e..a3f09346a9 100644 --- a/Stepic/Sources/Modules/Discussions/DiscussionsDataFlow.swift +++ b/Stepic/Sources/Modules/Discussions/DiscussionsDataFlow.swift @@ -57,7 +57,7 @@ enum Discussions { struct Request {} struct Response { - let result: Result + let result: StepikResult } struct ViewModel { @@ -72,7 +72,7 @@ enum Discussions { } struct Response { - let result: Result + let result: StepikResult let direction: PaginationDirection } @@ -166,7 +166,7 @@ enum Discussions { } struct Response { - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/EditStep/EditStepDataFlow.swift b/Stepic/Sources/Modules/EditStep/EditStepDataFlow.swift index f4c07adbeb..3220848ad8 100644 --- a/Stepic/Sources/Modules/EditStep/EditStepDataFlow.swift +++ b/Stepic/Sources/Modules/EditStep/EditStepDataFlow.swift @@ -15,7 +15,7 @@ enum EditStep { struct Request { } struct Response { - let data: Result + let data: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionDataFlow.swift b/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionDataFlow.swift index a2622bfeb5..a232207688 100644 --- a/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionDataFlow.swift +++ b/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionDataFlow.swift @@ -8,7 +8,7 @@ enum CourseListsCollection { struct Request { } struct Response { - var result: Result<[CourseListModel]> + var result: StepikResult<[CourseListModel]> } struct ViewModel { diff --git a/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionInteractor.swift b/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionInteractor.swift index cccfc0fe8f..77946ed323 100644 --- a/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionInteractor.swift +++ b/Stepic/Sources/Modules/ExploreSubmodules/CourseListsCollection/CourseListsCollectionInteractor.swift @@ -26,14 +26,14 @@ final class CourseListsCollectionInteractor: CourseListsCollectionInteractorProt self.provider.fetchCachedCourseLists().then { cachedCourseLists -> Promise<[CourseListModel]> in // Pass cached data to presenter and start fetching from remote - let response = Result<[CourseListModel]>.success(cachedCourseLists) + let response = StepikResult<[CourseListModel]>.success(cachedCourseLists) self.presenter.presentCourses( response: CourseListsCollection.CourseListsLoad.Response(result: response) ) return self.provider.fetchRemoteCourseLists() }.done { remoteCourseLists in - let response = Result<[CourseListModel]>.success(remoteCourseLists) + let response = StepikResult<[CourseListModel]>.success(remoteCourseLists) self.presenter.presentCourses( response: CourseListsCollection.CourseListsLoad.Response(result: response) ) diff --git a/Stepic/Sources/Modules/ExploreSubmodules/Tags/TagsDataFlow.swift b/Stepic/Sources/Modules/ExploreSubmodules/Tags/TagsDataFlow.swift index 78b8439c0f..3938fa2d80 100644 --- a/Stepic/Sources/Modules/ExploreSubmodules/Tags/TagsDataFlow.swift +++ b/Stepic/Sources/Modules/ExploreSubmodules/Tags/TagsDataFlow.swift @@ -17,7 +17,7 @@ enum Tags { struct Request { } struct Response { - let result: Result<[(UniqueIdentifierType, Tag)]> + let result: StepikResult<[(UniqueIdentifierType, Tag)]> } struct ViewModel { diff --git a/Stepic/Sources/Modules/Lesson/LessonDataFlow.swift b/Stepic/Sources/Modules/Lesson/LessonDataFlow.swift index 79daafd952..96c790061f 100644 --- a/Stepic/Sources/Modules/Lesson/LessonDataFlow.swift +++ b/Stepic/Sources/Modules/Lesson/LessonDataFlow.swift @@ -16,7 +16,7 @@ enum LessonDataFlow { } struct Response { - let state: Result + let state: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/Quizzes/BaseQuiz/BaseQuizDataFlow.swift b/Stepic/Sources/Modules/Quizzes/BaseQuiz/BaseQuizDataFlow.swift index b29fa5ddea..0eb581b21d 100644 --- a/Stepic/Sources/Modules/Quizzes/BaseQuiz/BaseQuizDataFlow.swift +++ b/Stepic/Sources/Modules/Quizzes/BaseQuiz/BaseQuizDataFlow.swift @@ -16,7 +16,7 @@ enum BaseQuiz { } struct Response { - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/Quizzes/CodeQuizFullscreen/Tabs/CodeQuizFullscreenRunCode/CodeQuizFullscreenRunCodeDataFlow.swift b/Stepic/Sources/Modules/Quizzes/CodeQuizFullscreen/Tabs/CodeQuizFullscreenRunCode/CodeQuizFullscreenRunCodeDataFlow.swift index c5f2c92829..19b0252585 100644 --- a/Stepic/Sources/Modules/Quizzes/CodeQuizFullscreen/Tabs/CodeQuizFullscreenRunCode/CodeQuizFullscreenRunCodeDataFlow.swift +++ b/Stepic/Sources/Modules/Quizzes/CodeQuizFullscreen/Tabs/CodeQuizFullscreenRunCode/CodeQuizFullscreenRunCodeDataFlow.swift @@ -44,7 +44,7 @@ enum CodeQuizFullscreenRunCode { struct Request {} struct Response { - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/Solution/SolutionDataFlow.swift b/Stepic/Sources/Modules/Solution/SolutionDataFlow.swift index 72b81658f4..4ab8fa183e 100644 --- a/Stepic/Sources/Modules/Solution/SolutionDataFlow.swift +++ b/Stepic/Sources/Modules/Solution/SolutionDataFlow.swift @@ -11,7 +11,7 @@ enum Solution { struct Request {} struct Response { - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/Step/StepDataFlow.swift b/Stepic/Sources/Modules/Step/StepDataFlow.swift index 3ea217dfed..95d8f322d9 100644 --- a/Stepic/Sources/Modules/Step/StepDataFlow.swift +++ b/Stepic/Sources/Modules/Step/StepDataFlow.swift @@ -12,7 +12,7 @@ enum StepDataFlow { } struct Response { - let result: Result + let result: StepikResult } struct ViewModel { @@ -113,7 +113,7 @@ enum StepDataFlow { struct Request {} struct Response { - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/Submissions/SubmissionsDataFlow.swift b/Stepic/Sources/Modules/Submissions/SubmissionsDataFlow.swift index 14455f98c9..442ae44265 100644 --- a/Stepic/Sources/Modules/Submissions/SubmissionsDataFlow.swift +++ b/Stepic/Sources/Modules/Submissions/SubmissionsDataFlow.swift @@ -8,7 +8,7 @@ enum Submissions { struct Request {} struct Response { - let result: Result + let result: StepikResult } struct ViewModel { @@ -21,7 +21,7 @@ enum Submissions { struct Request {} struct Response { - let result: Result + let result: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Modules/WriteComment/WriteCommentDataFlow.swift b/Stepic/Sources/Modules/WriteComment/WriteCommentDataFlow.swift index d96e32c662..18ed08afc6 100644 --- a/Stepic/Sources/Modules/WriteComment/WriteCommentDataFlow.swift +++ b/Stepic/Sources/Modules/WriteComment/WriteCommentDataFlow.swift @@ -62,7 +62,7 @@ enum WriteComment { struct Request {} struct Response { - let data: Result + let data: StepikResult } struct ViewModel { diff --git a/Stepic/Sources/Services/NetworkReachabilityService.swift b/Stepic/Sources/Services/NetworkReachabilityService.swift index ae80238c7b..cb6af19721 100644 --- a/Stepic/Sources/Services/NetworkReachabilityService.swift +++ b/Stepic/Sources/Services/NetworkReachabilityService.swift @@ -29,7 +29,7 @@ final class NetworkReachabilityService: NetworkReachabilityServiceProtocol { var connectionType: NetworkReachabilityConnectionType { if self.reachabilityManager?.isReachableOnEthernetOrWiFi ?? false { return .ethernetOrWiFi - } else if self.reachabilityManager?.isReachableOnWWAN ?? false { + } else if self.reachabilityManager?.isReachableOnCellular ?? false { return .wwan } else { return .unknown diff --git a/StepicTests/DownloaderTests.swift b/StepicTests/DownloaderTests.swift index 141f754317..14e6a02cb3 100644 --- a/StepicTests/DownloaderTests.swift +++ b/StepicTests/DownloaderTests.swift @@ -7,10 +7,10 @@ // import Foundation +import Mockingjay import Nimble import Quick import XCTest -import Mockingjay @testable import Stepic From 05ac909a42041d9a573aedee4ea9d53366009f5e Mon Sep 17 00:00:00 2001 From: Ivan Magda Date: Tue, 31 Mar 2020 12:01:55 +0300 Subject: [PATCH 3/6] Fix WebView height (#685) * Wait when page is fully loaded * Update kotlin-playground * Fix initial kotlin playground height * Update jquery * Early exit poll ready state --- Stepic.xcodeproj/project.pbxproj | 12 +- Stepic/Legacy/Helpers/HTMLProcessor.swift | 2 +- .../Model/Constants/Scripts/Scripts.plist | 6 +- .../Model/Constants/Scripts/Scripts.swift | 30 ++--- .../ContentProcessingInjection.swift | 2 +- .../ProcessedContentTextView.swift | 39 ++++-- Stepic/jquery-3.2.1.min.js | 4 - Stepic/jquery-3.4.1.min.js | 2 + Stepic/kotlin-playground-1.21.1.min.js | 46 +++++++ Stepic/wysiwyg.css | 115 +++++++++++------- 10 files changed, 172 insertions(+), 86 deletions(-) delete mode 100644 Stepic/jquery-3.2.1.min.js create mode 100644 Stepic/jquery-3.4.1.min.js create mode 100644 Stepic/kotlin-playground-1.21.1.min.js diff --git a/Stepic.xcodeproj/project.pbxproj b/Stepic.xcodeproj/project.pbxproj index 505e13c1fb..54ba1991ae 100644 --- a/Stepic.xcodeproj/project.pbxproj +++ b/Stepic.xcodeproj/project.pbxproj @@ -141,7 +141,6 @@ 08484F1C211B5DB20006266F /* StorySkeletonPlaceholderView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 08484F1B211B5DB20006266F /* StorySkeletonPlaceholderView.xib */; }; 084BD9BB1E5368B600B1901E /* PickerViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 084BD9BA1E5368B600B1901E /* PickerViewController.swift */; }; 084C658D1FDAD04C006A3E17 /* RemoteConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 084C658C1FDAD04C006A3E17 /* RemoteConfig.swift */; }; - 084C9AF81EC4C11A00AC5C3C /* jquery-3.2.1.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 084C9AF71EC4C11A00AC5C3C /* jquery-3.2.1.min.js */; }; 084DDDE1204EDF7600913503 /* NotificationRequestAlertViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 084DDDE0204EDF7500913503 /* NotificationRequestAlertViewController.swift */; }; 084F7AA71E76EF690088368A /* LastStep.swift in Sources */ = {isa = PBXBuildFile; fileRef = 084F7AA61E76EF690088368A /* LastStep.swift */; }; 084F7AAA1E76EF780088368A /* LastStep+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 084F7AA91E76EF780088368A /* LastStep+CoreDataProperties.swift */; }; @@ -452,6 +451,8 @@ 2C4BE7E0221328E700AEAC34 /* CourseReview+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4BE7DF221328E700AEAC34 /* CourseReview+CoreDataProperties.swift */; }; 2C4BE7E22213294700AEAC34 /* CourseReviewSummary+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4BE7E12213294700AEAC34 /* CourseReviewSummary+CoreDataProperties.swift */; }; 2C4DDADF242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C4DDADE242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift */; }; + 2C4F3B092432693D002ADB53 /* kotlin-playground-1.21.1.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 2C4F3B072432693D002ADB53 /* kotlin-playground-1.21.1.min.js */; }; + 2C4F3B0A2432693D002ADB53 /* jquery-3.4.1.min.js in Resources */ = {isa = PBXBuildFile; fileRef = 2C4F3B082432693D002ADB53 /* jquery-3.4.1.min.js */; }; 2C5240D32399257B000DDA13 /* UIStatusBarStyle+DarkContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C5240D22399257B000DDA13 /* UIStatusBarStyle+DarkContent.swift */; }; 2C546C1323DA02AB00352F27 /* String+SafeSubscript.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C546C1223DA02AB00352F27 /* String+SafeSubscript.swift */; }; 2C546C1523DA05F300352F27 /* StringExtensionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C546C1423DA05F300352F27 /* StringExtensionsTests.swift */; }; @@ -1320,7 +1321,6 @@ 084BD9BA1E5368B600B1901E /* PickerViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PickerViewController.swift; sourceTree = ""; }; 084C658C1FDAD04C006A3E17 /* RemoteConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteConfig.swift; sourceTree = ""; }; 084C7EA61E85A130002D0796 /* Model_steps_restrictions_v14.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_steps_restrictions_v14.xcdatamodel; sourceTree = ""; }; - 084C9AF71EC4C11A00AC5C3C /* jquery-3.2.1.min.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = "jquery-3.2.1.min.js"; sourceTree = ""; }; 084DB9D31FA283C00074B11E /* Model_progress_activities_v20.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_progress_activities_v20.xcdatamodel; sourceTree = ""; }; 084DDDE0204EDF7500913503 /* NotificationRequestAlertViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NotificationRequestAlertViewController.swift; sourceTree = ""; }; 084F7A951E76EAB10088368A /* Model_last_step_v13.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_last_step_v13.xcdatamodel; sourceTree = ""; }; @@ -1673,6 +1673,8 @@ 2C4BE7DF221328E700AEAC34 /* CourseReview+CoreDataProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "CourseReview+CoreDataProperties.swift"; sourceTree = ""; }; 2C4BE7E12213294700AEAC34 /* CourseReviewSummary+CoreDataProperties.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "CourseReviewSummary+CoreDataProperties.swift"; sourceTree = ""; }; 2C4DDADE242FD1A400A0B4C8 /* HTTPHeader+Stepik.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "HTTPHeader+Stepik.swift"; sourceTree = ""; }; + 2C4F3B072432693D002ADB53 /* kotlin-playground-1.21.1.min.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = "kotlin-playground-1.21.1.min.js"; sourceTree = ""; }; + 2C4F3B082432693D002ADB53 /* jquery-3.4.1.min.js */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.javascript; path = "jquery-3.4.1.min.js"; sourceTree = ""; }; 2C5240D22399257B000DDA13 /* UIStatusBarStyle+DarkContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIStatusBarStyle+DarkContent.swift"; sourceTree = ""; }; 2C546C1223DA02AB00352F27 /* String+SafeSubscript.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+SafeSubscript.swift"; sourceTree = ""; }; 2C546C1423DA05F300352F27 /* StringExtensionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringExtensionsTests.swift; sourceTree = ""; }; @@ -2669,7 +2671,8 @@ 08DB7DAA1D50F92B0006E9F6 /* Stepic.entitlements */, 08CA59D41BBA1628008DC44D /* Stepic-Bridging-Header.h */, 2CDE82E1221D5CCB00C41887 /* highlight.js */, - 084C9AF71EC4C11A00AC5C3C /* jquery-3.2.1.min.js */, + 2C4F3B082432693D002ADB53 /* jquery-3.4.1.min.js */, + 2C4F3B072432693D002ADB53 /* kotlin-playground-1.21.1.min.js */, 08C0A4351BF12CDF0010F049 /* CustomMessagesDesign.json */, 08A7B0E71EB340F500C1BA71 /* Auth.plist */, 2C104B672069064D0026FEB9 /* autocomplete_suggestions.plist */, @@ -6407,7 +6410,7 @@ 2C7FEE7A1FDAFB4600B2B4F1 /* OnboardingPageView.xib in Resources */, 2C5DF1461FED2B36003B1177 /* StepCardView.xib in Resources */, 2CA9D9832010A13C007AA743 /* ProgressTableViewCell.xib in Resources */, - 084C9AF81EC4C11A00AC5C3C /* jquery-3.2.1.min.js in Resources */, + 2C4F3B092432693D002ADB53 /* kotlin-playground-1.21.1.min.js in Resources */, 082B54D120A9DD3C00144817 /* PersonalDeadlines.storyboard in Resources */, 2C22043220E2804F0060117A /* AchievementSkeletonPlaceholderView.xib in Resources */, 2CA9D98D20123347007AA743 /* adjectives_m.plist in Resources */, @@ -6452,6 +6455,7 @@ 62E9815A6AAC6C12E9B9D862 /* ProfileHeaderInfoView.xib in Resources */, 08FCC79420F3BAEB008B84B9 /* stepikcontent.css in Resources */, 2C6B2F9D20D7F24800F7C976 /* AchievementPopupViewController.xib in Resources */, + 2C4F3B0A2432693D002ADB53 /* jquery-3.4.1.min.js in Resources */, 2CBCBD4B20D1AAFC000B5732 /* AchievementsListTableViewCell.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Stepic/Legacy/Helpers/HTMLProcessor.swift b/Stepic/Legacy/Helpers/HTMLProcessor.swift index 89cd1d25c7..65103d2550 100644 --- a/Stepic/Legacy/Helpers/HTMLProcessor.swift +++ b/Stepic/Legacy/Helpers/HTMLProcessor.swift @@ -44,7 +44,7 @@ final class HTMLProcessor { case .styles: return Scripts.styles case .kotlinRunnableSamples: - return Scripts.kotlinRunnableSamples + return Scripts.localKotlinPlayground case .audio: return Scripts.audioTagWrapper case .mathJaxCompletion: diff --git a/Stepic/Legacy/Model/Constants/Scripts/Scripts.plist b/Stepic/Legacy/Model/Constants/Scripts/Scripts.plist index af9332a873..1dee724993 100644 --- a/Stepic/Legacy/Model/Constants/Scripts/Scripts.plist +++ b/Stepic/Legacy/Model/Constants/Scripts/Scripts.plist @@ -12,14 +12,14 @@ <link rel="stylesheet" type="text/css" href="stepikcontent.css"> wysiwygCSSWrapper <link rel="stylesheet" type="text/css" href="wysiwyg.css"> - KotlinRunnableSamples - <script src="https://unpkg.com/kotlin-playground@1.10.0/dist/playground.min.js" data-selector="kotlin-runnable"></script> AudioTagWrapperInit <script type="text/javascript">plyr.setup({loadSprite: false})</script> AudioTagWrapper <link rel="stylesheet" href="plyr.css"><script type="text/javascript" src="plyr.js"></script> localJQueryScript - <script type="text/javascript" src="jquery-3.2.1.min.js"></script> + <script type="text/javascript" src="jquery-3.4.1.min.js"></script> + localKotlinPlaygroundScript + <script type="text/javascript" src="kotlin-playground-1.21.1.min.js" data-selector="kotlin-runnable"></script> ClickableImages <script type="text/javascript"> $(document).ready(function() { diff --git a/Stepic/Legacy/Model/Constants/Scripts/Scripts.swift b/Stepic/Legacy/Model/Constants/Scripts/Scripts.swift index 4023c4c733..e16bf0a097 100644 --- a/Stepic/Legacy/Model/Constants/Scripts/Scripts.swift +++ b/Stepic/Legacy/Model/Constants/Scripts/Scripts.swift @@ -16,9 +16,9 @@ struct Scripts { private static let mathJaxFinishedScriptKey = "MathJaxFinishScript" private static let clickableImagesScriptKey = "ClickableImages" private static let localJQueryScriptKey = "localJQueryScript" + private static let localKotlinPlaygroundScript = "localKotlinPlaygroundScript" private static let audioTagWrapperKey = "AudioTagWrapper" private static let audioTagWrapperInitKey = "AudioTagWrapperInit" - private static let kotlinRunnableSamplesKey = "KotlinRunnableSamples" private static let wysiwygStylesKey = "wysiwygCSSWrapper" private static let commonStylesKey = "contentCSSWrapper" private static let textColorScriptKey = "textColorScript" @@ -27,47 +27,47 @@ struct Scripts { private static let fontSizeScriptKey = "FontSizeScript" static var localJQuery: String { - self.loadScriptWithKey(localJQueryScriptKey) + self.loadScriptWithKey(self.localJQueryScriptKey) + } + + static var localKotlinPlayground: String { + self.loadScriptWithKey(self.localKotlinPlaygroundScript) } static var localTex: String { - "\(loadScriptWithKey(localTexScriptKey))\(mathJaxLocalPathScript)" + "\(self.loadScriptWithKey(self.localTexScriptKey))\(self.mathJaxLocalPathScript)" } static var metaViewport: String { - self.loadScriptWithKey(metaViewportKey) + self.loadScriptWithKey(self.metaViewportKey) } static var mathJaxFinished: String { - self.loadScriptWithKey(mathJaxFinishedScriptKey) + self.loadScriptWithKey(self.mathJaxFinishedScriptKey) } static var clickableImages: String { - "\(localJQuery)\(loadScriptWithKey(clickableImagesScriptKey))" + "\(self.localJQuery)\(self.loadScriptWithKey(self.clickableImagesScriptKey))" } static var audioTagWrapper: String { - self.loadScriptWithKey(audioTagWrapperKey) + self.loadScriptWithKey(self.audioTagWrapperKey) } static var audioTagWrapperInit: String { - self.loadScriptWithKey(audioTagWrapperInitKey) - } - - static var kotlinRunnableSamples: String { - self.loadScriptWithKey(kotlinRunnableSamplesKey) + self.loadScriptWithKey(self.audioTagWrapperInitKey) } static var styles: String { - "\(loadScriptWithKey(wysiwygStylesKey))\(loadScriptWithKey(commonStylesKey))" + "\(self.loadScriptWithKey(self.wysiwygStylesKey))\(self.loadScriptWithKey(self.commonStylesKey))" } static var highlightJS: String { - "\(loadScriptWithKey(highlightJSKey))" + "\(self.loadScriptWithKey(self.highlightJSKey))" } static var webkitCalloutDisable: String { - "\(loadScriptWithKey(webkitCalloutDisableKey))" + "\(self.loadScriptWithKey(self.webkitCalloutDisableKey))" } static func textColor(color: UIColor) -> String { diff --git a/Stepic/Sources/Frameworks/ContentProcessor/ContentProcessingInjection.swift b/Stepic/Sources/Frameworks/ContentProcessor/ContentProcessingInjection.swift index 689531691d..01678ac237 100644 --- a/Stepic/Sources/Frameworks/ContentProcessor/ContentProcessingInjection.swift +++ b/Stepic/Sources/Frameworks/ContentProcessor/ContentProcessingInjection.swift @@ -49,7 +49,7 @@ final class MathJaxInjection: ContentProcessingInjection { /// Kotlin runnable code playground final class KotlinRunnableSamplesInjection: ContentProcessingInjection { - var headScript: String { Scripts.kotlinRunnableSamples } + var headScript: String { Scripts.localKotlinPlayground } func shouldInject(to code: String) -> Bool { code.contains(" Guarantee { + private func waitCompleteState() -> Guarantee { Guarantee { seal in - self.webView.evaluateJavaScript("document.readyState;") { _, _ in - seal(()) + func poll(retryCount: Int) { + after( + seconds: Double(retryCount) * Self.pollDocumentReadyStateInterval + ).done { + self.webView.evaluateJavaScript("document.readyState;") { res, error in + if error != nil { + seal(()) + } else if let readyState = res as? String, readyState == "complete" { + seal(()) + } else { + poll(retryCount: retryCount + 1) + } + } + } } + + poll(retryCount: 1) } } @@ -212,8 +227,8 @@ final class ProcessedContentTextView: UIView { } private func fetchHeightWithInterval(_ count: Int = 0) { - let currentTime = TimeInterval(count) * ProcessedContentTextView.reloadTimeStandardInterval - guard currentTime <= ProcessedContentTextView.reloadTimeout else { + let currentTime = TimeInterval(count) * Self.reloadTimeStandardInterval + guard currentTime <= Self.reloadTimeout else { return } @@ -238,8 +253,8 @@ final class ProcessedContentTextView: UIView { } private func fetchWidthWithInterval(_ count: Int = 0) { - let currentTime = TimeInterval(count) * ProcessedContentTextView.reloadTimeStandardInterval - guard currentTime <= ProcessedContentTextView.reloadTimeout else { + let currentTime = TimeInterval(count) * Self.reloadTimeStandardInterval + guard currentTime <= Self.reloadTimeout else { return } @@ -272,7 +287,7 @@ extension ProcessedContentTextView: ProgrammaticallyInitializableViewProtocol { make.leading.equalToSuperview().offset(self.appearance.insets.left) make.trailing.equalToSuperview().offset(-self.appearance.insets.right) make.bottom.equalToSuperview().offset(-self.appearance.insets.bottom) - make.height.equalTo(ProcessedContentTextView.defaultWebViewHeight) + make.height.equalTo(Self.defaultWebViewHeight) } } } @@ -282,7 +297,7 @@ extension ProcessedContentTextView: ProgrammaticallyInitializableViewProtocol { extension ProcessedContentTextView: WKNavigationDelegate { // swiftlint:disable:next implicitly_unwrapped_optional func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { - self.refreshContentHeight().then { + self.waitCompleteState().then { self.getContentHeight() }.done { height in self.webView.snp.updateConstraints { $0.height.equalTo(height) } diff --git a/Stepic/jquery-3.2.1.min.js b/Stepic/jquery-3.2.1.min.js deleted file mode 100644 index 644d35e274..0000000000 --- a/Stepic/jquery-3.2.1.min.js +++ /dev/null @@ -1,4 +0,0 @@ -/*! jQuery v3.2.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.2.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext;function B(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()}var C=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,D=/^.[^:#\[\.,]*$/;function E(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):D.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(E(this,a||[],!1))},not:function(a){return this.pushStack(E(this,a||[],!0))},is:function(a){return!!E(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var F,G=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,H=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||F,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:G.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),C.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};H.prototype=r.fn,F=r(d);var I=/^(?:parents|prev(?:Until|All))/,J={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function K(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return K(a,"nextSibling")},prev:function(a){return K(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return B(a,"iframe")?a.contentDocument:(B(a,"template")&&(a=a.content||a),r.merge([],a.childNodes))}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(J[a]||r.uniqueSort(e),I.test(a)&&e.reverse()),this.pushStack(e)}});var L=/[^\x20\t\r\n\f]+/g;function M(a){var b={};return r.each(a.match(L)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?M(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=e||a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function N(a){return a}function O(a){throw a}function P(a,b,c,d){var e;try{a&&r.isFunction(e=a.promise)?e.call(a).done(b).fail(c):a&&r.isFunction(e=a.then)?e.call(a,b,c):b.apply(void 0,[a].slice(d))}catch(a){c.apply(void 0,[a])}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b=f&&(d!==O&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:N,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:N)),c[2][3].add(g(0,a,r.isFunction(d)?d:O))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(P(a,g.done(h(c)).resolve,g.reject,!b),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)P(e[c],h(c),g.reject);return g.promise()}});var Q=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&Q.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var R=r.Deferred();r.fn.ready=function(a){return R.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||R.resolveWith(d,[r]))}}),r.ready.then=R.then;function S(){d.removeEventListener("DOMContentLoaded",S), -a.removeEventListener("load",S),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",S),a.addEventListener("load",S));var T=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)T(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h1,null,!0)},removeData:function(a){return this.each(function(){X.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=W.get(a,b),c&&(!d||Array.isArray(c)?d=W.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return W.get(a,c)||W.access(a,c,{empty:r.Callbacks("once memory").add(function(){W.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length\x20\t\r\n\f]+)/i,la=/^$|\/(?:java|ecma)script/i,ma={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ma.optgroup=ma.option,ma.tbody=ma.tfoot=ma.colgroup=ma.caption=ma.thead,ma.th=ma.td;function na(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&B(a,b)?r.merge([a],c):c}function oa(a,b){for(var c=0,d=a.length;c-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=na(l.appendChild(f),"script"),j&&oa(g),c){k=0;while(f=g[k++])la.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var ra=d.documentElement,sa=/^key/,ta=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ua=/^([^.]*)(?:\.(.+)|)/;function va(){return!0}function wa(){return!1}function xa(){try{return d.activeElement}catch(a){}}function ya(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ya(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=wa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(ra,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(L)||[""],j=b.length;while(j--)h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.hasData(a)&&W.get(a);if(q&&(i=q.events)){b=(b||"").match(L)||[""],j=b.length;while(j--)if(h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&W.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(W.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i\x20\t\r\n\f]*)[^>]*)\/>/gi,Aa=/\s*$/g;function Ea(a,b){return B(a,"table")&&B(11!==b.nodeType?b:b.firstChild,"tr")?r(">tbody",a)[0]||a:a}function Fa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ga(a){var b=Ca.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ha(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(W.hasData(a)&&(f=W.access(a),g=W.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c1&&"string"==typeof q&&!o.checkClone&&Ba.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ja(f,b,c,d)});if(m&&(e=qa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(na(e,"script"),Fa),i=h.length;l")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=na(h),f=na(a),d=0,e=f.length;d0&&oa(g,!i&&na(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(U(c)){if(b=c[W.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[W.expando]=void 0}c[X.expando]&&(c[X.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ka(this,a,!0)},remove:function(a){return Ka(this,a)},text:function(a){return T(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.appendChild(a)}})},prepend:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(na(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return T(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!Aa.test(a)&&!ma[(ka.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c1)}});function _a(a,b,c,d,e){return new _a.prototype.init(a,b,c,d,e)}r.Tween=_a,_a.prototype={constructor:_a,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=_a.propHooks[this.prop];return a&&a.get?a.get(this):_a.propHooks._default.get(this)},run:function(a){var b,c=_a.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):_a.propHooks._default.set(this),this}},_a.prototype.init.prototype=_a.prototype,_a.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},_a.propHooks.scrollTop=_a.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=_a.prototype.init,r.fx.step={};var ab,bb,cb=/^(?:toggle|show|hide)$/,db=/queueHooks$/;function eb(){bb&&(d.hidden===!1&&a.requestAnimationFrame?a.requestAnimationFrame(eb):a.setTimeout(eb,r.fx.interval),r.fx.tick())}function fb(){return a.setTimeout(function(){ab=void 0}),ab=r.now()}function gb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ca[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function hb(a,b,c){for(var d,e=(kb.tweeners[b]||[]).concat(kb.tweeners["*"]),f=0,g=e.length;f1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?lb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b), -null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&B(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(L);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),lb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=mb[b]||r.find.attr;mb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=mb[g],mb[g]=e,e=null!=c(a,b,d)?g:null,mb[g]=f),e}});var nb=/^(?:input|select|textarea|button)$/i,ob=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return T(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):nb.test(a.nodeName)||ob.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function pb(a){var b=a.match(L)||[];return b.join(" ")}function qb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,qb(this)))});if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,qb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,qb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(L)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=qb(this),b&&W.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":W.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+pb(qb(c))+" ").indexOf(b)>-1)return!0;return!1}});var rb=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":Array.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:pb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(Array.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var sb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!sb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,sb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(W.get(h,"events")||{})[b.type]&&W.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&U(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!U(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=W.access(d,b);e||d.addEventListener(a,c,!0),W.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=W.access(d,b)-1;e?W.access(d,b,e):(d.removeEventListener(a,c,!0),W.remove(d,b))}}});var tb=a.location,ub=r.now(),vb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(Array.isArray(b))r.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(Array.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!ja.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:Array.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}});var Bb=/%20/g,Cb=/#.*$/,Db=/([?&])_=[^&]*/,Eb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Fb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Gb=/^(?:GET|HEAD)$/,Hb=/^\/\//,Ib={},Jb={},Kb="*/".concat("*"),Lb=d.createElement("a");Lb.href=tb.href;function Mb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(L)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nb(a,b,c,d){var e={},f=a===Jb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Ob(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Pb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Qb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:tb.href,type:"GET",isLocal:Fb.test(tb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Ob(Ob(a,r.ajaxSettings),b):Ob(r.ajaxSettings,a)},ajaxPrefilter:Mb(Ib),ajaxTransport:Mb(Jb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Eb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||tb.href)+"").replace(Hb,tb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(L)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Lb.protocol+"//"+Lb.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Nb(Ib,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Gb.test(o.type),f=o.url.replace(Cb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(Bb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(vb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Db,"$1"),n=(vb.test(f)?"&":"?")+"_="+ub++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Kb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Nb(Jb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Pb(o,y,d)),v=Qb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Rb={0:200,1223:204},Sb=r.ajaxSettings.xhr();o.cors=!!Sb&&"withCredentials"in Sb,o.ajax=Sb=!!Sb,r.ajaxTransport(function(b){var c,d;if(o.cors||Sb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Rb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("