Repository: shadowsocks/ShadowsocksX-NG
Branch: develop
Commit: 719203afc60e
Files: 574
Total size: 3.2 MB
Directory structure:
gitextract_rw2t5x3v/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── Bug_report.md
│ │ └── Feature_request.md
│ └── workflows/
│ ├── feature.yml
│ └── release.yml
├── .gitignore
├── .gitmodules
├── LICENSE
├── LaunchHelper/
│ ├── LaunchHelper/
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.m
│ │ ├── Assets.xcassets/
│ │ │ └── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ └── MainMenu.xib
│ │ ├── Info.plist
│ │ └── main.m
│ └── LaunchHelper.xcodeproj/
│ └── project.pbxproj
├── Makefile
├── Podfile
├── Pods/
│ ├── Alamofire/
│ │ ├── LICENSE
│ │ ├── README.md
│ │ └── Source/
│ │ ├── AFError.swift
│ │ ├── Alamofire.swift
│ │ ├── AlamofireExtended.swift
│ │ ├── AuthenticationInterceptor.swift
│ │ ├── CachedResponseHandler.swift
│ │ ├── Combine.swift
│ │ ├── DispatchQueue+Alamofire.swift
│ │ ├── EventMonitor.swift
│ │ ├── HTTPHeaders.swift
│ │ ├── HTTPMethod.swift
│ │ ├── MultipartFormData.swift
│ │ ├── MultipartUpload.swift
│ │ ├── NetworkReachabilityManager.swift
│ │ ├── Notifications.swift
│ │ ├── OperationQueue+Alamofire.swift
│ │ ├── ParameterEncoder.swift
│ │ ├── ParameterEncoding.swift
│ │ ├── Protected.swift
│ │ ├── RedirectHandler.swift
│ │ ├── Request.swift
│ │ ├── RequestInterceptor.swift
│ │ ├── RequestTaskMap.swift
│ │ ├── Response.swift
│ │ ├── ResponseSerialization.swift
│ │ ├── Result+Alamofire.swift
│ │ ├── RetryPolicy.swift
│ │ ├── ServerTrustEvaluation.swift
│ │ ├── Session.swift
│ │ ├── SessionDelegate.swift
│ │ ├── StringEncoding+Alamofire.swift
│ │ ├── URLConvertible+URLRequestConvertible.swift
│ │ ├── URLEncodedFormEncoder.swift
│ │ ├── URLRequest+Alamofire.swift
│ │ ├── URLSessionConfiguration+Alamofire.swift
│ │ └── Validation.swift
│ ├── BRLOptionParser/
│ │ ├── BRLOptionParser/
│ │ │ ├── BRLOptionParser.h
│ │ │ └── BRLOptionParser.m
│ │ ├── LICENSE
│ │ └── README.markdown
│ ├── GCDWebServer/
│ │ ├── GCDWebServer/
│ │ │ ├── Core/
│ │ │ │ ├── GCDWebServer.h
│ │ │ │ ├── GCDWebServer.m
│ │ │ │ ├── GCDWebServerConnection.h
│ │ │ │ ├── GCDWebServerConnection.m
│ │ │ │ ├── GCDWebServerFunctions.h
│ │ │ │ ├── GCDWebServerFunctions.m
│ │ │ │ ├── GCDWebServerHTTPStatusCodes.h
│ │ │ │ ├── GCDWebServerPrivate.h
│ │ │ │ ├── GCDWebServerRequest.h
│ │ │ │ ├── GCDWebServerRequest.m
│ │ │ │ ├── GCDWebServerResponse.h
│ │ │ │ └── GCDWebServerResponse.m
│ │ │ ├── Requests/
│ │ │ │ ├── GCDWebServerDataRequest.h
│ │ │ │ ├── GCDWebServerDataRequest.m
│ │ │ │ ├── GCDWebServerFileRequest.h
│ │ │ │ ├── GCDWebServerFileRequest.m
│ │ │ │ ├── GCDWebServerMultiPartFormRequest.h
│ │ │ │ ├── GCDWebServerMultiPartFormRequest.m
│ │ │ │ ├── GCDWebServerURLEncodedFormRequest.h
│ │ │ │ └── GCDWebServerURLEncodedFormRequest.m
│ │ │ └── Responses/
│ │ │ ├── GCDWebServerDataResponse.h
│ │ │ ├── GCDWebServerDataResponse.m
│ │ │ ├── GCDWebServerErrorResponse.h
│ │ │ ├── GCDWebServerErrorResponse.m
│ │ │ ├── GCDWebServerFileResponse.h
│ │ │ ├── GCDWebServerFileResponse.m
│ │ │ ├── GCDWebServerStreamedResponse.h
│ │ │ └── GCDWebServerStreamedResponse.m
│ │ ├── LICENSE
│ │ └── README.md
│ ├── MASShortcut/
│ │ ├── Framework/
│ │ │ ├── Model/
│ │ │ │ ├── MASKeyCodes.h
│ │ │ │ ├── MASKeyMasks.h
│ │ │ │ ├── MASShortcut.h
│ │ │ │ ├── MASShortcut.m
│ │ │ │ ├── MASShortcutValidator.h
│ │ │ │ └── MASShortcutValidator.m
│ │ │ ├── Monitoring/
│ │ │ │ ├── MASHotKey.h
│ │ │ │ ├── MASHotKey.m
│ │ │ │ ├── MASShortcutMonitor.h
│ │ │ │ └── MASShortcutMonitor.m
│ │ │ ├── Shortcut.h
│ │ │ ├── UI/
│ │ │ │ ├── MASLocalization.h
│ │ │ │ ├── MASLocalization.m
│ │ │ │ ├── MASShortcutView+Bindings.h
│ │ │ │ ├── MASShortcutView+Bindings.m
│ │ │ │ ├── MASShortcutView.h
│ │ │ │ └── MASShortcutView.m
│ │ │ └── User Defaults Storage/
│ │ │ ├── MASDictionaryTransformer.h
│ │ │ ├── MASDictionaryTransformer.m
│ │ │ ├── MASShortcutBinder.h
│ │ │ └── MASShortcutBinder.m
│ │ ├── LICENSE
│ │ ├── README.md
│ │ └── Resources/
│ │ ├── cs.lproj/
│ │ │ └── Localizable.strings
│ │ ├── de.lproj/
│ │ │ └── Localizable.strings
│ │ ├── en.lproj/
│ │ │ └── Localizable.strings
│ │ ├── es.lproj/
│ │ │ └── Localizable.strings
│ │ ├── fr.lproj/
│ │ │ └── Localizable.strings
│ │ ├── it.lproj/
│ │ │ └── Localizable.strings
│ │ ├── ja.lproj/
│ │ │ └── Localizable.strings
│ │ ├── ko.lproj/
│ │ │ └── Localizable.strings
│ │ ├── nl.lproj/
│ │ │ └── Localizable.strings
│ │ ├── pl.lproj/
│ │ │ └── Localizable.strings
│ │ ├── pt.lproj/
│ │ │ └── Localizable.strings
│ │ ├── ru.lproj/
│ │ │ └── Localizable.strings
│ │ ├── sv.lproj/
│ │ │ └── Localizable.strings
│ │ ├── zh-Hans.lproj/
│ │ │ └── Localizable.strings
│ │ └── zh-Hant.lproj/
│ │ └── Localizable.strings
│ ├── Pods.xcodeproj/
│ │ └── project.pbxproj
│ ├── RxCocoa/
│ │ ├── LICENSE.md
│ │ ├── Platform/
│ │ │ ├── DataStructures/
│ │ │ │ ├── Bag.swift
│ │ │ │ ├── InfiniteSequence.swift
│ │ │ │ ├── PriorityQueue.swift
│ │ │ │ └── Queue.swift
│ │ │ ├── DispatchQueue+Extensions.swift
│ │ │ ├── Platform.Darwin.swift
│ │ │ ├── Platform.Linux.swift
│ │ │ └── RecursiveLock.swift
│ │ ├── README.md
│ │ └── RxCocoa/
│ │ ├── Common/
│ │ │ ├── ControlTarget.swift
│ │ │ ├── DelegateProxy.swift
│ │ │ ├── DelegateProxyType.swift
│ │ │ ├── Infallible+Bind.swift
│ │ │ ├── Observable+Bind.swift
│ │ │ ├── RxCocoaObjCRuntimeError+Extensions.swift
│ │ │ ├── RxTarget.swift
│ │ │ ├── SectionedViewDataSourceType.swift
│ │ │ └── TextInput.swift
│ │ ├── Foundation/
│ │ │ ├── KVORepresentable+CoreGraphics.swift
│ │ │ ├── KVORepresentable+Swift.swift
│ │ │ ├── KVORepresentable.swift
│ │ │ ├── NSObject+Rx+KVORepresentable.swift
│ │ │ ├── NSObject+Rx+RawRepresentable.swift
│ │ │ ├── NSObject+Rx.swift
│ │ │ ├── NotificationCenter+Rx.swift
│ │ │ └── URLSession+Rx.swift
│ │ ├── Runtime/
│ │ │ ├── _RX.m
│ │ │ ├── _RXDelegateProxy.m
│ │ │ ├── _RXKVOObserver.m
│ │ │ ├── _RXObjCRuntime.m
│ │ │ └── include/
│ │ │ ├── RxCocoaRuntime.h
│ │ │ ├── _RX.h
│ │ │ ├── _RXDelegateProxy.h
│ │ │ ├── _RXKVOObserver.h
│ │ │ └── _RXObjCRuntime.h
│ │ ├── RxCocoa.h
│ │ ├── RxCocoa.swift
│ │ ├── Traits/
│ │ │ ├── ControlEvent.swift
│ │ │ ├── ControlProperty.swift
│ │ │ ├── Driver/
│ │ │ │ ├── BehaviorRelay+Driver.swift
│ │ │ │ ├── ControlEvent+Driver.swift
│ │ │ │ ├── ControlProperty+Driver.swift
│ │ │ │ ├── Driver+Subscription.swift
│ │ │ │ ├── Driver.swift
│ │ │ │ └── ObservableConvertibleType+Driver.swift
│ │ │ ├── SharedSequence/
│ │ │ │ ├── ObservableConvertibleType+SharedSequence.swift
│ │ │ │ ├── SchedulerType+SharedSequence.swift
│ │ │ │ ├── SharedSequence+Operators+arity.swift
│ │ │ │ ├── SharedSequence+Operators.swift
│ │ │ │ └── SharedSequence.swift
│ │ │ └── Signal/
│ │ │ ├── ControlEvent+Signal.swift
│ │ │ ├── ObservableConvertibleType+Signal.swift
│ │ │ ├── PublishRelay+Signal.swift
│ │ │ ├── Signal+Subscription.swift
│ │ │ └── Signal.swift
│ │ ├── iOS/
│ │ │ ├── DataSources/
│ │ │ │ ├── RxCollectionViewReactiveArrayDataSource.swift
│ │ │ │ ├── RxPickerViewAdapter.swift
│ │ │ │ └── RxTableViewReactiveArrayDataSource.swift
│ │ │ ├── Events/
│ │ │ │ └── ItemEvents.swift
│ │ │ ├── NSTextStorage+Rx.swift
│ │ │ ├── Protocols/
│ │ │ │ ├── RxCollectionViewDataSourceType.swift
│ │ │ │ ├── RxPickerViewDataSourceType.swift
│ │ │ │ └── RxTableViewDataSourceType.swift
│ │ │ ├── Proxies/
│ │ │ │ ├── RxCollectionViewDataSourcePrefetchingProxy.swift
│ │ │ │ ├── RxCollectionViewDataSourceProxy.swift
│ │ │ │ ├── RxCollectionViewDelegateProxy.swift
│ │ │ │ ├── RxNavigationControllerDelegateProxy.swift
│ │ │ │ ├── RxPickerViewDataSourceProxy.swift
│ │ │ │ ├── RxPickerViewDelegateProxy.swift
│ │ │ │ ├── RxScrollViewDelegateProxy.swift
│ │ │ │ ├── RxSearchBarDelegateProxy.swift
│ │ │ │ ├── RxSearchControllerDelegateProxy.swift
│ │ │ │ ├── RxTabBarControllerDelegateProxy.swift
│ │ │ │ ├── RxTabBarDelegateProxy.swift
│ │ │ │ ├── RxTableViewDataSourcePrefetchingProxy.swift
│ │ │ │ ├── RxTableViewDataSourceProxy.swift
│ │ │ │ ├── RxTableViewDelegateProxy.swift
│ │ │ │ ├── RxTextStorageDelegateProxy.swift
│ │ │ │ ├── RxTextViewDelegateProxy.swift
│ │ │ │ └── RxWKNavigationDelegateProxy.swift
│ │ │ ├── UIActivityIndicatorView+Rx.swift
│ │ │ ├── UIApplication+Rx.swift
│ │ │ ├── UIBarButtonItem+Rx.swift
│ │ │ ├── UIButton+Rx.swift
│ │ │ ├── UICollectionView+Rx.swift
│ │ │ ├── UIControl+Rx.swift
│ │ │ ├── UIDatePicker+Rx.swift
│ │ │ ├── UIGestureRecognizer+Rx.swift
│ │ │ ├── UINavigationController+Rx.swift
│ │ │ ├── UIPickerView+Rx.swift
│ │ │ ├── UIRefreshControl+Rx.swift
│ │ │ ├── UIScrollView+Rx.swift
│ │ │ ├── UISearchBar+Rx.swift
│ │ │ ├── UISearchController+Rx.swift
│ │ │ ├── UISegmentedControl+Rx.swift
│ │ │ ├── UISlider+Rx.swift
│ │ │ ├── UIStepper+Rx.swift
│ │ │ ├── UISwitch+Rx.swift
│ │ │ ├── UITabBar+Rx.swift
│ │ │ ├── UITabBarController+Rx.swift
│ │ │ ├── UITableView+Rx.swift
│ │ │ ├── UITextField+Rx.swift
│ │ │ ├── UITextView+Rx.swift
│ │ │ └── WKWebView+Rx.swift
│ │ └── macOS/
│ │ ├── NSButton+Rx.swift
│ │ ├── NSControl+Rx.swift
│ │ ├── NSSlider+Rx.swift
│ │ ├── NSTextField+Rx.swift
│ │ ├── NSTextView+Rx.swift
│ │ └── NSView+Rx.swift
│ ├── RxRelay/
│ │ ├── LICENSE.md
│ │ ├── README.md
│ │ └── RxRelay/
│ │ ├── BehaviorRelay.swift
│ │ ├── Observable+Bind.swift
│ │ ├── PublishRelay.swift
│ │ ├── ReplayRelay.swift
│ │ └── Utils.swift
│ ├── RxSwift/
│ │ ├── LICENSE.md
│ │ ├── Platform/
│ │ │ ├── AtomicInt.swift
│ │ │ ├── DataStructures/
│ │ │ │ ├── Bag.swift
│ │ │ │ ├── InfiniteSequence.swift
│ │ │ │ ├── PriorityQueue.swift
│ │ │ │ └── Queue.swift
│ │ │ ├── DispatchQueue+Extensions.swift
│ │ │ ├── Platform.Darwin.swift
│ │ │ ├── Platform.Linux.swift
│ │ │ └── RecursiveLock.swift
│ │ ├── README.md
│ │ └── RxSwift/
│ │ ├── AnyObserver.swift
│ │ ├── Binder.swift
│ │ ├── Cancelable.swift
│ │ ├── Concurrency/
│ │ │ ├── AsyncLock.swift
│ │ │ ├── Lock.swift
│ │ │ ├── LockOwnerType.swift
│ │ │ ├── SynchronizedDisposeType.swift
│ │ │ ├── SynchronizedOnType.swift
│ │ │ └── SynchronizedUnsubscribeType.swift
│ │ ├── ConnectableObservableType.swift
│ │ ├── Date+Dispatch.swift
│ │ ├── Disposable.swift
│ │ ├── Disposables/
│ │ │ ├── AnonymousDisposable.swift
│ │ │ ├── BinaryDisposable.swift
│ │ │ ├── BooleanDisposable.swift
│ │ │ ├── CompositeDisposable.swift
│ │ │ ├── Disposables.swift
│ │ │ ├── DisposeBag.swift
│ │ │ ├── DisposeBase.swift
│ │ │ ├── NopDisposable.swift
│ │ │ ├── RefCountDisposable.swift
│ │ │ ├── ScheduledDisposable.swift
│ │ │ ├── SerialDisposable.swift
│ │ │ ├── SingleAssignmentDisposable.swift
│ │ │ └── SubscriptionDisposable.swift
│ │ ├── Errors.swift
│ │ ├── Event.swift
│ │ ├── Extensions/
│ │ │ └── Bag+Rx.swift
│ │ ├── GroupedObservable.swift
│ │ ├── ImmediateSchedulerType.swift
│ │ ├── Observable.swift
│ │ ├── ObservableConvertibleType.swift
│ │ ├── ObservableType+Extensions.swift
│ │ ├── ObservableType.swift
│ │ ├── Observables/
│ │ │ ├── AddRef.swift
│ │ │ ├── Amb.swift
│ │ │ ├── AsMaybe.swift
│ │ │ ├── AsSingle.swift
│ │ │ ├── Buffer.swift
│ │ │ ├── Catch.swift
│ │ │ ├── CombineLatest+Collection.swift
│ │ │ ├── CombineLatest+arity.swift
│ │ │ ├── CombineLatest.swift
│ │ │ ├── CompactMap.swift
│ │ │ ├── Concat.swift
│ │ │ ├── Create.swift
│ │ │ ├── Debounce.swift
│ │ │ ├── Debug.swift
│ │ │ ├── Decode.swift
│ │ │ ├── DefaultIfEmpty.swift
│ │ │ ├── Deferred.swift
│ │ │ ├── Delay.swift
│ │ │ ├── DelaySubscription.swift
│ │ │ ├── Dematerialize.swift
│ │ │ ├── DistinctUntilChanged.swift
│ │ │ ├── Do.swift
│ │ │ ├── ElementAt.swift
│ │ │ ├── Empty.swift
│ │ │ ├── Enumerated.swift
│ │ │ ├── Error.swift
│ │ │ ├── Filter.swift
│ │ │ ├── First.swift
│ │ │ ├── Generate.swift
│ │ │ ├── GroupBy.swift
│ │ │ ├── Just.swift
│ │ │ ├── Map.swift
│ │ │ ├── Materialize.swift
│ │ │ ├── Merge.swift
│ │ │ ├── Multicast.swift
│ │ │ ├── Never.swift
│ │ │ ├── ObserveOn.swift
│ │ │ ├── Optional.swift
│ │ │ ├── Producer.swift
│ │ │ ├── Range.swift
│ │ │ ├── Reduce.swift
│ │ │ ├── Repeat.swift
│ │ │ ├── RetryWhen.swift
│ │ │ ├── Sample.swift
│ │ │ ├── Scan.swift
│ │ │ ├── Sequence.swift
│ │ │ ├── ShareReplayScope.swift
│ │ │ ├── SingleAsync.swift
│ │ │ ├── Sink.swift
│ │ │ ├── Skip.swift
│ │ │ ├── SkipUntil.swift
│ │ │ ├── SkipWhile.swift
│ │ │ ├── StartWith.swift
│ │ │ ├── SubscribeOn.swift
│ │ │ ├── Switch.swift
│ │ │ ├── SwitchIfEmpty.swift
│ │ │ ├── Take.swift
│ │ │ ├── TakeLast.swift
│ │ │ ├── TakeWithPredicate.swift
│ │ │ ├── Throttle.swift
│ │ │ ├── Timeout.swift
│ │ │ ├── Timer.swift
│ │ │ ├── ToArray.swift
│ │ │ ├── Using.swift
│ │ │ ├── Window.swift
│ │ │ ├── WithLatestFrom.swift
│ │ │ ├── WithUnretained.swift
│ │ │ ├── Zip+Collection.swift
│ │ │ ├── Zip+arity.swift
│ │ │ └── Zip.swift
│ │ ├── ObserverType.swift
│ │ ├── Observers/
│ │ │ ├── AnonymousObserver.swift
│ │ │ ├── ObserverBase.swift
│ │ │ └── TailRecursiveSink.swift
│ │ ├── Reactive.swift
│ │ ├── Rx.swift
│ │ ├── RxMutableBox.swift
│ │ ├── SchedulerType.swift
│ │ ├── Schedulers/
│ │ │ ├── ConcurrentDispatchQueueScheduler.swift
│ │ │ ├── ConcurrentMainScheduler.swift
│ │ │ ├── CurrentThreadScheduler.swift
│ │ │ ├── HistoricalScheduler.swift
│ │ │ ├── HistoricalSchedulerTimeConverter.swift
│ │ │ ├── Internal/
│ │ │ │ ├── DispatchQueueConfiguration.swift
│ │ │ │ ├── InvocableScheduledItem.swift
│ │ │ │ ├── InvocableType.swift
│ │ │ │ ├── ScheduledItem.swift
│ │ │ │ └── ScheduledItemType.swift
│ │ │ ├── MainScheduler.swift
│ │ │ ├── OperationQueueScheduler.swift
│ │ │ ├── RecursiveScheduler.swift
│ │ │ ├── SchedulerServices+Emulation.swift
│ │ │ ├── SerialDispatchQueueScheduler.swift
│ │ │ ├── VirtualTimeConverterType.swift
│ │ │ └── VirtualTimeScheduler.swift
│ │ ├── Subjects/
│ │ │ ├── AsyncSubject.swift
│ │ │ ├── BehaviorSubject.swift
│ │ │ ├── PublishSubject.swift
│ │ │ ├── ReplaySubject.swift
│ │ │ └── SubjectType.swift
│ │ ├── SwiftSupport/
│ │ │ └── SwiftSupport.swift
│ │ └── Traits/
│ │ ├── Infallible/
│ │ │ ├── Infallible+CombineLatest+arity.swift
│ │ │ ├── Infallible+Create.swift
│ │ │ ├── Infallible+Operators.swift
│ │ │ ├── Infallible+Zip+arity.swift
│ │ │ ├── Infallible.swift
│ │ │ └── ObservableConvertibleType+Infallible.swift
│ │ └── PrimitiveSequence/
│ │ ├── Completable+AndThen.swift
│ │ ├── Completable.swift
│ │ ├── Maybe.swift
│ │ ├── ObservableType+PrimitiveSequence.swift
│ │ ├── PrimitiveSequence+Zip+arity.swift
│ │ ├── PrimitiveSequence.swift
│ │ └── Single.swift
│ └── Target Support Files/
│ ├── Alamofire/
│ │ ├── Alamofire-Info.plist
│ │ ├── Alamofire-dummy.m
│ │ ├── Alamofire-prefix.pch
│ │ ├── Alamofire-umbrella.h
│ │ ├── Alamofire.debug.xcconfig
│ │ ├── Alamofire.modulemap
│ │ ├── Alamofire.release.xcconfig
│ │ ├── Alamofire.xcconfig
│ │ └── Info.plist
│ ├── BRLOptionParser/
│ │ ├── BRLOptionParser-dummy.m
│ │ ├── BRLOptionParser-prefix.pch
│ │ ├── BRLOptionParser.debug.xcconfig
│ │ ├── BRLOptionParser.release.xcconfig
│ │ └── BRLOptionParser.xcconfig
│ ├── GCDWebServer/
│ │ ├── GCDWebServer-Info.plist
│ │ ├── GCDWebServer-dummy.m
│ │ ├── GCDWebServer-prefix.pch
│ │ ├── GCDWebServer-umbrella.h
│ │ ├── GCDWebServer.debug.xcconfig
│ │ ├── GCDWebServer.modulemap
│ │ ├── GCDWebServer.release.xcconfig
│ │ ├── GCDWebServer.xcconfig
│ │ └── Info.plist
│ ├── MASShortcut/
│ │ ├── Info.plist
│ │ ├── MASShortcut-Info.plist
│ │ ├── MASShortcut-dummy.m
│ │ ├── MASShortcut-prefix.pch
│ │ ├── MASShortcut-umbrella.h
│ │ ├── MASShortcut.debug.xcconfig
│ │ ├── MASShortcut.modulemap
│ │ ├── MASShortcut.release.xcconfig
│ │ ├── MASShortcut.xcconfig
│ │ ├── ResourceBundle-MASShortcut-Info.plist
│ │ └── ResourceBundle-MASShortcut-MASShortcut-Info.plist
│ ├── Pods-ShadowsocksX-NG/
│ │ ├── Info.plist
│ │ ├── Pods-ShadowsocksX-NG-Info.plist
│ │ ├── Pods-ShadowsocksX-NG-acknowledgements.markdown
│ │ ├── Pods-ShadowsocksX-NG-acknowledgements.plist
│ │ ├── Pods-ShadowsocksX-NG-dummy.m
│ │ ├── Pods-ShadowsocksX-NG-frameworks.sh
│ │ ├── Pods-ShadowsocksX-NG-resources.sh
│ │ ├── Pods-ShadowsocksX-NG-umbrella.h
│ │ ├── Pods-ShadowsocksX-NG.debug.xcconfig
│ │ ├── Pods-ShadowsocksX-NG.modulemap
│ │ └── Pods-ShadowsocksX-NG.release.xcconfig
│ ├── Pods-ShadowsocksX-NGTests/
│ │ ├── Info.plist
│ │ ├── Pods-ShadowsocksX-NGTests-Info.plist
│ │ ├── Pods-ShadowsocksX-NGTests-acknowledgements.markdown
│ │ ├── Pods-ShadowsocksX-NGTests-acknowledgements.plist
│ │ ├── Pods-ShadowsocksX-NGTests-dummy.m
│ │ ├── Pods-ShadowsocksX-NGTests-frameworks.sh
│ │ ├── Pods-ShadowsocksX-NGTests-resources.sh
│ │ ├── Pods-ShadowsocksX-NGTests-umbrella.h
│ │ ├── Pods-ShadowsocksX-NGTests.debug.xcconfig
│ │ ├── Pods-ShadowsocksX-NGTests.modulemap
│ │ └── Pods-ShadowsocksX-NGTests.release.xcconfig
│ ├── Pods-proxy_conf_helper/
│ │ ├── Pods-proxy_conf_helper-acknowledgements.markdown
│ │ ├── Pods-proxy_conf_helper-acknowledgements.plist
│ │ ├── Pods-proxy_conf_helper-dummy.m
│ │ ├── Pods-proxy_conf_helper-frameworks.sh
│ │ ├── Pods-proxy_conf_helper-resources.sh
│ │ ├── Pods-proxy_conf_helper.debug.xcconfig
│ │ └── Pods-proxy_conf_helper.release.xcconfig
│ ├── RxCocoa/
│ │ ├── Info.plist
│ │ ├── RxCocoa-Info.plist
│ │ ├── RxCocoa-dummy.m
│ │ ├── RxCocoa-prefix.pch
│ │ ├── RxCocoa-umbrella.h
│ │ ├── RxCocoa.debug.xcconfig
│ │ ├── RxCocoa.modulemap
│ │ ├── RxCocoa.release.xcconfig
│ │ └── RxCocoa.xcconfig
│ ├── RxRelay/
│ │ ├── RxRelay-Info.plist
│ │ ├── RxRelay-dummy.m
│ │ ├── RxRelay-prefix.pch
│ │ ├── RxRelay-umbrella.h
│ │ ├── RxRelay.debug.xcconfig
│ │ ├── RxRelay.modulemap
│ │ └── RxRelay.release.xcconfig
│ └── RxSwift/
│ ├── Info.plist
│ ├── RxSwift-Info.plist
│ ├── RxSwift-dummy.m
│ ├── RxSwift-prefix.pch
│ ├── RxSwift-umbrella.h
│ ├── RxSwift.debug.xcconfig
│ ├── RxSwift.modulemap
│ ├── RxSwift.release.xcconfig
│ └── RxSwift.xcconfig
├── README.md
├── ShadowsocksX-NG/
│ ├── AppDelegate.swift
│ ├── Assets.xcassets/
│ │ ├── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ └── Contents.json
│ ├── Base.lproj/
│ │ ├── ImportWindowController.xib
│ │ ├── Localizable.strings
│ │ ├── MainMenu.xib
│ │ ├── PreferencesWinController.xib
│ │ ├── PreferencesWindowController.xib
│ │ ├── ShareServerProfilesWindowController.xib
│ │ └── UserRulesController.xib
│ ├── Credits.rtf
│ ├── Diagnose.swift
│ ├── ImportWindowController.swift
│ ├── Info.plist
│ ├── LaunchAgentUtils.swift
│ ├── LaunchAtLoginController.h
│ ├── LaunchAtLoginController.m
│ ├── Notifications.swift
│ ├── PACURLFormatter.swift
│ ├── PACUtils.swift
│ ├── PreferencesWinController.swift
│ ├── PreferencesWindowController.swift
│ ├── ProxyConfHelper.h
│ ├── ProxyConfHelper.m
│ ├── ProxyConfTool.h
│ ├── ProxyConfTool.m
│ ├── ProxyInterfacesViewCtrl.swift
│ ├── SWBApplication.h
│ ├── SWBApplication.m
│ ├── SWBQRCodeWindowController.h
│ ├── SWBQRCodeWindowController.m
│ ├── SWBQRCodeWindowController.xib
│ ├── ServerProfile.swift
│ ├── ServerProfileManager.swift
│ ├── ShadowsocksX-NG-Bridging-Header.h
│ ├── ShareServerProfilesWindowController.swift
│ ├── ShortcutsController.h
│ ├── ShortcutsController.m
│ ├── ToastWindowController.swift
│ ├── ToastWindowController.xib
│ ├── UserRulesController.swift
│ ├── Utils.h
│ ├── Utils.m
│ ├── Utils.swift
│ ├── abp.js
│ ├── fix_dir_owner.sh
│ ├── gfwlist.txt
│ ├── install_helper.sh
│ ├── kcptun/
│ │ ├── install_kcptun.sh
│ │ └── kcptun.sh
│ ├── privoxy/
│ │ ├── install_privoxy.sh
│ │ ├── privoxy.template.config
│ │ ├── start_privoxy.sh
│ │ ├── stop_privoxy.sh
│ │ └── user-privoxy.config
│ ├── proxy_conf_helper_version.h
│ ├── simple-obfs/
│ │ └── install_simple_obfs.sh
│ ├── ss-local/
│ │ ├── install_ss_local.sh
│ │ ├── start_ss_local.sh
│ │ └── stop_ss_local.sh
│ ├── user-rule.txt
│ ├── v2ray-plugin/
│ │ └── install_v2ray_plugin.sh
│ └── zh-Hans.lproj/
│ ├── ImportWindowController.strings
│ ├── Localizable.strings
│ ├── MainMenu.strings
│ ├── PreferencesWinController.strings
│ ├── PreferencesWindowController.strings
│ ├── ShareServerProfilesWindowController.strings
│ └── UserRulesController.strings
├── ShadowsocksX-NG.xcodeproj/
│ ├── project.pbxproj
│ └── xcshareddata/
│ └── xcschemes/
│ ├── ShadowsocksX-NG.xcscheme
│ ├── ShadowsocksX-NGTests.xcscheme
│ └── proxy_conf_helper.xcscheme
├── ShadowsocksX-NG.xcworkspace/
│ └── xcshareddata/
│ └── WorkspaceSettings.xcsettings
├── ShadowsocksX-NGTests/
│ ├── Info.plist
│ ├── ServerProfileTests.swift
│ └── ShadowsocksX_NGTests.swift
├── _config.yml
├── deps/
│ ├── Makefile
│ └── patch/
│ └── privoxy/
│ └── configure.in.patch
├── genstrings.py
└── proxy_conf_helper/
└── main.m
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/Bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**System and Shadowsocksx-NG version: (please complete the following information):**
- OS Version: [e.g. 10.13.1]
- Version [e.g. 22]
**Diagnoisis file:**
Please first upgrade to the latest version.
Then export the diagnosis file and upload it to here.
**ss-local.log**
Please upload the ss-local.log file here the file is in `~/Library/Logs`
1) Open 'Advanced Settings -> enable Verbose Mode'
2) Continue run `Shadowsocksx-NG` for 5 minutes
3) Upload the `~/Library/Logs/ss-local.log` here (with or without compress)
**Application log**
Open the `Console.app` and search `Shadowsocksx-NG`
Copy paste the log here
**Crash Log**
If the app crashes and pop up a crash log, please copy and paste here
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/Feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/workflows/feature.yml
================================================
name: Feature Building
on:
push:
branches:
- '*'
pull_request:
branches:
- '*'
jobs:
build:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: recursive
fetch-depth: 0
- name: Build
run: |
brew install automake
brew install autoconf
brew install libtool
make VERSION="${GITHUB_SHA::7}" debug
make debug-dmg
shasum -a 256 build/Debug/ShadowsocksX-NG.dmg > build/Debug/ShadowsocksX-NG.dmg.checksum
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: ShadowsocksX-NG
path: |
build/Debug/ShadowsocksX-NG.dmg
build/Debug/ShadowsocksX-NG.dmg.checksum
================================================
FILE: .github/workflows/release.yml
================================================
name: Release Building
on:
push:
tags:
- '*'
jobs:
build:
runs-on: macos-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
submodules: recursive
fetch-depth: 0
- name: Build
run: |
brew install automake
brew install autoconf
brew install libtool
make VERSION="${GITHUB_REF_NAME}" release
make release-dmg
shasum -a 256 build/Release/ShadowsocksX-NG.dmg > build/Release/ShadowsocksX-NG.dmg.checksum
- name: Upload artifacts
uses: actions/upload-artifact@v3
with:
name: ShadowsocksX-NG
path: |
build/Release/ShadowsocksX-NG.dmg
build/Release/ShadowsocksX-NG.dmg.checksum
- name: Release
uses: softprops/action-gh-release@v1
with:
generate_release_notes: true
files: |
build/Release/ShadowsocksX-NG.dmg
build/Release/ShadowsocksX-NG.dmg.checksum
================================================
FILE: .gitignore
================================================
#####
# OS X temporary files that should never be committed
.DS_Store
*.swp
*.lock
profile
####
# Xcode temporary files that should never be committed
*~.nib
####
# Objective-C/Swift specific
*.hmap
*.ipa
####
# Xcode build files
DerivedData/
build/
Builds/
#####
# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)
*.pbxuser
*.mode1v3
*.mode2v3
*.perspectivev3
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
####
# Xcode 4
xcuserdata
!xcschemes
# Xcode 4
*.moved-aside
####
# XCode 4 workspaces - more detailed
!xcshareddata
!default.xcworkspace
*.xcworkspacedata
####
# Xcode 5
*.xccheckout
*.xcuserstate
####
# Xcode 7
*.xcscmblueprint
####
# AppCode
.idea/
####
# Other Xcode files
profile
*.hmap
*.ipa
####
# Carthage
Carthage/Build
IDEWorkspaceChecks.plist
####
# Dependencies
deps/dist
deps/pcre*
deps/libev*
deps/privoxy*
ShadowsocksX-NG/kcptun/client
ShadowsocksX-NG/privoxy/privoxy
ShadowsocksX-NG/simple-obfs/obfs-local
ShadowsocksX-NG/ss-local/ss-local
ShadowsocksX-NG/v2ray-plugin/v2ray-plugin
================================================
FILE: .gitmodules
================================================
[submodule "shadowsocks-libev"]
path = deps/shadowsocks-libev
url = https://github.com/shadowsocks/shadowsocks-libev
[submodule "libsodium"]
path = deps/libsodium
url = https://github.com/jedisct1/libsodium
[submodule "mbedtls"]
path = deps/mbedtls
url = https://github.com/Mbed-TLS/mbedtls
[submodule "c-ares"]
path = deps/c-ares
url = https://github.com/c-ares/c-ares
[submodule "deps/shadowsocks-libev"]
path = deps/shadowsocks-libev
url = https://github.com/shadowsocks/shadowsocks-libev
[submodule "deps/libsodium"]
path = deps/libsodium
url = https://github.com/jedisct1/libsodium
[submodule "deps/mbedtls"]
path = deps/mbedtls
url = https://github.com/Mbed-TLS/mbedtls
[submodule "deps/c-ares"]
path = deps/c-ares
url = https://github.com/c-ares/c-ares
[submodule "deps/v2ray-plugin"]
path = deps/v2ray-plugin
url = https://github.com/shadowsocks/v2ray-plugin
[submodule "deps/kcptun"]
path = deps/kcptun
url = https://github.com/xtaci/kcptun
[submodule "deps/simple-obfs"]
path = deps/simple-obfs
url = https://github.com/shadowsocks/simple-obfs
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: LaunchHelper/LaunchHelper/AppDelegate.h
================================================
//
// AppDelegate.h
// LaunchHelper
//
// Created by 邱宇舟 on 2017/3/28.
// Copyright © 2017年 qiuyuzhou. All rights reserved.
//
#import
@interface AppDelegate : NSObject
@end
================================================
FILE: LaunchHelper/LaunchHelper/AppDelegate.m
================================================
//
// AppDelegate.m
// LaunchHelper
//
// Created by 邱宇舟 on 2017/3/28.
// Copyright © 2017年 qiuyuzhou. All rights reserved.
//
#import "AppDelegate.h"
@interface AppDelegate ()
@property (weak) IBOutlet NSWindow *window;
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
NSLog(@"ShadowsocksX-NG LaunchHelper");
NSWorkspace* ws = [NSWorkspace sharedWorkspace];
BOOL bLaunched = NO;
bLaunched = [ws launchApplication: @"/Applications/ShadowsocksX-NG.app"];
if (!bLaunched) {
bLaunched = [ws launchApplication: @"ShadowsocksX-NG.app"];
}
if (!bLaunched) {
NSArray *pathComponents = [[[NSBundle mainBundle] bundlePath] pathComponents];
pathComponents = [pathComponents subarrayWithRange:NSMakeRange(0, [pathComponents count] - 4)];
NSString *path = [NSString pathWithComponents:pathComponents];
[[NSWorkspace sharedWorkspace] launchApplication:path];
}
[NSApp terminate:nil];
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
@end
================================================
FILE: LaunchHelper/LaunchHelper/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"images" : [
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "16x16",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "32x32",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "128x128",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "256x256",
"scale" : "2x"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "1x"
},
{
"idiom" : "mac",
"size" : "512x512",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
================================================
FILE: LaunchHelper/LaunchHelper/Base.lproj/MainMenu.xib
================================================
================================================
FILE: LaunchHelper/LaunchHelper/Info.plist
================================================
CFBundleDevelopmentRegion
en
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIconFile
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
$(PRODUCT_NAME)
CFBundlePackageType
APPL
CFBundleShortVersionString
1.0
CFBundleVersion
2
LSBackgroundOnly
LSMinimumSystemVersion
$(MACOSX_DEPLOYMENT_TARGET)
NSHumanReadableCopyright
Copyright © 2017年 qiuyuzhou. All rights reserved.
NSMainNibFile
MainMenu
NSPrincipalClass
NSApplication
================================================
FILE: LaunchHelper/LaunchHelper/main.m
================================================
//
// main.m
// LaunchHelper
//
// Created by 邱宇舟 on 2017/3/28.
// Copyright © 2017年 qiuyuzhou. All rights reserved.
//
#import
int main(int argc, const char * argv[]) {
return NSApplicationMain(argc, argv);
}
================================================
FILE: LaunchHelper/LaunchHelper.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
9B9F13921E8A282C00DE4794 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B9F13911E8A282C00DE4794 /* AppDelegate.m */; };
9B9F13951E8A282C00DE4794 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 9B9F13941E8A282C00DE4794 /* main.m */; };
9B9F13971E8A282C00DE4794 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 9B9F13961E8A282C00DE4794 /* Assets.xcassets */; };
9B9F139A1E8A282C00DE4794 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 9B9F13981E8A282C00DE4794 /* MainMenu.xib */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
9B9F138D1E8A282C00DE4794 /* LaunchHelper.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LaunchHelper.app; sourceTree = BUILT_PRODUCTS_DIR; };
9B9F13901E8A282C00DE4794 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; };
9B9F13911E8A282C00DE4794 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; };
9B9F13941E8A282C00DE4794 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; };
9B9F13961E8A282C00DE4794 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
9B9F13991E8A282C00DE4794 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; };
9B9F139B1E8A282C00DE4794 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
9B9F138A1E8A282C00DE4794 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
9B9F13841E8A282C00DE4794 = {
isa = PBXGroup;
children = (
9B9F138F1E8A282C00DE4794 /* LaunchHelper */,
9B9F138E1E8A282C00DE4794 /* Products */,
);
sourceTree = "";
};
9B9F138E1E8A282C00DE4794 /* Products */ = {
isa = PBXGroup;
children = (
9B9F138D1E8A282C00DE4794 /* LaunchHelper.app */,
);
name = Products;
sourceTree = "";
};
9B9F138F1E8A282C00DE4794 /* LaunchHelper */ = {
isa = PBXGroup;
children = (
9B9F13901E8A282C00DE4794 /* AppDelegate.h */,
9B9F13911E8A282C00DE4794 /* AppDelegate.m */,
9B9F13961E8A282C00DE4794 /* Assets.xcassets */,
9B9F13981E8A282C00DE4794 /* MainMenu.xib */,
9B9F139B1E8A282C00DE4794 /* Info.plist */,
9B9F13931E8A282C00DE4794 /* Supporting Files */,
);
path = LaunchHelper;
sourceTree = "";
};
9B9F13931E8A282C00DE4794 /* Supporting Files */ = {
isa = PBXGroup;
children = (
9B9F13941E8A282C00DE4794 /* main.m */,
);
name = "Supporting Files";
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
9B9F138C1E8A282C00DE4794 /* LaunchHelper */ = {
isa = PBXNativeTarget;
buildConfigurationList = 9B9F139E1E8A282C00DE4794 /* Build configuration list for PBXNativeTarget "LaunchHelper" */;
buildPhases = (
9B9F13891E8A282C00DE4794 /* Sources */,
9B9F138A1E8A282C00DE4794 /* Frameworks */,
9B9F138B1E8A282C00DE4794 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = LaunchHelper;
productName = LaunchHelper;
productReference = 9B9F138D1E8A282C00DE4794 /* LaunchHelper.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
9B9F13851E8A282C00DE4794 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1250;
ORGANIZATIONNAME = qiuyuzhou;
TargetAttributes = {
9B9F138C1E8A282C00DE4794 = {
CreatedOnToolsVersion = 8.2.1;
ProvisioningStyle = Automatic;
};
};
};
buildConfigurationList = 9B9F13881E8A282C00DE4794 /* Build configuration list for PBXProject "LaunchHelper" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
hasScannedForEncodings = 0;
knownRegions = (
English,
en,
Base,
);
mainGroup = 9B9F13841E8A282C00DE4794;
productRefGroup = 9B9F138E1E8A282C00DE4794 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
9B9F138C1E8A282C00DE4794 /* LaunchHelper */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
9B9F138B1E8A282C00DE4794 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
9B9F13971E8A282C00DE4794 /* Assets.xcassets in Resources */,
9B9F139A1E8A282C00DE4794 /* MainMenu.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
9B9F13891E8A282C00DE4794 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
9B9F13951E8A282C00DE4794 /* main.m in Sources */,
9B9F13921E8A282C00DE4794 /* AppDelegate.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
9B9F13981E8A282C00DE4794 /* MainMenu.xib */ = {
isa = PBXVariantGroup;
children = (
9B9F13991E8A282C00DE4794 /* Base */,
);
name = MainMenu.xib;
sourceTree = "";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
9B9F139C1E8A282C00DE4794 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.12;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
};
name = Debug;
};
9B9F139D1E8A282C00DE4794 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 10.12;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
};
name = Release;
};
9B9F139F1E8A282C00DE4794 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "Apple Development";
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = LaunchHelper/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.12;
PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NG.LaunchHelper";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SKIP_INSTALL = YES;
};
name = Debug;
};
9B9F13A01E8A282C00DE4794 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_IDENTITY = "Apple Development";
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "-";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = LaunchHelper/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 10.12;
PRODUCT_BUNDLE_IDENTIFIER = "com.qiuyuzhou.ShadowsocksX-NG.LaunchHelper";
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
SKIP_INSTALL = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
9B9F13881E8A282C00DE4794 /* Build configuration list for PBXProject "LaunchHelper" */ = {
isa = XCConfigurationList;
buildConfigurations = (
9B9F139C1E8A282C00DE4794 /* Debug */,
9B9F139D1E8A282C00DE4794 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
9B9F139E1E8A282C00DE4794 /* Build configuration list for PBXNativeTarget "LaunchHelper" */ = {
isa = XCConfigurationList;
buildConfigurations = (
9B9F139F1E8A282C00DE4794 /* Debug */,
9B9F13A01E8A282C00DE4794 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 9B9F13851E8A282C00DE4794 /* Project object */;
}
================================================
FILE: Makefile
================================================
VERSION ?= 0.0.0
.PHONY: all
all: debug
.PHONY: debug
debug: deps/dist set-version
xcodebuild -workspace ShadowsocksX-NG.xcworkspace -scheme ShadowsocksX-NG -configuration Debug SYMROOT=$${PWD}/build
.PHONY: release
release: deps/dist set-version
xcodebuild -workspace ShadowsocksX-NG.xcworkspace -scheme ShadowsocksX-NG -configuration Release SYMROOT=$${PWD}/build
.PHONY: debug-dmg release-dmg
debug-dmg release-dmg: TARGET = $(subst -dmg,,$@)
debug-dmg release-dmg:
t="$(TARGET)" && t="`tr '[:lower:]' '[:upper:]' <<< $${t:0:1}`$${t:1}" \
&& rm -rf build/$${t}/ShadowsocksX-NG/ \
&& mkdir build/$${t}/ShadowsocksX-NG \
&& cp -r build/$${t}/ShadowsocksX-NG.app build/$${t}/ShadowsocksX-NG/ \
&& ln -s /Applications build/$${t}/ShadowsocksX-NG/Applications \
&& hdiutil create build/$${t}/ShadowsocksX-NG.dmg -ov -volname "ShadowsocksX-NG" -fs HFS+ -srcfolder build/$${t}/ShadowsocksX-NG/ \
&& rm -rf build/$${t}/ShadowsocksX-NG/
.PHONY: set-version
set-version:
agvtool new-marketing-version $(VERSION)
deps/dist:
$(MAKE) -C deps
.PHONY: clean
clean:
$(MAKE) -C deps clean
================================================
FILE: Podfile
================================================
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
platform :macos, '10.12'
target 'ShadowsocksX-NG' do
# Comment this line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for ShadowsocksX-NG
pod 'Alamofire', '~> 5.4.3'
pod "GCDWebServer", "~> 3.0"
pod 'MASShortcut', '~> 2'
# https://github.com/ReactiveX/RxSwift/blob/master/Documentation/GettingStarted.md
pod 'RxSwift', '~> 6.2.0'
pod 'RxCocoa', '~> 6.2.0'
target 'ShadowsocksX-NGTests' do
inherit! :search_paths
# Pods for testing
end
end
target 'proxy_conf_helper' do
pod 'BRLOptionParser', '~> 0.3.1'
end
================================================
FILE: Pods/Alamofire/LICENSE
================================================
Copyright (c) 2014-2021 Alamofire Software Foundation (http://alamofire.org/)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: Pods/Alamofire/README.md
================================================

[](https://github.com/Alamofire/Alamofire/actions)
[](https://img.shields.io/cocoapods/v/Alamofire.svg)
[](https://github.com/Carthage/Carthage)
[](https://alamofire.github.io/Alamofire)
[](https://twitter.com/AlamofireSF)
[](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[](https://www.codetriage.com/alamofire/alamofire)
Alamofire is an HTTP networking library written in Swift.
- [Features](#features)
- [Component Libraries](#component-libraries)
- [Requirements](#requirements)
- [Migration Guides](#migration-guides)
- [Communication](#communication)
- [Installation](#installation)
- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#using-alamofire)
- [**Introduction -**](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#introduction) [Making Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-requests), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching)
- **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameters and Parameter Encoder](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md##request-parameters-and-parameter-encoders), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication)
- **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server)
- **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output)
- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md)
- **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#sessiondelegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request)
- **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests-with-requestinterceptor)
- **Model Objects -** [Custom Response Handlers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#customizing-response-handlers)
- **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability)
- [Open Radars](#open-radars)
- [FAQ](#faq)
- [Credits](#credits)
- [Donations](#donations)
- [License](#license)
## Features
- [x] Chainable Request / Response Methods
- [x] Combine Support
- [x] URL / JSON Parameter Encoding
- [x] Upload File / Data / Stream / MultipartFormData
- [x] Download File using Request or Resume Data
- [x] Authentication with `URLCredential`
- [x] HTTP Response Validation
- [x] Upload and Download Progress Closures with Progress
- [x] cURL Command Output
- [x] Dynamically Adapt and Retry Requests
- [x] TLS Certificate and Public Key Pinning
- [x] Network Reachability
- [x] Comprehensive Unit and Integration Test Coverage
- [x] [Complete Documentation](https://alamofire.github.io/Alamofire)
## Component Libraries
In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem.
- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system.
- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire.
## Requirements
- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
- Xcode 11+
- Swift 5.1+
## Migration Guides
- [Alamofire 5.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%205.0%20Migration%20Guide.md)
- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md)
- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md)
- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md)
## Communication
- If you **need help with making network requests** using Alamofire, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`.
- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built.
- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire).
- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire).
- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire).
- If you **found a bug**, open an issue here on GitHub and follow the guide. The more detail the better!
- If you **want to contribute**, submit a pull request!
## Installation
### CocoaPods
[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`:
```ruby
pod 'Alamofire', '~> 5.2'
```
### Carthage
[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`:
```ogdl
github "Alamofire/Alamofire" ~> 5.2
```
### Swift Package Manager
The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms.
Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`.
```swift
dependencies: [
.package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.2.0"))
]
```
### Manually
If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually.
#### Embedded Framework
- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:
```bash
$ git init
```
- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command:
```bash
$ git submodule add https://github.com/Alamofire/Alamofire.git
```
- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project.
> It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.
- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target.
- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
- In the tab bar at the top of that window, open the "General" panel.
- Click on the `+` button under the "Embedded Binaries" section.
- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder.
> It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`.
- Select the top `Alamofire.framework` for iOS and the bottom one for macOS.
> You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS`, or `Alamofire watchOS`.
- And that's it!
> The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.
## Open Radars
The following radars have some effect on the current implementation of Alamofire.
- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in the test case
- `rdar://26870455` - Background URL Session Configurations do not work in the simulator
- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest`
- `FB7624529` - `urlSession(_:task:didFinishCollecting:)` never called on watchOS
## Resolved Radars
The following radars have been resolved over time after being filed against the Alamofire project.
- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage.
- (Resolved): 9/1/17 in Xcode 9 beta 6.
- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+
- (Resolved): Just add `CFNetwork` to your linked frameworks.
## Workarounds
- Collection of `URLSessionTaskMetrics` is currently disabled on watchOS due to `FB7624529`.
## FAQ
### What's the origin of the name Alamofire?
Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas.
## Credits
Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases.
### Security Disclosure
If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
## Donations
The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization.
Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free.
Donating to the ASF will enable us to:
- Pay our yearly legal fees to keep the non-profit in good status
- Pay for our mail servers to help us stay on top of all questions and security issues
- Potentially fund test servers to make it easier for us to test the edge cases
- Potentially fund developers to work on one of our projects full-time
The community adoption of the ASF libraries has been amazing.
We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward.
With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members.
If you use any of our libraries for work, see if your employers would be interested in donating.
Any amount you can donate today to help us reach our goal would be greatly appreciated.
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ)
## License
Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details.
================================================
FILE: Pods/Alamofire/Source/AFError.swift
================================================
//
// AFError.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with
/// their own associated reasons.
public enum AFError: Error {
/// The underlying reason the `.multipartEncodingFailed` error occurred.
public enum MultipartEncodingFailureReason {
/// The `fileURL` provided for reading an encodable body part isn't a file `URL`.
case bodyPartURLInvalid(url: URL)
/// The filename of the `fileURL` provided has either an empty `lastPathComponent` or `pathExtension.
case bodyPartFilenameInvalid(in: URL)
/// The file at the `fileURL` provided was not reachable.
case bodyPartFileNotReachable(at: URL)
/// Attempting to check the reachability of the `fileURL` provided threw an error.
case bodyPartFileNotReachableWithError(atURL: URL, error: Error)
/// The file at the `fileURL` provided is actually a directory.
case bodyPartFileIsDirectory(at: URL)
/// The size of the file at the `fileURL` provided was not returned by the system.
case bodyPartFileSizeNotAvailable(at: URL)
/// The attempt to find the size of the file at the `fileURL` provided threw an error.
case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error)
/// An `InputStream` could not be created for the provided `fileURL`.
case bodyPartInputStreamCreationFailed(for: URL)
/// An `OutputStream` could not be created when attempting to write the encoded data to disk.
case outputStreamCreationFailed(for: URL)
/// The encoded body data could not be written to disk because a file already exists at the provided `fileURL`.
case outputStreamFileAlreadyExists(at: URL)
/// The `fileURL` provided for writing the encoded body data to disk is not a file `URL`.
case outputStreamURLInvalid(url: URL)
/// The attempt to write the encoded body data to disk failed with an underlying error.
case outputStreamWriteFailed(error: Error)
/// The attempt to read an encoded body part `InputStream` failed with underlying system error.
case inputStreamReadFailed(error: Error)
}
/// Represents unexpected input stream length that occur when encoding the `MultipartFormData`. Instances will be
/// embedded within an `AFError.multipartEncodingFailed` `.inputStreamReadFailed` case.
public struct UnexpectedInputStreamLength: Error {
/// The expected byte count to read.
public var bytesExpected: UInt64
/// The actual byte count read.
public var bytesRead: UInt64
}
/// The underlying reason the `.parameterEncodingFailed` error occurred.
public enum ParameterEncodingFailureReason {
/// The `URLRequest` did not have a `URL` to encode.
case missingURL
/// JSON serialization failed with an underlying system error during the encoding process.
case jsonEncodingFailed(error: Error)
/// Custom parameter encoding failed due to the associated `Error`.
case customEncodingFailed(error: Error)
}
/// The underlying reason the `.parameterEncoderFailed` error occurred.
public enum ParameterEncoderFailureReason {
/// Possible missing components.
public enum RequiredComponent {
/// The `URL` was missing or unable to be extracted from the passed `URLRequest` or during encoding.
case url
/// The `HTTPMethod` could not be extracted from the passed `URLRequest`.
case httpMethod(rawValue: String)
}
/// A `RequiredComponent` was missing during encoding.
case missingRequiredComponent(RequiredComponent)
/// The underlying encoder failed with the associated error.
case encoderFailed(error: Error)
}
/// The underlying reason the `.responseValidationFailed` error occurred.
public enum ResponseValidationFailureReason {
/// The data file containing the server response did not exist.
case dataFileNil
/// The data file containing the server response at the associated `URL` could not be read.
case dataFileReadFailed(at: URL)
/// The response did not contain a `Content-Type` and the `acceptableContentTypes` provided did not contain a
/// wildcard type.
case missingContentType(acceptableContentTypes: [String])
/// The response `Content-Type` did not match any type in the provided `acceptableContentTypes`.
case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String)
/// The response status code was not acceptable.
case unacceptableStatusCode(code: Int)
/// Custom response validation failed due to the associated `Error`.
case customValidationFailed(error: Error)
}
/// The underlying reason the response serialization error occurred.
public enum ResponseSerializationFailureReason {
/// The server response contained no data or the data was zero length.
case inputDataNilOrZeroLength
/// The file containing the server response did not exist.
case inputFileNil
/// The file containing the server response could not be read from the associated `URL`.
case inputFileReadFailed(at: URL)
/// String serialization failed using the provided `String.Encoding`.
case stringSerializationFailed(encoding: String.Encoding)
/// JSON serialization failed with an underlying system error.
case jsonSerializationFailed(error: Error)
/// A `DataDecoder` failed to decode the response due to the associated `Error`.
case decodingFailed(error: Error)
/// A custom response serializer failed due to the associated `Error`.
case customSerializationFailed(error: Error)
/// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type.
case invalidEmptyResponse(type: String)
}
/// Underlying reason a server trust evaluation error occurred.
public enum ServerTrustFailureReason {
/// The output of a server trust evaluation.
public struct Output {
/// The host for which the evaluation was performed.
public let host: String
/// The `SecTrust` value which was evaluated.
public let trust: SecTrust
/// The `OSStatus` of evaluation operation.
public let status: OSStatus
/// The result of the evaluation operation.
public let result: SecTrustResultType
/// Creates an `Output` value from the provided values.
init(_ host: String, _ trust: SecTrust, _ status: OSStatus, _ result: SecTrustResultType) {
self.host = host
self.trust = trust
self.status = status
self.result = result
}
}
/// No `ServerTrustEvaluator` was found for the associated host.
case noRequiredEvaluator(host: String)
/// No certificates were found with which to perform the trust evaluation.
case noCertificatesFound
/// No public keys were found with which to perform the trust evaluation.
case noPublicKeysFound
/// During evaluation, application of the associated `SecPolicy` failed.
case policyApplicationFailed(trust: SecTrust, policy: SecPolicy, status: OSStatus)
/// During evaluation, setting the associated anchor certificates failed.
case settingAnchorCertificatesFailed(status: OSStatus, certificates: [SecCertificate])
/// During evaluation, creation of the revocation policy failed.
case revocationPolicyCreationFailed
/// `SecTrust` evaluation failed with the associated `Error`, if one was produced.
case trustEvaluationFailed(error: Error?)
/// Default evaluation failed with the associated `Output`.
case defaultEvaluationFailed(output: Output)
/// Host validation failed with the associated `Output`.
case hostValidationFailed(output: Output)
/// Revocation check failed with the associated `Output` and options.
case revocationCheckFailed(output: Output, options: RevocationTrustEvaluator.Options)
/// Certificate pinning failed.
case certificatePinningFailed(host: String, trust: SecTrust, pinnedCertificates: [SecCertificate], serverCertificates: [SecCertificate])
/// Public key pinning failed.
case publicKeyPinningFailed(host: String, trust: SecTrust, pinnedKeys: [SecKey], serverKeys: [SecKey])
/// Custom server trust evaluation failed due to the associated `Error`.
case customEvaluationFailed(error: Error)
}
/// The underlying reason the `.urlRequestValidationFailed`
public enum URLRequestValidationFailureReason {
/// URLRequest with GET method had body data.
case bodyDataInGETRequest(Data)
}
/// `UploadableConvertible` threw an error in `createUploadable()`.
case createUploadableFailed(error: Error)
/// `URLRequestConvertible` threw an error in `asURLRequest()`.
case createURLRequestFailed(error: Error)
/// `SessionDelegate` threw an error while attempting to move downloaded file to destination URL.
case downloadedFileMoveFailed(error: Error, source: URL, destination: URL)
/// `Request` was explicitly cancelled.
case explicitlyCancelled
/// `URLConvertible` type failed to create a valid `URL`.
case invalidURL(url: URLConvertible)
/// Multipart form encoding failed.
case multipartEncodingFailed(reason: MultipartEncodingFailureReason)
/// `ParameterEncoding` threw an error during the encoding process.
case parameterEncodingFailed(reason: ParameterEncodingFailureReason)
/// `ParameterEncoder` threw an error while running the encoder.
case parameterEncoderFailed(reason: ParameterEncoderFailureReason)
/// `RequestAdapter` threw an error during adaptation.
case requestAdaptationFailed(error: Error)
/// `RequestRetrier` threw an error during the request retry process.
case requestRetryFailed(retryError: Error, originalError: Error)
/// Response validation failed.
case responseValidationFailed(reason: ResponseValidationFailureReason)
/// Response serialization failed.
case responseSerializationFailed(reason: ResponseSerializationFailureReason)
/// `ServerTrustEvaluating` instance threw an error during trust evaluation.
case serverTrustEvaluationFailed(reason: ServerTrustFailureReason)
/// `Session` which issued the `Request` was deinitialized, most likely because its reference went out of scope.
case sessionDeinitialized
/// `Session` was explicitly invalidated, possibly with the `Error` produced by the underlying `URLSession`.
case sessionInvalidated(error: Error?)
/// `URLSessionTask` completed with error.
case sessionTaskFailed(error: Error)
/// `URLRequest` failed validation.
case urlRequestValidationFailed(reason: URLRequestValidationFailureReason)
}
extension Error {
/// Returns the instance cast as an `AFError`.
public var asAFError: AFError? {
self as? AFError
}
/// Returns the instance cast as an `AFError`. If casting fails, a `fatalError` with the specified `message` is thrown.
public func asAFError(orFailWith message: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> AFError {
guard let afError = self as? AFError else {
fatalError(message(), file: file, line: line)
}
return afError
}
/// Casts the instance as `AFError` or returns `defaultAFError`
func asAFError(or defaultAFError: @autoclosure () -> AFError) -> AFError {
self as? AFError ?? defaultAFError()
}
}
// MARK: - Error Booleans
extension AFError {
/// Returns whether the instance is `.sessionDeinitialized`.
public var isSessionDeinitializedError: Bool {
if case .sessionDeinitialized = self { return true }
return false
}
/// Returns whether the instance is `.sessionInvalidated`.
public var isSessionInvalidatedError: Bool {
if case .sessionInvalidated = self { return true }
return false
}
/// Returns whether the instance is `.explicitlyCancelled`.
public var isExplicitlyCancelledError: Bool {
if case .explicitlyCancelled = self { return true }
return false
}
/// Returns whether the instance is `.invalidURL`.
public var isInvalidURLError: Bool {
if case .invalidURL = self { return true }
return false
}
/// Returns whether the instance is `.parameterEncodingFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncodingError: Bool {
if case .parameterEncodingFailed = self { return true }
return false
}
/// Returns whether the instance is `.parameterEncoderFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isParameterEncoderError: Bool {
if case .parameterEncoderFailed = self { return true }
return false
}
/// Returns whether the instance is `.multipartEncodingFailed`. When `true`, the `url` and `underlyingError`
/// properties will contain the associated values.
public var isMultipartEncodingError: Bool {
if case .multipartEncodingFailed = self { return true }
return false
}
/// Returns whether the instance is `.requestAdaptationFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isRequestAdaptationError: Bool {
if case .requestAdaptationFailed = self { return true }
return false
}
/// Returns whether the instance is `.responseValidationFailed`. When `true`, the `acceptableContentTypes`,
/// `responseContentType`, `responseCode`, and `underlyingError` properties will contain the associated values.
public var isResponseValidationError: Bool {
if case .responseValidationFailed = self { return true }
return false
}
/// Returns whether the instance is `.responseSerializationFailed`. When `true`, the `failedStringEncoding` and
/// `underlyingError` properties will contain the associated values.
public var isResponseSerializationError: Bool {
if case .responseSerializationFailed = self { return true }
return false
}
/// Returns whether the instance is `.serverTrustEvaluationFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isServerTrustEvaluationError: Bool {
if case .serverTrustEvaluationFailed = self { return true }
return false
}
/// Returns whether the instance is `requestRetryFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isRequestRetryError: Bool {
if case .requestRetryFailed = self { return true }
return false
}
/// Returns whether the instance is `createUploadableFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isCreateUploadableError: Bool {
if case .createUploadableFailed = self { return true }
return false
}
/// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isCreateURLRequestError: Bool {
if case .createURLRequestFailed = self { return true }
return false
}
/// Returns whether the instance is `downloadedFileMoveFailed`. When `true`, the `destination` and `underlyingError` properties will
/// contain the associated values.
public var isDownloadedFileMoveError: Bool {
if case .downloadedFileMoveFailed = self { return true }
return false
}
/// Returns whether the instance is `createURLRequestFailed`. When `true`, the `underlyingError` property will
/// contain the associated value.
public var isSessionTaskError: Bool {
if case .sessionTaskFailed = self { return true }
return false
}
}
// MARK: - Convenience Properties
extension AFError {
/// The `URLConvertible` associated with the error.
public var urlConvertible: URLConvertible? {
guard case let .invalidURL(url) = self else { return nil }
return url
}
/// The `URL` associated with the error.
public var url: URL? {
guard case let .multipartEncodingFailed(reason) = self else { return nil }
return reason.url
}
/// The underlying `Error` responsible for generating the failure associated with `.sessionInvalidated`,
/// `.parameterEncodingFailed`, `.parameterEncoderFailed`, `.multipartEncodingFailed`, `.requestAdaptationFailed`,
/// `.responseSerializationFailed`, `.requestRetryFailed` errors.
public var underlyingError: Error? {
switch self {
case let .multipartEncodingFailed(reason):
return reason.underlyingError
case let .parameterEncodingFailed(reason):
return reason.underlyingError
case let .parameterEncoderFailed(reason):
return reason.underlyingError
case let .requestAdaptationFailed(error):
return error
case let .requestRetryFailed(retryError, _):
return retryError
case let .responseValidationFailed(reason):
return reason.underlyingError
case let .responseSerializationFailed(reason):
return reason.underlyingError
case let .serverTrustEvaluationFailed(reason):
return reason.underlyingError
case let .sessionInvalidated(error):
return error
case let .createUploadableFailed(error):
return error
case let .createURLRequestFailed(error):
return error
case let .downloadedFileMoveFailed(error, _, _):
return error
case let .sessionTaskFailed(error):
return error
case .explicitlyCancelled,
.invalidURL,
.sessionDeinitialized,
.urlRequestValidationFailed:
return nil
}
}
/// The acceptable `Content-Type`s of a `.responseValidationFailed` error.
public var acceptableContentTypes: [String]? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.acceptableContentTypes
}
/// The response `Content-Type` of a `.responseValidationFailed` error.
public var responseContentType: String? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.responseContentType
}
/// The response code of a `.responseValidationFailed` error.
public var responseCode: Int? {
guard case let .responseValidationFailed(reason) = self else { return nil }
return reason.responseCode
}
/// The `String.Encoding` associated with a failed `.stringResponse()` call.
public var failedStringEncoding: String.Encoding? {
guard case let .responseSerializationFailed(reason) = self else { return nil }
return reason.failedStringEncoding
}
/// The `source` URL of a `.downloadedFileMoveFailed` error.
public var sourceURL: URL? {
guard case let .downloadedFileMoveFailed(_, source, _) = self else { return nil }
return source
}
/// The `destination` URL of a `.downloadedFileMoveFailed` error.
public var destinationURL: URL? {
guard case let .downloadedFileMoveFailed(_, _, destination) = self else { return nil }
return destination
}
/// The download resume data of any underlying network error. Only produced by `DownloadRequest`s.
public var downloadResumeData: Data? {
(underlyingError as? URLError)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
}
}
extension AFError.ParameterEncodingFailureReason {
var underlyingError: Error? {
switch self {
case let .jsonEncodingFailed(error),
let .customEncodingFailed(error):
return error
case .missingURL:
return nil
}
}
}
extension AFError.ParameterEncoderFailureReason {
var underlyingError: Error? {
switch self {
case let .encoderFailed(error):
return error
case .missingRequiredComponent:
return nil
}
}
}
extension AFError.MultipartEncodingFailureReason {
var url: URL? {
switch self {
case let .bodyPartURLInvalid(url),
let .bodyPartFilenameInvalid(url),
let .bodyPartFileNotReachable(url),
let .bodyPartFileIsDirectory(url),
let .bodyPartFileSizeNotAvailable(url),
let .bodyPartInputStreamCreationFailed(url),
let .outputStreamCreationFailed(url),
let .outputStreamFileAlreadyExists(url),
let .outputStreamURLInvalid(url),
let .bodyPartFileNotReachableWithError(url, _),
let .bodyPartFileSizeQueryFailedWithError(url, _):
return url
case .outputStreamWriteFailed,
.inputStreamReadFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .bodyPartFileNotReachableWithError(_, error),
let .bodyPartFileSizeQueryFailedWithError(_, error),
let .outputStreamWriteFailed(error),
let .inputStreamReadFailed(error):
return error
case .bodyPartURLInvalid,
.bodyPartFilenameInvalid,
.bodyPartFileNotReachable,
.bodyPartFileIsDirectory,
.bodyPartFileSizeNotAvailable,
.bodyPartInputStreamCreationFailed,
.outputStreamCreationFailed,
.outputStreamFileAlreadyExists,
.outputStreamURLInvalid:
return nil
}
}
}
extension AFError.ResponseValidationFailureReason {
var acceptableContentTypes: [String]? {
switch self {
case let .missingContentType(types),
let .unacceptableContentType(types, _):
return types
case .dataFileNil,
.dataFileReadFailed,
.unacceptableStatusCode,
.customValidationFailed:
return nil
}
}
var responseContentType: String? {
switch self {
case let .unacceptableContentType(_, responseType):
return responseType
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableStatusCode,
.customValidationFailed:
return nil
}
}
var responseCode: Int? {
switch self {
case let .unacceptableStatusCode(code):
return code
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableContentType,
.customValidationFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .customValidationFailed(error):
return error
case .dataFileNil,
.dataFileReadFailed,
.missingContentType,
.unacceptableContentType,
.unacceptableStatusCode:
return nil
}
}
}
extension AFError.ResponseSerializationFailureReason {
var failedStringEncoding: String.Encoding? {
switch self {
case let .stringSerializationFailed(encoding):
return encoding
case .inputDataNilOrZeroLength,
.inputFileNil,
.inputFileReadFailed(_),
.jsonSerializationFailed(_),
.decodingFailed(_),
.customSerializationFailed(_),
.invalidEmptyResponse:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .jsonSerializationFailed(error),
let .decodingFailed(error),
let .customSerializationFailed(error):
return error
case .inputDataNilOrZeroLength,
.inputFileNil,
.inputFileReadFailed,
.stringSerializationFailed,
.invalidEmptyResponse:
return nil
}
}
}
extension AFError.ServerTrustFailureReason {
var output: AFError.ServerTrustFailureReason.Output? {
switch self {
case let .defaultEvaluationFailed(output),
let .hostValidationFailed(output),
let .revocationCheckFailed(output, _):
return output
case .noRequiredEvaluator,
.noCertificatesFound,
.noPublicKeysFound,
.policyApplicationFailed,
.settingAnchorCertificatesFailed,
.revocationPolicyCreationFailed,
.trustEvaluationFailed,
.certificatePinningFailed,
.publicKeyPinningFailed,
.customEvaluationFailed:
return nil
}
}
var underlyingError: Error? {
switch self {
case let .customEvaluationFailed(error):
return error
case let .trustEvaluationFailed(error):
return error
case .noRequiredEvaluator,
.noCertificatesFound,
.noPublicKeysFound,
.policyApplicationFailed,
.settingAnchorCertificatesFailed,
.revocationPolicyCreationFailed,
.defaultEvaluationFailed,
.hostValidationFailed,
.revocationCheckFailed,
.certificatePinningFailed,
.publicKeyPinningFailed:
return nil
}
}
}
// MARK: - Error Descriptions
extension AFError: LocalizedError {
public var errorDescription: String? {
switch self {
case .explicitlyCancelled:
return "Request explicitly cancelled."
case let .invalidURL(url):
return "URL is not valid: \(url)"
case let .parameterEncodingFailed(reason):
return reason.localizedDescription
case let .parameterEncoderFailed(reason):
return reason.localizedDescription
case let .multipartEncodingFailed(reason):
return reason.localizedDescription
case let .requestAdaptationFailed(error):
return "Request adaption failed with error: \(error.localizedDescription)"
case let .responseValidationFailed(reason):
return reason.localizedDescription
case let .responseSerializationFailed(reason):
return reason.localizedDescription
case let .requestRetryFailed(retryError, originalError):
return """
Request retry failed with retry error: \(retryError.localizedDescription), \
original error: \(originalError.localizedDescription)
"""
case .sessionDeinitialized:
return """
Session was invalidated without error, so it was likely deinitialized unexpectedly. \
Be sure to retain a reference to your Session for the duration of your requests.
"""
case let .sessionInvalidated(error):
return "Session was invalidated with error: \(error?.localizedDescription ?? "No description.")"
case let .serverTrustEvaluationFailed(reason):
return "Server trust evaluation failed due to reason: \(reason.localizedDescription)"
case let .urlRequestValidationFailed(reason):
return "URLRequest validation failed due to reason: \(reason.localizedDescription)"
case let .createUploadableFailed(error):
return "Uploadable creation failed with error: \(error.localizedDescription)"
case let .createURLRequestFailed(error):
return "URLRequest creation failed with error: \(error.localizedDescription)"
case let .downloadedFileMoveFailed(error, source, destination):
return "Moving downloaded file from: \(source) to: \(destination) failed with error: \(error.localizedDescription)"
case let .sessionTaskFailed(error):
return "URLSessionTask failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ParameterEncodingFailureReason {
var localizedDescription: String {
switch self {
case .missingURL:
return "URL request to encode was missing a URL"
case let .jsonEncodingFailed(error):
return "JSON could not be encoded because of error:\n\(error.localizedDescription)"
case let .customEncodingFailed(error):
return "Custom parameter encoder failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ParameterEncoderFailureReason {
var localizedDescription: String {
switch self {
case let .missingRequiredComponent(component):
return "Encoding failed due to a missing request component: \(component)"
case let .encoderFailed(error):
return "The underlying encoder failed with the error: \(error)"
}
}
}
extension AFError.MultipartEncodingFailureReason {
var localizedDescription: String {
switch self {
case let .bodyPartURLInvalid(url):
return "The URL provided is not a file URL: \(url)"
case let .bodyPartFilenameInvalid(url):
return "The URL provided does not have a valid filename: \(url)"
case let .bodyPartFileNotReachable(url):
return "The URL provided is not reachable: \(url)"
case let .bodyPartFileNotReachableWithError(url, error):
return """
The system returned an error while checking the provided URL for reachability.
URL: \(url)
Error: \(error)
"""
case let .bodyPartFileIsDirectory(url):
return "The URL provided is a directory: \(url)"
case let .bodyPartFileSizeNotAvailable(url):
return "Could not fetch the file size from the provided URL: \(url)"
case let .bodyPartFileSizeQueryFailedWithError(url, error):
return """
The system returned an error while attempting to fetch the file size from the provided URL.
URL: \(url)
Error: \(error)
"""
case let .bodyPartInputStreamCreationFailed(url):
return "Failed to create an InputStream for the provided URL: \(url)"
case let .outputStreamCreationFailed(url):
return "Failed to create an OutputStream for URL: \(url)"
case let .outputStreamFileAlreadyExists(url):
return "A file already exists at the provided URL: \(url)"
case let .outputStreamURLInvalid(url):
return "The provided OutputStream URL is invalid: \(url)"
case let .outputStreamWriteFailed(error):
return "OutputStream write failed with error: \(error)"
case let .inputStreamReadFailed(error):
return "InputStream read failed with error: \(error)"
}
}
}
extension AFError.ResponseSerializationFailureReason {
var localizedDescription: String {
switch self {
case .inputDataNilOrZeroLength:
return "Response could not be serialized, input data was nil or zero length."
case .inputFileNil:
return "Response could not be serialized, input file was nil."
case let .inputFileReadFailed(url):
return "Response could not be serialized, input file could not be read: \(url)."
case let .stringSerializationFailed(encoding):
return "String could not be serialized with encoding: \(encoding)."
case let .jsonSerializationFailed(error):
return "JSON could not be serialized because of error:\n\(error.localizedDescription)"
case let .invalidEmptyResponse(type):
return """
Empty response could not be serialized to type: \(type). \
Use Empty as the expected type for such responses.
"""
case let .decodingFailed(error):
return "Response could not be decoded because of error:\n\(error.localizedDescription)"
case let .customSerializationFailed(error):
return "Custom response serializer failed with error:\n\(error.localizedDescription)"
}
}
}
extension AFError.ResponseValidationFailureReason {
var localizedDescription: String {
switch self {
case .dataFileNil:
return "Response could not be validated, data file was nil."
case let .dataFileReadFailed(url):
return "Response could not be validated, data file could not be read: \(url)."
case let .missingContentType(types):
return """
Response Content-Type was missing and acceptable content types \
(\(types.joined(separator: ","))) do not match "*/*".
"""
case let .unacceptableContentType(acceptableTypes, responseType):
return """
Response Content-Type "\(responseType)" does not match any acceptable types: \
\(acceptableTypes.joined(separator: ",")).
"""
case let .unacceptableStatusCode(code):
return "Response status code was unacceptable: \(code)."
case let .customValidationFailed(error):
return "Custom response validation failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.ServerTrustFailureReason {
var localizedDescription: String {
switch self {
case let .noRequiredEvaluator(host):
return "A ServerTrustEvaluating value is required for host \(host) but none was found."
case .noCertificatesFound:
return "No certificates were found or provided for evaluation."
case .noPublicKeysFound:
return "No public keys were found or provided for evaluation."
case .policyApplicationFailed:
return "Attempting to set a SecPolicy failed."
case .settingAnchorCertificatesFailed:
return "Attempting to set the provided certificates as anchor certificates failed."
case .revocationPolicyCreationFailed:
return "Attempting to create a revocation policy failed."
case let .trustEvaluationFailed(error):
return "SecTrust evaluation failed with error: \(error?.localizedDescription ?? "None")"
case let .defaultEvaluationFailed(output):
return "Default evaluation failed for host \(output.host)."
case let .hostValidationFailed(output):
return "Host validation failed for host \(output.host)."
case let .revocationCheckFailed(output, _):
return "Revocation check failed for host \(output.host)."
case let .certificatePinningFailed(host, _, _, _):
return "Certificate pinning failed for host \(host)."
case let .publicKeyPinningFailed(host, _, _, _):
return "Public key pinning failed for host \(host)."
case let .customEvaluationFailed(error):
return "Custom trust evaluation failed with error: \(error.localizedDescription)"
}
}
}
extension AFError.URLRequestValidationFailureReason {
var localizedDescription: String {
switch self {
case let .bodyDataInGETRequest(data):
return """
Invalid URLRequest: Requests with GET method cannot have body data:
\(String(decoding: data, as: UTF8.self))
"""
}
}
}
================================================
FILE: Pods/Alamofire/Source/Alamofire.swift
================================================
//
// Alamofire.swift
//
// Copyright (c) 2014-2021 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// Reference to `Session.default` for quick bootstrapping and examples.
public let AF = Session.default
/// Current Alamofire version. Necessary since SPM doesn't use dynamic libraries. Plus this will be more accurate.
let version = "5.4.3"
================================================
FILE: Pods/Alamofire/Source/AlamofireExtended.swift
================================================
//
// AlamofireExtended.swift
//
// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// Type that acts as a generic extension point for all `AlamofireExtended` types.
public struct AlamofireExtension {
/// Stores the type or meta-type of any extended type.
public private(set) var type: ExtendedType
/// Create an instance from the provided value.
///
/// - Parameter type: Instance being extended.
public init(_ type: ExtendedType) {
self.type = type
}
}
/// Protocol describing the `af` extension points for Alamofire extended types.
public protocol AlamofireExtended {
/// Type being extended.
associatedtype ExtendedType
/// Static Alamofire extension point.
static var af: AlamofireExtension.Type { get set }
/// Instance Alamofire extension point.
var af: AlamofireExtension { get set }
}
extension AlamofireExtended {
/// Static Alamofire extension point.
public static var af: AlamofireExtension.Type {
get { AlamofireExtension.self }
set {}
}
/// Instance Alamofire extension point.
public var af: AlamofireExtension {
get { AlamofireExtension(self) }
set {}
}
}
================================================
FILE: Pods/Alamofire/Source/AuthenticationInterceptor.swift
================================================
//
// AuthenticationInterceptor.swift
//
// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Types adopting the `AuthenticationCredential` protocol can be used to authenticate `URLRequest`s.
///
/// One common example of an `AuthenticationCredential` is an OAuth2 credential containing an access token used to
/// authenticate all requests on behalf of a user. The access token generally has an expiration window of 60 minutes
/// which will then require a refresh of the credential using the refresh token to generate a new access token.
public protocol AuthenticationCredential {
/// Whether the credential requires a refresh. This property should always return `true` when the credential is
/// expired. It is also wise to consider returning `true` when the credential will expire in several seconds or
/// minutes depending on the expiration window of the credential.
///
/// For example, if the credential is valid for 60 minutes, then it would be wise to return `true` when the
/// credential is only valid for 5 minutes or less. That ensures the credential will not expire as it is passed
/// around backend services.
var requiresRefresh: Bool { get }
}
// MARK: -
/// Types adopting the `Authenticator` protocol can be used to authenticate `URLRequest`s with an
/// `AuthenticationCredential` as well as refresh the `AuthenticationCredential` when required.
public protocol Authenticator: AnyObject {
/// The type of credential associated with the `Authenticator` instance.
associatedtype Credential: AuthenticationCredential
/// Applies the `Credential` to the `URLRequest`.
///
/// In the case of OAuth2, the access token of the `Credential` would be added to the `URLRequest` as a Bearer
/// token to the `Authorization` header.
///
/// - Parameters:
/// - credential: The `Credential`.
/// - urlRequest: The `URLRequest`.
func apply(_ credential: Credential, to urlRequest: inout URLRequest)
/// Refreshes the `Credential` and executes the `completion` closure with the `Result` once complete.
///
/// Refresh can be called in one of two ways. It can be called before the `Request` is actually executed due to
/// a `requiresRefresh` returning `true` during the adapt portion of the `Request` creation process. It can also
/// be triggered by a failed `Request` where the authentication server denied access due to an expired or
/// invalidated access token.
///
/// In the case of OAuth2, this method would use the refresh token of the `Credential` to generate a new
/// `Credential` using the authentication service. Once complete, the `completion` closure should be called with
/// the new `Credential`, or the error that occurred.
///
/// In general, if the refresh call fails with certain status codes from the authentication server (commonly a 401),
/// the refresh token in the `Credential` can no longer be used to generate a valid `Credential`. In these cases,
/// you will need to reauthenticate the user with their username / password.
///
/// Please note, these are just general examples of common use cases. They are not meant to solve your specific
/// authentication server challenges. Please work with your authentication server team to ensure your
/// `Authenticator` logic matches their expectations.
///
/// - Parameters:
/// - credential: The `Credential` to refresh.
/// - session: The `Session` requiring the refresh.
/// - completion: The closure to be executed once the refresh is complete.
func refresh(_ credential: Credential, for session: Session, completion: @escaping (Result) -> Void)
/// Determines whether the `URLRequest` failed due to an authentication error based on the `HTTPURLResponse`.
///
/// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `false`
/// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then you
/// will need to work with your authentication server team to understand how to identify when this occurs.
///
/// In the case of OAuth2, where an authentication server can invalidate credentials, you will need to inspect the
/// `HTTPURLResponse` or possibly the `Error` for when this occurs. This is commonly handled by the authentication
/// server returning a 401 status code and some additional header to indicate an OAuth2 failure occurred.
///
/// It is very important to understand how your authentication server works to be able to implement this correctly.
/// For example, if your authentication server returns a 401 when an OAuth2 error occurs, and your downstream
/// service also returns a 401 when you are not authorized to perform that operation, how do you know which layer
/// of the backend returned you a 401? You do not want to trigger a refresh unless you know your authentication
/// server is actually the layer rejecting the request. Again, work with your authentication server team to understand
/// how to identify an OAuth2 401 error vs. a downstream 401 error to avoid endless refresh loops.
///
/// - Parameters:
/// - urlRequest: The `URLRequest`.
/// - response: The `HTTPURLResponse`.
/// - error: The `Error`.
///
/// - Returns: `true` if the `URLRequest` failed due to an authentication error, `false` otherwise.
func didRequest(_ urlRequest: URLRequest, with response: HTTPURLResponse, failDueToAuthenticationError error: Error) -> Bool
/// Determines whether the `URLRequest` is authenticated with the `Credential`.
///
/// If the authentication server **CANNOT** invalidate credentials after they are issued, then simply return `true`
/// for this method. If the authentication server **CAN** invalidate credentials due to security breaches, then
/// read on.
///
/// When an authentication server can invalidate credentials, it means that you may have a non-expired credential
/// that appears to be valid, but will be rejected by the authentication server when used. Generally when this
/// happens, a number of requests are all sent when the application is foregrounded, and all of them will be
/// rejected by the authentication server in the order they are received. The first failed request will trigger a
/// refresh internally, which will update the credential, and then retry all the queued requests with the new
/// credential. However, it is possible that some of the original requests will not return from the authentication
/// server until the refresh has completed. This is where this method comes in.
///
/// When the authentication server rejects a credential, we need to check to make sure we haven't refreshed the
/// credential while the request was in flight. If it has already refreshed, then we don't need to trigger an
/// additional refresh. If it hasn't refreshed, then we need to refresh.
///
/// Now that it is understood how the result of this method is used in the refresh lifecyle, let's walk through how
/// to implement it. You should return `true` in this method if the `URLRequest` is authenticated in a way that
/// matches the values in the `Credential`. In the case of OAuth2, this would mean that the Bearer token in the
/// `Authorization` header of the `URLRequest` matches the access token in the `Credential`. If it matches, then we
/// know the `Credential` was used to authenticate the `URLRequest` and should return `true`. If the Bearer token
/// did not match the access token, then you should return `false`.
///
/// - Parameters:
/// - urlRequest: The `URLRequest`.
/// - credential: The `Credential`.
///
/// - Returns: `true` if the `URLRequest` is authenticated with the `Credential`, `false` otherwise.
func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: Credential) -> Bool
}
// MARK: -
/// Represents various authentication failures that occur when using the `AuthenticationInterceptor`. All errors are
/// still vended from Alamofire as `AFError` types. The `AuthenticationError` instances will be embedded within
/// `AFError` `.requestAdaptationFailed` or `.requestRetryFailed` cases.
public enum AuthenticationError: Error {
/// The credential was missing so the request could not be authenticated.
case missingCredential
/// The credential was refreshed too many times within the `RefreshWindow`.
case excessiveRefresh
}
// MARK: -
/// The `AuthenticationInterceptor` class manages the queuing and threading complexity of authenticating requests.
/// It relies on an `Authenticator` type to handle the actual `URLRequest` authentication and `Credential` refresh.
public class AuthenticationInterceptor: RequestInterceptor where AuthenticatorType: Authenticator {
// MARK: Typealiases
/// Type of credential used to authenticate requests.
public typealias Credential = AuthenticatorType.Credential
// MARK: Helper Types
/// Type that defines a time window used to identify excessive refresh calls. When enabled, prior to executing a
/// refresh, the `AuthenticationInterceptor` compares the timestamp history of previous refresh calls against the
/// `RefreshWindow`. If more refreshes have occurred within the refresh window than allowed, the refresh is
/// cancelled and an `AuthorizationError.excessiveRefresh` error is thrown.
public struct RefreshWindow {
/// `TimeInterval` defining the duration of the time window before the current time in which the number of
/// refresh attempts is compared against `maximumAttempts`. For example, if `interval` is 30 seconds, then the
/// `RefreshWindow` represents the past 30 seconds. If more attempts occurred in the past 30 seconds than
/// `maximumAttempts`, an `.excessiveRefresh` error will be thrown.
public let interval: TimeInterval
/// Total refresh attempts allowed within `interval` before throwing an `.excessiveRefresh` error.
public let maximumAttempts: Int
/// Creates a `RefreshWindow` instance from the specified `interval` and `maximumAttempts`.
///
/// - Parameters:
/// - interval: `TimeInterval` defining the duration of the time window before the current time.
/// - maximumAttempts: The maximum attempts allowed within the `TimeInterval`.
public init(interval: TimeInterval = 30.0, maximumAttempts: Int = 5) {
self.interval = interval
self.maximumAttempts = maximumAttempts
}
}
private struct AdaptOperation {
let urlRequest: URLRequest
let session: Session
let completion: (Result) -> Void
}
private enum AdaptResult {
case adapt(Credential)
case doNotAdapt(AuthenticationError)
case adaptDeferred
}
private struct MutableState {
var credential: Credential?
var isRefreshing = false
var refreshTimestamps: [TimeInterval] = []
var refreshWindow: RefreshWindow?
var adaptOperations: [AdaptOperation] = []
var requestsToRetry: [(RetryResult) -> Void] = []
}
// MARK: Properties
/// The `Credential` used to authenticate requests.
public var credential: Credential? {
get { mutableState.credential }
set { mutableState.credential = newValue }
}
let authenticator: AuthenticatorType
let queue = DispatchQueue(label: "org.alamofire.authentication.inspector")
@Protected
private var mutableState = MutableState()
// MARK: Initialization
/// Creates an `AuthenticationInterceptor` instance from the specified parameters.
///
/// A `nil` `RefreshWindow` will result in the `AuthenticationInterceptor` not checking for excessive refresh calls.
/// It is recommended to always use a `RefreshWindow` to avoid endless refresh cycles.
///
/// - Parameters:
/// - authenticator: The `Authenticator` type.
/// - credential: The `Credential` if it exists. `nil` by default.
/// - refreshWindow: The `RefreshWindow` used to identify excessive refresh calls. `RefreshWindow()` by default.
public init(authenticator: AuthenticatorType,
credential: Credential? = nil,
refreshWindow: RefreshWindow? = RefreshWindow()) {
self.authenticator = authenticator
mutableState.credential = credential
mutableState.refreshWindow = refreshWindow
}
// MARK: Adapt
public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) {
let adaptResult: AdaptResult = $mutableState.write { mutableState in
// Queue the adapt operation if a refresh is already in place.
guard !mutableState.isRefreshing else {
let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion)
mutableState.adaptOperations.append(operation)
return .adaptDeferred
}
// Throw missing credential error is the credential is missing.
guard let credential = mutableState.credential else {
let error = AuthenticationError.missingCredential
return .doNotAdapt(error)
}
// Queue the adapt operation and trigger refresh operation if credential requires refresh.
guard !credential.requiresRefresh else {
let operation = AdaptOperation(urlRequest: urlRequest, session: session, completion: completion)
mutableState.adaptOperations.append(operation)
refresh(credential, for: session, insideLock: &mutableState)
return .adaptDeferred
}
return .adapt(credential)
}
switch adaptResult {
case let .adapt(credential):
var authenticatedRequest = urlRequest
authenticator.apply(credential, to: &authenticatedRequest)
completion(.success(authenticatedRequest))
case let .doNotAdapt(adaptError):
completion(.failure(adaptError))
case .adaptDeferred:
// No-op: adapt operation captured during refresh.
break
}
}
// MARK: Retry
public func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
// Do not attempt retry if there was not an original request and response from the server.
guard let urlRequest = request.request, let response = request.response else {
completion(.doNotRetry)
return
}
// Do not attempt retry unless the `Authenticator` verifies failure was due to authentication error (i.e. 401 status code).
guard authenticator.didRequest(urlRequest, with: response, failDueToAuthenticationError: error) else {
completion(.doNotRetry)
return
}
// Do not attempt retry if there is no credential.
guard let credential = credential else {
let error = AuthenticationError.missingCredential
completion(.doNotRetryWithError(error))
return
}
// Retry the request if the `Authenticator` verifies it was authenticated with a previous credential.
guard authenticator.isRequest(urlRequest, authenticatedWith: credential) else {
completion(.retry)
return
}
$mutableState.write { mutableState in
mutableState.requestsToRetry.append(completion)
guard !mutableState.isRefreshing else { return }
refresh(credential, for: session, insideLock: &mutableState)
}
}
// MARK: Refresh
private func refresh(_ credential: Credential, for session: Session, insideLock mutableState: inout MutableState) {
guard !isRefreshExcessive(insideLock: &mutableState) else {
let error = AuthenticationError.excessiveRefresh
handleRefreshFailure(error, insideLock: &mutableState)
return
}
mutableState.refreshTimestamps.append(ProcessInfo.processInfo.systemUptime)
mutableState.isRefreshing = true
// Dispatch to queue to hop out of the lock in case authenticator.refresh is implemented synchronously.
queue.async {
self.authenticator.refresh(credential, for: session) { result in
self.$mutableState.write { mutableState in
switch result {
case let .success(credential):
self.handleRefreshSuccess(credential, insideLock: &mutableState)
case let .failure(error):
self.handleRefreshFailure(error, insideLock: &mutableState)
}
}
}
}
}
private func isRefreshExcessive(insideLock mutableState: inout MutableState) -> Bool {
guard let refreshWindow = mutableState.refreshWindow else { return false }
let refreshWindowMin = ProcessInfo.processInfo.systemUptime - refreshWindow.interval
let refreshAttemptsWithinWindow = mutableState.refreshTimestamps.reduce(into: 0) { attempts, refreshTimestamp in
guard refreshWindowMin <= refreshTimestamp else { return }
attempts += 1
}
let isRefreshExcessive = refreshAttemptsWithinWindow >= refreshWindow.maximumAttempts
return isRefreshExcessive
}
private func handleRefreshSuccess(_ credential: Credential, insideLock mutableState: inout MutableState) {
mutableState.credential = credential
let adaptOperations = mutableState.adaptOperations
let requestsToRetry = mutableState.requestsToRetry
mutableState.adaptOperations.removeAll()
mutableState.requestsToRetry.removeAll()
mutableState.isRefreshing = false
// Dispatch to queue to hop out of the mutable state lock
queue.async {
adaptOperations.forEach { self.adapt($0.urlRequest, for: $0.session, completion: $0.completion) }
requestsToRetry.forEach { $0(.retry) }
}
}
private func handleRefreshFailure(_ error: Error, insideLock mutableState: inout MutableState) {
let adaptOperations = mutableState.adaptOperations
let requestsToRetry = mutableState.requestsToRetry
mutableState.adaptOperations.removeAll()
mutableState.requestsToRetry.removeAll()
mutableState.isRefreshing = false
// Dispatch to queue to hop out of the mutable state lock
queue.async {
adaptOperations.forEach { $0.completion(.failure(error)) }
requestsToRetry.forEach { $0(.doNotRetryWithError(error)) }
}
}
}
================================================
FILE: Pods/Alamofire/Source/CachedResponseHandler.swift
================================================
//
// CachedResponseHandler.swift
//
// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that handles whether the data task should store the HTTP response in the cache.
public protocol CachedResponseHandler {
/// Determines whether the HTTP response should be stored in the cache.
///
/// The `completion` closure should be passed one of three possible options:
///
/// 1. The cached response provided by the server (this is the most common use case).
/// 2. A modified version of the cached response (you may want to modify it in some way before caching).
/// 3. A `nil` value to prevent the cached response from being stored in the cache.
///
/// - Parameters:
/// - task: The data task whose request resulted in the cached response.
/// - response: The cached response to potentially store in the cache.
/// - completion: The closure to execute containing cached response, a modified response, or `nil`.
func dataTask(_ task: URLSessionDataTask,
willCacheResponse response: CachedURLResponse,
completion: @escaping (CachedURLResponse?) -> Void)
}
// MARK: -
/// `ResponseCacher` is a convenience `CachedResponseHandler` making it easy to cache, not cache, or modify a cached
/// response.
public struct ResponseCacher {
/// Defines the behavior of the `ResponseCacher` type.
public enum Behavior {
/// Stores the cached response in the cache.
case cache
/// Prevents the cached response from being stored in the cache.
case doNotCache
/// Modifies the cached response before storing it in the cache.
case modify((URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)
}
/// Returns a `ResponseCacher` with a follow `Behavior`.
public static let cache = ResponseCacher(behavior: .cache)
/// Returns a `ResponseCacher` with a do not follow `Behavior`.
public static let doNotCache = ResponseCacher(behavior: .doNotCache)
/// The `Behavior` of the `ResponseCacher`.
public let behavior: Behavior
/// Creates a `ResponseCacher` instance from the `Behavior`.
///
/// - Parameter behavior: The `Behavior`.
public init(behavior: Behavior) {
self.behavior = behavior
}
}
extension ResponseCacher: CachedResponseHandler {
public func dataTask(_ task: URLSessionDataTask,
willCacheResponse response: CachedURLResponse,
completion: @escaping (CachedURLResponse?) -> Void) {
switch behavior {
case .cache:
completion(response)
case .doNotCache:
completion(nil)
case let .modify(closure):
let response = closure(task, response)
completion(response)
}
}
}
================================================
FILE: Pods/Alamofire/Source/Combine.swift
================================================
//
// Combine.swift
//
// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(Combine)
import Combine
import Dispatch
import Foundation
// MARK: - DataRequest / UploadRequest
/// A Combine `Publisher` that publishes the `DataResponse` of the provided `DataRequest`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct DataResponsePublisher: Publisher {
public typealias Output = DataResponse
public typealias Failure = Never
private typealias Handler = (@escaping (_ response: DataResponse) -> Void) -> DataRequest
private let request: DataRequest
private let responseHandler: Handler
/// Creates an instance which will serialize responses using the provided `ResponseSerializer`.
///
/// - Parameters:
/// - request: `DataRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
/// - serializer: `ResponseSerializer` used to produce the published `DataResponse`.
public init(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer)
where Value == Serializer.SerializedObject {
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`.
///
/// - Parameters:
/// - request: `DataRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
/// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`.
public init(_ request: DataRequest,
queue: DispatchQueue,
serializer: Serializer)
where Value == Serializer.SerializedObject {
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Publishes only the `Result` of the `DataResponse` value.
///
/// - Returns: The `AnyPublisher` publishing the `Result` value.
public func result() -> AnyPublisher, Never> {
map { $0.result }.eraseToAnyPublisher()
}
/// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance.
///
/// - Returns: The `AnyPublisher` publishing the stream.
public func value() -> AnyPublisher {
setFailureType(to: AFError.self).flatMap { $0.result.publisher }.eraseToAnyPublisher()
}
public func receive(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input {
subscriber.receive(subscription: Inner(request: request,
responseHandler: responseHandler,
downstream: subscriber))
}
private final class Inner: Subscription, Cancellable
where Downstream.Input == Output {
typealias Failure = Downstream.Failure
@Protected
private var downstream: Downstream?
private let request: DataRequest
private let responseHandler: Handler
init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) {
self.request = request
self.responseHandler = responseHandler
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = downstream else { return }
self.downstream = nil
responseHandler { response in
_ = downstream.receive(response)
downstream.receive(completion: .finished)
}.resume()
}
func cancel() {
request.cancel()
downstream = nil
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension DataResponsePublisher where Value == Data? {
/// Creates an instance which publishes a `DataResponse` value without serialization.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public init(_ request: DataRequest, queue: DispatchQueue) {
self.request = request
responseHandler = { request.response(queue: queue, completionHandler: $0) }
}
}
extension DataRequest {
/// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `ResponseSerializer` used to serialize response `Data`.
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher
where Serializer.SerializedObject == T {
DataResponsePublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishData(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher {
publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding
/// will be determined by the server response, falling back to the default HTTP character
/// set, `ISO-8859-1`.
/// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishString(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
encoding: String.Encoding? = nil,
emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher {
publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor,
encoding: encoding,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default.
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default.
/// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishDecodable(type: T.Type = T.self,
queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
decoder: DataDecoder = JSONDecoder(),
emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes,
emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher {
publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
decoder: decoder,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyResponseMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing.
///
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher {
DataResponsePublisher(self, queue: queue)
}
}
// A Combine `Publisher` that publishes a sequence of `Stream` values received by the provided `DataStreamRequest`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct DataStreamPublisher: Publisher {
public typealias Output = DataStreamRequest.Stream
public typealias Failure = Never
private typealias Handler = (@escaping DataStreamRequest.Handler) -> DataStreamRequest
private let request: DataStreamRequest
private let streamHandler: Handler
/// Creates an instance which will serialize responses using the provided `DataStreamSerializer`.
///
/// - Parameters:
/// - request: `DataStreamRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `Stream` values will be published. `.main` by
/// default.
/// - serializer: `DataStreamSerializer` used to produce the published `Stream` values.
public init(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer)
where Value == Serializer.SerializedObject {
self.request = request
streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) }
}
/// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s.
///
/// - Returns: The `AnyPublisher` publishing the `Result` value.
public func result() -> AnyPublisher, Never> {
compactMap { stream in
switch stream.event {
case let .stream(result):
return result
// If the stream has completed with an error, send the error value downstream as a `.failure`.
case let .complete(completion):
return completion.error.map(Result.failure)
}
}
.eraseToAnyPublisher()
}
/// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the
/// `AFError` instance.
///
/// - Returns: The `AnyPublisher` publishing the stream.
public func value() -> AnyPublisher {
result().setFailureType(to: AFError.self).flatMap { $0.publisher }.eraseToAnyPublisher()
}
public func receive(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input {
subscriber.receive(subscription: Inner(request: request,
streamHandler: streamHandler,
downstream: subscriber))
}
private final class Inner: Subscription, Cancellable
where Downstream.Input == Output {
typealias Failure = Downstream.Failure
@Protected
private var downstream: Downstream?
private let request: DataStreamRequest
private let streamHandler: Handler
init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) {
self.request = request
self.streamHandler = streamHandler
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = downstream else { return }
self.downstream = nil
streamHandler { stream in
_ = downstream.receive(stream)
if case .complete = stream.event {
downstream.receive(completion: .finished)
}
}.resume()
}
func cancel() {
request.cancel()
downstream = nil
}
}
}
extension DataStreamRequest {
/// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`.
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishStream(using serializer: Serializer,
on queue: DispatchQueue = .main) -> DataStreamPublisher {
DataStreamPublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data`
/// unserialized.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher {
publishStream(using: PassthroughStreamSerializer(), on: queue)
}
/// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream
/// `Data` values into `String` values.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher {
publishStream(using: StringStreamSerializer(), on: queue)
}
/// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided
/// parameters to serialize stream `Data` values into the provided type.
///
/// - Parameters:
/// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default.
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default.
/// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization.
/// `PassthroughPreprocessor()` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishDecodable(type: T.Type = T.self,
queue: DispatchQueue = .main,
decoder: DataDecoder = JSONDecoder(),
preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher {
publishStream(using: DecodableStreamSerializer(decoder: decoder,
dataPreprocessor: preprocessor),
on: queue)
}
}
/// A Combine `Publisher` that publishes the `DownloadResponse` of the provided `DownloadRequest`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct DownloadResponsePublisher: Publisher {
public typealias Output = DownloadResponse
public typealias Failure = Never
private typealias Handler = (@escaping (_ response: DownloadResponse) -> Void) -> DownloadRequest
private let request: DownloadRequest
private let responseHandler: Handler
/// Creates an instance which will serialize responses using the provided `ResponseSerializer`.
///
/// - Parameters:
/// - request: `DownloadRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default.
/// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`.
public init(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer)
where Value == Serializer.SerializedObject {
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value.
///
/// - Parameters:
/// - request: `DownloadRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
/// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public init(_ request: DownloadRequest,
queue: DispatchQueue,
serializer: Serializer)
where Value == Serializer.SerializedObject {
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Publishes only the `Result` of the `DownloadResponse` value.
///
/// - Returns: The `AnyPublisher` publishing the `Result` value.
public func result() -> AnyPublisher, Never> {
map { $0.result }.eraseToAnyPublisher()
}
/// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance.
///
/// - Returns: The `AnyPublisher` publishing the stream.
public func value() -> AnyPublisher {
setFailureType(to: AFError.self).flatMap { $0.result.publisher }.eraseToAnyPublisher()
}
public func receive(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input {
subscriber.receive(subscription: Inner(request: request,
responseHandler: responseHandler,
downstream: subscriber))
}
private final class Inner: Subscription, Cancellable
where Downstream.Input == Output {
typealias Failure = Downstream.Failure
@Protected
private var downstream: Downstream?
private let request: DownloadRequest
private let responseHandler: Handler
init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) {
self.request = request
self.responseHandler = responseHandler
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = downstream else { return }
self.downstream = nil
responseHandler { response in
_ = downstream.receive(response)
downstream.receive(completion: .finished)
}.resume()
}
func cancel() {
request.cancel()
downstream = nil
}
}
}
extension DownloadRequest {
/// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk.
/// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher
where Serializer.SerializedObject == T {
DownloadResponsePublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and
/// `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk.
/// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishResponse(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher
where Serializer.SerializedObject == T {
DownloadResponsePublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the
/// response.
///
/// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher {
publishResponse(using: URLResponseSerializer(), on: queue)
}
/// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishData(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set = DataResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher {
publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding
/// will be determined by the server response, falling back to the default HTTP character
/// set, `ISO-8859-1`.
/// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishString(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
encoding: String.Encoding? = nil,
emptyResponseCodes: Set = StringResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher {
publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor,
encoding: encoding,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default.
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default.
/// - emptyResponseCodes: `Set` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishDecodable(type: T.Type = T.self,
queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DecodableResponseSerializer.defaultDataPreprocessor,
decoder: DataDecoder = JSONDecoder(),
emptyResponseCodes: Set = DecodableResponseSerializer.defaultEmptyResponseCodes,
emptyResponseMethods: Set = DecodableResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher {
publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
decoder: decoder,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyResponseMethods),
on: queue)
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
extension DownloadResponsePublisher where Value == URL? {
/// Creates an instance which publishes a `DownloadResponse` value without serialization.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public init(_ request: DownloadRequest, queue: DispatchQueue) {
self.request = request
responseHandler = { request.response(queue: queue, completionHandler: $0) }
}
}
extension DownloadRequest {
/// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing.
///
/// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher {
DownloadResponsePublisher(self, queue: queue)
}
}
#endif
================================================
FILE: Pods/Alamofire/Source/DispatchQueue+Alamofire.swift
================================================
//
// DispatchQueue+Alamofire.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Dispatch
import Foundation
extension DispatchQueue {
/// Execute the provided closure after a `TimeInterval`.
///
/// - Parameters:
/// - delay: `TimeInterval` to delay execution.
/// - closure: Closure to execute.
func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) {
asyncAfter(deadline: .now() + delay, execute: closure)
}
}
================================================
FILE: Pods/Alamofire/Source/EventMonitor.swift
================================================
//
// EventMonitor.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Protocol outlining the lifetime events inside Alamofire. It includes both events received from the various
/// `URLSession` delegate protocols as well as various events from the lifetime of `Request` and its subclasses.
public protocol EventMonitor {
/// The `DispatchQueue` onto which Alamofire's root `CompositeEventMonitor` will dispatch events. `.main` by default.
var queue: DispatchQueue { get }
// MARK: - URLSession Events
// MARK: URLSessionDelegate Events
/// Event called during `URLSessionDelegate`'s `urlSession(_:didBecomeInvalidWithError:)` method.
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?)
// MARK: URLSessionTaskDelegate Events
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didReceive:completionHandler:)` method.
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge)
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` method.
func urlSession(_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:needNewBodyStream:)` method.
func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask)
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` method.
func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest)
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didFinishCollecting:)` method.
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics)
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:task:didCompleteWithError:)` method.
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?)
/// Event called during `URLSessionTaskDelegate`'s `urlSession(_:taskIsWaitingForConnectivity:)` method.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask)
// MARK: URLSessionDataDelegate Events
/// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:didReceive:)` method.
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
/// Event called during `URLSessionDataDelegate`'s `urlSession(_:dataTask:willCacheResponse:completionHandler:)` method.
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse)
// MARK: URLSessionDownloadDelegate Events
/// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` method.
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
/// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)` method.
func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
/// Event called during `URLSessionDownloadDelegate`'s `urlSession(_:downloadTask:didFinishDownloadingTo:)` method.
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
// MARK: - Request Events
/// Event called when a `URLRequest` is first created for a `Request`. If a `RequestAdapter` is active, the
/// `URLRequest` will be adapted before being issued.
func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest)
/// Event called when the attempt to create a `URLRequest` from a `Request`'s original `URLRequestConvertible` value fails.
func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError)
/// Event called when a `RequestAdapter` adapts the `Request`'s initial `URLRequest`.
func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest)
/// Event called when a `RequestAdapter` fails to adapt the `Request`'s initial `URLRequest`.
func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError)
/// Event called when a final `URLRequest` is created for a `Request`.
func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest)
/// Event called when a `URLSessionTask` subclass instance is created for a `Request`.
func request(_ request: Request, didCreateTask task: URLSessionTask)
/// Event called when a `Request` receives a `URLSessionTaskMetrics` value.
func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics)
/// Event called when a `Request` fails due to an error created by Alamofire. e.g. When certificate pinning fails.
func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError)
/// Event called when a `Request`'s task completes, possibly with an error. A `Request` may receive this event
/// multiple times if it is retried.
func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?)
/// Event called when a `Request` is about to be retried.
func requestIsRetrying(_ request: Request)
/// Event called when a `Request` finishes and response serializers are being called.
func requestDidFinish(_ request: Request)
/// Event called when a `Request` receives a `resume` call.
func requestDidResume(_ request: Request)
/// Event called when a `Request`'s associated `URLSessionTask` is resumed.
func request(_ request: Request, didResumeTask task: URLSessionTask)
/// Event called when a `Request` receives a `suspend` call.
func requestDidSuspend(_ request: Request)
/// Event called when a `Request`'s associated `URLSessionTask` is suspended.
func request(_ request: Request, didSuspendTask task: URLSessionTask)
/// Event called when a `Request` receives a `cancel` call.
func requestDidCancel(_ request: Request)
/// Event called when a `Request`'s associated `URLSessionTask` is cancelled.
func request(_ request: Request, didCancelTask task: URLSessionTask)
// MARK: DataRequest Events
/// Event called when a `DataRequest` calls a `Validation`.
func request(_ request: DataRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
data: Data?,
withResult result: Request.ValidationResult)
/// Event called when a `DataRequest` creates a `DataResponse` value without calling a `ResponseSerializer`.
func request(_ request: DataRequest, didParseResponse response: DataResponse)
/// Event called when a `DataRequest` calls a `ResponseSerializer` and creates a generic `DataResponse`.
func request(_ request: DataRequest, didParseResponse response: DataResponse)
// MARK: DataStreamRequest Events
/// Event called when a `DataStreamRequest` calls a `Validation` closure.
///
/// - Parameters:
/// - request: `DataStreamRequest` which is calling the `Validation`.
/// - urlRequest: `URLRequest` of the request being validated.
/// - response: `HTTPURLResponse` of the request being validated.
/// - result: Produced `ValidationResult`.
func request(_ request: DataStreamRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
withResult result: Request.ValidationResult)
/// Event called when a `DataStreamSerializer` produces a value from streamed `Data`.
///
/// - Parameters:
/// - request: `DataStreamRequest` for which the value was serialized.
/// - result: `Result` of the serialization attempt.
func request(_ request: DataStreamRequest, didParseStream result: Result)
// MARK: UploadRequest Events
/// Event called when an `UploadRequest` creates its `Uploadable` value, indicating the type of upload it represents.
func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable)
/// Event called when an `UploadRequest` failed to create its `Uploadable` value due to an error.
func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError)
/// Event called when an `UploadRequest` provides the `InputStream` from its `Uploadable` value. This only occurs if
/// the `InputStream` does not wrap a `Data` value or file `URL`.
func request(_ request: UploadRequest, didProvideInputStream stream: InputStream)
// MARK: DownloadRequest Events
/// Event called when a `DownloadRequest`'s `URLSessionDownloadTask` finishes and the temporary file has been moved.
func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result)
/// Event called when a `DownloadRequest`'s `Destination` closure is called and creates the destination URL the
/// downloaded file will be moved to.
func request(_ request: DownloadRequest, didCreateDestinationURL url: URL)
/// Event called when a `DownloadRequest` calls a `Validation`.
func request(_ request: DownloadRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
fileURL: URL?,
withResult result: Request.ValidationResult)
/// Event called when a `DownloadRequest` creates a `DownloadResponse` without calling a `ResponseSerializer`.
func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse)
/// Event called when a `DownloadRequest` calls a `DownloadResponseSerializer` and creates a generic `DownloadResponse`
func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse)
}
extension EventMonitor {
/// The default queue on which `CompositeEventMonitor`s will call the `EventMonitor` methods. `.main` by default.
public var queue: DispatchQueue { .main }
// MARK: Default Implementations
public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge) {}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) {}
public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest) {}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didFinishCollecting metrics: URLSessionTaskMetrics) {}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {}
public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {}
public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse) {}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64) {}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {}
public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {}
public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {}
public func request(_ request: Request,
didAdaptInitialRequest initialRequest: URLRequest,
to adaptedRequest: URLRequest) {}
public func request(_ request: Request,
didFailToAdaptURLRequest initialRequest: URLRequest,
withError error: AFError) {}
public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {}
public func request(_ request: Request, didCreateTask task: URLSessionTask) {}
public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {}
public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {}
public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {}
public func requestIsRetrying(_ request: Request) {}
public func requestDidFinish(_ request: Request) {}
public func requestDidResume(_ request: Request) {}
public func request(_ request: Request, didResumeTask task: URLSessionTask) {}
public func requestDidSuspend(_ request: Request) {}
public func request(_ request: Request, didSuspendTask task: URLSessionTask) {}
public func requestDidCancel(_ request: Request) {}
public func request(_ request: Request, didCancelTask task: URLSessionTask) {}
public func request(_ request: DataRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
data: Data?,
withResult result: Request.ValidationResult) {}
public func request(_ request: DataRequest, didParseResponse response: DataResponse) {}
public func request(_ request: DataRequest, didParseResponse response: DataResponse) {}
public func request(_ request: DataStreamRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
withResult result: Request.ValidationResult) {}
public func request(_ request: DataStreamRequest, didParseStream result: Result) {}
public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {}
public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {}
public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {}
public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {}
public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {}
public func request(_ request: DownloadRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
fileURL: URL?,
withResult result: Request.ValidationResult) {}
public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {}
public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {}
}
/// An `EventMonitor` which can contain multiple `EventMonitor`s and calls their methods on their queues.
public final class CompositeEventMonitor: EventMonitor {
public let queue = DispatchQueue(label: "org.alamofire.compositeEventMonitor", qos: .utility)
let monitors: [EventMonitor]
init(monitors: [EventMonitor]) {
self.monitors = monitors
}
func performEvent(_ event: @escaping (EventMonitor) -> Void) {
queue.async {
for monitor in self.monitors {
monitor.queue.async { event(monitor) }
}
}
}
public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
performEvent { $0.urlSession(session, didBecomeInvalidWithError: error) }
}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge) {
performEvent { $0.urlSession(session, task: task, didReceive: challenge) }
}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) {
performEvent {
$0.urlSession(session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
public func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
performEvent {
$0.urlSession(session, taskNeedsNewBodyStream: task)
}
}
public func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest) {
performEvent {
$0.urlSession(session,
task: task,
willPerformHTTPRedirection: response,
newRequest: request)
}
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
performEvent { $0.urlSession(session, task: task, didFinishCollecting: metrics) }
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
performEvent { $0.urlSession(session, task: task, didCompleteWithError: error) }
}
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
performEvent { $0.urlSession(session, taskIsWaitingForConnectivity: task) }
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
performEvent { $0.urlSession(session, dataTask: dataTask, didReceive: data) }
}
public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse) {
performEvent { $0.urlSession(session, dataTask: dataTask, willCacheResponse: proposedResponse) }
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64) {
performEvent {
$0.urlSession(session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes)
}
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
performEvent {
$0.urlSession(session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
}
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL) {
performEvent { $0.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) }
}
public func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {
performEvent { $0.request(request, didCreateInitialURLRequest: urlRequest) }
}
public func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {
performEvent { $0.request(request, didFailToCreateURLRequestWithError: error) }
}
public func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
performEvent { $0.request(request, didAdaptInitialRequest: initialRequest, to: adaptedRequest) }
}
public func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) {
performEvent { $0.request(request, didFailToAdaptURLRequest: initialRequest, withError: error) }
}
public func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
performEvent { $0.request(request, didCreateURLRequest: urlRequest) }
}
public func request(_ request: Request, didCreateTask task: URLSessionTask) {
performEvent { $0.request(request, didCreateTask: task) }
}
public func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
performEvent { $0.request(request, didGatherMetrics: metrics) }
}
public func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {
performEvent { $0.request(request, didFailTask: task, earlyWithError: error) }
}
public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
performEvent { $0.request(request, didCompleteTask: task, with: error) }
}
public func requestIsRetrying(_ request: Request) {
performEvent { $0.requestIsRetrying(request) }
}
public func requestDidFinish(_ request: Request) {
performEvent { $0.requestDidFinish(request) }
}
public func requestDidResume(_ request: Request) {
performEvent { $0.requestDidResume(request) }
}
public func request(_ request: Request, didResumeTask task: URLSessionTask) {
performEvent { $0.request(request, didResumeTask: task) }
}
public func requestDidSuspend(_ request: Request) {
performEvent { $0.requestDidSuspend(request) }
}
public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
performEvent { $0.request(request, didSuspendTask: task) }
}
public func requestDidCancel(_ request: Request) {
performEvent { $0.requestDidCancel(request) }
}
public func request(_ request: Request, didCancelTask task: URLSessionTask) {
performEvent { $0.request(request, didCancelTask: task) }
}
public func request(_ request: DataRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
data: Data?,
withResult result: Request.ValidationResult) {
performEvent { $0.request(request,
didValidateRequest: urlRequest,
response: response,
data: data,
withResult: result)
}
}
public func request(_ request: DataRequest, didParseResponse response: DataResponse) {
performEvent { $0.request(request, didParseResponse: response) }
}
public func request(_ request: DataRequest, didParseResponse response: DataResponse) {
performEvent { $0.request(request, didParseResponse: response) }
}
public func request(_ request: DataStreamRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
withResult result: Request.ValidationResult) {
performEvent { $0.request(request,
didValidateRequest: urlRequest,
response: response,
withResult: result)
}
}
public func request(_ request: DataStreamRequest, didParseStream result: Result) {
performEvent { $0.request(request, didParseStream: result) }
}
public func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
performEvent { $0.request(request, didCreateUploadable: uploadable) }
}
public func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {
performEvent { $0.request(request, didFailToCreateUploadableWithError: error) }
}
public func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
performEvent { $0.request(request, didProvideInputStream: stream) }
}
public func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {
performEvent { $0.request(request, didFinishDownloadingUsing: task, with: result) }
}
public func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
performEvent { $0.request(request, didCreateDestinationURL: url) }
}
public func request(_ request: DownloadRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
fileURL: URL?,
withResult result: Request.ValidationResult) {
performEvent { $0.request(request,
didValidateRequest: urlRequest,
response: response,
fileURL: fileURL,
withResult: result) }
}
public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {
performEvent { $0.request(request, didParseResponse: response) }
}
public func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {
performEvent { $0.request(request, didParseResponse: response) }
}
}
/// `EventMonitor` that allows optional closures to be set to receive events.
open class ClosureEventMonitor: EventMonitor {
/// Closure called on the `urlSession(_:didBecomeInvalidWithError:)` event.
open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
/// Closure called on the `urlSession(_:task:didReceive:completionHandler:)`.
open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> Void)?
/// Closure that receives `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)` event.
open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
/// Closure called on the `urlSession(_:task:needNewBodyStream:)` event.
open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> Void)?
/// Closure called on the `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` event.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> Void)?
/// Closure called on the `urlSession(_:task:didFinishCollecting:)` event.
open var taskDidFinishCollectingMetrics: ((URLSession, URLSessionTask, URLSessionTaskMetrics) -> Void)?
/// Closure called on the `urlSession(_:task:didCompleteWithError:)` event.
open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
/// Closure called on the `urlSession(_:taskIsWaitingForConnectivity:)` event.
open var taskIsWaitingForConnectivity: ((URLSession, URLSessionTask) -> Void)?
/// Closure that receives the `urlSession(_:dataTask:didReceive:)` event.
open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
/// Closure called on the `urlSession(_:dataTask:willCacheResponse:completionHandler:)` event.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> Void)?
/// Closure called on the `urlSession(_:downloadTask:didFinishDownloadingTo:)` event.
open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
/// Closure called on the `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`
/// event.
open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Closure called on the `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)` event.
open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: - Request Events
/// Closure called on the `request(_:didCreateInitialURLRequest:)` event.
open var requestDidCreateInitialURLRequest: ((Request, URLRequest) -> Void)?
/// Closure called on the `request(_:didFailToCreateURLRequestWithError:)` event.
open var requestDidFailToCreateURLRequestWithError: ((Request, AFError) -> Void)?
/// Closure called on the `request(_:didAdaptInitialRequest:to:)` event.
open var requestDidAdaptInitialRequestToAdaptedRequest: ((Request, URLRequest, URLRequest) -> Void)?
/// Closure called on the `request(_:didFailToAdaptURLRequest:withError:)` event.
open var requestDidFailToAdaptURLRequestWithError: ((Request, URLRequest, AFError) -> Void)?
/// Closure called on the `request(_:didCreateURLRequest:)` event.
open var requestDidCreateURLRequest: ((Request, URLRequest) -> Void)?
/// Closure called on the `request(_:didCreateTask:)` event.
open var requestDidCreateTask: ((Request, URLSessionTask) -> Void)?
/// Closure called on the `request(_:didGatherMetrics:)` event.
open var requestDidGatherMetrics: ((Request, URLSessionTaskMetrics) -> Void)?
/// Closure called on the `request(_:didFailTask:earlyWithError:)` event.
open var requestDidFailTaskEarlyWithError: ((Request, URLSessionTask, AFError) -> Void)?
/// Closure called on the `request(_:didCompleteTask:with:)` event.
open var requestDidCompleteTaskWithError: ((Request, URLSessionTask, AFError?) -> Void)?
/// Closure called on the `requestIsRetrying(_:)` event.
open var requestIsRetrying: ((Request) -> Void)?
/// Closure called on the `requestDidFinish(_:)` event.
open var requestDidFinish: ((Request) -> Void)?
/// Closure called on the `requestDidResume(_:)` event.
open var requestDidResume: ((Request) -> Void)?
/// Closure called on the `request(_:didResumeTask:)` event.
open var requestDidResumeTask: ((Request, URLSessionTask) -> Void)?
/// Closure called on the `requestDidSuspend(_:)` event.
open var requestDidSuspend: ((Request) -> Void)?
/// Closure called on the `request(_:didSuspendTask:)` event.
open var requestDidSuspendTask: ((Request, URLSessionTask) -> Void)?
/// Closure called on the `requestDidCancel(_:)` event.
open var requestDidCancel: ((Request) -> Void)?
/// Closure called on the `request(_:didCancelTask:)` event.
open var requestDidCancelTask: ((Request, URLSessionTask) -> Void)?
/// Closure called on the `request(_:didValidateRequest:response:data:withResult:)` event.
open var requestDidValidateRequestResponseDataWithResult: ((DataRequest, URLRequest?, HTTPURLResponse, Data?, Request.ValidationResult) -> Void)?
/// Closure called on the `request(_:didParseResponse:)` event.
open var requestDidParseResponse: ((DataRequest, DataResponse) -> Void)?
/// Closure called on the `request(_:didValidateRequest:response:withResult:)` event.
open var requestDidValidateRequestResponseWithResult: ((DataStreamRequest, URLRequest?, HTTPURLResponse, Request.ValidationResult) -> Void)?
/// Closure called on the `request(_:didCreateUploadable:)` event.
open var requestDidCreateUploadable: ((UploadRequest, UploadRequest.Uploadable) -> Void)?
/// Closure called on the `request(_:didFailToCreateUploadableWithError:)` event.
open var requestDidFailToCreateUploadableWithError: ((UploadRequest, AFError) -> Void)?
/// Closure called on the `request(_:didProvideInputStream:)` event.
open var requestDidProvideInputStream: ((UploadRequest, InputStream) -> Void)?
/// Closure called on the `request(_:didFinishDownloadingUsing:with:)` event.
open var requestDidFinishDownloadingUsingTaskWithResult: ((DownloadRequest, URLSessionTask, Result) -> Void)?
/// Closure called on the `request(_:didCreateDestinationURL:)` event.
open var requestDidCreateDestinationURL: ((DownloadRequest, URL) -> Void)?
/// Closure called on the `request(_:didValidateRequest:response:temporaryURL:destinationURL:withResult:)` event.
open var requestDidValidateRequestResponseFileURLWithResult: ((DownloadRequest, URLRequest?, HTTPURLResponse, URL?, Request.ValidationResult) -> Void)?
/// Closure called on the `request(_:didParseResponse:)` event.
open var requestDidParseDownloadResponse: ((DownloadRequest, DownloadResponse) -> Void)?
public let queue: DispatchQueue
/// Creates an instance using the provided queue.
///
/// - Parameter queue: `DispatchQueue` on which events will fired. `.main` by default.
public init(queue: DispatchQueue = .main) {
self.queue = queue
}
open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
sessionDidBecomeInvalidWithError?(session, error)
}
open func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge) {
taskDidReceiveChallenge?(session, task, challenge)
}
open func urlSession(_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64) {
taskDidSendBodyData?(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
open func urlSession(_ session: URLSession, taskNeedsNewBodyStream task: URLSessionTask) {
taskNeedNewBodyStream?(session, task)
}
open func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest) {
taskWillPerformHTTPRedirection?(session, task, response, request)
}
open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
taskDidFinishCollectingMetrics?(session, task, metrics)
}
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
taskDidComplete?(session, task, error)
}
open func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
taskIsWaitingForConnectivity?(session, task)
}
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
dataTaskDidReceiveData?(session, dataTask, data)
}
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse) {
dataTaskWillCacheResponse?(session, dataTask, proposedResponse)
}
open func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64) {
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
open func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64) {
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
open func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
// MARK: Request Events
open func request(_ request: Request, didCreateInitialURLRequest urlRequest: URLRequest) {
requestDidCreateInitialURLRequest?(request, urlRequest)
}
open func request(_ request: Request, didFailToCreateURLRequestWithError error: AFError) {
requestDidFailToCreateURLRequestWithError?(request, error)
}
open func request(_ request: Request, didAdaptInitialRequest initialRequest: URLRequest, to adaptedRequest: URLRequest) {
requestDidAdaptInitialRequestToAdaptedRequest?(request, initialRequest, adaptedRequest)
}
open func request(_ request: Request, didFailToAdaptURLRequest initialRequest: URLRequest, withError error: AFError) {
requestDidFailToAdaptURLRequestWithError?(request, initialRequest, error)
}
open func request(_ request: Request, didCreateURLRequest urlRequest: URLRequest) {
requestDidCreateURLRequest?(request, urlRequest)
}
open func request(_ request: Request, didCreateTask task: URLSessionTask) {
requestDidCreateTask?(request, task)
}
open func request(_ request: Request, didGatherMetrics metrics: URLSessionTaskMetrics) {
requestDidGatherMetrics?(request, metrics)
}
open func request(_ request: Request, didFailTask task: URLSessionTask, earlyWithError error: AFError) {
requestDidFailTaskEarlyWithError?(request, task, error)
}
open func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
requestDidCompleteTaskWithError?(request, task, error)
}
open func requestIsRetrying(_ request: Request) {
requestIsRetrying?(request)
}
open func requestDidFinish(_ request: Request) {
requestDidFinish?(request)
}
open func requestDidResume(_ request: Request) {
requestDidResume?(request)
}
public func request(_ request: Request, didResumeTask task: URLSessionTask) {
requestDidResumeTask?(request, task)
}
open func requestDidSuspend(_ request: Request) {
requestDidSuspend?(request)
}
public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
requestDidSuspendTask?(request, task)
}
open func requestDidCancel(_ request: Request) {
requestDidCancel?(request)
}
public func request(_ request: Request, didCancelTask task: URLSessionTask) {
requestDidCancelTask?(request, task)
}
open func request(_ request: DataRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
data: Data?,
withResult result: Request.ValidationResult) {
requestDidValidateRequestResponseDataWithResult?(request, urlRequest, response, data, result)
}
open func request(_ request: DataRequest, didParseResponse response: DataResponse) {
requestDidParseResponse?(request, response)
}
public func request(_ request: DataStreamRequest, didValidateRequest urlRequest: URLRequest?, response: HTTPURLResponse, withResult result: Request.ValidationResult) {
requestDidValidateRequestResponseWithResult?(request, urlRequest, response, result)
}
open func request(_ request: UploadRequest, didCreateUploadable uploadable: UploadRequest.Uploadable) {
requestDidCreateUploadable?(request, uploadable)
}
open func request(_ request: UploadRequest, didFailToCreateUploadableWithError error: AFError) {
requestDidFailToCreateUploadableWithError?(request, error)
}
open func request(_ request: UploadRequest, didProvideInputStream stream: InputStream) {
requestDidProvideInputStream?(request, stream)
}
open func request(_ request: DownloadRequest, didFinishDownloadingUsing task: URLSessionTask, with result: Result) {
requestDidFinishDownloadingUsingTaskWithResult?(request, task, result)
}
open func request(_ request: DownloadRequest, didCreateDestinationURL url: URL) {
requestDidCreateDestinationURL?(request, url)
}
open func request(_ request: DownloadRequest,
didValidateRequest urlRequest: URLRequest?,
response: HTTPURLResponse,
fileURL: URL?,
withResult result: Request.ValidationResult) {
requestDidValidateRequestResponseFileURLWithResult?(request,
urlRequest,
response,
fileURL,
result)
}
open func request(_ request: DownloadRequest, didParseResponse response: DownloadResponse) {
requestDidParseDownloadResponse?(request, response)
}
}
================================================
FILE: Pods/Alamofire/Source/HTTPHeaders.swift
================================================
//
// HTTPHeaders.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// An order-preserving and case-insensitive representation of HTTP headers.
public struct HTTPHeaders {
private var headers: [HTTPHeader] = []
/// Creates an empty instance.
public init() {}
/// Creates an instance from an array of `HTTPHeader`s. Duplicate case-insensitive names are collapsed into the last
/// name and value encountered.
public init(_ headers: [HTTPHeader]) {
self.init()
headers.forEach { update($0) }
}
/// Creates an instance from a `[String: String]`. Duplicate case-insensitive names are collapsed into the last name
/// and value encountered.
public init(_ dictionary: [String: String]) {
self.init()
dictionary.forEach { update(HTTPHeader(name: $0.key, value: $0.value)) }
}
/// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`.
///
/// - Parameters:
/// - name: The `HTTPHeader` name.
/// - value: The `HTTPHeader value.
public mutating func add(name: String, value: String) {
update(HTTPHeader(name: name, value: value))
}
/// Case-insensitively updates or appends the provided `HTTPHeader` into the instance.
///
/// - Parameter header: The `HTTPHeader` to update or append.
public mutating func add(_ header: HTTPHeader) {
update(header)
}
/// Case-insensitively updates or appends an `HTTPHeader` into the instance using the provided `name` and `value`.
///
/// - Parameters:
/// - name: The `HTTPHeader` name.
/// - value: The `HTTPHeader value.
public mutating func update(name: String, value: String) {
update(HTTPHeader(name: name, value: value))
}
/// Case-insensitively updates or appends the provided `HTTPHeader` into the instance.
///
/// - Parameter header: The `HTTPHeader` to update or append.
public mutating func update(_ header: HTTPHeader) {
guard let index = headers.index(of: header.name) else {
headers.append(header)
return
}
headers.replaceSubrange(index...index, with: [header])
}
/// Case-insensitively removes an `HTTPHeader`, if it exists, from the instance.
///
/// - Parameter name: The name of the `HTTPHeader` to remove.
public mutating func remove(name: String) {
guard let index = headers.index(of: name) else { return }
headers.remove(at: index)
}
/// Sort the current instance by header name, case insensitively.
public mutating func sort() {
headers.sort { $0.name.lowercased() < $1.name.lowercased() }
}
/// Returns an instance sorted by header name.
///
/// - Returns: A copy of the current instance sorted by name.
public func sorted() -> HTTPHeaders {
var headers = self
headers.sort()
return headers
}
/// Case-insensitively find a header's value by name.
///
/// - Parameter name: The name of the header to search for, case-insensitively.
///
/// - Returns: The value of header, if it exists.
public func value(for name: String) -> String? {
guard let index = headers.index(of: name) else { return nil }
return headers[index].value
}
/// Case-insensitively access the header with the given name.
///
/// - Parameter name: The name of the header.
public subscript(_ name: String) -> String? {
get { value(for: name) }
set {
if let value = newValue {
update(name: name, value: value)
} else {
remove(name: name)
}
}
}
/// The dictionary representation of all headers.
///
/// This representation does not preserve the current order of the instance.
public var dictionary: [String: String] {
let namesAndValues = headers.map { ($0.name, $0.value) }
return Dictionary(namesAndValues, uniquingKeysWith: { _, last in last })
}
}
extension HTTPHeaders: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, String)...) {
self.init()
elements.forEach { update(name: $0.0, value: $0.1) }
}
}
extension HTTPHeaders: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: HTTPHeader...) {
self.init(elements)
}
}
extension HTTPHeaders: Sequence {
public func makeIterator() -> IndexingIterator<[HTTPHeader]> {
headers.makeIterator()
}
}
extension HTTPHeaders: Collection {
public var startIndex: Int {
headers.startIndex
}
public var endIndex: Int {
headers.endIndex
}
public subscript(position: Int) -> HTTPHeader {
headers[position]
}
public func index(after i: Int) -> Int {
headers.index(after: i)
}
}
extension HTTPHeaders: CustomStringConvertible {
public var description: String {
headers.map { $0.description }
.joined(separator: "\n")
}
}
// MARK: - HTTPHeader
/// A representation of a single HTTP header's name / value pair.
public struct HTTPHeader: Hashable {
/// Name of the header.
public let name: String
/// Value of the header.
public let value: String
/// Creates an instance from the given `name` and `value`.
///
/// - Parameters:
/// - name: The name of the header.
/// - value: The value of the header.
public init(name: String, value: String) {
self.name = name
self.value = value
}
}
extension HTTPHeader: CustomStringConvertible {
public var description: String {
"\(name): \(value)"
}
}
extension HTTPHeader {
/// Returns an `Accept` header.
///
/// - Parameter value: The `Accept` value.
/// - Returns: The header.
public static func accept(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Accept", value: value)
}
/// Returns an `Accept-Charset` header.
///
/// - Parameter value: The `Accept-Charset` value.
/// - Returns: The header.
public static func acceptCharset(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Accept-Charset", value: value)
}
/// Returns an `Accept-Language` header.
///
/// Alamofire offers a default Accept-Language header that accumulates and encodes the system's preferred languages.
/// Use `HTTPHeader.defaultAcceptLanguage`.
///
/// - Parameter value: The `Accept-Language` value.
///
/// - Returns: The header.
public static func acceptLanguage(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Accept-Language", value: value)
}
/// Returns an `Accept-Encoding` header.
///
/// Alamofire offers a default accept encoding value that provides the most common values. Use
/// `HTTPHeader.defaultAcceptEncoding`.
///
/// - Parameter value: The `Accept-Encoding` value.
///
/// - Returns: The header
public static func acceptEncoding(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Accept-Encoding", value: value)
}
/// Returns a `Basic` `Authorization` header using the `username` and `password` provided.
///
/// - Parameters:
/// - username: The username of the header.
/// - password: The password of the header.
///
/// - Returns: The header.
public static func authorization(username: String, password: String) -> HTTPHeader {
let credential = Data("\(username):\(password)".utf8).base64EncodedString()
return authorization("Basic \(credential)")
}
/// Returns a `Bearer` `Authorization` header using the `bearerToken` provided
///
/// - Parameter bearerToken: The bearer token.
///
/// - Returns: The header.
public static func authorization(bearerToken: String) -> HTTPHeader {
authorization("Bearer \(bearerToken)")
}
/// Returns an `Authorization` header.
///
/// Alamofire provides built-in methods to produce `Authorization` headers. For a Basic `Authorization` header use
/// `HTTPHeader.authorization(username:password:)`. For a Bearer `Authorization` header, use
/// `HTTPHeader.authorization(bearerToken:)`.
///
/// - Parameter value: The `Authorization` value.
///
/// - Returns: The header.
public static func authorization(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Authorization", value: value)
}
/// Returns a `Content-Disposition` header.
///
/// - Parameter value: The `Content-Disposition` value.
///
/// - Returns: The header.
public static func contentDisposition(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Content-Disposition", value: value)
}
/// Returns a `Content-Type` header.
///
/// All Alamofire `ParameterEncoding`s and `ParameterEncoder`s set the `Content-Type` of the request, so it may not be necessary to manually
/// set this value.
///
/// - Parameter value: The `Content-Type` value.
///
/// - Returns: The header.
public static func contentType(_ value: String) -> HTTPHeader {
HTTPHeader(name: "Content-Type", value: value)
}
/// Returns a `User-Agent` header.
///
/// - Parameter value: The `User-Agent` value.
///
/// - Returns: The header.
public static func userAgent(_ value: String) -> HTTPHeader {
HTTPHeader(name: "User-Agent", value: value)
}
}
extension Array where Element == HTTPHeader {
/// Case-insensitively finds the index of an `HTTPHeader` with the provided name, if it exists.
func index(of name: String) -> Int? {
let lowercasedName = name.lowercased()
return firstIndex { $0.name.lowercased() == lowercasedName }
}
}
// MARK: - Defaults
extension HTTPHeaders {
/// The default set of `HTTPHeaders` used by Alamofire. Includes `Accept-Encoding`, `Accept-Language`, and
/// `User-Agent`.
public static let `default`: HTTPHeaders = [.defaultAcceptEncoding,
.defaultAcceptLanguage,
.defaultUserAgent]
}
extension HTTPHeader {
/// Returns Alamofire's default `Accept-Encoding` header, appropriate for the encodings supported by particular OS
/// versions.
///
/// See the [Accept-Encoding HTTP header documentation](https://tools.ietf.org/html/rfc7230#section-4.2.3) .
public static let defaultAcceptEncoding: HTTPHeader = {
let encodings: [String]
if #available(iOS 11.0, macOS 10.13, tvOS 11.0, watchOS 4.0, *) {
encodings = ["br", "gzip", "deflate"]
} else {
encodings = ["gzip", "deflate"]
}
return .acceptEncoding(encodings.qualityEncoded())
}()
/// Returns Alamofire's default `Accept-Language` header, generated by querying `Locale` for the user's
/// `preferredLanguages`.
///
/// See the [Accept-Language HTTP header documentation](https://tools.ietf.org/html/rfc7231#section-5.3.5).
public static let defaultAcceptLanguage: HTTPHeader = {
.acceptLanguage(Locale.preferredLanguages.prefix(6).qualityEncoded())
}()
/// Returns Alamofire's default `User-Agent` header.
///
/// See the [User-Agent header documentation](https://tools.ietf.org/html/rfc7231#section-5.5.3).
///
/// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) Alamofire/5.0.0`
public static let defaultUserAgent: HTTPHeader = {
let info = Bundle.main.infoDictionary
let executable = (info?[kCFBundleExecutableKey as String] as? String) ??
(ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ??
"Unknown"
let bundle = info?[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info?["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info?[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let version = ProcessInfo.processInfo.operatingSystemVersion
let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
let osName: String = {
#if os(iOS)
#if targetEnvironment(macCatalyst)
return "macOS(Catalyst)"
#else
return "iOS"
#endif
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(macOS)
return "macOS"
#elseif os(Linux)
return "Linux"
#elseif os(Windows)
return "Windows"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion = "Alamofire/\(version)"
let userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
return .userAgent(userAgent)
}()
}
extension Collection where Element == String {
func qualityEncoded() -> String {
enumerated().map { index, encoding in
let quality = 1.0 - (Double(index) * 0.1)
return "\(encoding);q=\(quality)"
}.joined(separator: ", ")
}
}
// MARK: - System Type Extensions
extension URLRequest {
/// Returns `allHTTPHeaderFields` as `HTTPHeaders`.
public var headers: HTTPHeaders {
get { allHTTPHeaderFields.map(HTTPHeaders.init) ?? HTTPHeaders() }
set { allHTTPHeaderFields = newValue.dictionary }
}
}
extension HTTPURLResponse {
/// Returns `allHeaderFields` as `HTTPHeaders`.
public var headers: HTTPHeaders {
(allHeaderFields as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders()
}
}
extension URLSessionConfiguration {
/// Returns `httpAdditionalHeaders` as `HTTPHeaders`.
public var headers: HTTPHeaders {
get { (httpAdditionalHeaders as? [String: String]).map(HTTPHeaders.init) ?? HTTPHeaders() }
set { httpAdditionalHeaders = newValue.dictionary }
}
}
================================================
FILE: Pods/Alamofire/Source/HTTPMethod.swift
================================================
//
// HTTPMethod.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
/// Type representing HTTP methods. Raw `String` value is stored and compared case-sensitively, so
/// `HTTPMethod.get != HTTPMethod(rawValue: "get")`.
///
/// See https://tools.ietf.org/html/rfc7231#section-4.3
public struct HTTPMethod: RawRepresentable, Equatable, Hashable {
/// `CONNECT` method.
public static let connect = HTTPMethod(rawValue: "CONNECT")
/// `DELETE` method.
public static let delete = HTTPMethod(rawValue: "DELETE")
/// `GET` method.
public static let get = HTTPMethod(rawValue: "GET")
/// `HEAD` method.
public static let head = HTTPMethod(rawValue: "HEAD")
/// `OPTIONS` method.
public static let options = HTTPMethod(rawValue: "OPTIONS")
/// `PATCH` method.
public static let patch = HTTPMethod(rawValue: "PATCH")
/// `POST` method.
public static let post = HTTPMethod(rawValue: "POST")
/// `PUT` method.
public static let put = HTTPMethod(rawValue: "PUT")
/// `TRACE` method.
public static let trace = HTTPMethod(rawValue: "TRACE")
public let rawValue: String
public init(rawValue: String) {
self.rawValue = rawValue
}
}
================================================
FILE: Pods/Alamofire/Source/MultipartFormData.swift
================================================
//
// MultipartFormData.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
import MobileCoreServices
#elseif os(macOS)
import CoreServices
#endif
/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode
/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead
/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the
/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for
/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset.
///
/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well
/// and the w3 form documentation.
///
/// - https://www.ietf.org/rfc/rfc2388.txt
/// - https://www.ietf.org/rfc/rfc2045.txt
/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13
open class MultipartFormData {
// MARK: - Helper Types
enum EncodingCharacters {
static let crlf = "\r\n"
}
enum BoundaryGenerator {
enum BoundaryType {
case initial, encapsulated, final
}
static func randomBoundary() -> String {
let first = UInt32.random(in: UInt32.min...UInt32.max)
let second = UInt32.random(in: UInt32.min...UInt32.max)
return String(format: "alamofire.boundary.%08x%08x", first, second)
}
static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data {
let boundaryText: String
switch boundaryType {
case .initial:
boundaryText = "--\(boundary)\(EncodingCharacters.crlf)"
case .encapsulated:
boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)"
case .final:
boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)"
}
return Data(boundaryText.utf8)
}
}
class BodyPart {
let headers: HTTPHeaders
let bodyStream: InputStream
let bodyContentLength: UInt64
var hasInitialBoundary = false
var hasFinalBoundary = false
init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) {
self.headers = headers
self.bodyStream = bodyStream
self.bodyContentLength = bodyContentLength
}
}
// MARK: - Properties
/// Default memory threshold used when encoding `MultipartFormData`, in bytes.
public static let encodingMemoryThreshold: UInt64 = 10_000_000
/// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`.
open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)"
/// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries.
public var contentLength: UInt64 { bodyParts.reduce(0) { $0 + $1.bodyContentLength } }
/// The boundary used to separate the body parts in the encoded form data.
public let boundary: String
let fileManager: FileManager
private var bodyParts: [BodyPart]
private var bodyPartError: AFError?
private let streamBufferSize: Int
// MARK: - Lifecycle
/// Creates an instance.
///
/// - Parameters:
/// - fileManager: `FileManager` to use for file operations, if needed.
/// - boundary: Boundary `String` used to separate body parts.
public init(fileManager: FileManager = .default, boundary: String? = nil) {
self.fileManager = fileManager
self.boundary = boundary ?? BoundaryGenerator.randomBoundary()
bodyParts = []
//
// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more
// information, please refer to the following article:
// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html
//
streamBufferSize = 1024
}
// MARK: - Body Parts
/// Creates a body part from the data and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
/// - `Content-Type: #{mimeType}` (HTTP Header)
/// - Encoded file data
/// - Multipart form boundary
///
/// - Parameters:
/// - data: `Data` to encoding into the instance.
/// - name: Name to associate with the `Data` in the `Content-Disposition` HTTP header.
/// - fileName: Filename to associate with the `Data` in the `Content-Disposition` HTTP header.
/// - mimeType: MIME type to associate with the data in the `Content-Type` HTTP header.
public func append(_ data: Data, withName name: String, fileName: String? = nil, mimeType: String? = nil) {
let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
let stream = InputStream(data: data)
let length = UInt64(data.count)
append(stream, withLength: length, headers: headers)
}
/// Creates a body part from the file and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header)
/// - `Content-Type: #{generated mimeType}` (HTTP Header)
/// - Encoded file data
/// - Multipart form boundary
///
/// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the
/// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the
/// system associated MIME type.
///
/// - Parameters:
/// - fileURL: `URL` of the file whose content will be encoded into the instance.
/// - name: Name to associate with the file content in the `Content-Disposition` HTTP header.
public func append(_ fileURL: URL, withName name: String) {
let fileName = fileURL.lastPathComponent
let pathExtension = fileURL.pathExtension
if !fileName.isEmpty && !pathExtension.isEmpty {
let mime = mimeType(forPathExtension: pathExtension)
append(fileURL, withName: name, fileName: fileName, mimeType: mime)
} else {
setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL))
}
}
/// Creates a body part from the file and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header)
/// - Content-Type: #{mimeType} (HTTP Header)
/// - Encoded file data
/// - Multipart form boundary
///
/// - Parameters:
/// - fileURL: `URL` of the file whose content will be encoded into the instance.
/// - name: Name to associate with the file content in the `Content-Disposition` HTTP header.
/// - fileName: Filename to associate with the file content in the `Content-Disposition` HTTP header.
/// - mimeType: MIME type to associate with the file content in the `Content-Type` HTTP header.
public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) {
let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
//============================================================
// Check 1 - is file URL?
//============================================================
guard fileURL.isFileURL else {
setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL))
return
}
//============================================================
// Check 2 - is file URL reachable?
//============================================================
do {
let isReachable = try fileURL.checkPromisedItemIsReachable()
guard isReachable else {
setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL))
return
}
} catch {
setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error))
return
}
//============================================================
// Check 3 - is file URL a directory?
//============================================================
var isDirectory: ObjCBool = false
let path = fileURL.path
guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else {
setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL))
return
}
//============================================================
// Check 4 - can the file size be extracted?
//============================================================
let bodyContentLength: UInt64
do {
guard let fileSize = try fileManager.attributesOfItem(atPath: path)[.size] as? NSNumber else {
setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL))
return
}
bodyContentLength = fileSize.uint64Value
} catch {
setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error))
return
}
//============================================================
// Check 5 - can a stream be created from file URL?
//============================================================
guard let stream = InputStream(url: fileURL) else {
setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL))
return
}
append(stream, withLength: bodyContentLength, headers: headers)
}
/// Creates a body part from the stream and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header)
/// - `Content-Type: #{mimeType}` (HTTP Header)
/// - Encoded stream data
/// - Multipart form boundary
///
/// - Parameters:
/// - stream: `InputStream` to encode into the instance.
/// - length: Length, in bytes, of the stream.
/// - name: Name to associate with the stream content in the `Content-Disposition` HTTP header.
/// - fileName: Filename to associate with the stream content in the `Content-Disposition` HTTP header.
/// - mimeType: MIME type to associate with the stream content in the `Content-Type` HTTP header.
public func append(_ stream: InputStream,
withLength length: UInt64,
name: String,
fileName: String,
mimeType: String) {
let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType)
append(stream, withLength: length, headers: headers)
}
/// Creates a body part with the stream, length, and headers and appends it to the instance.
///
/// The body part data will be encoded using the following format:
///
/// - HTTP headers
/// - Encoded stream data
/// - Multipart form boundary
///
/// - Parameters:
/// - stream: `InputStream` to encode into the instance.
/// - length: Length, in bytes, of the stream.
/// - headers: `HTTPHeaders` for the body part.
public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) {
let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length)
bodyParts.append(bodyPart)
}
// MARK: - Data Encoding
/// Encodes all appended body parts into a single `Data` value.
///
/// - Note: This method will load all the appended body parts into memory all at the same time. This method should
/// only be used when the encoded data will have a small memory footprint. For large data cases, please use
/// the `writeEncodedData(to:))` method.
///
/// - Returns: The encoded `Data`, if encoding is successful.
/// - Throws: An `AFError` if encoding encounters an error.
public func encode() throws -> Data {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
var encoded = Data()
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
let encodedData = try encode(bodyPart)
encoded.append(encodedData)
}
return encoded
}
/// Writes all appended body parts to the given file `URL`.
///
/// This process is facilitated by reading and writing with input and output streams, respectively. Thus,
/// this approach is very memory efficient and should be used for large body part data.
///
/// - Parameter fileURL: File `URL` to which to write the form data.
/// - Throws: An `AFError` if encoding encounters an error.
public func writeEncodedData(to fileURL: URL) throws {
if let bodyPartError = bodyPartError {
throw bodyPartError
}
if fileManager.fileExists(atPath: fileURL.path) {
throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL))
} else if !fileURL.isFileURL {
throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL))
}
guard let outputStream = OutputStream(url: fileURL, append: false) else {
throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL))
}
outputStream.open()
defer { outputStream.close() }
bodyParts.first?.hasInitialBoundary = true
bodyParts.last?.hasFinalBoundary = true
for bodyPart in bodyParts {
try write(bodyPart, to: outputStream)
}
}
// MARK: - Private - Body Part Encoding
private func encode(_ bodyPart: BodyPart) throws -> Data {
var encoded = Data()
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
encoded.append(initialData)
let headerData = encodeHeaders(for: bodyPart)
encoded.append(headerData)
let bodyStreamData = try encodeBodyStream(for: bodyPart)
encoded.append(bodyStreamData)
if bodyPart.hasFinalBoundary {
encoded.append(finalBoundaryData())
}
return encoded
}
private func encodeHeaders(for bodyPart: BodyPart) -> Data {
let headerText = bodyPart.headers.map { "\($0.name): \($0.value)\(EncodingCharacters.crlf)" }
.joined()
+ EncodingCharacters.crlf
return Data(headerText.utf8)
}
private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data {
let inputStream = bodyPart.bodyStream
inputStream.open()
defer { inputStream.close() }
var encoded = Data()
while inputStream.hasBytesAvailable {
var buffer = [UInt8](repeating: 0, count: streamBufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let error = inputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
}
if bytesRead > 0 {
encoded.append(buffer, count: bytesRead)
} else {
break
}
}
guard UInt64(encoded.count) == bodyPart.bodyContentLength else {
let error = AFError.UnexpectedInputStreamLength(bytesExpected: bodyPart.bodyContentLength,
bytesRead: UInt64(encoded.count))
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error))
}
return encoded
}
// MARK: - Private - Writing Body Part to Output Stream
private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws {
try writeInitialBoundaryData(for: bodyPart, to: outputStream)
try writeHeaderData(for: bodyPart, to: outputStream)
try writeBodyStream(for: bodyPart, to: outputStream)
try writeFinalBoundaryData(for: bodyPart, to: outputStream)
}
private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData()
return try write(initialData, to: outputStream)
}
private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
let headerData = encodeHeaders(for: bodyPart)
return try write(headerData, to: outputStream)
}
private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws {
let inputStream = bodyPart.bodyStream
inputStream.open()
defer { inputStream.close() }
while inputStream.hasBytesAvailable {
var buffer = [UInt8](repeating: 0, count: streamBufferSize)
let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize)
if let streamError = inputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError))
}
if bytesRead > 0 {
if buffer.count != bytesRead {
buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable {
let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite)
if let error = outputStream.streamError {
throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error))
}
bytesToWrite -= bytesWritten
if bytesToWrite > 0 {
buffer = Array(buffer[bytesWritten.. String {
if
let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(),
let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() {
return contentType as String
}
return "application/octet-stream"
}
// MARK: - Private - Content Headers
private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> HTTPHeaders {
var disposition = "form-data; name=\"\(name)\""
if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" }
var headers: HTTPHeaders = [.contentDisposition(disposition)]
if let mimeType = mimeType { headers.add(.contentType(mimeType)) }
return headers
}
// MARK: - Private - Boundary Encoding
private func initialBoundaryData() -> Data {
BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary)
}
private func encapsulatedBoundaryData() -> Data {
BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary)
}
private func finalBoundaryData() -> Data {
BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary)
}
// MARK: - Private - Errors
private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) {
guard bodyPartError == nil else { return }
bodyPartError = AFError.multipartEncodingFailed(reason: reason)
}
}
================================================
FILE: Pods/Alamofire/Source/MultipartUpload.swift
================================================
//
// MultipartUpload.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Internal type which encapsulates a `MultipartFormData` upload.
final class MultipartUpload {
lazy var result = Result { try build() }
@Protected
private(set) var multipartFormData: MultipartFormData
let encodingMemoryThreshold: UInt64
let request: URLRequestConvertible
let fileManager: FileManager
init(encodingMemoryThreshold: UInt64,
request: URLRequestConvertible,
multipartFormData: MultipartFormData) {
self.encodingMemoryThreshold = encodingMemoryThreshold
self.request = request
fileManager = multipartFormData.fileManager
self.multipartFormData = multipartFormData
}
func build() throws -> UploadRequest.Uploadable {
let uploadable: UploadRequest.Uploadable
if multipartFormData.contentLength < encodingMemoryThreshold {
let data = try multipartFormData.encode()
uploadable = .data(data)
} else {
let tempDirectoryURL = fileManager.temporaryDirectory
let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data")
let fileName = UUID().uuidString
let fileURL = directoryURL.appendingPathComponent(fileName)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
do {
try multipartFormData.writeEncodedData(to: fileURL)
} catch {
// Cleanup after attempted write if it fails.
try? fileManager.removeItem(at: fileURL)
throw error
}
uploadable = .file(fileURL, shouldRemove: true)
}
return uploadable
}
}
extension MultipartUpload: UploadConvertible {
func asURLRequest() throws -> URLRequest {
var urlRequest = try request.asURLRequest()
$multipartFormData.read { multipartFormData in
urlRequest.headers.add(.contentType(multipartFormData.contentType))
}
return urlRequest
}
func createUploadable() throws -> UploadRequest.Uploadable {
try result.get()
}
}
================================================
FILE: Pods/Alamofire/Source/NetworkReachabilityManager.swift
================================================
//
// NetworkReachabilityManager.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if !(os(watchOS) || os(Linux))
import Foundation
import SystemConfiguration
/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both cellular and
/// WiFi network interfaces.
///
/// Reachability can be used to determine background information about why a network operation failed, or to retry
/// network requests when a connection is established. It should not be used to prevent a user from initiating a network
/// request, as it's possible that an initial request may be required to establish reachability.
open class NetworkReachabilityManager {
/// Defines the various states of network reachability.
public enum NetworkReachabilityStatus {
/// It is unknown whether the network is reachable.
case unknown
/// The network is not reachable.
case notReachable
/// The network is reachable on the associated `ConnectionType`.
case reachable(ConnectionType)
init(_ flags: SCNetworkReachabilityFlags) {
guard flags.isActuallyReachable else { self = .notReachable; return }
var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
if flags.isCellular { networkStatus = .reachable(.cellular) }
self = networkStatus
}
/// Defines the various connection types detected by reachability flags.
public enum ConnectionType {
/// The connection type is either over Ethernet or WiFi.
case ethernetOrWiFi
/// The connection type is a cellular connection.
case cellular
}
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
public typealias Listener = (NetworkReachabilityStatus) -> Void
/// Default `NetworkReachabilityManager` for the zero address and a `listenerQueue` of `.main`.
public static let `default` = NetworkReachabilityManager()
// MARK: - Properties
/// Whether the network is currently reachable.
open var isReachable: Bool { isReachableOnCellular || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the cellular interface.
///
/// - Note: Using this property to decide whether to make a high or low bandwidth request is not recommended.
/// Instead, set the `allowsCellularAccess` on any `URLRequest`s being issued.
///
open var isReachableOnCellular: Bool { status == .reachable(.cellular) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
open var isReachableOnEthernetOrWiFi: Bool { status == .reachable(.ethernetOrWiFi) }
/// `DispatchQueue` on which reachability will update.
public let reachabilityQueue = DispatchQueue(label: "org.alamofire.reachabilityQueue")
/// Flags of the current reachability type, if any.
open var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
return (SCNetworkReachabilityGetFlags(reachability, &flags)) ? flags : nil
}
/// The current network reachability status.
open var status: NetworkReachabilityStatus {
flags.map(NetworkReachabilityStatus.init) ?? .unknown
}
/// Mutable state storage.
struct MutableState {
/// A closure executed when the network reachability status changes.
var listener: Listener?
/// `DispatchQueue` on which listeners will be called.
var listenerQueue: DispatchQueue?
/// Previously calculated status.
var previousStatus: NetworkReachabilityStatus?
}
/// `SCNetworkReachability` instance providing notifications.
private let reachability: SCNetworkReachability
/// Protected storage for mutable state.
@Protected
private var mutableState = MutableState()
// MARK: - Initialization
/// Creates an instance with the specified host.
///
/// - Note: The `host` value must *not* contain a scheme, just the hostname.
///
/// - Parameters:
/// - host: Host used to evaluate network reachability. Must *not* include the scheme (e.g. `https`).
public convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/// Creates an instance that monitors the address 0.0.0.0.
///
/// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
/// status of the device, both IPv4 and IPv6.
public convenience init?() {
var zero = sockaddr()
zero.sa_len = UInt8(MemoryLayout.size)
zero.sa_family = sa_family_t(AF_INET)
guard let reachability = SCNetworkReachabilityCreateWithAddress(nil, &zero) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
}
deinit {
stopListening()
}
// MARK: - Listening
/// Starts listening for changes in network reachability status.
///
/// - Note: Stops and removes any existing listener.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which to call the `listener` closure. `.main` by default.
/// - listener: `Listener` closure called when reachability changes.
///
/// - Returns: `true` if listening was started successfully, `false` otherwise.
@discardableResult
open func startListening(onQueue queue: DispatchQueue = .main,
onUpdatePerforming listener: @escaping Listener) -> Bool {
stopListening()
$mutableState.write { state in
state.listenerQueue = queue
state.listener = listener
}
var context = SCNetworkReachabilityContext(version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: nil,
release: nil,
copyDescription: nil)
let callback: SCNetworkReachabilityCallBack = { _, flags, info in
guard let info = info else { return }
let instance = Unmanaged.fromOpaque(info).takeUnretainedValue()
instance.notifyListener(flags)
}
let queueAdded = SCNetworkReachabilitySetDispatchQueue(reachability, reachabilityQueue)
let callbackAdded = SCNetworkReachabilitySetCallback(reachability, callback, &context)
// Manually call listener to give initial state, since the framework may not.
if let currentFlags = flags {
reachabilityQueue.async {
self.notifyListener(currentFlags)
}
}
return callbackAdded && queueAdded
}
/// Stops listening for changes in network reachability status.
open func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
$mutableState.write { state in
state.listener = nil
state.listenerQueue = nil
state.previousStatus = nil
}
}
// MARK: - Internal - Listener Notification
/// Calls the `listener` closure of the `listenerQueue` if the computed status hasn't changed.
///
/// - Note: Should only be called from the `reachabilityQueue`.
///
/// - Parameter flags: `SCNetworkReachabilityFlags` to use to calculate the status.
func notifyListener(_ flags: SCNetworkReachabilityFlags) {
let newStatus = NetworkReachabilityStatus(flags)
$mutableState.write { state in
guard state.previousStatus != newStatus else { return }
state.previousStatus = newStatus
let listener = state.listener
state.listenerQueue?.async { listener?(newStatus) }
}
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
extension SCNetworkReachabilityFlags {
var isReachable: Bool { contains(.reachable) }
var isConnectionRequired: Bool { contains(.connectionRequired) }
var canConnectAutomatically: Bool { contains(.connectionOnDemand) || contains(.connectionOnTraffic) }
var canConnectWithoutUserInteraction: Bool { canConnectAutomatically && !contains(.interventionRequired) }
var isActuallyReachable: Bool { isReachable && (!isConnectionRequired || canConnectWithoutUserInteraction) }
var isCellular: Bool {
#if os(iOS) || os(tvOS)
return contains(.isWWAN)
#else
return false
#endif
}
/// Human readable `String` for all states, to help with debugging.
var readableDescription: String {
let W = isCellular ? "W" : "-"
let R = isReachable ? "R" : "-"
let c = isConnectionRequired ? "c" : "-"
let t = contains(.transientConnection) ? "t" : "-"
let i = contains(.interventionRequired) ? "i" : "-"
let C = contains(.connectionOnTraffic) ? "C" : "-"
let D = contains(.connectionOnDemand) ? "D" : "-"
let l = contains(.isLocalAddress) ? "l" : "-"
let d = contains(.isDirect) ? "d" : "-"
let a = contains(.connectionAutomatic) ? "a" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)\(a)"
}
}
#endif
================================================
FILE: Pods/Alamofire/Source/Notifications.swift
================================================
//
// Notifications.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Request {
/// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`.
public static let didResumeNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume")
/// Posted when a `Request` is suspended. The `Notification` contains the suspended `Request`.
public static let didSuspendNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspend")
/// Posted when a `Request` is cancelled. The `Notification` contains the cancelled `Request`.
public static let didCancelNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancel")
/// Posted when a `Request` is finished. The `Notification` contains the completed `Request`.
public static let didFinishNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didFinish")
/// Posted when a `URLSessionTask` is resumed. The `Notification` contains the `Request` associated with the `URLSessionTask`.
public static let didResumeTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResumeTask")
/// Posted when a `URLSessionTask` is suspended. The `Notification` contains the `Request` associated with the `URLSessionTask`.
public static let didSuspendTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didSuspendTask")
/// Posted when a `URLSessionTask` is cancelled. The `Notification` contains the `Request` associated with the `URLSessionTask`.
public static let didCancelTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCancelTask")
/// Posted when a `URLSessionTask` is completed. The `Notification` contains the `Request` associated with the `URLSessionTask`.
public static let didCompleteTaskNotification = Notification.Name(rawValue: "org.alamofire.notification.name.request.didCompleteTask")
}
// MARK: -
extension Notification {
/// The `Request` contained by the instance's `userInfo`, `nil` otherwise.
public var request: Request? {
userInfo?[String.requestKey] as? Request
}
/// Convenience initializer for a `Notification` containing a `Request` payload.
///
/// - Parameters:
/// - name: The name of the notification.
/// - request: The `Request` payload.
init(name: Notification.Name, request: Request) {
self.init(name: name, object: nil, userInfo: [String.requestKey: request])
}
}
extension NotificationCenter {
/// Convenience function for posting notifications with `Request` payloads.
///
/// - Parameters:
/// - name: The name of the notification.
/// - request: The `Request` payload.
func postNotification(named name: Notification.Name, with request: Request) {
let notification = Notification(name: name, request: request)
post(notification)
}
}
extension String {
/// User info dictionary key representing the `Request` associated with the notification.
fileprivate static let requestKey = "org.alamofire.notification.key.request"
}
/// `EventMonitor` that provides Alamofire's notifications.
public final class AlamofireNotifications: EventMonitor {
public func requestDidResume(_ request: Request) {
NotificationCenter.default.postNotification(named: Request.didResumeNotification, with: request)
}
public func requestDidSuspend(_ request: Request) {
NotificationCenter.default.postNotification(named: Request.didSuspendNotification, with: request)
}
public func requestDidCancel(_ request: Request) {
NotificationCenter.default.postNotification(named: Request.didCancelNotification, with: request)
}
public func requestDidFinish(_ request: Request) {
NotificationCenter.default.postNotification(named: Request.didFinishNotification, with: request)
}
public func request(_ request: Request, didResumeTask task: URLSessionTask) {
NotificationCenter.default.postNotification(named: Request.didResumeTaskNotification, with: request)
}
public func request(_ request: Request, didSuspendTask task: URLSessionTask) {
NotificationCenter.default.postNotification(named: Request.didSuspendTaskNotification, with: request)
}
public func request(_ request: Request, didCancelTask task: URLSessionTask) {
NotificationCenter.default.postNotification(named: Request.didCancelTaskNotification, with: request)
}
public func request(_ request: Request, didCompleteTask task: URLSessionTask, with error: AFError?) {
NotificationCenter.default.postNotification(named: Request.didCompleteTaskNotification, with: request)
}
}
================================================
FILE: Pods/Alamofire/Source/OperationQueue+Alamofire.swift
================================================
//
// OperationQueue+Alamofire.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension OperationQueue {
/// Creates an instance using the provided parameters.
///
/// - Parameters:
/// - qualityOfService: `QualityOfService` to be applied to the queue. `.default` by default.
/// - maxConcurrentOperationCount: Maximum concurrent operations.
/// `OperationQueue.defaultMaxConcurrentOperationCount` by default.
/// - underlyingQueue: Underlying `DispatchQueue`. `nil` by default.
/// - name: Name for the queue. `nil` by default.
/// - startSuspended: Whether the queue starts suspended. `false` by default.
convenience init(qualityOfService: QualityOfService = .default,
maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount,
underlyingQueue: DispatchQueue? = nil,
name: String? = nil,
startSuspended: Bool = false) {
self.init()
self.qualityOfService = qualityOfService
self.maxConcurrentOperationCount = maxConcurrentOperationCount
self.underlyingQueue = underlyingQueue
self.name = name
isSuspended = startSuspended
}
}
================================================
FILE: Pods/Alamofire/Source/ParameterEncoder.swift
================================================
//
// ParameterEncoder.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that can encode any `Encodable` type into a `URLRequest`.
public protocol ParameterEncoder {
/// Encode the provided `Encodable` parameters into `request`.
///
/// - Parameters:
/// - parameters: The `Encodable` parameter value.
/// - request: The `URLRequest` into which to encode the parameters.
///
/// - Returns: A `URLRequest` with the result of the encoding.
/// - Throws: An `Error` when encoding fails. For Alamofire provided encoders, this will be an instance of
/// `AFError.parameterEncoderFailed` with an associated `ParameterEncoderFailureReason`.
func encode(_ parameters: Parameters?, into request: URLRequest) throws -> URLRequest
}
/// A `ParameterEncoder` that encodes types as JSON body data.
///
/// If no `Content-Type` header is already set on the provided `URLRequest`s, it's set to `application/json`.
open class JSONParameterEncoder: ParameterEncoder {
/// Returns an encoder with default parameters.
public static var `default`: JSONParameterEncoder { JSONParameterEncoder() }
/// Returns an encoder with `JSONEncoder.outputFormatting` set to `.prettyPrinted`.
public static var prettyPrinted: JSONParameterEncoder {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
return JSONParameterEncoder(encoder: encoder)
}
/// Returns an encoder with `JSONEncoder.outputFormatting` set to `.sortedKeys`.
@available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
public static var sortedKeys: JSONParameterEncoder {
let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
return JSONParameterEncoder(encoder: encoder)
}
/// `JSONEncoder` used to encode parameters.
public let encoder: JSONEncoder
/// Creates an instance with the provided `JSONEncoder`.
///
/// - Parameter encoder: The `JSONEncoder`. `JSONEncoder()` by default.
public init(encoder: JSONEncoder = JSONEncoder()) {
self.encoder = encoder
}
open func encode(_ parameters: Parameters?,
into request: URLRequest) throws -> URLRequest {
guard let parameters = parameters else { return request }
var request = request
do {
let data = try encoder.encode(parameters)
request.httpBody = data
if request.headers["Content-Type"] == nil {
request.headers.update(.contentType("application/json"))
}
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return request
}
}
/// A `ParameterEncoder` that encodes types as URL-encoded query strings to be set on the URL or as body data, depending
/// on the `Destination` set.
///
/// If no `Content-Type` header is already set on the provided `URLRequest`s, it will be set to
/// `application/x-www-form-urlencoded; charset=utf-8`.
///
/// Encoding behavior can be customized by passing an instance of `URLEncodedFormEncoder` to the initializer.
open class URLEncodedFormParameterEncoder: ParameterEncoder {
/// Defines where the URL-encoded string should be set for each `URLRequest`.
public enum Destination {
/// Applies the encoded query string to any existing query string for `.get`, `.head`, and `.delete` request.
/// Sets it to the `httpBody` for all other methods.
case methodDependent
/// Applies the encoded query string to any existing query string from the `URLRequest`.
case queryString
/// Applies the encoded query string to the `httpBody` of the `URLRequest`.
case httpBody
/// Determines whether the URL-encoded string should be applied to the `URLRequest`'s `url`.
///
/// - Parameter method: The `HTTPMethod`.
///
/// - Returns: Whether the URL-encoded string should be applied to a `URL`.
func encodesParametersInURL(for method: HTTPMethod) -> Bool {
switch self {
case .methodDependent: return [.get, .head, .delete].contains(method)
case .queryString: return true
case .httpBody: return false
}
}
}
/// Returns an encoder with default parameters.
public static var `default`: URLEncodedFormParameterEncoder { URLEncodedFormParameterEncoder() }
/// The `URLEncodedFormEncoder` to use.
public let encoder: URLEncodedFormEncoder
/// The `Destination` for the URL-encoded string.
public let destination: Destination
/// Creates an instance with the provided `URLEncodedFormEncoder` instance and `Destination` value.
///
/// - Parameters:
/// - encoder: The `URLEncodedFormEncoder`. `URLEncodedFormEncoder()` by default.
/// - destination: The `Destination`. `.methodDependent` by default.
public init(encoder: URLEncodedFormEncoder = URLEncodedFormEncoder(), destination: Destination = .methodDependent) {
self.encoder = encoder
self.destination = destination
}
open func encode(_ parameters: Parameters?,
into request: URLRequest) throws -> URLRequest {
guard let parameters = parameters else { return request }
var request = request
guard let url = request.url else {
throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
}
guard let method = request.method else {
let rawValue = request.method?.rawValue ?? "nil"
throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.httpMethod(rawValue: rawValue)))
}
if destination.encodesParametersInURL(for: method),
var components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let query: String = try Result { try encoder.encode(parameters) }
.mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
let newQueryString = [components.percentEncodedQuery, query].compactMap { $0 }.joinedWithAmpersands()
components.percentEncodedQuery = newQueryString.isEmpty ? nil : newQueryString
guard let newURL = components.url else {
throw AFError.parameterEncoderFailed(reason: .missingRequiredComponent(.url))
}
request.url = newURL
} else {
if request.headers["Content-Type"] == nil {
request.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
}
request.httpBody = try Result { try encoder.encode(parameters) }
.mapError { AFError.parameterEncoderFailed(reason: .encoderFailed(error: $0)) }.get()
}
return request
}
}
================================================
FILE: Pods/Alamofire/Source/ParameterEncoding.swift
================================================
//
// ParameterEncoding.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
/// A type used to define how a set of parameters are applied to a `URLRequest`.
public protocol ParameterEncoding {
/// Creates a `URLRequest` by encoding parameters and applying them on the passed request.
///
/// - Parameters:
/// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded.
/// - parameters: `Parameters` to encode onto the request.
///
/// - Returns: The encoded `URLRequest`.
/// - Throws: Any `Error` produced during parameter encoding.
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
// MARK: -
/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
/// the HTTP body depends on the destination of the encoding.
///
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
/// `application/x-www-form-urlencoded; charset=utf-8`.
///
/// There is no published specification for how to encode collection types. By default the convention of appending
/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
/// square brackets appended to array keys.
///
/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
/// `true` as 1 and `false` as 0.
public struct URLEncoding: ParameterEncoding {
// MARK: Helper Types
/// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
/// resulting URL request.
public enum Destination {
/// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and
/// sets as the HTTP body for requests with any other HTTP method.
case methodDependent
/// Sets or appends encoded query string result to existing query string.
case queryString
/// Sets encoded query string result as the HTTP body of the URL request.
case httpBody
func encodesParametersInURL(for method: HTTPMethod) -> Bool {
switch self {
case .methodDependent: return [.get, .head, .delete].contains(method)
case .queryString: return true
case .httpBody: return false
}
}
}
/// Configures how `Array` parameters are encoded.
public enum ArrayEncoding {
/// An empty set of square brackets is appended to the key for every value. This is the default behavior.
case brackets
/// No brackets are appended. The key is encoded as is.
case noBrackets
func encode(key: String) -> String {
switch self {
case .brackets:
return "\(key)[]"
case .noBrackets:
return key
}
}
}
/// Configures how `Bool` parameters are encoded.
public enum BoolEncoding {
/// Encode `true` as `1` and `false` as `0`. This is the default behavior.
case numeric
/// Encode `true` and `false` as string literals.
case literal
func encode(value: Bool) -> String {
switch self {
case .numeric:
return value ? "1" : "0"
case .literal:
return value ? "true" : "false"
}
}
}
// MARK: Properties
/// Returns a default `URLEncoding` instance with a `.methodDependent` destination.
public static var `default`: URLEncoding { URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) }
/// The destination defining where the encoded query string is to be applied to the URL request.
public let destination: Destination
/// The encoding to use for `Array` parameters.
public let arrayEncoding: ArrayEncoding
/// The encoding to use for `Bool` parameters.
public let boolEncoding: BoolEncoding
// MARK: Initialization
/// Creates an instance using the specified parameters.
///
/// - Parameters:
/// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by
/// default.
/// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default.
/// - boolEncoding: `BoolEncoding` to use. `.numeric` by default.
public init(destination: Destination = .methodDependent,
arrayEncoding: ArrayEncoding = .brackets,
boolEncoding: BoolEncoding = .numeric) {
self.destination = destination
self.arrayEncoding = arrayEncoding
self.boolEncoding = boolEncoding
}
// MARK: Encoding
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = urlRequest.method, destination.encodesParametersInURL(for: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.headers["Content-Type"] == nil {
urlRequest.headers.update(.contentType("application/x-www-form-urlencoded; charset=utf-8"))
}
urlRequest.httpBody = Data(query(parameters).utf8)
}
return urlRequest
}
/// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively.
///
/// - Parameters:
/// - key: Key of the query component.
/// - value: Value of the query component.
///
/// - Returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
switch value {
case let dictionary as [String: Any]:
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
case let array as [Any]:
for value in array {
components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
}
case let number as NSNumber:
if number.isBool {
components.append((escape(key), escape(boolEncoding.encode(value: number.boolValue))))
} else {
components.append((escape(key), escape("\(number)")))
}
case let bool as Bool:
components.append((escape(key), escape(boolEncoding.encode(value: bool))))
default:
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Creates a percent-escaped string following RFC 3986 for a query string key or value.
///
/// - Parameter string: `String` to be percent-escaped.
///
/// - Returns: The percent-escaped `String`.
public func escape(_ string: String) -> String {
string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
}
// MARK: -
/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates an instance using the specified `WritingOptions`.
///
/// - Parameter options: `JSONSerialization.WritingOptions` to use.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.headers["Content-Type"] == nil {
urlRequest.headers.update(.contentType("application/json"))
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Encodes any JSON compatible object into a `URLRequest`.
///
/// - Parameters:
/// - urlRequest: `URLRequestConvertible` value into which the object will be encoded.
/// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default.
///
/// - Returns: The encoded `URLRequest`.
/// - Throws: Any `Error` produced during encoding.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.headers["Content-Type"] == nil {
urlRequest.headers.update(.contentType("application/json"))
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool {
// Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of
// swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22).
String(cString: objCType) == "c"
}
}
================================================
FILE: Pods/Alamofire/Source/Protected.swift
================================================
//
// Protected.swift
//
// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
private protocol Lock {
func lock()
func unlock()
}
extension Lock {
/// Executes a closure returning a value while acquiring the lock.
///
/// - Parameter closure: The closure to run.
///
/// - Returns: The value the closure generated.
func around(_ closure: () -> T) -> T {
lock(); defer { unlock() }
return closure()
}
/// Execute a closure while acquiring the lock.
///
/// - Parameter closure: The closure to run.
func around(_ closure: () -> Void) {
lock(); defer { unlock() }
closure()
}
}
#if os(Linux)
/// A `pthread_mutex_t` wrapper.
final class MutexLock: Lock {
private var mutex: UnsafeMutablePointer
init() {
mutex = .allocate(capacity: 1)
var attr = pthread_mutexattr_t()
pthread_mutexattr_init(&attr)
pthread_mutexattr_settype(&attr, .init(PTHREAD_MUTEX_ERRORCHECK))
let error = pthread_mutex_init(mutex, &attr)
precondition(error == 0, "Failed to create pthread_mutex")
}
deinit {
let error = pthread_mutex_destroy(mutex)
precondition(error == 0, "Failed to destroy pthread_mutex")
}
fileprivate func lock() {
let error = pthread_mutex_lock(mutex)
precondition(error == 0, "Failed to lock pthread_mutex")
}
fileprivate func unlock() {
let error = pthread_mutex_unlock(mutex)
precondition(error == 0, "Failed to unlock pthread_mutex")
}
}
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
/// An `os_unfair_lock` wrapper.
final class UnfairLock: Lock {
private let unfairLock: os_unfair_lock_t
init() {
unfairLock = .allocate(capacity: 1)
unfairLock.initialize(to: os_unfair_lock())
}
deinit {
unfairLock.deinitialize(count: 1)
unfairLock.deallocate()
}
fileprivate func lock() {
os_unfair_lock_lock(unfairLock)
}
fileprivate func unlock() {
os_unfair_lock_unlock(unfairLock)
}
}
#endif
/// A thread-safe wrapper around a value.
@propertyWrapper
@dynamicMemberLookup
final class Protected {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
private let lock = UnfairLock()
#elseif os(Linux)
private let lock = MutexLock()
#endif
private var value: T
init(_ value: T) {
self.value = value
}
/// The contained value. Unsafe for anything more than direct read or write.
var wrappedValue: T {
get { lock.around { value } }
set { lock.around { value = newValue } }
}
var projectedValue: Protected { self }
init(wrappedValue: T) {
value = wrappedValue
}
/// Synchronously read or transform the contained value.
///
/// - Parameter closure: The closure to execute.
///
/// - Returns: The return value of the closure passed.
func read(_ closure: (T) -> U) -> U {
lock.around { closure(self.value) }
}
/// Synchronously modify the protected value.
///
/// - Parameter closure: The closure to execute.
///
/// - Returns: The modified value.
@discardableResult
func write(_ closure: (inout T) -> U) -> U {
lock.around { closure(&self.value) }
}
subscript(dynamicMember keyPath: WritableKeyPath) -> Property {
get { lock.around { value[keyPath: keyPath] } }
set { lock.around { value[keyPath: keyPath] = newValue } }
}
}
extension Protected where T: RangeReplaceableCollection {
/// Adds a new element to the end of this protected collection.
///
/// - Parameter newElement: The `Element` to append.
func append(_ newElement: T.Element) {
write { (ward: inout T) in
ward.append(newElement)
}
}
/// Adds the elements of a sequence to the end of this protected collection.
///
/// - Parameter newElements: The `Sequence` to append.
func append(contentsOf newElements: S) where S.Element == T.Element {
write { (ward: inout T) in
ward.append(contentsOf: newElements)
}
}
/// Add the elements of a collection to the end of the protected collection.
///
/// - Parameter newElements: The `Collection` to append.
func append(contentsOf newElements: C) where C.Element == T.Element {
write { (ward: inout T) in
ward.append(contentsOf: newElements)
}
}
}
extension Protected where T == Data? {
/// Adds the contents of a `Data` value to the end of the protected `Data`.
///
/// - Parameter data: The `Data` to be appended.
func append(_ data: Data) {
write { (ward: inout T) in
ward?.append(data)
}
}
}
extension Protected where T == Request.MutableState {
/// Attempts to transition to the passed `State`.
///
/// - Parameter state: The `State` to attempt transition to.
///
/// - Returns: Whether the transition occurred.
func attemptToTransitionTo(_ state: Request.State) -> Bool {
lock.around {
guard value.state.canTransitionTo(state) else { return false }
value.state = state
return true
}
}
/// Perform a closure while locked with the provided `Request.State`.
///
/// - Parameter perform: The closure to perform while locked.
func withState(perform: (Request.State) -> Void) {
lock.around { perform(value.state) }
}
}
================================================
FILE: Pods/Alamofire/Source/RedirectHandler.swift
================================================
//
// RedirectHandler.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that handles how an HTTP redirect response from a remote server should be redirected to the new request.
public protocol RedirectHandler {
/// Determines how the HTTP redirect response should be redirected to the new request.
///
/// The `completion` closure should be passed one of three possible options:
///
/// 1. The new request specified by the redirect (this is the most common use case).
/// 2. A modified version of the new request (you may want to route it somewhere else).
/// 3. A `nil` value to deny the redirect request and return the body of the redirect response.
///
/// - Parameters:
/// - task: The `URLSessionTask` whose request resulted in a redirect.
/// - request: The `URLRequest` to the new location specified by the redirect response.
/// - response: The `HTTPURLResponse` containing the server's response to the original request.
/// - completion: The closure to execute containing the new `URLRequest`, a modified `URLRequest`, or `nil`.
func task(_ task: URLSessionTask,
willBeRedirectedTo request: URLRequest,
for response: HTTPURLResponse,
completion: @escaping (URLRequest?) -> Void)
}
// MARK: -
/// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect.
public struct Redirector {
/// Defines the behavior of the `Redirector` type.
public enum Behavior {
/// Follow the redirect as defined in the response.
case follow
/// Do not follow the redirect defined in the response.
case doNotFollow
/// Modify the redirect request defined in the response.
case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?)
}
/// Returns a `Redirector` with a `.follow` `Behavior`.
public static let follow = Redirector(behavior: .follow)
/// Returns a `Redirector` with a `.doNotFollow` `Behavior`.
public static let doNotFollow = Redirector(behavior: .doNotFollow)
/// The `Behavior` of the `Redirector`.
public let behavior: Behavior
/// Creates a `Redirector` instance from the `Behavior`.
///
/// - Parameter behavior: The `Behavior`.
public init(behavior: Behavior) {
self.behavior = behavior
}
}
// MARK: -
extension Redirector: RedirectHandler {
public func task(_ task: URLSessionTask,
willBeRedirectedTo request: URLRequest,
for response: HTTPURLResponse,
completion: @escaping (URLRequest?) -> Void) {
switch behavior {
case .follow:
completion(request)
case .doNotFollow:
completion(nil)
case let .modify(closure):
let request = closure(task, request, response)
completion(request)
}
}
}
================================================
FILE: Pods/Alamofire/Source/Request.swift
================================================
//
// Request.swift
//
// Copyright (c) 2014-2020 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback
/// handling.
public class Request {
/// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or
/// `cancel()` on the `Request`.
public enum State {
/// Initial state of the `Request`.
case initialized
/// `State` set when `resume()` is called. Any tasks created for the `Request` will have `resume()` called on
/// them in this state.
case resumed
/// `State` set when `suspend()` is called. Any tasks created for the `Request` will have `suspend()` called on
/// them in this state.
case suspended
/// `State` set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on
/// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer transition
/// to any other state.
case cancelled
/// `State` set when all response serialization completion closures have been cleared on the `Request` and
/// enqueued on their respective queues.
case finished
/// Determines whether `self` can be transitioned to the provided `State`.
func canTransitionTo(_ state: State) -> Bool {
switch (self, state) {
case (.initialized, _):
return true
case (_, .initialized), (.cancelled, _), (.finished, _):
return false
case (.resumed, .cancelled), (.suspended, .cancelled), (.resumed, .suspended), (.suspended, .resumed):
return true
case (.suspended, .suspended), (.resumed, .resumed):
return false
case (_, .finished):
return true
}
}
}
// MARK: - Initial State
/// `UUID` providing a unique identifier for the `Request`, used in the `Hashable` and `Equatable` conformances.
public let id: UUID
/// The serial queue for all internal async actions.
public let underlyingQueue: DispatchQueue
/// The queue used for all serialization actions. By default it's a serial queue that targets `underlyingQueue`.
public let serializationQueue: DispatchQueue
/// `EventMonitor` used for event callbacks.
public let eventMonitor: EventMonitor?
/// The `Request`'s interceptor.
public let interceptor: RequestInterceptor?
/// The `Request`'s delegate.
public private(set) weak var delegate: RequestDelegate?
// MARK: - Mutable State
/// Type encapsulating all mutable state that may need to be accessed from anything other than the `underlyingQueue`.
struct MutableState {
/// State of the `Request`.
var state: State = .initialized
/// `ProgressHandler` and `DispatchQueue` provided for upload progress callbacks.
var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
/// `ProgressHandler` and `DispatchQueue` provided for download progress callbacks.
var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)?
/// `RedirectHandler` provided for to handle request redirection.
var redirectHandler: RedirectHandler?
/// `CachedResponseHandler` provided to handle response caching.
var cachedResponseHandler: CachedResponseHandler?
/// Queue and closure called when the `Request` is able to create a cURL description of itself.
var cURLHandler: (queue: DispatchQueue, handler: (String) -> Void)?
/// Queue and closure called when the `Request` creates a `URLRequest`.
var urlRequestHandler: (queue: DispatchQueue, handler: (URLRequest) -> Void)?
/// Queue and closure called when the `Request` creates a `URLSessionTask`.
var urlSessionTaskHandler: (queue: DispatchQueue, handler: (URLSessionTask) -> Void)?
/// Response serialization closures that handle response parsing.
var responseSerializers: [() -> Void] = []
/// Response serialization completion closures executed once all response serializers are complete.
var responseSerializerCompletions: [() -> Void] = []
/// Whether response serializer processing is finished.
var responseSerializerProcessingFinished = false
/// `URLCredential` used for authentication challenges.
var credential: URLCredential?
/// All `URLRequest`s created by Alamofire on behalf of the `Request`.
var requests: [URLRequest] = []
/// All `URLSessionTask`s created by Alamofire on behalf of the `Request`.
var tasks: [URLSessionTask] = []
/// All `URLSessionTaskMetrics` values gathered by Alamofire on behalf of the `Request`. Should correspond
/// exactly the the `tasks` created.
var metrics: [URLSessionTaskMetrics] = []
/// Number of times any retriers provided retried the `Request`.
var retryCount = 0
/// Final `AFError` for the `Request`, whether from various internal Alamofire calls or as a result of a `task`.
var error: AFError?
/// Whether the instance has had `finish()` called and is running the serializers. Should be replaced with a
/// representation in the state machine in the future.
var isFinishing = false
}
/// Protected `MutableState` value that provides thread-safe access to state values.
@Protected
fileprivate var mutableState = MutableState()
/// `State` of the `Request`.
public var state: State { mutableState.state }
/// Returns whether `state` is `.initialized`.
public var isInitialized: Bool { state == .initialized }
/// Returns whether `state is `.resumed`.
public var isResumed: Bool { state == .resumed }
/// Returns whether `state` is `.suspended`.
public var isSuspended: Bool { state == .suspended }
/// Returns whether `state` is `.cancelled`.
public var isCancelled: Bool { state == .cancelled }
/// Returns whether `state` is `.finished`.
public var isFinished: Bool { state == .finished }
// MARK: Progress
/// Closure type executed when monitoring the upload or download progress of a request.
public typealias ProgressHandler = (Progress) -> Void
/// `Progress` of the upload of the body of the executed `URLRequest`. Reset to `0` if the `Request` is retried.
public let uploadProgress = Progress(totalUnitCount: 0)
/// `Progress` of the download of any response data. Reset to `0` if the `Request` is retried.
public let downloadProgress = Progress(totalUnitCount: 0)
/// `ProgressHandler` called when `uploadProgress` is updated, on the provided `DispatchQueue`.
private var uploadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
get { mutableState.uploadProgressHandler }
set { mutableState.uploadProgressHandler = newValue }
}
/// `ProgressHandler` called when `downloadProgress` is updated, on the provided `DispatchQueue`.
fileprivate var downloadProgressHandler: (handler: ProgressHandler, queue: DispatchQueue)? {
get { mutableState.downloadProgressHandler }
set { mutableState.downloadProgressHandler = newValue }
}
// MARK: Redirect Handling
/// `RedirectHandler` set on the instance.
public private(set) var redirectHandler: RedirectHandler? {
get { mutableState.redirectHandler }
set { mutableState.redirectHandler = newValue }
}
// MARK: Cached Response Handling
/// `CachedResponseHandler` set on the instance.
public private(set) var cachedResponseHandler: CachedResponseHandler? {
get { mutableState.cachedResponseHandler }
set { mutableState.cachedResponseHandler = newValue }
}
// MARK: URLCredential
/// `URLCredential` used for authentication challenges. Created by calling one of the `authenticate` methods.
public private(set) var credential: URLCredential? {
get { mutableState.credential }
set { mutableState.credential = newValue }
}
// MARK: Validators
/// `Validator` callback closures that store the validation calls enqueued.
@Protected
fileprivate var validators: [() -> Void] = []
// MARK: URLRequests
/// All `URLRequests` created on behalf of the `Request`, including original and adapted requests.
public var requests: [URLRequest] { mutableState.requests }
/// First `URLRequest` created on behalf of the `Request`. May not be the first one actually executed.
public var firstRequest: URLRequest? { requests.first }
/// Last `URLRequest` created on behalf of the `Request`.
public var lastRequest: URLRequest? { requests.last }
/// Current `URLRequest` created on behalf of the `Request`.
public var request: URLRequest? { lastRequest }
/// `URLRequest`s from all of the `URLSessionTask`s executed on behalf of the `Request`. May be different from
/// `requests` due to `URLSession` manipulation.
public var performedRequests: [URLRequest] { $mutableState.read { $0.tasks.compactMap { $0.currentRequest } } }
// MARK: HTTPURLResponse
/// `HTTPURLResponse` received from the server, if any. If the `Request` was retried, this is the response of the
/// last `URLSessionTask`.
public var response: HTTPURLResponse? { lastTask?.response as? HTTPURLResponse }
// MARK: Tasks
/// All `URLSessionTask`s created on behalf of the `Request`.
public var tasks: [URLSessionTask] { mutableState.tasks }
/// First `URLSessionTask` created on behalf of the `Request`.
public var firstTask: URLSessionTask? { tasks.first }
/// Last `URLSessionTask` crated on behalf of the `Request`.
public var lastTask: URLSessionTask? { tasks.last }
/// Current `URLSessionTask` created on behalf of the `Request`.
public var task: URLSessionTask? { lastTask }
// MARK: Metrics
/// All `URLSessionTaskMetrics` gathered on behalf of the `Request`. Should correspond to the `tasks` created.
public var allMetrics: [URLSessionTaskMetrics] { mutableState.metrics }
/// First `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var firstMetrics: URLSessionTaskMetrics? { allMetrics.first }
/// Last `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var lastMetrics: URLSessionTaskMetrics? { allMetrics.last }
/// Current `URLSessionTaskMetrics` gathered on behalf of the `Request`.
public var metrics: URLSessionTaskMetrics? { lastMetrics }
// MARK: Retry Count
/// Number of times the `Request` has been retried.
public var retryCount: Int { mutableState.retryCount }
// MARK: Error
/// `Error` returned from Alamofire internally, from the network request directly, or any validators executed.
public fileprivate(set) var error: AFError? {
get { mutableState.error }
set { mutableState.error = newValue }
}
/// Default initializer for the `Request` superclass.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate) {
self.id = id
self.underlyingQueue = underlyingQueue
self.serializationQueue = serializationQueue
self.eventMonitor = eventMonitor
self.interceptor = interceptor
self.delegate = delegate
}
// MARK: - Internal Event API
// All API must be called from underlyingQueue.
/// Called when an initial `URLRequest` has been created on behalf of the instance. If a `RequestAdapter` is active,
/// the `URLRequest` will be adapted before being issued.
///
/// - Parameter request: The `URLRequest` created.
func didCreateInitialURLRequest(_ request: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.requests.append(request) }
eventMonitor?.request(self, didCreateInitialURLRequest: request)
}
/// Called when initial `URLRequest` creation has failed, typically through a `URLRequestConvertible`.
///
/// - Note: Triggers retry.
///
/// - Parameter error: `AFError` thrown from the failed creation.
func didFailToCreateURLRequest(with error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
eventMonitor?.request(self, didFailToCreateURLRequestWithError: error)
callCURLHandlerIfNecessary()
retryOrFinish(error: error)
}
/// Called when a `RequestAdapter` has successfully adapted a `URLRequest`.
///
/// - Parameters:
/// - initialRequest: The `URLRequest` that was adapted.
/// - adaptedRequest: The `URLRequest` returned by the `RequestAdapter`.
func didAdaptInitialRequest(_ initialRequest: URLRequest, to adaptedRequest: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.requests.append(adaptedRequest) }
eventMonitor?.request(self, didAdaptInitialRequest: initialRequest, to: adaptedRequest)
}
/// Called when a `RequestAdapter` fails to adapt a `URLRequest`.
///
/// - Note: Triggers retry.
///
/// - Parameters:
/// - request: The `URLRequest` the adapter was called with.
/// - error: The `AFError` returned by the `RequestAdapter`.
func didFailToAdaptURLRequest(_ request: URLRequest, withError error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
eventMonitor?.request(self, didFailToAdaptURLRequest: request, withError: error)
callCURLHandlerIfNecessary()
retryOrFinish(error: error)
}
/// Final `URLRequest` has been created for the instance.
///
/// - Parameter request: The `URLRequest` created.
func didCreateURLRequest(_ request: URLRequest) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.read { state in
state.urlRequestHandler?.queue.async { state.urlRequestHandler?.handler(request) }
}
eventMonitor?.request(self, didCreateURLRequest: request)
callCURLHandlerIfNecessary()
}
/// Asynchronously calls any stored `cURLHandler` and then removes it from `mutableState`.
private func callCURLHandlerIfNecessary() {
$mutableState.write { mutableState in
guard let cURLHandler = mutableState.cURLHandler else { return }
cURLHandler.queue.async { cURLHandler.handler(self.cURLDescription()) }
mutableState.cURLHandler = nil
}
}
/// Called when a `URLSessionTask` is created on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` created.
func didCreateTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { state in
state.tasks.append(task)
guard let urlSessionTaskHandler = state.urlSessionTaskHandler else { return }
urlSessionTaskHandler.queue.async { urlSessionTaskHandler.handler(task) }
}
eventMonitor?.request(self, didCreateTask: task)
}
/// Called when resumption is completed.
func didResume() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.requestDidResume(self)
}
/// Called when a `URLSessionTask` is resumed on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` resumed.
func didResumeTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didResumeTask: task)
}
/// Called when suspension is completed.
func didSuspend() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.requestDidSuspend(self)
}
/// Called when a `URLSessionTask` is suspended on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` suspended.
func didSuspendTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didSuspendTask: task)
}
/// Called when cancellation is completed, sets `error` to `AFError.explicitlyCancelled`.
func didCancel() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
error = error ?? AFError.explicitlyCancelled
eventMonitor?.requestDidCancel(self)
}
/// Called when a `URLSessionTask` is cancelled on behalf of the instance.
///
/// - Parameter task: The `URLSessionTask` cancelled.
func didCancelTask(_ task: URLSessionTask) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
eventMonitor?.request(self, didCancelTask: task)
}
/// Called when a `URLSessionTaskMetrics` value is gathered on behalf of the instance.
///
/// - Parameter metrics: The `URLSessionTaskMetrics` gathered.
func didGatherMetrics(_ metrics: URLSessionTaskMetrics) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.metrics.append(metrics) }
eventMonitor?.request(self, didGatherMetrics: metrics)
}
/// Called when a `URLSessionTask` fails before it is finished, typically during certificate pinning.
///
/// - Parameters:
/// - task: The `URLSessionTask` which failed.
/// - error: The early failure `AFError`.
func didFailTask(_ task: URLSessionTask, earlyWithError error: AFError) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = error
// Task will still complete, so didCompleteTask(_:with:) will handle retry.
eventMonitor?.request(self, didFailTask: task, earlyWithError: error)
}
/// Called when a `URLSessionTask` completes. All tasks will eventually call this method.
///
/// - Note: Response validation is synchronously triggered in this step.
///
/// - Parameters:
/// - task: The `URLSessionTask` which completed.
/// - error: The `AFError` `task` may have completed with. If `error` has already been set on the instance, this
/// value is ignored.
func didCompleteTask(_ task: URLSessionTask, with error: AFError?) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
self.error = self.error ?? error
validators.forEach { $0() }
eventMonitor?.request(self, didCompleteTask: task, with: error)
retryOrFinish(error: self.error)
}
/// Called when the `RequestDelegate` is going to retry this `Request`. Calls `reset()`.
func prepareForRetry() {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
$mutableState.write { $0.retryCount += 1 }
reset()
eventMonitor?.requestIsRetrying(self)
}
/// Called to determine whether retry will be triggered for the particular error, or whether the instance should
/// call `finish()`.
///
/// - Parameter error: The possible `AFError` which may trigger retry.
func retryOrFinish(error: AFError?) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
guard let error = error, let delegate = delegate else { finish(); return }
delegate.retryResult(for: self, dueTo: error) { retryResult in
switch retryResult {
case .doNotRetry:
self.finish()
case let .doNotRetryWithError(retryError):
self.finish(error: retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
case .retry, .retryWithDelay:
delegate.retryRequest(self, withDelay: retryResult.delay)
}
}
}
/// Finishes this `Request` and starts the response serializers.
///
/// - Parameter error: The possible `Error` with which the instance will finish.
func finish(error: AFError? = nil) {
dispatchPrecondition(condition: .onQueue(underlyingQueue))
guard !mutableState.isFinishing else { return }
mutableState.isFinishing = true
if let error = error { self.error = error }
// Start response handlers
processNextResponseSerializer()
eventMonitor?.requestDidFinish(self)
}
/// Appends the response serialization closure to the instance.
///
/// - Note: This method will also `resume` the instance if `delegate.startImmediately` returns `true`.
///
/// - Parameter closure: The closure containing the response serialization call.
func appendResponseSerializer(_ closure: @escaping () -> Void) {
$mutableState.write { mutableState in
mutableState.responseSerializers.append(closure)
if mutableState.state == .finished {
mutableState.state = .resumed
}
if mutableState.responseSerializerProcessingFinished {
underlyingQueue.async { self.processNextResponseSerializer() }
}
if mutableState.state.canTransitionTo(.resumed) {
underlyingQueue.async { if self.delegate?.startImmediately == true { self.resume() } }
}
}
}
/// Returns the next response serializer closure to execute if there's one left.
///
/// - Returns: The next response serialization closure, if there is one.
func nextResponseSerializer() -> (() -> Void)? {
var responseSerializer: (() -> Void)?
$mutableState.write { mutableState in
let responseSerializerIndex = mutableState.responseSerializerCompletions.count
if responseSerializerIndex < mutableState.responseSerializers.count {
responseSerializer = mutableState.responseSerializers[responseSerializerIndex]
}
}
return responseSerializer
}
/// Processes the next response serializer and calls all completions if response serialization is complete.
func processNextResponseSerializer() {
guard let responseSerializer = nextResponseSerializer() else {
// Execute all response serializer completions and clear them
var completions: [() -> Void] = []
$mutableState.write { mutableState in
completions = mutableState.responseSerializerCompletions
// Clear out all response serializers and response serializer completions in mutable state since the
// request is complete. It's important to do this prior to calling the completion closures in case
// the completions call back into the request triggering a re-processing of the response serializers.
// An example of how this can happen is by calling cancel inside a response completion closure.
mutableState.responseSerializers.removeAll()
mutableState.responseSerializerCompletions.removeAll()
if mutableState.state.canTransitionTo(.finished) {
mutableState.state = .finished
}
mutableState.responseSerializerProcessingFinished = true
mutableState.isFinishing = false
}
completions.forEach { $0() }
// Cleanup the request
cleanup()
return
}
serializationQueue.async { responseSerializer() }
}
/// Notifies the `Request` that the response serializer is complete.
///
/// - Parameter completion: The completion handler provided with the response serializer, called when all serializers
/// are complete.
func responseSerializerDidComplete(completion: @escaping () -> Void) {
$mutableState.write { $0.responseSerializerCompletions.append(completion) }
processNextResponseSerializer()
}
/// Resets all task and response serializer related state for retry.
func reset() {
error = nil
uploadProgress.totalUnitCount = 0
uploadProgress.completedUnitCount = 0
downloadProgress.totalUnitCount = 0
downloadProgress.completedUnitCount = 0
$mutableState.write { state in
state.isFinishing = false
state.responseSerializerCompletions = []
}
}
/// Called when updating the upload progress.
///
/// - Parameters:
/// - totalBytesSent: Total bytes sent so far.
/// - totalBytesExpectedToSend: Total bytes expected to send.
func updateUploadProgress(totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
uploadProgress.totalUnitCount = totalBytesExpectedToSend
uploadProgress.completedUnitCount = totalBytesSent
uploadProgressHandler?.queue.async { self.uploadProgressHandler?.handler(self.uploadProgress) }
}
/// Perform a closure on the current `state` while locked.
///
/// - Parameter perform: The closure to perform.
func withState(perform: (State) -> Void) {
$mutableState.withState(perform: perform)
}
// MARK: Task Creation
/// Called when creating a `URLSessionTask` for this `Request`. Subclasses must override.
///
/// - Parameters:
/// - request: `URLRequest` to use to create the `URLSessionTask`.
/// - session: `URLSession` which creates the `URLSessionTask`.
///
/// - Returns: The `URLSessionTask` created.
func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
fatalError("Subclasses must override.")
}
// MARK: - Public API
// These APIs are callable from any queue.
// MARK: State
/// Cancels the instance. Once cancelled, a `Request` can no longer be resumed or suspended.
///
/// - Returns: The instance.
@discardableResult
public func cancel() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.cancelled) else { return }
mutableState.state = .cancelled
underlyingQueue.async { self.didCancel() }
guard let task = mutableState.tasks.last, task.state != .completed else {
underlyingQueue.async { self.finish() }
return
}
// Resume to ensure metrics are gathered.
task.resume()
task.cancel()
underlyingQueue.async { self.didCancelTask(task) }
}
return self
}
/// Suspends the instance.
///
/// - Returns: The instance.
@discardableResult
public func suspend() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.suspended) else { return }
mutableState.state = .suspended
underlyingQueue.async { self.didSuspend() }
guard let task = mutableState.tasks.last, task.state != .completed else { return }
task.suspend()
underlyingQueue.async { self.didSuspendTask(task) }
}
return self
}
/// Resumes the instance.
///
/// - Returns: The instance.
@discardableResult
public func resume() -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.resumed) else { return }
mutableState.state = .resumed
underlyingQueue.async { self.didResume() }
guard let task = mutableState.tasks.last, task.state != .completed else { return }
task.resume()
underlyingQueue.async { self.didResumeTask(task) }
}
return self
}
// MARK: - Closure API
/// Associates a credential using the provided values with the instance.
///
/// - Parameters:
/// - username: The username.
/// - password: The password.
/// - persistence: The `URLCredential.Persistence` for the created `URLCredential`. `.forSession` by default.
///
/// - Returns: The instance.
@discardableResult
public func authenticate(username: String, password: String, persistence: URLCredential.Persistence = .forSession) -> Self {
let credential = URLCredential(user: username, password: password, persistence: persistence)
return authenticate(with: credential)
}
/// Associates the provided credential with the instance.
///
/// - Parameter credential: The `URLCredential`.
///
/// - Returns: The instance.
@discardableResult
public func authenticate(with credential: URLCredential) -> Self {
mutableState.credential = credential
return self
}
/// Sets a closure to be called periodically during the lifecycle of the instance as data is read from the server.
///
/// - Note: Only the last closure provided is used.
///
/// - Parameters:
/// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
/// - closure: The closure to be executed periodically as data is read from the server.
///
/// - Returns: The instance.
@discardableResult
public func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
mutableState.downloadProgressHandler = (handler: closure, queue: queue)
return self
}
/// Sets a closure to be called periodically during the lifecycle of the instance as data is sent to the server.
///
/// - Note: Only the last closure provided is used.
///
/// - Parameters:
/// - queue: The `DispatchQueue` to execute the closure on. `.main` by default.
/// - closure: The closure to be executed periodically as data is sent to the server.
///
/// - Returns: The instance.
@discardableResult
public func uploadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self {
mutableState.uploadProgressHandler = (handler: closure, queue: queue)
return self
}
// MARK: Redirects
/// Sets the redirect handler for the instance which will be used if a redirect response is encountered.
///
/// - Note: Attempting to set the redirect handler more than once is a logic error and will crash.
///
/// - Parameter handler: The `RedirectHandler`.
///
/// - Returns: The instance.
@discardableResult
public func redirect(using handler: RedirectHandler) -> Self {
$mutableState.write { mutableState in
precondition(mutableState.redirectHandler == nil, "Redirect handler has already been set.")
mutableState.redirectHandler = handler
}
return self
}
// MARK: Cached Responses
/// Sets the cached response handler for the `Request` which will be used when attempting to cache a response.
///
/// - Note: Attempting to set the cache handler more than once is a logic error and will crash.
///
/// - Parameter handler: The `CachedResponseHandler`.
///
/// - Returns: The instance.
@discardableResult
public func cacheResponse(using handler: CachedResponseHandler) -> Self {
$mutableState.write { mutableState in
precondition(mutableState.cachedResponseHandler == nil, "Cached response handler has already been set.")
mutableState.cachedResponseHandler = handler
}
return self
}
// MARK: - Lifetime APIs
/// Sets a handler to be called when the cURL description of the request is available.
///
/// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which `handler` will be called.
/// - handler: Closure to be called when the cURL description is available.
///
/// - Returns: The instance.
@discardableResult
public func cURLDescription(on queue: DispatchQueue, calling handler: @escaping (String) -> Void) -> Self {
$mutableState.write { mutableState in
if mutableState.requests.last != nil {
queue.async { handler(self.cURLDescription()) }
} else {
mutableState.cURLHandler = (queue, handler)
}
}
return self
}
/// Sets a handler to be called when the cURL description of the request is available.
///
/// - Note: When waiting for a `Request`'s `URLRequest` to be created, only the last `handler` will be called.
///
/// - Parameter handler: Closure to be called when the cURL description is available. Called on the instance's
/// `underlyingQueue` by default.
///
/// - Returns: The instance.
@discardableResult
public func cURLDescription(calling handler: @escaping (String) -> Void) -> Self {
$mutableState.write { mutableState in
if mutableState.requests.last != nil {
underlyingQueue.async { handler(self.cURLDescription()) }
} else {
mutableState.cURLHandler = (underlyingQueue, handler)
}
}
return self
}
/// Sets a closure to called whenever Alamofire creates a `URLRequest` for this instance.
///
/// - Note: This closure will be called multiple times if the instance adapts incoming `URLRequest`s or is retried.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
/// - handler: Closure to be called when a `URLRequest` is available.
///
/// - Returns: The instance.
@discardableResult
public func onURLRequestCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLRequest) -> Void) -> Self {
$mutableState.write { state in
if let request = state.requests.last {
queue.async { handler(request) }
}
state.urlRequestHandler = (queue, handler)
}
return self
}
/// Sets a closure to be called whenever the instance creates a `URLSessionTask`.
///
/// - Note: This API should only be used to provide `URLSessionTask`s to existing API, like `NSFileProvider`. It
/// **SHOULD NOT** be used to interact with tasks directly, as that may be break Alamofire features.
/// Additionally, this closure may be called multiple times if the instance is retried.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which `handler` will be called. `.main` by default.
/// - handler: Closure to be called when the `URLSessionTask` is available.
///
/// - Returns: The instance.
@discardableResult
public func onURLSessionTaskCreation(on queue: DispatchQueue = .main, perform handler: @escaping (URLSessionTask) -> Void) -> Self {
$mutableState.write { state in
if let task = state.tasks.last {
queue.async { handler(task) }
}
state.urlSessionTaskHandler = (queue, handler)
}
return self
}
// MARK: Cleanup
/// Final cleanup step executed when the instance finishes response serialization.
func cleanup() {
delegate?.cleanup(after: self)
// No-op: override in subclass
}
}
// MARK: - Protocol Conformances
extension Request: Equatable {
public static func ==(lhs: Request, rhs: Request) -> Bool {
lhs.id == rhs.id
}
}
extension Request: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension Request: CustomStringConvertible {
/// A textual representation of this instance, including the `HTTPMethod` and `URL` if the `URLRequest` has been
/// created, as well as the response status code, if a response has been received.
public var description: String {
guard let request = performedRequests.last ?? lastRequest,
let url = request.url,
let method = request.httpMethod else { return "No request created yet." }
let requestDescription = "\(method) \(url.absoluteString)"
return response.map { "\(requestDescription) (\($0.statusCode))" } ?? requestDescription
}
}
extension Request {
/// cURL representation of the instance.
///
/// - Returns: The cURL equivalent of the instance.
public func cURLDescription() -> String {
guard
let request = lastRequest,
let url = request.url,
let host = url.host,
let method = request.httpMethod else { return "$ curl command could not be created" }
var components = ["$ curl -v"]
components.append("-X \(method)")
if let credentialStorage = delegate?.sessionConfiguration.urlCredentialStorage {
let protectionSpace = URLProtectionSpace(host: host,
port: url.port ?? 0,
protocol: url.scheme,
realm: host,
authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentials(for: protectionSpace)?.values {
for credential in credentials {
guard let user = credential.user, let password = credential.password else { continue }
components.append("-u \(user):\(password)")
}
} else {
if let credential = credential, let user = credential.user, let password = credential.password {
components.append("-u \(user):\(password)")
}
}
}
if let configuration = delegate?.sessionConfiguration, configuration.httpShouldSetCookies {
if
let cookieStorage = configuration.httpCookieStorage,
let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty {
let allCookies = cookies.map { "\($0.name)=\($0.value)" }.joined(separator: ";")
components.append("-b \"\(allCookies)\"")
}
}
var headers = HTTPHeaders()
if let sessionHeaders = delegate?.sessionConfiguration.headers {
for header in sessionHeaders where header.name != "Cookie" {
headers[header.name] = header.value
}
}
for header in request.headers where header.name != "Cookie" {
headers[header.name] = header.value
}
for header in headers {
let escapedValue = header.value.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-H \"\(header.name): \(escapedValue)\"")
}
if let httpBodyData = request.httpBody {
let httpBody = String(decoding: httpBodyData, as: UTF8.self)
var escapedBody = httpBody.replacingOccurrences(of: "\\\"", with: "\\\\\"")
escapedBody = escapedBody.replacingOccurrences(of: "\"", with: "\\\"")
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(url.absoluteString)\"")
return components.joined(separator: " \\\n\t")
}
}
/// Protocol abstraction for `Request`'s communication back to the `SessionDelegate`.
public protocol RequestDelegate: AnyObject {
/// `URLSessionConfiguration` used to create the underlying `URLSessionTask`s.
var sessionConfiguration: URLSessionConfiguration { get }
/// Determines whether the `Request` should automatically call `resume()` when adding the first response handler.
var startImmediately: Bool { get }
/// Notifies the delegate the `Request` has reached a point where it needs cleanup.
///
/// - Parameter request: The `Request` to cleanup after.
func cleanup(after request: Request)
/// Asynchronously ask the delegate whether a `Request` will be retried.
///
/// - Parameters:
/// - request: `Request` which failed.
/// - error: `Error` which produced the failure.
/// - completion: Closure taking the `RetryResult` for evaluation.
func retryResult(for request: Request, dueTo error: AFError, completion: @escaping (RetryResult) -> Void)
/// Asynchronously retry the `Request`.
///
/// - Parameters:
/// - request: `Request` which will be retried.
/// - timeDelay: `TimeInterval` after which the retry will be triggered.
func retryRequest(_ request: Request, withDelay timeDelay: TimeInterval?)
}
// MARK: - Subclasses
// MARK: - DataRequest
/// `Request` subclass which handles in-memory `Data` download using `URLSessionDataTask`.
public class DataRequest: Request {
/// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
public let convertible: URLRequestConvertible
/// `Data` read from the server so far.
public var data: Data? { mutableData }
/// Protected storage for the `Data` read by the instance.
@Protected
private var mutableData: Data? = nil
/// Creates a `DataRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this instance.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
convertible: URLRequestConvertible,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate) {
self.convertible = convertible
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func reset() {
super.reset()
mutableData = nil
}
/// Called when `Data` is received by this instance.
///
/// - Note: Also calls `updateDownloadProgress`.
///
/// - Parameter data: The `Data` received.
func didReceive(data: Data) {
if self.data == nil {
mutableData = data
} else {
$mutableData.write { $0?.append(data) }
}
updateDownloadProgress()
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
let copiedRequest = request
return session.dataTask(with: copiedRequest)
}
/// Called to updated the `downloadProgress` of the instance.
func updateDownloadProgress() {
let totalBytesReceived = Int64(data?.count ?? 0)
let totalBytesExpected = task?.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
downloadProgress.totalUnitCount = totalBytesExpected
downloadProgress.completedUnitCount = totalBytesReceived
downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
}
/// Validates the request, using the specified closure.
///
/// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter validation: `Validation` closure used to validate the response.
///
/// - Returns: The instance.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response, self.data)
if case let .failure(error) = result { self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error))) }
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
data: self.data,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
}
// MARK: - DataStreamRequest
/// `Request` subclass which streams HTTP response `Data` through a `Handler` closure.
public final class DataStreamRequest: Request {
/// Closure type handling `DataStreamRequest.Stream` values.
public typealias Handler = (Stream) throws -> Void
/// Type encapsulating an `Event` as it flows through the stream, as well as a `CancellationToken` which can be used
/// to stop the stream at any time.
public struct Stream {
/// Latest `Event` from the stream.
public let event: Event
/// Token used to cancel the stream.
public let token: CancellationToken
/// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
public func cancel() {
token.cancel()
}
}
/// Type representing an event flowing through the stream. Contains either the `Result` of processing streamed
/// `Data` or the completion of the stream.
public enum Event {
/// Output produced every time the instance receives additional `Data`. The associated value contains the
/// `Result` of processing the incoming `Data`.
case stream(Result)
/// Output produced when the instance has completed, whether due to stream end, cancellation, or an error.
/// Associated `Completion` value contains the final state.
case complete(Completion)
}
/// Value containing the state of a `DataStreamRequest` when the stream was completed.
public struct Completion {
/// Last `URLRequest` issued by the instance.
public let request: URLRequest?
/// Last `HTTPURLResponse` received by the instance.
public let response: HTTPURLResponse?
/// Last `URLSessionTaskMetrics` produced for the instance.
public let metrics: URLSessionTaskMetrics?
/// `AFError` produced for the instance, if any.
public let error: AFError?
}
/// Type used to cancel an ongoing stream.
public struct CancellationToken {
weak var request: DataStreamRequest?
init(_ request: DataStreamRequest) {
self.request = request
}
/// Cancel the ongoing stream by canceling the underlying `DataStreamRequest`.
public func cancel() {
request?.cancel()
}
}
/// `URLRequestConvertible` value used to create `URLRequest`s for this instance.
public let convertible: URLRequestConvertible
/// Whether or not the instance will be cancelled if stream parsing encounters an error.
public let automaticallyCancelOnStreamError: Bool
/// Internal mutable state specific to this type.
struct StreamMutableState {
/// `OutputStream` bound to the `InputStream` produced by `asInputStream`, if it has been called.
var outputStream: OutputStream?
/// Stream closures called as `Data` is received.
var streams: [(_ data: Data) -> Void] = []
/// Number of currently executing streams. Used to ensure completions are only fired after all streams are
/// enqueued.
var numberOfExecutingStreams = 0
/// Completion calls enqueued while streams are still executing.
var enqueuedCompletionEvents: [() -> Void] = []
}
@Protected
var streamMutableState = StreamMutableState()
/// Creates a `DataStreamRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()`
/// by default.
/// - convertible: `URLRequestConvertible` value used to create `URLRequest`s for this
/// instance.
/// - automaticallyCancelOnStreamError: `Bool` indicating whether the instance will be cancelled when an `Error`
/// is thrown while serializing stream `Data`.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default
/// targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by
/// the `Request`.
init(id: UUID = UUID(),
convertible: URLRequestConvertible,
automaticallyCancelOnStreamError: Bool,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate) {
self.convertible = convertible
self.automaticallyCancelOnStreamError = automaticallyCancelOnStreamError
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
let copiedRequest = request
return session.dataTask(with: copiedRequest)
}
override func finish(error: AFError? = nil) {
$streamMutableState.write { state in
state.outputStream?.close()
}
super.finish(error: error)
}
func didReceive(data: Data) {
$streamMutableState.write { state in
if let stream = state.outputStream {
underlyingQueue.async {
var bytes = Array(data)
stream.write(&bytes, maxLength: bytes.count)
}
}
state.numberOfExecutingStreams += state.streams.count
let localState = state
underlyingQueue.async { localState.streams.forEach { $0(data) } }
}
}
/// Validates the `URLRequest` and `HTTPURLResponse` received for the instance using the provided `Validation` closure.
///
/// - Parameter validation: `Validation` closure used to validate the request and response.
///
/// - Returns: The `DataStreamRequest`.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response)
if case let .failure(error) = result {
self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
}
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
/// Produces an `InputStream` that receives the `Data` received by the instance.
///
/// - Note: The `InputStream` produced by this method must have `open()` called before being able to read `Data`.
/// Additionally, this method will automatically call `resume()` on the instance, regardless of whether or
/// not the creating session has `startRequestsImmediately` set to `true`.
///
/// - Parameter bufferSize: Size, in bytes, of the buffer between the `OutputStream` and `InputStream`.
///
/// - Returns: The `InputStream` bound to the internal `OutboundStream`.
public func asInputStream(bufferSize: Int = 1024) -> InputStream? {
defer { resume() }
var inputStream: InputStream?
$streamMutableState.write { state in
Foundation.Stream.getBoundStreams(withBufferSize: bufferSize,
inputStream: &inputStream,
outputStream: &state.outputStream)
state.outputStream?.open()
}
return inputStream
}
func capturingError(from closure: () throws -> Void) {
do {
try closure()
} catch {
self.error = error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
cancel()
}
}
func appendStreamCompletion(on queue: DispatchQueue,
stream: @escaping Handler) {
appendResponseSerializer {
self.underlyingQueue.async {
self.responseSerializerDidComplete {
self.$streamMutableState.write { state in
guard state.numberOfExecutingStreams == 0 else {
state.enqueuedCompletionEvents.append {
self.enqueueCompletion(on: queue, stream: stream)
}
return
}
self.enqueueCompletion(on: queue, stream: stream)
}
}
}
}
}
func enqueueCompletion(on queue: DispatchQueue,
stream: @escaping Handler) {
queue.async {
do {
let completion = Completion(request: self.request,
response: self.response,
metrics: self.metrics,
error: self.error)
try stream(.init(event: .complete(completion), token: .init(self)))
} catch {
// Ignore error, as errors on Completion can't be handled anyway.
}
}
}
}
extension DataStreamRequest.Stream {
/// Incoming `Result` values from `Event.stream`.
public var result: Result? {
guard case let .stream(result) = event else { return nil }
return result
}
/// `Success` value of the instance, if any.
public var value: Success? {
guard case let .success(value) = result else { return nil }
return value
}
/// `Failure` value of the instance, if any.
public var error: Failure? {
guard case let .failure(error) = result else { return nil }
return error
}
/// `Completion` value of the instance, if any.
public var completion: DataStreamRequest.Completion? {
guard case let .complete(completion) = event else { return nil }
return completion
}
}
// MARK: - DownloadRequest
/// `Request` subclass which downloads `Data` to a file on disk using `URLSessionDownloadTask`.
public class DownloadRequest: Request {
/// A set of options to be executed prior to moving a downloaded file from the temporary `URL` to the destination
/// `URL`.
public struct Options: OptionSet {
/// Specifies that intermediate directories for the destination URL should be created.
public static let createIntermediateDirectories = Options(rawValue: 1 << 0)
/// Specifies that any previous file at the destination `URL` should be removed.
public static let removePreviousFile = Options(rawValue: 1 << 1)
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
// MARK: Destination
/// A closure executed once a `DownloadRequest` has successfully completed in order to determine where to move the
/// temporary file written to during the download process. The closure takes two arguments: the temporary file URL
/// and the `HTTPURLResponse`, and returns two values: the file URL where the temporary file should be moved and
/// the options defining how the file should be moved.
///
/// - Note: Downloads from a local `file://` `URL`s do not use the `Destination` closure, as those downloads do not
/// return an `HTTPURLResponse`. Instead the file is merely moved within the temporary directory.
public typealias Destination = (_ temporaryURL: URL,
_ response: HTTPURLResponse) -> (destinationURL: URL, options: Options)
/// Creates a download file destination closure which uses the default file manager to move the temporary file to a
/// file URL in the first available directory with the specified search path directory and search path domain mask.
///
/// - Parameters:
/// - directory: The search path directory. `.documentDirectory` by default.
/// - domain: The search path domain mask. `.userDomainMask` by default.
/// - options: `DownloadRequest.Options` used when moving the downloaded file to its destination. None by
/// default.
/// - Returns: The `Destination` closure.
public class func suggestedDownloadDestination(for directory: FileManager.SearchPathDirectory = .documentDirectory,
in domain: FileManager.SearchPathDomainMask = .userDomainMask,
options: Options = []) -> Destination {
{ temporaryURL, response in
let directoryURLs = FileManager.default.urls(for: directory, in: domain)
let url = directoryURLs.first?.appendingPathComponent(response.suggestedFilename!) ?? temporaryURL
return (url, options)
}
}
/// Default `Destination` used by Alamofire to ensure all downloads persist. This `Destination` prepends
/// `Alamofire_` to the automatically generated download name and moves it within the temporary directory. Files
/// with this destination must be additionally moved if they should survive the system reclamation of temporary
/// space.
static let defaultDestination: Destination = { url, _ in
(defaultDestinationURL(url), [])
}
/// Default `URL` creation closure. Creates a `URL` in the temporary directory with `Alamofire_` prepended to the
/// provided file name.
static let defaultDestinationURL: (URL) -> URL = { url in
let filename = "Alamofire_\(url.lastPathComponent)"
let destination = url.deletingLastPathComponent().appendingPathComponent(filename)
return destination
}
// MARK: Downloadable
/// Type describing the source used to create the underlying `URLSessionDownloadTask`.
public enum Downloadable {
/// Download should be started from the `URLRequest` produced by the associated `URLRequestConvertible` value.
case request(URLRequestConvertible)
/// Download should be started from the associated resume `Data` value.
case resumeData(Data)
}
// MARK: Mutable State
/// Type containing all mutable state for `DownloadRequest` instances.
private struct DownloadRequestMutableState {
/// Possible resume `Data` produced when cancelling the instance.
var resumeData: Data?
/// `URL` to which `Data` is being downloaded.
var fileURL: URL?
}
/// Protected mutable state specific to `DownloadRequest`.
@Protected
private var mutableDownloadState = DownloadRequestMutableState()
/// If the download is resumable and is eventually cancelled or fails, this value may be used to resume the download
/// using the `download(resumingWith data:)` API.
///
/// - Note: For more information about `resumeData`, see [Apple's documentation](https://developer.apple.com/documentation/foundation/urlsessiondownloadtask/1411634-cancel).
public var resumeData: Data? { mutableDownloadState.resumeData ?? error?.downloadResumeData }
/// If the download is successful, the `URL` where the file was downloaded.
public var fileURL: URL? { mutableDownloadState.fileURL }
// MARK: Initial State
/// `Downloadable` value used for this instance.
public let downloadable: Downloadable
/// The `Destination` to which the downloaded file is moved.
let destination: Destination
/// Creates a `DownloadRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - downloadable: `Downloadable` value used to create `URLSessionDownloadTasks` for the instance.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`
/// - destination: `Destination` closure used to move the downloaded file to its final location.
init(id: UUID = UUID(),
downloadable: Downloadable,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
delegate: RequestDelegate,
destination: @escaping Destination) {
self.downloadable = downloadable
self.destination = destination
super.init(id: id,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
override func reset() {
super.reset()
$mutableDownloadState.write {
$0.resumeData = nil
$0.fileURL = nil
}
}
/// Called when a download has finished.
///
/// - Parameters:
/// - task: `URLSessionTask` that finished the download.
/// - result: `Result` of the automatic move to `destination`.
func didFinishDownloading(using task: URLSessionTask, with result: Result) {
eventMonitor?.request(self, didFinishDownloadingUsing: task, with: result)
switch result {
case let .success(url): mutableDownloadState.fileURL = url
case let .failure(error): self.error = error
}
}
/// Updates the `downloadProgress` using the provided values.
///
/// - Parameters:
/// - bytesWritten: Total bytes written so far.
/// - totalBytesExpectedToWrite: Total bytes expected to write.
func updateDownloadProgress(bytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
downloadProgress.totalUnitCount = totalBytesExpectedToWrite
downloadProgress.completedUnitCount += bytesWritten
downloadProgressHandler?.queue.async { self.downloadProgressHandler?.handler(self.downloadProgress) }
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
session.downloadTask(with: request)
}
/// Creates a `URLSessionTask` from the provided resume data.
///
/// - Parameters:
/// - data: `Data` used to resume the download.
/// - session: `URLSession` used to create the `URLSessionTask`.
///
/// - Returns: The `URLSessionTask` created.
public func task(forResumeData data: Data, using session: URLSession) -> URLSessionTask {
session.downloadTask(withResumeData: data)
}
/// Cancels the instance. Once cancelled, a `DownloadRequest` can no longer be resumed or suspended.
///
/// - Note: This method will NOT produce resume data. If you wish to cancel and produce resume data, use
/// `cancel(producingResumeData:)` or `cancel(byProducingResumeData:)`.
///
/// - Returns: The instance.
@discardableResult
override public func cancel() -> Self {
cancel(producingResumeData: false)
}
/// Cancels the instance, optionally producing resume data. Once cancelled, a `DownloadRequest` can no longer be
/// resumed or suspended.
///
/// - Note: If `producingResumeData` is `true`, the `resumeData` property will be populated with any resume data, if
/// available.
///
/// - Returns: The instance.
@discardableResult
public func cancel(producingResumeData shouldProduceResumeData: Bool) -> Self {
cancel(optionallyProducingResumeData: shouldProduceResumeData ? { _ in } : nil)
}
/// Cancels the instance while producing resume data. Once cancelled, a `DownloadRequest` can no longer be resumed
/// or suspended.
///
/// - Note: The resume data passed to the completion handler will also be available on the instance's `resumeData`
/// property.
///
/// - Parameter completionHandler: The completion handler that is called when the download has been successfully
/// cancelled. It is not guaranteed to be called on a particular queue, so you may
/// want use an appropriate queue to perform your work.
///
/// - Returns: The instance.
@discardableResult
public func cancel(byProducingResumeData completionHandler: @escaping (_ data: Data?) -> Void) -> Self {
cancel(optionallyProducingResumeData: completionHandler)
}
/// Internal implementation of cancellation that optionally takes a resume data handler. If no handler is passed,
/// cancellation is performed without producing resume data.
///
/// - Parameter completionHandler: Optional resume data handler.
///
/// - Returns: The instance.
private func cancel(optionallyProducingResumeData completionHandler: ((_ resumeData: Data?) -> Void)?) -> Self {
$mutableState.write { mutableState in
guard mutableState.state.canTransitionTo(.cancelled) else { return }
mutableState.state = .cancelled
underlyingQueue.async { self.didCancel() }
guard let task = mutableState.tasks.last as? URLSessionDownloadTask, task.state != .completed else {
underlyingQueue.async { self.finish() }
return
}
if let completionHandler = completionHandler {
// Resume to ensure metrics are gathered.
task.resume()
task.cancel { resumeData in
self.mutableDownloadState.resumeData = resumeData
self.underlyingQueue.async { self.didCancelTask(task) }
completionHandler(resumeData)
}
} else {
// Resume to ensure metrics are gathered.
task.resume()
task.cancel(byProducingResumeData: { _ in })
self.underlyingQueue.async { self.didCancelTask(task) }
}
}
return self
}
/// Validates the request, using the specified closure.
///
/// - Note: If validation fails, subsequent calls to response handlers will have an associated error.
///
/// - Parameter validation: `Validation` closure to validate the response.
///
/// - Returns: The instance.
@discardableResult
public func validate(_ validation: @escaping Validation) -> Self {
let validator: () -> Void = { [unowned self] in
guard self.error == nil, let response = self.response else { return }
let result = validation(self.request, response, self.fileURL)
if case let .failure(error) = result {
self.error = error.asAFError(or: .responseValidationFailed(reason: .customValidationFailed(error: error)))
}
self.eventMonitor?.request(self,
didValidateRequest: self.request,
response: response,
fileURL: self.fileURL,
withResult: result)
}
$validators.write { $0.append(validator) }
return self
}
}
// MARK: - UploadRequest
/// `DataRequest` subclass which handles `Data` upload from memory, file, or stream using `URLSessionUploadTask`.
public class UploadRequest: DataRequest {
/// Type describing the origin of the upload, whether `Data`, file, or stream.
public enum Uploadable {
/// Upload from the provided `Data` value.
case data(Data)
/// Upload from the provided file `URL`, as well as a `Bool` determining whether the source file should be
/// automatically removed once uploaded.
case file(URL, shouldRemove: Bool)
/// Upload from the provided `InputStream`.
case stream(InputStream)
}
// MARK: Initial State
/// The `UploadableConvertible` value used to produce the `Uploadable` value for this instance.
public let upload: UploadableConvertible
/// `FileManager` used to perform cleanup tasks, including the removal of multipart form encoded payloads written
/// to disk.
public let fileManager: FileManager
// MARK: Mutable State
/// `Uploadable` value used by the instance.
public var uploadable: Uploadable?
/// Creates an `UploadRequest` using the provided parameters.
///
/// - Parameters:
/// - id: `UUID` used for the `Hashable` and `Equatable` implementations. `UUID()` by default.
/// - convertible: `UploadConvertible` value used to determine the type of upload to be performed.
/// - underlyingQueue: `DispatchQueue` on which all internal `Request` work is performed.
/// - serializationQueue: `DispatchQueue` on which all serialization work is performed. By default targets
/// `underlyingQueue`, but can be passed another queue from a `Session`.
/// - eventMonitor: `EventMonitor` called for event callbacks from internal `Request` actions.
/// - interceptor: `RequestInterceptor` used throughout the request lifecycle.
/// - delegate: `RequestDelegate` that provides an interface to actions not performed by the `Request`.
init(id: UUID = UUID(),
convertible: UploadConvertible,
underlyingQueue: DispatchQueue,
serializationQueue: DispatchQueue,
eventMonitor: EventMonitor?,
interceptor: RequestInterceptor?,
fileManager: FileManager,
delegate: RequestDelegate) {
upload = convertible
self.fileManager = fileManager
super.init(id: id,
convertible: convertible,
underlyingQueue: underlyingQueue,
serializationQueue: serializationQueue,
eventMonitor: eventMonitor,
interceptor: interceptor,
delegate: delegate)
}
/// Called when the `Uploadable` value has been created from the `UploadConvertible`.
///
/// - Parameter uploadable: The `Uploadable` that was created.
func didCreateUploadable(_ uploadable: Uploadable) {
self.uploadable = uploadable
eventMonitor?.request(self, didCreateUploadable: uploadable)
}
/// Called when the `Uploadable` value could not be created.
///
/// - Parameter error: `AFError` produced by the failure.
func didFailToCreateUploadable(with error: AFError) {
self.error = error
eventMonitor?.request(self, didFailToCreateUploadableWithError: error)
retryOrFinish(error: error)
}
override func task(for request: URLRequest, using session: URLSession) -> URLSessionTask {
guard let uploadable = uploadable else {
fatalError("Attempting to create a URLSessionUploadTask when Uploadable value doesn't exist.")
}
switch uploadable {
case let .data(data): return session.uploadTask(with: request, from: data)
case let .file(url, _): return session.uploadTask(with: request, fromFile: url)
case .stream: return session.uploadTask(withStreamedRequest: request)
}
}
override func reset() {
// Uploadable must be recreated on every retry.
uploadable = nil
super.reset()
}
/// Produces the `InputStream` from `uploadable`, if it can.
///
/// - Note: Calling this method with a non-`.stream` `Uploadable` is a logic error and will crash.
///
/// - Returns: The `InputStream`.
func inputStream() -> InputStream {
guard let uploadable = uploadable else {
fatalError("Attempting to access the input stream but the uploadable doesn't exist.")
}
guard case let .stream(stream) = uploadable else {
fatalError("Attempted to access the stream of an UploadRequest that wasn't created with one.")
}
eventMonitor?.request(self, didProvideInputStream: stream)
return stream
}
override public func cleanup() {
defer { super.cleanup() }
guard
let uploadable = self.uploadable,
case let .file(url, shouldRemove) = uploadable,
shouldRemove
else { return }
try? fileManager.removeItem(at: url)
}
}
/// A type that can produce an `UploadRequest.Uploadable` value.
public protocol UploadableConvertible {
/// Produces an `UploadRequest.Uploadable` value from the instance.
///
/// - Returns: The `UploadRequest.Uploadable`.
/// - Throws: Any `Error` produced during creation.
func createUploadable() throws -> UploadRequest.Uploadable
}
extension UploadRequest.Uploadable: UploadableConvertible {
public func createUploadable() throws -> UploadRequest.Uploadable {
self
}
}
/// A type that can be converted to an upload, whether from an `UploadRequest.Uploadable` or `URLRequestConvertible`.
public protocol UploadConvertible: UploadableConvertible & URLRequestConvertible {}
================================================
FILE: Pods/Alamofire/Source/RequestInterceptor.swift
================================================
//
// RequestInterceptor.swift
//
// Copyright (c) 2019 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary.
public protocol RequestAdapter {
/// Inspects and adapts the specified `URLRequest` in some manner and calls the completion handler with the Result.
///
/// - Parameters:
/// - urlRequest: The `URLRequest` to adapt.
/// - session: The `Session` that will execute the `URLRequest`.
/// - completion: The completion handler that must be called when adaptation is complete.
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void)
}
// MARK: -
/// Outcome of determination whether retry is necessary.
public enum RetryResult {
/// Retry should be attempted immediately.
case retry
/// Retry should be attempted after the associated `TimeInterval`.
case retryWithDelay(TimeInterval)
/// Do not retry.
case doNotRetry
/// Do not retry due to the associated `Error`.
case doNotRetryWithError(Error)
}
extension RetryResult {
var retryRequired: Bool {
switch self {
case .retry, .retryWithDelay: return true
default: return false
}
}
var delay: TimeInterval? {
switch self {
case let .retryWithDelay(delay): return delay
default: return nil
}
}
var error: Error? {
guard case let .doNotRetryWithError(error) = self else { return nil }
return error
}
}
/// A type that determines whether a request should be retried after being executed by the specified session manager
/// and encountering an error.
public protocol RequestRetrier {
/// Determines whether the `Request` should be retried by calling the `completion` closure.
///
/// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs
/// to be retried. The one requirement is that the completion closure is called to ensure the request is properly
/// cleaned up after.
///
/// - Parameters:
/// - request: `Request` that failed due to the provided `Error`.
/// - session: `Session` that produced the `Request`.
/// - error: `Error` encountered while executing the `Request`.
/// - completion: Completion closure to be executed when a retry decision has been determined.
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void)
}
// MARK: -
/// Type that provides both `RequestAdapter` and `RequestRetrier` functionality.
public protocol RequestInterceptor: RequestAdapter, RequestRetrier {}
extension RequestInterceptor {
public func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) {
completion(.success(urlRequest))
}
public func retry(_ request: Request,
for session: Session,
dueTo error: Error,
completion: @escaping (RetryResult) -> Void) {
completion(.doNotRetry)
}
}
/// `RequestAdapter` closure definition.
public typealias AdaptHandler = (URLRequest, Session, _ completion: @escaping (Result) -> Void) -> Void
/// `RequestRetrier` closure definition.
public typealias RetryHandler = (Request, Session, Error, _ completion: @escaping (RetryResult) -> Void) -> Void
// MARK: -
/// Closure-based `RequestAdapter`.
open class Adapter: RequestInterceptor {
private let adaptHandler: AdaptHandler
/// Creates an instance using the provided closure.
///
/// - Parameter adaptHandler: `AdaptHandler` closure to be executed when handling request adaptation.
public init(_ adaptHandler: @escaping AdaptHandler) {
self.adaptHandler = adaptHandler
}
open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) {
adaptHandler(urlRequest, session, completion)
}
}
// MARK: -
/// Closure-based `RequestRetrier`.
open class Retrier: RequestInterceptor {
private let retryHandler: RetryHandler
/// Creates an instance using the provided closure.
///
/// - Parameter retryHandler: `RetryHandler` closure to be executed when handling request retry.
public init(_ retryHandler: @escaping RetryHandler) {
self.retryHandler = retryHandler
}
open func retry(_ request: Request,
for session: Session,
dueTo error: Error,
completion: @escaping (RetryResult) -> Void) {
retryHandler(request, session, error, completion)
}
}
// MARK: -
/// `RequestInterceptor` which can use multiple `RequestAdapter` and `RequestRetrier` values.
open class Interceptor: RequestInterceptor {
/// All `RequestAdapter`s associated with the instance. These adapters will be run until one fails.
public let adapters: [RequestAdapter]
/// All `RequestRetrier`s associated with the instance. These retriers will be run one at a time until one triggers retry.
public let retriers: [RequestRetrier]
/// Creates an instance from `AdaptHandler` and `RetryHandler` closures.
///
/// - Parameters:
/// - adaptHandler: `AdaptHandler` closure to be used.
/// - retryHandler: `RetryHandler` closure to be used.
public init(adaptHandler: @escaping AdaptHandler, retryHandler: @escaping RetryHandler) {
adapters = [Adapter(adaptHandler)]
retriers = [Retrier(retryHandler)]
}
/// Creates an instance from `RequestAdapter` and `RequestRetrier` values.
///
/// - Parameters:
/// - adapter: `RequestAdapter` value to be used.
/// - retrier: `RequestRetrier` value to be used.
public init(adapter: RequestAdapter, retrier: RequestRetrier) {
adapters = [adapter]
retriers = [retrier]
}
/// Creates an instance from the arrays of `RequestAdapter` and `RequestRetrier` values.
///
/// - Parameters:
/// - adapters: `RequestAdapter` values to be used.
/// - retriers: `RequestRetrier` values to be used.
/// - interceptors: `RequestInterceptor`s to be used.
public init(adapters: [RequestAdapter] = [], retriers: [RequestRetrier] = [], interceptors: [RequestInterceptor] = []) {
self.adapters = adapters + interceptors
self.retriers = retriers + interceptors
}
open func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result) -> Void) {
adapt(urlRequest, for: session, using: adapters, completion: completion)
}
private func adapt(_ urlRequest: URLRequest,
for session: Session,
using adapters: [RequestAdapter],
completion: @escaping (Result) -> Void) {
var pendingAdapters = adapters
guard !pendingAdapters.isEmpty else { completion(.success(urlRequest)); return }
let adapter = pendingAdapters.removeFirst()
adapter.adapt(urlRequest, for: session) { result in
switch result {
case let .success(urlRequest):
self.adapt(urlRequest, for: session, using: pendingAdapters, completion: completion)
case .failure:
completion(result)
}
}
}
open func retry(_ request: Request,
for session: Session,
dueTo error: Error,
completion: @escaping (RetryResult) -> Void) {
retry(request, for: session, dueTo: error, using: retriers, completion: completion)
}
private func retry(_ request: Request,
for session: Session,
dueTo error: Error,
using retriers: [RequestRetrier],
completion: @escaping (RetryResult) -> Void) {
var pendingRetriers = retriers
guard !pendingRetriers.isEmpty else { completion(.doNotRetry); return }
let retrier = pendingRetriers.removeFirst()
retrier.retry(request, for: session, dueTo: error) { result in
switch result {
case .retry, .retryWithDelay, .doNotRetryWithError:
completion(result)
case .doNotRetry:
// Only continue to the next retrier if retry was not triggered and no error was encountered
self.retry(request, for: session, dueTo: error, using: pendingRetriers, completion: completion)
}
}
}
}
================================================
FILE: Pods/Alamofire/Source/RequestTaskMap.swift
================================================
//
// RequestTaskMap.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// A type that maintains a two way, one to one map of `URLSessionTask`s to `Request`s.
struct RequestTaskMap {
private typealias Events = (completed: Bool, metricsGathered: Bool)
private var tasksToRequests: [URLSessionTask: Request]
private var requestsToTasks: [Request: URLSessionTask]
private var taskEvents: [URLSessionTask: Events]
var requests: [Request] {
Array(tasksToRequests.values)
}
init(tasksToRequests: [URLSessionTask: Request] = [:],
requestsToTasks: [Request: URLSessionTask] = [:],
taskEvents: [URLSessionTask: (completed: Bool, metricsGathered: Bool)] = [:]) {
self.tasksToRequests = tasksToRequests
self.requestsToTasks = requestsToTasks
self.taskEvents = taskEvents
}
subscript(_ request: Request) -> URLSessionTask? {
get { requestsToTasks[request] }
set {
guard let newValue = newValue else {
guard let task = requestsToTasks[request] else {
fatalError("RequestTaskMap consistency error: no task corresponding to request found.")
}
requestsToTasks.removeValue(forKey: request)
tasksToRequests.removeValue(forKey: task)
taskEvents.removeValue(forKey: task)
return
}
requestsToTasks[request] = newValue
tasksToRequests[newValue] = request
taskEvents[newValue] = (completed: false, metricsGathered: false)
}
}
subscript(_ task: URLSessionTask) -> Request? {
get { tasksToRequests[task] }
set {
guard let newValue = newValue else {
guard let request = tasksToRequests[task] else {
fatalError("RequestTaskMap consistency error: no request corresponding to task found.")
}
tasksToRequests.removeValue(forKey: task)
requestsToTasks.removeValue(forKey: request)
taskEvents.removeValue(forKey: task)
return
}
tasksToRequests[task] = newValue
requestsToTasks[newValue] = task
taskEvents[task] = (completed: false, metricsGathered: false)
}
}
var count: Int {
precondition(tasksToRequests.count == requestsToTasks.count,
"RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)")
return tasksToRequests.count
}
var eventCount: Int {
precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)")
return taskEvents.count
}
var isEmpty: Bool {
precondition(tasksToRequests.isEmpty == requestsToTasks.isEmpty,
"RequestTaskMap.isEmpty invalid, requests.isEmpty: \(tasksToRequests.isEmpty) != tasks.isEmpty: \(requestsToTasks.isEmpty)")
return tasksToRequests.isEmpty
}
var isEventsEmpty: Bool {
precondition(taskEvents.isEmpty == isEmpty, "RequestTaskMap.isEventsEmpty invalid, isEmpty: \(isEmpty) != taskEvents.isEmpty: \(taskEvents.isEmpty)")
return taskEvents.isEmpty
}
mutating func disassociateIfNecessaryAfterGatheringMetricsForTask(_ task: URLSessionTask) -> Bool {
guard let events = taskEvents[task] else {
fatalError("RequestTaskMap consistency error: no events corresponding to task found.")
}
switch (events.completed, events.metricsGathered) {
case (_, true): fatalError("RequestTaskMap consistency error: duplicate metricsGatheredForTask call.")
case (false, false): taskEvents[task] = (completed: false, metricsGathered: true); return false
case (true, false): self[task] = nil; return true
}
}
mutating func disassociateIfNecessaryAfterCompletingTask(_ task: URLSessionTask) -> Bool {
guard let events = taskEvents[task] else {
fatalError("RequestTaskMap consistency error: no events corresponding to task found.")
}
switch (events.completed, events.metricsGathered) {
case (true, _): fatalError("RequestTaskMap consistency error: duplicate completionReceivedForTask call.")
#if os(Linux) // Linux doesn't gather metrics, so unconditionally remove the reference and return true.
default: self[task] = nil; return true
#else
case (false, false):
if #available(macOS 10.12, iOS 10, watchOS 7, tvOS 10, *) {
taskEvents[task] = (completed: true, metricsGathered: false); return false
} else {
// watchOS < 7 doesn't gather metrics, so unconditionally remove the reference and return true.
self[task] = nil; return true
}
case (false, true):
self[task] = nil; return true
#endif
}
}
}
================================================
FILE: Pods/Alamofire/Source/Response.swift
================================================
//
// Response.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Default type of `DataResponse` returned by Alamofire, with an `AFError` `Failure` type.
public typealias AFDataResponse = DataResponse
/// Default type of `DownloadResponse` returned by Alamofire, with an `AFError` `Failure` type.
public typealias AFDownloadResponse = DownloadResponse
/// Type used to store all values associated with a serialized response of a `DataRequest` or `UploadRequest`.
public struct DataResponse {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The final metrics of the response.
///
/// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
///
public let metrics: URLSessionTaskMetrics?
/// The time taken to serialize the response.
public let serializationDuration: TimeInterval
/// The result of response serialization.
public let result: Result
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Success? { result.success }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Failure? { result.failure }
/// Creates a `DataResponse` instance with the specified parameters derived from the response serialization.
///
/// - Parameters:
/// - request: The `URLRequest` sent to the server.
/// - response: The `HTTPURLResponse` from the server.
/// - data: The `Data` returned by the server.
/// - metrics: The `URLSessionTaskMetrics` of the `DataRequest` or `UploadRequest`.
/// - serializationDuration: The duration taken by serialization.
/// - result: The `Result` of response serialization.
public init(request: URLRequest?,
response: HTTPURLResponse?,
data: Data?,
metrics: URLSessionTaskMetrics?,
serializationDuration: TimeInterval,
result: Result) {
self.request = request
self.response = response
self.data = data
self.metrics = metrics
self.serializationDuration = serializationDuration
self.result = result
}
}
// MARK: -
extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
"\(result)"
}
/// The debug textual representation used when written to an output stream, which includes (if available) a summary
/// of the `URLRequest`, the request's headers and body (if decodable as a `String` below 100KB); the
/// `HTTPURLResponse`'s status code, headers, and body; the duration of the network and serialization actions; and
/// the `Result` of serialization.
public var debugDescription: String {
guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
let requestDescription = DebugDescription.description(of: urlRequest)
let responseDescription = response.map { response in
let responseBodyDescription = DebugDescription.description(for: data, headers: response.headers)
return """
\(DebugDescription.description(of: response))
\(responseBodyDescription.indentingNewlines())
"""
} ?? "[Response]: None"
let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
return """
\(requestDescription)
\(responseDescription)
[Network Duration]: \(networkDuration)
[Serialization Duration]: \(serializationDuration)s
[Result]: \(result)
"""
}
}
// MARK: -
extension DataResponse {
/// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: DataResponse = ...
/// let possibleInt = possibleData.map { $0.count }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's
/// result is a failure, returns a response wrapping the same failure.
public func map(_ transform: (Success) -> NewSuccess) -> DataResponse {
DataResponse(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.map(transform))
}
/// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result
/// value as a parameter.
///
/// Use the `tryMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse = ...
/// let possibleObject = possibleData.tryMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's
/// result is a failure, returns the same failure.
public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DataResponse {
DataResponse(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMap(transform))
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: DataResponse = ...
/// let withMyError = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
///
/// - Returns: A `DataResponse` instance containing the result of the transform.
public func mapError(_ transform: (Failure) -> NewFailure) -> DataResponse {
DataResponse(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.mapError(transform))
}
/// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `tryMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DataResponse = ...
/// let possibleObject = possibleData.tryMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `DataResponse` instance containing the result of the transform.
public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DataResponse {
DataResponse(request: request,
response: response,
data: data,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMapError(transform))
}
}
// MARK: -
/// Used to store all data associated with a serialized response of a download request.
public struct DownloadResponse {
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The final destination URL of the data returned from the server after it is moved.
public let fileURL: URL?
/// The resume data generated if the request was cancelled.
public let resumeData: Data?
/// The final metrics of the response.
///
/// - Note: Due to `FB7624529`, collection of `URLSessionTaskMetrics` on watchOS is currently disabled.`
///
public let metrics: URLSessionTaskMetrics?
/// The time taken to serialize the response.
public let serializationDuration: TimeInterval
/// The result of response serialization.
public let result: Result
/// Returns the associated value of the result if it is a success, `nil` otherwise.
public var value: Success? { result.success }
/// Returns the associated error value if the result if it is a failure, `nil` otherwise.
public var error: Failure? { result.failure }
/// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization.
///
/// - Parameters:
/// - request: The `URLRequest` sent to the server.
/// - response: The `HTTPURLResponse` from the server.
/// - temporaryURL: The temporary destination `URL` of the data returned from the server.
/// - destinationURL: The final destination `URL` of the data returned from the server, if it was moved.
/// - resumeData: The resume `Data` generated if the request was cancelled.
/// - metrics: The `URLSessionTaskMetrics` of the `DownloadRequest`.
/// - serializationDuration: The duration taken by serialization.
/// - result: The `Result` of response serialization.
public init(request: URLRequest?,
response: HTTPURLResponse?,
fileURL: URL?,
resumeData: Data?,
metrics: URLSessionTaskMetrics?,
serializationDuration: TimeInterval,
result: Result) {
self.request = request
self.response = response
self.fileURL = fileURL
self.resumeData = resumeData
self.metrics = metrics
self.serializationDuration = serializationDuration
self.result = result
}
}
// MARK: -
extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible {
/// The textual representation used when written to an output stream, which includes whether the result was a
/// success or failure.
public var description: String {
"\(result)"
}
/// The debug textual representation used when written to an output stream, which includes the URL request, the URL
/// response, the temporary and destination URLs, the resume data, the durations of the network and serialization
/// actions, and the response serialization result.
public var debugDescription: String {
guard let urlRequest = request else { return "[Request]: None\n[Result]: \(result)" }
let requestDescription = DebugDescription.description(of: urlRequest)
let responseDescription = response.map(DebugDescription.description(of:)) ?? "[Response]: None"
let networkDuration = metrics.map { "\($0.taskInterval.duration)s" } ?? "None"
let resumeDataDescription = resumeData.map { "\($0)" } ?? "None"
return """
\(requestDescription)
\(responseDescription)
[File URL]: \(fileURL?.path ?? "None")
[Resume Data]: \(resumeDataDescription)
[Network Duration]: \(networkDuration)
[Serialization Duration]: \(serializationDuration)s
[Result]: \(result)
"""
}
}
// MARK: -
extension DownloadResponse {
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `map` method with a closure that does not throw. For example:
///
/// let possibleData: DownloadResponse = ...
/// let possibleInt = possibleData.map { $0.count }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's
/// result is a failure, returns a response wrapping the same failure.
public func map(_ transform: (Success) -> NewSuccess) -> DownloadResponse {
DownloadResponse(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.map(transform))
}
/// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped
/// result value as a parameter.
///
/// Use the `tryMap` method with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse = ...
/// let possibleObject = possibleData.tryMap {
/// try JSONSerialization.jsonObject(with: $0)
/// }
///
/// - parameter transform: A closure that takes the success value of the instance's result.
///
/// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this
/// instance's result is a failure, returns the same failure.
public func tryMap(_ transform: (Success) throws -> NewSuccess) -> DownloadResponse {
DownloadResponse(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMap(transform))
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `mapError` function with a closure that does not throw. For example:
///
/// let possibleData: DownloadResponse = ...
/// let withMyError = possibleData.mapError { MyError.error($0) }
///
/// - Parameter transform: A closure that takes the error of the instance.
///
/// - Returns: A `DownloadResponse` instance containing the result of the transform.
public func mapError(_ transform: (Failure) -> NewFailure) -> DownloadResponse {
DownloadResponse(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.mapError(transform))
}
/// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter.
///
/// Use the `tryMapError` function with a closure that may throw an error. For example:
///
/// let possibleData: DownloadResponse = ...
/// let possibleObject = possibleData.tryMapError {
/// try someFailableFunction(taking: $0)
/// }
///
/// - Parameter transform: A throwing closure that takes the error of the instance.
///
/// - Returns: A `DownloadResponse` instance containing the result of the transform.
public func tryMapError(_ transform: (Failure) throws -> NewFailure) -> DownloadResponse {
DownloadResponse(request: request,
response: response,
fileURL: fileURL,
resumeData: resumeData,
metrics: metrics,
serializationDuration: serializationDuration,
result: result.tryMapError(transform))
}
}
private enum DebugDescription {
static func description(of request: URLRequest) -> String {
let requestSummary = "\(request.httpMethod!) \(request)"
let requestHeadersDescription = DebugDescription.description(for: request.headers)
let requestBodyDescription = DebugDescription.description(for: request.httpBody, headers: request.headers)
return """
[Request]: \(requestSummary)
\(requestHeadersDescription.indentingNewlines())
\(requestBodyDescription.indentingNewlines())
"""
}
static func description(of response: HTTPURLResponse) -> String {
"""
[Response]:
[Status Code]: \(response.statusCode)
\(DebugDescription.description(for: response.headers).indentingNewlines())
"""
}
static func description(for headers: HTTPHeaders) -> String {
guard !headers.isEmpty else { return "[Headers]: None" }
let headerDescription = "\(headers.sorted())".indentingNewlines()
return """
[Headers]:
\(headerDescription)
"""
}
static func description(for data: Data?,
headers: HTTPHeaders,
allowingPrintableTypes printableTypes: [String] = ["json", "xml", "text"],
maximumLength: Int = 100_000) -> String {
guard let data = data, !data.isEmpty else { return "[Body]: None" }
guard
data.count <= maximumLength,
printableTypes.compactMap({ headers["Content-Type"]?.contains($0) }).contains(true)
else { return "[Body]: \(data.count) bytes" }
return """
[Body]:
\(String(decoding: data, as: UTF8.self)
.trimmingCharacters(in: .whitespacesAndNewlines)
.indentingNewlines())
"""
}
}
extension String {
fileprivate func indentingNewlines(by spaceCount: Int = 4) -> String {
let spaces = String(repeating: " ", count: spaceCount)
return replacingOccurrences(of: "\n", with: "\n\(spaces)")
}
}
================================================
FILE: Pods/Alamofire/Source/ResponseSerialization.swift
================================================
//
// ResponseSerialization.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
// MARK: Protocols
/// The type to which all data response serializers must conform in order to serialize a response.
public protocol DataResponseSerializerProtocol {
/// The type of serialized object to be created.
associatedtype SerializedObject
/// Serialize the response `Data` into the provided type..
///
/// - Parameters:
/// - request: `URLRequest` which was used to perform the request, if any.
/// - response: `HTTPURLResponse` received from the server, if any.
/// - data: `Data` returned from the server, if any.
/// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
///
/// - Returns: The `SerializedObject`.
/// - Throws: Any `Error` produced during serialization.
func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> SerializedObject
}
/// The type to which all download response serializers must conform in order to serialize a response.
public protocol DownloadResponseSerializerProtocol {
/// The type of serialized object to be created.
associatedtype SerializedObject
/// Serialize the downloaded response `Data` from disk into the provided type..
///
/// - Parameters:
/// - request: `URLRequest` which was used to perform the request, if any.
/// - response: `HTTPURLResponse` received from the server, if any.
/// - fileURL: File `URL` to which the response data was downloaded.
/// - error: `Error` produced by Alamofire or the underlying `URLSession` during the request.
///
/// - Returns: The `SerializedObject`.
/// - Throws: Any `Error` produced during serialization.
func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> SerializedObject
}
/// A serializer that can handle both data and download responses.
public protocol ResponseSerializer: DataResponseSerializerProtocol & DownloadResponseSerializerProtocol {
/// `DataPreprocessor` used to prepare incoming `Data` for serialization.
var dataPreprocessor: DataPreprocessor { get }
/// `HTTPMethod`s for which empty response bodies are considered appropriate.
var emptyRequestMethods: Set { get }
/// HTTP response codes for which empty response bodies are considered appropriate.
var emptyResponseCodes: Set { get }
}
/// Type used to preprocess `Data` before it handled by a serializer.
public protocol DataPreprocessor {
/// Process `Data` before it's handled by a serializer.
/// - Parameter data: The raw `Data` to process.
func preprocess(_ data: Data) throws -> Data
}
/// `DataPreprocessor` that returns passed `Data` without any transform.
public struct PassthroughPreprocessor: DataPreprocessor {
public init() {}
public func preprocess(_ data: Data) throws -> Data { data }
}
/// `DataPreprocessor` that trims Google's typical `)]}',\n` XSSI JSON header.
public struct GoogleXSSIPreprocessor: DataPreprocessor {
public init() {}
public func preprocess(_ data: Data) throws -> Data {
(data.prefix(6) == Data(")]}',\n".utf8)) ? data.dropFirst(6) : data
}
}
extension ResponseSerializer {
/// Default `DataPreprocessor`. `PassthroughPreprocessor` by default.
public static var defaultDataPreprocessor: DataPreprocessor { PassthroughPreprocessor() }
/// Default `HTTPMethod`s for which empty response bodies are considered appropriate. `[.head]` by default.
public static var defaultEmptyRequestMethods: Set { [.head] }
/// HTTP response codes for which empty response bodies are considered appropriate. `[204, 205]` by default.
public static var defaultEmptyResponseCodes: Set { [204, 205] }
public var dataPreprocessor: DataPreprocessor { Self.defaultDataPreprocessor }
public var emptyRequestMethods: Set { Self.defaultEmptyRequestMethods }
public var emptyResponseCodes: Set { Self.defaultEmptyResponseCodes }
/// Determines whether the `request` allows empty response bodies, if `request` exists.
///
/// - Parameter request: `URLRequest` to evaluate.
///
/// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `request` was `nil`.
public func requestAllowsEmptyResponseData(_ request: URLRequest?) -> Bool? {
request.flatMap { $0.httpMethod }
.flatMap(HTTPMethod.init)
.map { emptyRequestMethods.contains($0) }
}
/// Determines whether the `response` allows empty response bodies, if `response` exists`.
///
/// - Parameter response: `HTTPURLResponse` to evaluate.
///
/// - Returns: `Bool` representing the outcome of the evaluation, or `nil` if `response` was `nil`.
public func responseAllowsEmptyResponseData(_ response: HTTPURLResponse?) -> Bool? {
response.flatMap { $0.statusCode }
.map { emptyResponseCodes.contains($0) }
}
/// Determines whether `request` and `response` allow empty response bodies.
///
/// - Parameters:
/// - request: `URLRequest` to evaluate.
/// - response: `HTTPURLResponse` to evaluate.
///
/// - Returns: `true` if `request` or `response` allow empty bodies, `false` otherwise.
public func emptyResponseAllowed(forRequest request: URLRequest?, response: HTTPURLResponse?) -> Bool {
(requestAllowsEmptyResponseData(request) == true) || (responseAllowsEmptyResponseData(response) == true)
}
}
/// By default, any serializer declared to conform to both types will get file serialization for free, as it just feeds
/// the data read from disk into the data response serializer.
extension DownloadResponseSerializerProtocol where Self: DataResponseSerializerProtocol {
public func serializeDownload(request: URLRequest?, response: HTTPURLResponse?, fileURL: URL?, error: Error?) throws -> Self.SerializedObject {
guard error == nil else { throw error! }
guard let fileURL = fileURL else {
throw AFError.responseSerializationFailed(reason: .inputFileNil)
}
let data: Data
do {
data = try Data(contentsOf: fileURL)
} catch {
throw AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))
}
do {
return try serialize(request: request, response: response, data: data, error: error)
} catch {
throw error
}
}
}
// MARK: - Default
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response(queue: DispatchQueue = .main, completionHandler: @escaping (AFDataResponse) -> Void) -> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let result = AFResult(value: self.data, error: self.error)
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DataResponse(request: self.request,
response: self.response,
data: self.data,
metrics: self.metrics,
serializationDuration: 0,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default
/// - responseSerializer: The response serializer responsible for serializing the request, response, and data.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response(queue: DispatchQueue = .main,
responseSerializer: Serializer,
completionHandler: @escaping (AFDataResponse) -> Void)
-> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let start = ProcessInfo.processInfo.systemUptime
let result: AFResult = Result {
try responseSerializer.serialize(request: self.request,
response: self.response,
data: self.data,
error: self.error)
}.mapError { error in
error.asAFError(or: .responseSerializationFailed(reason: .customSerializationFailed(error: error)))
}
let end = ProcessInfo.processInfo.systemUptime
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DataResponse(request: self.request,
response: self.response,
data: self.data,
metrics: self.metrics,
serializationDuration: end - start,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
guard let serializerError = result.failure, let delegate = self.delegate else {
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
return
}
delegate.retryResult(for: self, dueTo: serializerError) { retryResult in
var didComplete: (() -> Void)?
defer {
if let didComplete = didComplete {
self.responseSerializerDidComplete { queue.async { didComplete() } }
}
}
switch retryResult {
case .doNotRetry:
didComplete = { completionHandler(response) }
case let .doNotRetryWithError(retryError):
let result: AFResult = .failure(retryError.asAFError(orFailWith: "Received retryError was not already AFError"))
let response = DataResponse(request: self.request,
response: self.response,
data: self.data,
metrics: self.metrics,
serializationDuration: end - start,
result: result)
didComplete = { completionHandler(response) }
case .retry, .retryWithDelay:
delegate.retryRequest(self, withDelay: retryResult.delay)
}
}
}
}
return self
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response(queue: DispatchQueue = .main,
completionHandler: @escaping (AFDownloadResponse) -> Void)
-> Self {
appendResponseSerializer {
// Start work that should be on the serialization queue.
let result = AFResult(value: self.fileURL, error: self.error)
// End work that should be on the serialization queue.
self.underlyingQueue.async {
let response = DownloadResponse(request: self.request,
response: self.response,
fileURL: self.fileURL,
resumeData: self.resumeData,
metrics: self.metrics,
serializationDuration: 0,
result: result)
self.eventMonitor?.request(self, didParseResponse: response)
self.responseSerializerDidComplete { queue.async { completionHandler(response) } }
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - Parameters:
/// - queue: The queue on which the completion handler is dispatched. `.main` by default.
/// - responseSerializer: The response serializer responsible for serializing the request, response, and data
/// contained in the destination `URL`.
/// - completionHandler: The code to be executed once the request has finished.
///
/// - Returns: The request.
@discardableResult
public func response(queue: DispatchQueue = .main,
responseSerializer: Serializer,
completionHandler: @escaping (AFDownloadResponse