diff --git a/.gitignore b/.gitignore index 30e159db9..6f854f028 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,8 @@ DerivedData Paco-iOS/Paco.xcodeproj/project.xcworkspace/xcuserdata/* Paco-iOS/Paco.xcodeproj/project.xcworkspace/xcshareddata/* Paco-iOS/Paco.xcodeproj/xcuserdata/* +Paco-iOS/Paco.xcworkspace/xcuserdata/* Paco-iOS/ParseKit/ParseKit.xcodeproj/xcuserdata/* Paco-iOS/ParseKit/lib/OCMock/OCMock.xcodeproj/xcuserdata/* -Paco-iOS/ParseKit/include* \ No newline at end of file +Paco-iOS/ParseKit/include* +Paco-iOS/DerivedData/* diff --git a/Paco-iOS/Paco.xcodeproj/project.pbxproj b/Paco-iOS/Paco.xcodeproj/project.pbxproj index 8026fff63..16b384fd9 100644 --- a/Paco-iOS/Paco.xcodeproj/project.pbxproj +++ b/Paco-iOS/Paco.xcodeproj/project.pbxproj @@ -89,8 +89,6 @@ 36A8201918B556CC00FE83A5 /* PacoScheduleGenerator+Daily.m in Sources */ = {isa = PBXBuildFile; fileRef = 36A8201718B556CC00FE83A5 /* PacoScheduleGenerator+Daily.m */; }; 36A8201C18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m in Sources */ = {isa = PBXBuildFile; fileRef = 36A8201B18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m */; }; 36A8201D18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m in Sources */ = {isa = PBXBuildFile; fileRef = 36A8201B18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m */; }; - 36AD6CDD17C420F800B93855 /* SSKeychain.m in Sources */ = {isa = PBXBuildFile; fileRef = 36AD6CDA17C420F800B93855 /* SSKeychain.m */; }; - 36AD6CDE17C420F800B93855 /* SSKeychainQuery.m in Sources */ = {isa = PBXBuildFile; fileRef = 36AD6CDC17C420F800B93855 /* SSKeychainQuery.m */; }; 36AD6CE217C4440000B93855 /* NSError+Paco.m in Sources */ = {isa = PBXBuildFile; fileRef = 36AD6CE117C4440000B93855 /* NSError+Paco.m */; }; 36AD6CEB17C5977E00B93855 /* PacoEvaluatorTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 36AD6CEA17C5977E00B93855 /* PacoEvaluatorTests.m */; }; 36B5A4F218282CBC004DB894 /* PacoScheduleGeneratorDailyESMTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 36B5A4F118282CBC004DB894 /* PacoScheduleGeneratorDailyESMTests.m */; }; @@ -162,9 +160,6 @@ 36B8EC0117568E29004CF035 /* smile_icon5_re.png in Resources */ = {isa = PBXBuildFile; fileRef = 36B8EBC417568E29004CF035 /* smile_icon5_re.png */; }; 36B8EC1017568E29004CF035 /* uicheckbox_checked.png in Resources */ = {isa = PBXBuildFile; fileRef = 36B8EBD317568E29004CF035 /* uicheckbox_checked.png */; }; 36B8EC1117568E29004CF035 /* uicheckbox_unchecked.png in Resources */ = {isa = PBXBuildFile; fileRef = 36B8EBD417568E29004CF035 /* uicheckbox_unchecked.png */; }; - 36B8EC2D17568E33004CF035 /* GTMNSString+URLArguments.m in Sources */ = {isa = PBXBuildFile; fileRef = 36B8EC1717568E33004CF035 /* GTMNSString+URLArguments.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 36B8EC3317568E33004CF035 /* GoogleAppEngineAuth.m in Sources */ = {isa = PBXBuildFile; fileRef = 36B8EC2A17568E33004CF035 /* GoogleAppEngineAuth.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 36B8EC3417568E33004CF035 /* GoogleClientLogin.m in Sources */ = {isa = PBXBuildFile; fileRef = 36B8EC2C17568E33004CF035 /* GoogleClientLogin.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 36B8EC3C17568E40004CF035 /* PacoTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 36B8EC3717568E40004CF035 /* PacoTests.m */; }; 36B8EC3D17568E40004CF035 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 36B8EC3917568E40004CF035 /* InfoPlist.strings */; }; 36BC10DD17FE09E8001EA9DD /* PacoIOSLocalNotificationTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 36BC10DC17FE09E8001EA9DD /* PacoIOSLocalNotificationTests.m */; }; @@ -181,65 +176,10 @@ 36F02D34180DE16B0027395F /* PacoNSDateCategoryTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 36F02D32180DE16B0027395F /* PacoNSDateCategoryTests.m */; }; 36F3EFE818FC645500ABF242 /* PacoESMDailyGeneratorWithCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 36F3EFE718FC645500ABF242 /* PacoESMDailyGeneratorWithCache.m */; }; 36F457E31863ABA900931049 /* welcome_paco.html in Resources */ = {isa = PBXBuildFile; fileRef = 36F457E21863ABA900931049 /* welcome_paco.html */; }; - 4448BCA11A808E7A0034FCE9 /* GTMGatherInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC531A808E7A0034FCE9 /* GTMGatherInputStream.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA21A808E7A0034FCE9 /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC551A808E7A0034FCE9 /* GTMHTTPFetcher.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA31A808E7A0034FCE9 /* GTMHTTPFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC5A1A808E7A0034FCE9 /* GTMHTTPFetcherLogging.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA41A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC5C1A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA51A808E7A0034FCE9 /* GTMHTTPFetcherService.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC5E1A808E7A0034FCE9 /* GTMHTTPFetcherService.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA61A808E7A0034FCE9 /* GTMHTTPFetchHistory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC601A808E7A0034FCE9 /* GTMHTTPFetchHistory.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA71A808E7A0034FCE9 /* GTMHTTPUploadFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC621A808E7A0034FCE9 /* GTMHTTPUploadFetcher.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA81A808E7A0034FCE9 /* GTMMIMEDocument.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC641A808E7A0034FCE9 /* GTMMIMEDocument.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCA91A808E7A0034FCE9 /* GTMReadMonitorInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC661A808E7A0034FCE9 /* GTMReadMonitorInputStream.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCAA1A808E7A0034FCE9 /* ReleaseNotes.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4448BC671A808E7A0034FCE9 /* ReleaseNotes.txt */; }; - 4448BCB61A808E7A0034FCE9 /* UnitTests-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 4448BC771A808E7A0034FCE9 /* UnitTests-Info.plist */; }; - 4448BCB71A808E7A0034FCE9 /* NSObject+SBJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC7B1A808E7A0034FCE9 /* NSObject+SBJSON.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCB81A808E7A0034FCE9 /* NSString+SBJSON.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC7D1A808E7A0034FCE9 /* NSString+SBJSON.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCB91A808E7A0034FCE9 /* SBJsonBase.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC7F1A808E7A0034FCE9 /* SBJsonBase.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCBA1A808E7A0034FCE9 /* SBJsonParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC811A808E7A0034FCE9 /* SBJsonParser.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCBB1A808E7A0034FCE9 /* SBJsonWriter.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC831A808E7A0034FCE9 /* SBJsonWriter.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCBC1A808E7A0034FCE9 /* GTMOAuth2Authentication.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC891A808E7A0034FCE9 /* GTMOAuth2Authentication.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCBD1A808E7A0034FCE9 /* GTMOAuth2SignIn.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC8B1A808E7A0034FCE9 /* GTMOAuth2SignIn.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCBE1A808E7A0034FCE9 /* GTMOAuth2Framework-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 4448BC8D1A808E7A0034FCE9 /* GTMOAuth2Framework-Info.plist */; }; - 4448BCBF1A808E7A0034FCE9 /* GTMOAuth2Window.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4448BC8E1A808E7A0034FCE9 /* GTMOAuth2Window.xib */; }; - 4448BCC01A808E7A0034FCE9 /* GTMOAuth2WindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BC901A808E7A0034FCE9 /* GTMOAuth2WindowController.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCC11A808E7A0034FCE9 /* ReleaseNotes.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4448BC911A808E7A0034FCE9 /* ReleaseNotes.txt */; }; - 4448BCDC1A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.m in Sources */ = {isa = PBXBuildFile; fileRef = 4448BCDA1A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; - 4448BCDD1A80901D0034FCE9 /* GTMOAuth2ViewTouch.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4448BCDB1A80901D0034FCE9 /* GTMOAuth2ViewTouch.xib */; }; - 44A843C51ADB9C0A009C7226 /* ExperimentEditOutcome.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A11ADB9C0A009C7226 /* ExperimentEditOutcome.java */; }; - 44A843C61ADB9C0A009C7226 /* Outcome.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A21ADB9C0A009C7226 /* Outcome.java */; }; - 44A843C71ADB9C0A009C7226 /* ActionTrigger.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A41ADB9C0A009C7226 /* ActionTrigger.java */; }; - 44A843C81ADB9C0A009C7226 /* EventInterface.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A51ADB9C0A009C7226 /* EventInterface.java */; }; - 44A843C91ADB9C0A009C7226 /* EventStore.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A61ADB9C0A009C7226 /* EventStore.java */; }; - 44A843CA1ADB9C0A009C7226 /* ExperimentDAO.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A71ADB9C0A009C7226 /* ExperimentDAO.java */; }; - 44A843CB1ADB9C0A009C7226 /* ExperimentDAOCore.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A81ADB9C0A009C7226 /* ExperimentDAOCore.java */; }; - 44A843CC1ADB9C0A009C7226 /* ExperimentGroup.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843A91ADB9C0A009C7226 /* ExperimentGroup.java */; }; - 44A843CD1ADB9C0A009C7226 /* ExperimentQueryResult.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843AA1ADB9C0A009C7226 /* ExperimentQueryResult.java */; }; - 44A843CE1ADB9C0A009C7226 /* ExperimentValidator.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843AB1ADB9C0A009C7226 /* ExperimentValidator.java */; }; - 44A843CF1ADB9C0A009C7226 /* Feedback.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843AC1ADB9C0A009C7226 /* Feedback.java */; }; - 44A843D01ADB9C0A009C7226 /* Input2.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843AD1ADB9C0A009C7226 /* Input2.java */; }; - 44A843D11ADB9C0A009C7226 /* InterruptCue.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843AE1ADB9C0A009C7226 /* InterruptCue.java */; }; - 44A843D21ADB9C0A009C7226 /* InterruptTrigger.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843AF1ADB9C0A009C7226 /* InterruptTrigger.java */; }; - 44A843D31ADB9C0A009C7226 /* ListMaker.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B01ADB9C0A009C7226 /* ListMaker.java */; }; - 44A843D41ADB9C0A009C7226 /* MinimumBufferable.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B11ADB9C0A009C7226 /* MinimumBufferable.java */; }; - 44A843D51ADB9C0A009C7226 /* PacoAction.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B21ADB9C0A009C7226 /* PacoAction.java */; }; - 44A843D61ADB9C0A009C7226 /* PacoActionAllOthers.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B31ADB9C0A009C7226 /* PacoActionAllOthers.java */; }; - 44A843D71ADB9C0A009C7226 /* PacoNotificationAction.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B41ADB9C0A009C7226 /* PacoNotificationAction.java */; }; - 44A843D81ADB9C0A009C7226 /* Schedule.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B51ADB9C0A009C7226 /* Schedule.java */; }; - 44A843D91ADB9C0A009C7226 /* ScheduleTrigger.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B61ADB9C0A009C7226 /* ScheduleTrigger.java */; }; - 44A843DA1ADB9C0A009C7226 /* SignalTime.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B71ADB9C0A009C7226 /* SignalTime.java */; }; - 44A843DB1ADB9C0A009C7226 /* Validatable.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B81ADB9C0A009C7226 /* Validatable.java */; }; - 44A843DC1ADB9C0A009C7226 /* ValidationMessage.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843B91ADB9C0A009C7226 /* ValidationMessage.java */; }; - 44A843DD1ADB9C0A009C7226 /* Validator.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843BA1ADB9C0A009C7226 /* Validator.java */; }; - 44A843DE1ADB9C0A009C7226 /* ActionScheduleGenerator.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843BC1ADB9C0A009C7226 /* ActionScheduleGenerator.java */; }; - 44A843DF1ADB9C0A009C7226 /* ActionSpecification.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843BD1ADB9C0A009C7226 /* ActionSpecification.java */; }; - 44A843E01ADB9C0A009C7226 /* EsmGenerator2.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843BE1ADB9C0A009C7226 /* EsmGenerator2.java */; }; - 44A843E11ADB9C0A009C7226 /* EsmSignalStore.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843BF1ADB9C0A009C7226 /* EsmSignalStore.java */; }; - 44A843E21ADB9C0A009C7226 /* NonESMSignalGenerator.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843C01ADB9C0A009C7226 /* NonESMSignalGenerator.java */; }; - 44A843E31ADB9C0A009C7226 /* ExperimentHelper.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843C21ADB9C0A009C7226 /* ExperimentHelper.java */; }; - 44A843E41ADB9C0A009C7226 /* SchedulePrinter.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843C31ADB9C0A009C7226 /* SchedulePrinter.java */; }; - 44A843E51ADB9C0A009C7226 /* TimeUtil.java in Sources */ = {isa = PBXBuildFile; fileRef = 44A843C41ADB9C0A009C7226 /* TimeUtil.java */; }; - 44A843E71ADB9C2F009C7226 /* j2objcprefixes.properties in Resources */ = {isa = PBXBuildFile; fileRef = 44A843E61ADB9C2F009C7226 /* j2objcprefixes.properties */; }; - 44F9DDF91ADB5EA50098BECB /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 44F9DDF81ADB5EA50098BECB /* libz.dylib */; }; + 44239C001EA9DD4B0026E69A /* AppAuth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44239BFD1EA9DD4B0026E69A /* AppAuth.framework */; }; + 44239C011EA9DD4B0026E69A /* GTMAppAuth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44239BFE1EA9DD4B0026E69A /* GTMAppAuth.framework */; }; + 44239C021EA9DD4B0026E69A /* GTMSessionFetcher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 44239BFF1EA9DD4B0026E69A /* GTMSessionFetcher.framework */; }; + 6A56DF05AC441FE9735102FE /* Pods_Paco.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8DA66BC3BA03A7F250872B5E /* Pods_Paco.framework */; }; 7F8531D41A37BE680028BA23 /* JCNotificationBanner.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F8531BE1A37BE680028BA23 /* JCNotificationBanner.m */; }; 7F8531D51A37BE680028BA23 /* JCNotificationBannerPresenter.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F8531C11A37BE680028BA23 /* JCNotificationBannerPresenter.m */; }; 7F8531D61A37BE680028BA23 /* JCNotificationBannerPresenterIOS7Style.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F8531C31A37BE680028BA23 /* JCNotificationBannerPresenterIOS7Style.m */; }; @@ -252,56 +192,7 @@ 7F8531DD1A37BE680028BA23 /* JCNotificationBannerWindow.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F8531D11A37BE680028BA23 /* JCNotificationBannerWindow.m */; }; 7F8531DE1A37BE680028BA23 /* JCNotificationCenter.m in Sources */ = {isa = PBXBuildFile; fileRef = 7F8531D31A37BE680028BA23 /* JCNotificationCenter.m */; }; 7FB660801AA8C305008D2327 /* paco32@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7FB6607E1AA8C305008D2327 /* paco32@2x.png */; }; - 7FB660811AA8C305008D2327 /* paco32@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7FB6607F1AA8C305008D2327 /* paco32@3x.png */; }; 7FB660901AA8C352008D2327 /* PacoTitleView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 7FB6608F1AA8C352008D2327 /* PacoTitleView.xib */; }; - A633A99F1B5DA0970046436D /* ExperimentEditOutcome.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A97A1B5DA0970046436D /* ExperimentEditOutcome.java */; }; - A633A9A01B5DA0970046436D /* Outcome.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A97B1B5DA0970046436D /* Outcome.java */; }; - A633A9A11B5DA0970046436D /* ActionTrigger.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A97D1B5DA0970046436D /* ActionTrigger.java */; }; - A633A9A21B5DA0970046436D /* EventInterface.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A97E1B5DA0970046436D /* EventInterface.java */; }; - A633A9A31B5DA0970046436D /* EventStore.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A97F1B5DA0970046436D /* EventStore.java */; }; - A633A9A41B5DA0970046436D /* ExperimentDAO.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9801B5DA0970046436D /* ExperimentDAO.java */; }; - A633A9A51B5DA0970046436D /* ExperimentDAOCore.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9811B5DA0970046436D /* ExperimentDAOCore.java */; }; - A633A9A61B5DA0970046436D /* ExperimentGroup.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9821B5DA0970046436D /* ExperimentGroup.java */; }; - A633A9A71B5DA0970046436D /* ExperimentQueryResult.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9831B5DA0970046436D /* ExperimentQueryResult.java */; }; - A633A9A81B5DA0970046436D /* ExperimentValidator.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9841B5DA0970046436D /* ExperimentValidator.java */; }; - A633A9A91B5DA0970046436D /* Feedback.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9851B5DA0970046436D /* Feedback.java */; }; - A633A9AA1B5DA0970046436D /* Input2.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9861B5DA0970046436D /* Input2.java */; }; - A633A9AB1B5DA0970046436D /* InterruptCue.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9871B5DA0970046436D /* InterruptCue.java */; }; - A633A9AC1B5DA0970046436D /* InterruptTrigger.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9881B5DA0970046436D /* InterruptTrigger.java */; }; - A633A9AD1B5DA0970046436D /* ListMaker.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9891B5DA0970046436D /* ListMaker.java */; }; - A633A9AE1B5DA0970046436D /* MinimumBufferable.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A98A1B5DA0970046436D /* MinimumBufferable.java */; }; - A633A9AF1B5DA0970046436D /* PacoAction.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A98B1B5DA0970046436D /* PacoAction.java */; }; - A633A9B01B5DA0970046436D /* PacoActionAllOthers.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A98C1B5DA0970046436D /* PacoActionAllOthers.java */; }; - A633A9B11B5DA0970046436D /* PacoNotificationAction.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A98D1B5DA0970046436D /* PacoNotificationAction.java */; }; - A633A9B21B5DA0970046436D /* Schedule.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A98E1B5DA0970046436D /* Schedule.java */; }; - A633A9B31B5DA0970046436D /* ScheduleTrigger.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A98F1B5DA0970046436D /* ScheduleTrigger.java */; }; - A633A9B41B5DA0970046436D /* SignalTime.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9901B5DA0970046436D /* SignalTime.java */; }; - A633A9B51B5DA0970046436D /* Validatable.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9911B5DA0970046436D /* Validatable.java */; }; - A633A9B61B5DA0970046436D /* ValidationMessage.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9921B5DA0970046436D /* ValidationMessage.java */; }; - A633A9B71B5DA0970046436D /* Validator.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9931B5DA0970046436D /* Validator.java */; }; - A633A9B81B5DA0970046436D /* ActionScheduleGenerator.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9951B5DA0970046436D /* ActionScheduleGenerator.java */; }; - A633A9B91B5DA0970046436D /* ActionSpecification.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9961B5DA0970046436D /* ActionSpecification.java */; }; - A633A9BA1B5DA0970046436D /* EsmGenerator2.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9971B5DA0970046436D /* EsmGenerator2.java */; }; - A633A9BB1B5DA0970046436D /* EsmSignalStore.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9981B5DA0970046436D /* EsmSignalStore.java */; }; - A633A9BC1B5DA0970046436D /* NonESMSignalGenerator.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A9991B5DA0970046436D /* NonESMSignalGenerator.java */; }; - A633A9BD1B5DA0970046436D /* ExperimentHelper.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A99B1B5DA0970046436D /* ExperimentHelper.java */; }; - A633A9BE1B5DA0970046436D /* SchedulePrinter.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A99C1B5DA0970046436D /* SchedulePrinter.java */; }; - A633A9BF1B5DA0970046436D /* TimeUtil.java in Sources */ = {isa = PBXBuildFile; fileRef = A633A99D1B5DA0970046436D /* TimeUtil.java */; }; - A633A9C01B5DA0970046436D /* readme.md in Sources */ = {isa = PBXBuildFile; fileRef = A633A99E1B5DA0970046436D /* readme.md */; }; - A633A9C21B5DA1B70046436D /* PacoJ2OBJCTests.m in Sources */ = {isa = PBXBuildFile; fileRef = A633A9C11B5DA1B70046436D /* PacoJ2OBJCTests.m */; }; - A6701D611B73D48C00229432 /* joda in Resources */ = {isa = PBXBuildFile; fileRef = A6701D601B73D48C00229432 /* joda */; }; - A67076101B62F26A00017D36 /* DerivedSources in Resources */ = {isa = PBXBuildFile; fileRef = A670760F1B62F26A00017D36 /* DerivedSources */; }; - A67076111B62F26A00017D36 /* DerivedSources in Resources */ = {isa = PBXBuildFile; fileRef = A670760F1B62F26A00017D36 /* DerivedSources */; }; - A676C7381B6043DE00F37572 /* Pacoj2Objc2JsonTests.m in Sources */ = {isa = PBXBuildFile; fileRef = A676C7371B6043DE00F37572 /* Pacoj2Objc2JsonTests.m */; }; - A676C73C1B615AAB00F37572 /* libobjc.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = A676C73B1B615AAB00F37572 /* libobjc.dylib */; }; - A678C2751B703955003F0D27 /* ModelBase.java in Sources */ = {isa = PBXBuildFile; fileRef = A678C2741B703955003F0D27 /* ModelBase.java */; }; - A678C2761B7042D3003F0D27 /* DerivedSources in Sources */ = {isa = PBXBuildFile; fileRef = A670760F1B62F26A00017D36 /* DerivedSources */; }; - A678C2E51B716283003F0D27 /* ModelBase.java in Sources */ = {isa = PBXBuildFile; fileRef = A678C2E41B716283003F0D27 /* ModelBase.java */; }; - A6ABFA971B742BA700F90598 /* ITAhoCorasickContainer.m in Sources */ = {isa = PBXBuildFile; fileRef = A6ABFA961B742BA700F90598 /* ITAhoCorasickContainer.m */; }; - A6ABFAA21B742BE800F90598 /* NSMutableDictionary+ITExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = A6ABFA9B1B742BE800F90598 /* NSMutableDictionary+ITExtension.m */; }; - A6ABFAA31B742BE800F90598 /* NSObject+ITNDescription.m in Sources */ = {isa = PBXBuildFile; fileRef = A6ABFA9D1B742BE800F90598 /* NSObject+ITNDescription.m */; }; - A6ABFAA41B742BE800F90598 /* NSObject+J2objcKVO.m in Sources */ = {isa = PBXBuildFile; fileRef = A6ABFA9F1B742BE800F90598 /* NSObject+J2objcKVO.m */; }; - A6ABFAA51B742BE800F90598 /* PacoSerializer.m in Sources */ = {isa = PBXBuildFile; fileRef = A6ABFAA11B742BE800F90598 /* PacoSerializer.m */; }; C567E89017A03FDE00267A26 /* deepbark_trial.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = C567E88F17A03FDE00267A26 /* deepbark_trial.mp3 */; }; C5B4691917B07E4900B6BC18 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C5B4691817B07E4900B6BC18 /* CoreGraphics.framework */; }; C5C4F5D217B163EF009E9F18 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C5C4F5D117B163EF009E9F18 /* QuartzCore.framework */; }; @@ -317,31 +208,6 @@ E4F9A79818899F39006A2803 /* PacoStepperView.m in Sources */ = {isa = PBXBuildFile; fileRef = E4F9A79718899F39006A2803 /* PacoStepperView.m */; }; /* End PBXBuildFile section */ -/* Begin PBXBuildRule section */ - 44F9DDF71ADB5D840098BECB /* PBXBuildRule */ = { - isa = PBXBuildRule; - compilerSpec = com.apple.compilers.proxy.script; - fileType = sourcecode.java; - isEditable = 1; - outputFiles = ( - "$(DERIVED_FILE_DIR)/${INPUT_FILE_BASE}.h", - "$(DERIVED_FILE_DIR)/${INPUT_FILE_BASE}.m", - ); - script = "../Shared/j2objc/j2objc -d ${DERIVED_FILE_DIR} -classpath ../Shared/lib/joda-time-2.5.jar -sourcepath ../Shared/src --prefixes ../Shared/j2objcprefixes.properties --no-package-directories -use-arc ${INPUT_FILE_PATH};"; - }; - A6D9AA8F1B59AA5C00595C06 /* PBXBuildRule */ = { - isa = PBXBuildRule; - compilerSpec = com.apple.compilers.proxy.script; - fileType = sourcecode.java; - isEditable = 1; - outputFiles = ( - "$(DERIVED_FILE_DIR)/${INPUT_FILE_BASE}.m", - "$(DERIVED_FILE_DIR)/${INPUT_FILE_BASE}.h", - ); - script = "../Shared/j2objc/j2objc -d ${DERIVED_FILE_DIR} -classpath ../Shared/lib/joda-time-2.5.jar -sourcepath ../Shared/src --prefixes ../Shared/j2objcprefixes.properties --no-package-directories -use-arc ${INPUT_FILE_PATH};"; - }; -/* End PBXBuildRule section */ - /* Begin PBXContainerItemProxy section */ 319771F3163F0733000AC06B /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; @@ -413,34 +279,6 @@ remoteGlobalIDString = D3FDC5820FFC4BFC00F1F797; remoteInfo = libParseKitMobile; }; - 4448BCC61A808E7A0034FCE9 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 4448BC561A808E7A0034FCE9 /* GTMHTTPFetcher.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = D2AAC07E0554694100DB518D; - remoteInfo = GTMHTTPFetcherLib; - }; - 4448BCC81A808E7A0034FCE9 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 4448BC561A808E7A0034FCE9 /* GTMHTTPFetcher.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 4F74D92F11E68BD300F2D927; - remoteInfo = UnitTests; - }; - 4448BCCE1A808E7A0034FCE9 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 4448BC851A808E7A0034FCE9 /* GTMOAuth2.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = D2AAC07E0554694100DB518D; - remoteInfo = OAuthTouchStaticLib; - }; - 4448BCD01A808E7A0034FCE9 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 4448BC851A808E7A0034FCE9 /* GTMOAuth2.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 4FC754FA13E77E25006A0C26; - remoteInfo = OAuthTouchNonGoogleStaticLib; - }; /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ @@ -542,10 +380,6 @@ 36A8201718B556CC00FE83A5 /* PacoScheduleGenerator+Daily.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "PacoScheduleGenerator+Daily.m"; sourceTree = ""; }; 36A8201A18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "PacoScheduleGenerator+Weekdays.h"; sourceTree = ""; }; 36A8201B18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "PacoScheduleGenerator+Weekdays.m"; sourceTree = ""; }; - 36AD6CD917C420F800B93855 /* SSKeychain.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SSKeychain.h; sourceTree = ""; }; - 36AD6CDA17C420F800B93855 /* SSKeychain.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SSKeychain.m; sourceTree = ""; }; - 36AD6CDB17C420F800B93855 /* SSKeychainQuery.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SSKeychainQuery.h; sourceTree = ""; }; - 36AD6CDC17C420F800B93855 /* SSKeychainQuery.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SSKeychainQuery.m; sourceTree = ""; }; 36AD6CE017C4440000B93855 /* NSError+Paco.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSError+Paco.h"; sourceTree = ""; }; 36AD6CE117C4440000B93855 /* NSError+Paco.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSError+Paco.m"; sourceTree = ""; }; 36AD6CE917C5977E00B93855 /* PacoEvaluatorTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PacoEvaluatorTests.h; sourceTree = ""; }; @@ -659,14 +493,6 @@ 36B8EBC417568E29004CF035 /* smile_icon5_re.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = smile_icon5_re.png; sourceTree = ""; }; 36B8EBD317568E29004CF035 /* uicheckbox_checked.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = uicheckbox_checked.png; sourceTree = ""; }; 36B8EBD417568E29004CF035 /* uicheckbox_unchecked.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = uicheckbox_unchecked.png; sourceTree = ""; }; - 36B8EC1517568E33004CF035 /* GTMGarbageCollection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMGarbageCollection.h; sourceTree = ""; }; - 36B8EC1617568E33004CF035 /* GTMNSString+URLArguments.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GTMNSString+URLArguments.h"; sourceTree = ""; }; - 36B8EC1717568E33004CF035 /* GTMNSString+URLArguments.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "GTMNSString+URLArguments.m"; sourceTree = ""; }; - 36B8EC1817568E33004CF035 /* GTMDefines.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMDefines.h; sourceTree = ""; }; - 36B8EC2917568E33004CF035 /* GoogleAppEngineAuth.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GoogleAppEngineAuth.h; sourceTree = ""; }; - 36B8EC2A17568E33004CF035 /* GoogleAppEngineAuth.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GoogleAppEngineAuth.m; sourceTree = ""; }; - 36B8EC2B17568E33004CF035 /* GoogleClientLogin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GoogleClientLogin.h; sourceTree = ""; }; - 36B8EC2C17568E33004CF035 /* GoogleClientLogin.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GoogleClientLogin.m; sourceTree = ""; }; 36B8EC3617568E40004CF035 /* PacoTests.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PacoTests.h; sourceTree = ""; }; 36B8EC3717568E40004CF035 /* PacoTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PacoTests.m; sourceTree = ""; }; 36B8EC3A17568E40004CF035 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; @@ -689,86 +515,9 @@ 36F02D32180DE16B0027395F /* PacoNSDateCategoryTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PacoNSDateCategoryTests.m; sourceTree = ""; }; 36F3EFE718FC645500ABF242 /* PacoESMDailyGeneratorWithCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PacoESMDailyGeneratorWithCache.m; sourceTree = ""; }; 36F457E21863ABA900931049 /* welcome_paco.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; path = welcome_paco.html; sourceTree = ""; }; - 4448BC521A808E7A0034FCE9 /* GTMGatherInputStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMGatherInputStream.h; sourceTree = ""; }; - 4448BC531A808E7A0034FCE9 /* GTMGatherInputStream.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMGatherInputStream.m; sourceTree = ""; }; - 4448BC541A808E7A0034FCE9 /* GTMHTTPFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcher.h; sourceTree = ""; }; - 4448BC551A808E7A0034FCE9 /* GTMHTTPFetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcher.m; sourceTree = ""; }; - 4448BC561A808E7A0034FCE9 /* GTMHTTPFetcher.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = GTMHTTPFetcher.xcodeproj; sourceTree = ""; }; - 4448BC591A808E7A0034FCE9 /* GTMHTTPFetcherLogging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcherLogging.h; sourceTree = ""; }; - 4448BC5A1A808E7A0034FCE9 /* GTMHTTPFetcherLogging.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcherLogging.m; sourceTree = ""; }; - 4448BC5B1A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcherLogViewController.h; sourceTree = ""; }; - 4448BC5C1A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcherLogViewController.m; sourceTree = ""; }; - 4448BC5D1A808E7A0034FCE9 /* GTMHTTPFetcherService.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcherService.h; sourceTree = ""; }; - 4448BC5E1A808E7A0034FCE9 /* GTMHTTPFetcherService.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcherService.m; sourceTree = ""; }; - 4448BC5F1A808E7A0034FCE9 /* GTMHTTPFetchHistory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetchHistory.h; sourceTree = ""; }; - 4448BC601A808E7A0034FCE9 /* GTMHTTPFetchHistory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetchHistory.m; sourceTree = ""; }; - 4448BC611A808E7A0034FCE9 /* GTMHTTPUploadFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPUploadFetcher.h; sourceTree = ""; }; - 4448BC621A808E7A0034FCE9 /* GTMHTTPUploadFetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPUploadFetcher.m; sourceTree = ""; }; - 4448BC631A808E7A0034FCE9 /* GTMMIMEDocument.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMMIMEDocument.h; sourceTree = ""; }; - 4448BC641A808E7A0034FCE9 /* GTMMIMEDocument.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMMIMEDocument.m; sourceTree = ""; }; - 4448BC651A808E7A0034FCE9 /* GTMReadMonitorInputStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMReadMonitorInputStream.h; sourceTree = ""; }; - 4448BC661A808E7A0034FCE9 /* GTMReadMonitorInputStream.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMReadMonitorInputStream.m; sourceTree = ""; }; - 4448BC671A808E7A0034FCE9 /* ReleaseNotes.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReleaseNotes.txt; sourceTree = ""; }; - 4448BC771A808E7A0034FCE9 /* UnitTests-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "UnitTests-Info.plist"; sourceTree = ""; }; - 4448BC791A808E7A0034FCE9 /* JSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSON.h; sourceTree = ""; }; - 4448BC7A1A808E7A0034FCE9 /* NSObject+SBJSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSObject+SBJSON.h"; sourceTree = ""; }; - 4448BC7B1A808E7A0034FCE9 /* NSObject+SBJSON.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+SBJSON.m"; sourceTree = ""; }; - 4448BC7C1A808E7A0034FCE9 /* NSString+SBJSON.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+SBJSON.h"; sourceTree = ""; }; - 4448BC7D1A808E7A0034FCE9 /* NSString+SBJSON.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+SBJSON.m"; sourceTree = ""; }; - 4448BC7E1A808E7A0034FCE9 /* SBJsonBase.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBJsonBase.h; sourceTree = ""; }; - 4448BC7F1A808E7A0034FCE9 /* SBJsonBase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBJsonBase.m; sourceTree = ""; }; - 4448BC801A808E7A0034FCE9 /* SBJsonParser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBJsonParser.h; sourceTree = ""; }; - 4448BC811A808E7A0034FCE9 /* SBJsonParser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBJsonParser.m; sourceTree = ""; }; - 4448BC821A808E7A0034FCE9 /* SBJsonWriter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SBJsonWriter.h; sourceTree = ""; }; - 4448BC831A808E7A0034FCE9 /* SBJsonWriter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SBJsonWriter.m; sourceTree = ""; }; - 4448BC851A808E7A0034FCE9 /* GTMOAuth2.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; path = GTMOAuth2.xcodeproj; sourceTree = ""; }; - 4448BC881A808E7A0034FCE9 /* GTMOAuth2Authentication.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMOAuth2Authentication.h; sourceTree = ""; }; - 4448BC891A808E7A0034FCE9 /* GTMOAuth2Authentication.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMOAuth2Authentication.m; sourceTree = ""; }; - 4448BC8A1A808E7A0034FCE9 /* GTMOAuth2SignIn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMOAuth2SignIn.h; sourceTree = ""; }; - 4448BC8B1A808E7A0034FCE9 /* GTMOAuth2SignIn.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMOAuth2SignIn.m; sourceTree = ""; }; - 4448BC8D1A808E7A0034FCE9 /* GTMOAuth2Framework-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GTMOAuth2Framework-Info.plist"; sourceTree = ""; }; - 4448BC8E1A808E7A0034FCE9 /* GTMOAuth2Window.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = GTMOAuth2Window.xib; sourceTree = ""; }; - 4448BC8F1A808E7A0034FCE9 /* GTMOAuth2WindowController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMOAuth2WindowController.h; sourceTree = ""; }; - 4448BC901A808E7A0034FCE9 /* GTMOAuth2WindowController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMOAuth2WindowController.m; sourceTree = ""; }; - 4448BC911A808E7A0034FCE9 /* ReleaseNotes.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReleaseNotes.txt; sourceTree = ""; }; - 4448BCD91A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMOAuth2ViewControllerTouch.h; sourceTree = ""; }; - 4448BCDA1A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMOAuth2ViewControllerTouch.m; sourceTree = ""; }; - 4448BCDB1A80901D0034FCE9 /* GTMOAuth2ViewTouch.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = GTMOAuth2ViewTouch.xib; sourceTree = ""; }; - 44A843A11ADB9C0A009C7226 /* ExperimentEditOutcome.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentEditOutcome.java; sourceTree = ""; }; - 44A843A21ADB9C0A009C7226 /* Outcome.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Outcome.java; sourceTree = ""; }; - 44A843A41ADB9C0A009C7226 /* ActionTrigger.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ActionTrigger.java; sourceTree = ""; }; - 44A843A51ADB9C0A009C7226 /* EventInterface.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EventInterface.java; sourceTree = ""; }; - 44A843A61ADB9C0A009C7226 /* EventStore.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EventStore.java; sourceTree = ""; }; - 44A843A71ADB9C0A009C7226 /* ExperimentDAO.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentDAO.java; sourceTree = ""; }; - 44A843A81ADB9C0A009C7226 /* ExperimentDAOCore.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentDAOCore.java; sourceTree = ""; }; - 44A843A91ADB9C0A009C7226 /* ExperimentGroup.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentGroup.java; sourceTree = ""; }; - 44A843AA1ADB9C0A009C7226 /* ExperimentQueryResult.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentQueryResult.java; sourceTree = ""; }; - 44A843AB1ADB9C0A009C7226 /* ExperimentValidator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentValidator.java; sourceTree = ""; }; - 44A843AC1ADB9C0A009C7226 /* Feedback.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Feedback.java; sourceTree = ""; }; - 44A843AD1ADB9C0A009C7226 /* Input2.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Input2.java; sourceTree = ""; }; - 44A843AE1ADB9C0A009C7226 /* InterruptCue.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = InterruptCue.java; sourceTree = ""; }; - 44A843AF1ADB9C0A009C7226 /* InterruptTrigger.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = InterruptTrigger.java; sourceTree = ""; }; - 44A843B01ADB9C0A009C7226 /* ListMaker.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ListMaker.java; sourceTree = ""; }; - 44A843B11ADB9C0A009C7226 /* MinimumBufferable.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = MinimumBufferable.java; sourceTree = ""; }; - 44A843B21ADB9C0A009C7226 /* PacoAction.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = PacoAction.java; sourceTree = ""; }; - 44A843B31ADB9C0A009C7226 /* PacoActionAllOthers.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = PacoActionAllOthers.java; sourceTree = ""; }; - 44A843B41ADB9C0A009C7226 /* PacoNotificationAction.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = PacoNotificationAction.java; sourceTree = ""; }; - 44A843B51ADB9C0A009C7226 /* Schedule.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Schedule.java; sourceTree = ""; }; - 44A843B61ADB9C0A009C7226 /* ScheduleTrigger.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ScheduleTrigger.java; sourceTree = ""; }; - 44A843B71ADB9C0A009C7226 /* SignalTime.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = SignalTime.java; sourceTree = ""; }; - 44A843B81ADB9C0A009C7226 /* Validatable.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Validatable.java; sourceTree = ""; }; - 44A843B91ADB9C0A009C7226 /* ValidationMessage.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ValidationMessage.java; sourceTree = ""; }; - 44A843BA1ADB9C0A009C7226 /* Validator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Validator.java; sourceTree = ""; }; - 44A843BC1ADB9C0A009C7226 /* ActionScheduleGenerator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ActionScheduleGenerator.java; sourceTree = ""; }; - 44A843BD1ADB9C0A009C7226 /* ActionSpecification.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ActionSpecification.java; sourceTree = ""; }; - 44A843BE1ADB9C0A009C7226 /* EsmGenerator2.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EsmGenerator2.java; sourceTree = ""; }; - 44A843BF1ADB9C0A009C7226 /* EsmSignalStore.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EsmSignalStore.java; sourceTree = ""; }; - 44A843C01ADB9C0A009C7226 /* NonESMSignalGenerator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = NonESMSignalGenerator.java; sourceTree = ""; }; - 44A843C21ADB9C0A009C7226 /* ExperimentHelper.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentHelper.java; sourceTree = ""; }; - 44A843C31ADB9C0A009C7226 /* SchedulePrinter.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = SchedulePrinter.java; sourceTree = ""; }; - 44A843C41ADB9C0A009C7226 /* TimeUtil.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = TimeUtil.java; sourceTree = ""; }; - 44A843E61ADB9C2F009C7226 /* j2objcprefixes.properties */ = {isa = PBXFileReference; lastKnownFileType = text; name = j2objcprefixes.properties; path = ../../../Shared/j2objcprefixes.properties; sourceTree = ""; }; - 44F9DDF81ADB5EA50098BECB /* libz.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libz.dylib; path = usr/lib/libz.dylib; sourceTree = SDKROOT; }; + 44239BFD1EA9DD4B0026E69A /* AppAuth.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppAuth.framework; path = "DerivedData/Paco/Build/Products/Debug-iphonesimulator/AppAuth/AppAuth.framework"; sourceTree = ""; }; + 44239BFE1EA9DD4B0026E69A /* GTMAppAuth.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GTMAppAuth.framework; path = "DerivedData/Paco/Build/Products/Debug-iphonesimulator/GTMAppAuth/GTMAppAuth.framework"; sourceTree = ""; }; + 44239BFF1EA9DD4B0026E69A /* GTMSessionFetcher.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GTMSessionFetcher.framework; path = "DerivedData/Paco/Build/Products/Debug-iphonesimulator/GTMSessionFetcher/GTMSessionFetcher.framework"; sourceTree = ""; }; 7F8531BD1A37BE680028BA23 /* JCNotificationBanner.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = JCNotificationBanner.h; path = jcnotificationbannerpresenter/Library/JCNotificationBanner.h; sourceTree = ""; }; 7F8531BE1A37BE680028BA23 /* JCNotificationBanner.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = JCNotificationBanner.m; path = jcnotificationbannerpresenter/Library/JCNotificationBanner.m; sourceTree = ""; }; 7F8531BF1A37BE680028BA23 /* JCNotificationBannerPresenter_Private.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = JCNotificationBannerPresenter_Private.h; path = jcnotificationbannerpresenter/Library/JCNotificationBannerPresenter_Private.h; sourceTree = ""; }; @@ -795,58 +544,9 @@ 7FB6607E1AA8C305008D2327 /* paco32@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "paco32@2x.png"; sourceTree = ""; }; 7FB6607F1AA8C305008D2327 /* paco32@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "paco32@3x.png"; sourceTree = ""; }; 7FB6608F1AA8C352008D2327 /* PacoTitleView.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = PacoTitleView.xib; sourceTree = ""; }; - A633A97A1B5DA0970046436D /* ExperimentEditOutcome.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentEditOutcome.java; sourceTree = ""; }; - A633A97B1B5DA0970046436D /* Outcome.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Outcome.java; sourceTree = ""; }; - A633A97D1B5DA0970046436D /* ActionTrigger.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ActionTrigger.java; sourceTree = ""; }; - A633A97E1B5DA0970046436D /* EventInterface.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EventInterface.java; sourceTree = ""; }; - A633A97F1B5DA0970046436D /* EventStore.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EventStore.java; sourceTree = ""; }; - A633A9801B5DA0970046436D /* ExperimentDAO.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentDAO.java; sourceTree = ""; }; - A633A9811B5DA0970046436D /* ExperimentDAOCore.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentDAOCore.java; sourceTree = ""; }; - A633A9821B5DA0970046436D /* ExperimentGroup.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentGroup.java; sourceTree = ""; }; - A633A9831B5DA0970046436D /* ExperimentQueryResult.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentQueryResult.java; sourceTree = ""; }; - A633A9841B5DA0970046436D /* ExperimentValidator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentValidator.java; sourceTree = ""; }; - A633A9851B5DA0970046436D /* Feedback.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Feedback.java; sourceTree = ""; }; - A633A9861B5DA0970046436D /* Input2.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Input2.java; sourceTree = ""; }; - A633A9871B5DA0970046436D /* InterruptCue.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = InterruptCue.java; sourceTree = ""; }; - A633A9881B5DA0970046436D /* InterruptTrigger.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = InterruptTrigger.java; sourceTree = ""; }; - A633A9891B5DA0970046436D /* ListMaker.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ListMaker.java; sourceTree = ""; }; - A633A98A1B5DA0970046436D /* MinimumBufferable.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = MinimumBufferable.java; sourceTree = ""; }; - A633A98B1B5DA0970046436D /* PacoAction.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = PacoAction.java; sourceTree = ""; }; - A633A98C1B5DA0970046436D /* PacoActionAllOthers.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = PacoActionAllOthers.java; sourceTree = ""; }; - A633A98D1B5DA0970046436D /* PacoNotificationAction.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = PacoNotificationAction.java; sourceTree = ""; }; - A633A98E1B5DA0970046436D /* Schedule.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Schedule.java; sourceTree = ""; }; - A633A98F1B5DA0970046436D /* ScheduleTrigger.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ScheduleTrigger.java; sourceTree = ""; }; - A633A9901B5DA0970046436D /* SignalTime.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = SignalTime.java; sourceTree = ""; }; - A633A9911B5DA0970046436D /* Validatable.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Validatable.java; sourceTree = ""; }; - A633A9921B5DA0970046436D /* ValidationMessage.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ValidationMessage.java; sourceTree = ""; }; - A633A9931B5DA0970046436D /* Validator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = Validator.java; sourceTree = ""; }; - A633A9951B5DA0970046436D /* ActionScheduleGenerator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ActionScheduleGenerator.java; sourceTree = ""; }; - A633A9961B5DA0970046436D /* ActionSpecification.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ActionSpecification.java; sourceTree = ""; }; - A633A9971B5DA0970046436D /* EsmGenerator2.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EsmGenerator2.java; sourceTree = ""; }; - A633A9981B5DA0970046436D /* EsmSignalStore.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = EsmSignalStore.java; sourceTree = ""; }; - A633A9991B5DA0970046436D /* NonESMSignalGenerator.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = NonESMSignalGenerator.java; sourceTree = ""; }; - A633A99B1B5DA0970046436D /* ExperimentHelper.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ExperimentHelper.java; sourceTree = ""; }; - A633A99C1B5DA0970046436D /* SchedulePrinter.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = SchedulePrinter.java; sourceTree = ""; }; - A633A99D1B5DA0970046436D /* TimeUtil.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = TimeUtil.java; sourceTree = ""; }; - A633A99E1B5DA0970046436D /* readme.md */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = net.daringfireball.markdown; path = readme.md; sourceTree = ""; }; - A633A9C11B5DA1B70046436D /* PacoJ2OBJCTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PacoJ2OBJCTests.m; sourceTree = ""; }; - A6701D601B73D48C00229432 /* joda */ = {isa = PBXFileReference; lastKnownFileType = folder; path = joda; sourceTree = ""; }; - A670760F1B62F26A00017D36 /* DerivedSources */ = {isa = PBXFileReference; lastKnownFileType = folder; name = DerivedSources; path = "DerivedData/Paco/Build/Intermediates/Paco.build/Debug-iphonesimulator/Paco.build/DerivedSources"; sourceTree = ""; }; - A676C7371B6043DE00F37572 /* Pacoj2Objc2JsonTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Pacoj2Objc2JsonTests.m; sourceTree = ""; }; - A676C7391B615A3D00F37572 /* libobjc.A.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libobjc.A.dylib; path = usr/lib/libobjc.A.dylib; sourceTree = SDKROOT; }; - A676C73B1B615AAB00F37572 /* libobjc.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libobjc.dylib; path = usr/lib/libobjc.dylib; sourceTree = SDKROOT; }; - A678C2741B703955003F0D27 /* ModelBase.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ModelBase.java; sourceTree = ""; }; - A678C2E41B716283003F0D27 /* ModelBase.java */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.java; path = ModelBase.java; sourceTree = ""; }; - A6ABFA951B742BA700F90598 /* ITAhoCorasickContainer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ITAhoCorasickContainer.h; sourceTree = ""; }; - A6ABFA961B742BA700F90598 /* ITAhoCorasickContainer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ITAhoCorasickContainer.m; sourceTree = ""; }; - A6ABFA9A1B742BE800F90598 /* NSMutableDictionary+ITExtension.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSMutableDictionary+ITExtension.h"; sourceTree = ""; }; - A6ABFA9B1B742BE800F90598 /* NSMutableDictionary+ITExtension.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSMutableDictionary+ITExtension.m"; sourceTree = ""; }; - A6ABFA9C1B742BE800F90598 /* NSObject+ITNDescription.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSObject+ITNDescription.h"; sourceTree = ""; }; - A6ABFA9D1B742BE800F90598 /* NSObject+ITNDescription.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+ITNDescription.m"; sourceTree = ""; }; - A6ABFA9E1B742BE800F90598 /* NSObject+J2objcKVO.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSObject+J2objcKVO.h"; sourceTree = ""; }; - A6ABFA9F1B742BE800F90598 /* NSObject+J2objcKVO.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSObject+J2objcKVO.m"; sourceTree = ""; }; - A6ABFAA01B742BE800F90598 /* PacoSerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PacoSerializer.h; sourceTree = ""; }; - A6ABFAA11B742BE800F90598 /* PacoSerializer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = PacoSerializer.m; sourceTree = ""; }; + 8DA66BC3BA03A7F250872B5E /* Pods_Paco.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Paco.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9D60D437C62D01DB8DA47FFA /* Pods-Paco.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Paco.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Paco/Pods-Paco.debug.xcconfig"; sourceTree = ""; }; + B8B04486F837EC6A07859438 /* Pods-Paco.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Paco.release.xcconfig"; path = "Pods/Target Support Files/Pods-Paco/Pods-Paco.release.xcconfig"; sourceTree = ""; }; C567E88F17A03FDE00267A26 /* deepbark_trial.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = deepbark_trial.mp3; sourceTree = ""; }; C5B4691817B07E4900B6BC18 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; C5C4F5D117B163EF009E9F18 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; }; @@ -874,8 +574,9 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - A676C73C1B615AAB00F37572 /* libobjc.dylib in Frameworks */, - 44F9DDF91ADB5EA50098BECB /* libz.dylib in Frameworks */, + 44239C001EA9DD4B0026E69A /* AppAuth.framework in Frameworks */, + 44239C011EA9DD4B0026E69A /* GTMAppAuth.framework in Frameworks */, + 44239C021EA9DD4B0026E69A /* GTMSessionFetcher.framework in Frameworks */, E4D5DE861837DE9A00E5446A /* MessageUI.framework in Frameworks */, C5C4F5D217B163EF009E9F18 /* QuartzCore.framework in Frameworks */, 319771C9163F0733000AC06B /* UIKit.framework in Frameworks */, @@ -889,6 +590,7 @@ 3197721D163F2672000AC06B /* SystemConfiguration.framework in Frameworks */, 3197721B163F265C000AC06B /* Security.framework in Frameworks */, 31977219163F2655000AC06B /* CFNetwork.framework in Frameworks */, + 6A56DF05AC441FE9735102FE /* Pods_Paco.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -908,14 +610,13 @@ 319771B9163F0733000AC06B = { isa = PBXGroup; children = ( - A670760F1B62F26A00017D36 /* DerivedSources */, - 44A8439B1ADB9C0A009C7226 /* src */, 319771CE163F0733000AC06B /* Paco */, 36B8EC3517568E40004CF035 /* PacoTests */, 36B8EC1217568E33004CF035 /* vendor */, 319771C7163F0733000AC06B /* Frameworks */, 319771C5163F0733000AC06B /* Products */, 36000C1517C6AEA900A8A9E7 /* ParseKit.xcodeproj */, + 4E3FFB9EF2A09E0E4F8D8E9A /* Pods */, ); sourceTree = ""; }; @@ -931,9 +632,9 @@ 319771C7163F0733000AC06B /* Frameworks */ = { isa = PBXGroup; children = ( - A676C73B1B615AAB00F37572 /* libobjc.dylib */, - A676C7391B615A3D00F37572 /* libobjc.A.dylib */, - 44F9DDF81ADB5EA50098BECB /* libz.dylib */, + 44239BFD1EA9DD4B0026E69A /* AppAuth.framework */, + 44239BFE1EA9DD4B0026E69A /* GTMAppAuth.framework */, + 44239BFF1EA9DD4B0026E69A /* GTMSessionFetcher.framework */, E4D5DE851837DE9900E5446A /* MessageUI.framework */, C5C4F5D117B163EF009E9F18 /* QuartzCore.framework */, C5B4691817B07E4900B6BC18 /* CoreGraphics.framework */, @@ -946,6 +647,7 @@ 31977218163F2655000AC06B /* CFNetwork.framework */, 319771C8163F0733000AC06B /* UIKit.framework */, 319771CA163F0733000AC06B /* Foundation.framework */, + 8DA66BC3BA03A7F250872B5E /* Pods_Paco.framework */, ); name = Frameworks; sourceTree = ""; @@ -1017,17 +719,6 @@ path = PublicExperimentScreen; sourceTree = ""; }; - 36AD6CD817C420F800B93855 /* sskeychain */ = { - isa = PBXGroup; - children = ( - 36AD6CD917C420F800B93855 /* SSKeychain.h */, - 36AD6CDA17C420F800B93855 /* SSKeychain.m */, - 36AD6CDB17C420F800B93855 /* SSKeychainQuery.h */, - 36AD6CDC17C420F800B93855 /* SSKeychainQuery.m */, - ); - path = sskeychain; - sourceTree = ""; - }; 36AD6CDF17C443DF00B93855 /* common */ = { isa = PBXGroup; children = ( @@ -1060,7 +751,6 @@ 36B8EB0117568DAF004CF035 /* core */ = { isa = PBXGroup; children = ( - A6ABFA981B742BE800F90598 /* serializer */, 36AD6CDF17C443DF00B93855 /* common */, 36B8EB0217568DAF004CF035 /* authentication */, 36B8EB0517568DAF004CF035 /* client */, @@ -1105,7 +795,6 @@ 36B8EB0B17568DAF004CF035 /* model */ = { isa = PBXGroup; children = ( - A670746F1B62E6DF00017D36 /* modal2 */, 36B8EB0C17568DAF004CF035 /* PacoModel.h */, 36B8EB0D17568DAF004CF035 /* PacoModel.m */, 36946B03177A37CE005E0C04 /* PacoExperimentFeedback.h */, @@ -1356,7 +1045,6 @@ 36B8EB9417568E29004CF035 /* resources */ = { isa = PBXGroup; children = ( - 44A843E61ADB9C2F009C7226 /* j2objcprefixes.properties */, E480BE131896F3C700662432 /* en.lproj */, 36488BB418C8FB2E004517E2 /* incompatible@2x.png */, 36F457E21863ABA900931049 /* welcome_paco.html */, @@ -1403,71 +1091,17 @@ 36B8EC1217568E33004CF035 /* vendor */ = { isa = PBXGroup; children = ( - A6ABFA941B742BA700F90598 /* aho-corasick */, - A6701D601B73D48C00229432 /* joda */, - 4448BC371A808E7A0034FCE9 /* gtm-oauth2 */, 36C4A33618A4DEEE00D8FE59 /* lumberjack */, C5C4F5D417B1738E009E9F18 /* jcnotificationbannerpresenter */, - 36AD6CD817C420F800B93855 /* sskeychain */, 363E211017AF8420007DE3CE /* reachability */, - 36B8EC1317568E33004CF035 /* google-toolbox-for-mac */, - 36B8EC2617568E33004CF035 /* touchengine */, ); path = vendor; sourceTree = ""; }; - 36B8EC1317568E33004CF035 /* google-toolbox-for-mac */ = { - isa = PBXGroup; - children = ( - 36B8EC1417568E33004CF035 /* Foundation */, - 36B8EC1817568E33004CF035 /* GTMDefines.h */, - ); - path = "google-toolbox-for-mac"; - sourceTree = ""; - }; - 36B8EC1417568E33004CF035 /* Foundation */ = { - isa = PBXGroup; - children = ( - 36B8EC1517568E33004CF035 /* GTMGarbageCollection.h */, - 36B8EC1617568E33004CF035 /* GTMNSString+URLArguments.h */, - 36B8EC1717568E33004CF035 /* GTMNSString+URLArguments.m */, - ); - path = Foundation; - sourceTree = ""; - }; - 36B8EC2617568E33004CF035 /* touchengine */ = { - isa = PBXGroup; - children = ( - 36B8EC2717568E33004CF035 /* iPhone */, - ); - path = touchengine; - sourceTree = ""; - }; - 36B8EC2717568E33004CF035 /* iPhone */ = { - isa = PBXGroup; - children = ( - 36B8EC2817568E33004CF035 /* GoogleAppEngineAuthGithub */, - ); - path = iPhone; - sourceTree = ""; - }; - 36B8EC2817568E33004CF035 /* GoogleAppEngineAuthGithub */ = { - isa = PBXGroup; - children = ( - 36B8EC2917568E33004CF035 /* GoogleAppEngineAuth.h */, - 36B8EC2A17568E33004CF035 /* GoogleAppEngineAuth.m */, - 36B8EC2B17568E33004CF035 /* GoogleClientLogin.h */, - 36B8EC2C17568E33004CF035 /* GoogleClientLogin.m */, - ); - path = GoogleAppEngineAuthGithub; - sourceTree = ""; - }; 36B8EC3517568E40004CF035 /* PacoTests */ = { isa = PBXGroup; children = ( - A633A9741B5DA0970046436D /* src */, 367233E318061FD6006611E6 /* PacoScheduleGeneratorTests.m */, - A633A9C11B5DA1B70046436D /* PacoJ2OBJCTests.m */, 361A11A518F85B7B000E9CA2 /* PacoScheduleGeneratorDailyTests.m */, 36F3EFE718FC645500ABF242 /* PacoESMDailyGeneratorWithCache.m */, 36B5A4F118282CBC004DB894 /* PacoScheduleGeneratorDailyESMTests.m */, @@ -1493,7 +1127,6 @@ 3662927C1821C10800FC647A /* PacoExperimentScheduleTests.m */, 366292851821C2EF00FC647A /* PacoUtilityTests.m */, 3640612F18230DA700DA5EB7 /* PacoExperimentTests.m */, - A676C7371B6043DE00F37572 /* Pacoj2Objc2JsonTests.m */, 36B8EC3817568E40004CF035 /* resources */, ); path = PacoTests; @@ -1523,366 +1156,13 @@ path = lumberjack; sourceTree = ""; }; - 4448BC371A808E7A0034FCE9 /* gtm-oauth2 */ = { - isa = PBXGroup; - children = ( - 4448BC511A808E7A0034FCE9 /* HTTPFetcher */, - 4448BC781A808E7A0034FCE9 /* JSON */, - 4448BC841A808E7A0034FCE9 /* Source */, - ); - path = "gtm-oauth2"; - sourceTree = ""; - }; - 4448BC511A808E7A0034FCE9 /* HTTPFetcher */ = { - isa = PBXGroup; - children = ( - 4448BC521A808E7A0034FCE9 /* GTMGatherInputStream.h */, - 4448BC531A808E7A0034FCE9 /* GTMGatherInputStream.m */, - 4448BC541A808E7A0034FCE9 /* GTMHTTPFetcher.h */, - 4448BC551A808E7A0034FCE9 /* GTMHTTPFetcher.m */, - 4448BC561A808E7A0034FCE9 /* GTMHTTPFetcher.xcodeproj */, - 4448BC591A808E7A0034FCE9 /* GTMHTTPFetcherLogging.h */, - 4448BC5A1A808E7A0034FCE9 /* GTMHTTPFetcherLogging.m */, - 4448BC5B1A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.h */, - 4448BC5C1A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.m */, - 4448BC5D1A808E7A0034FCE9 /* GTMHTTPFetcherService.h */, - 4448BC5E1A808E7A0034FCE9 /* GTMHTTPFetcherService.m */, - 4448BC5F1A808E7A0034FCE9 /* GTMHTTPFetchHistory.h */, - 4448BC601A808E7A0034FCE9 /* GTMHTTPFetchHistory.m */, - 4448BC611A808E7A0034FCE9 /* GTMHTTPUploadFetcher.h */, - 4448BC621A808E7A0034FCE9 /* GTMHTTPUploadFetcher.m */, - 4448BC631A808E7A0034FCE9 /* GTMMIMEDocument.h */, - 4448BC641A808E7A0034FCE9 /* GTMMIMEDocument.m */, - 4448BC651A808E7A0034FCE9 /* GTMReadMonitorInputStream.h */, - 4448BC661A808E7A0034FCE9 /* GTMReadMonitorInputStream.m */, - 4448BC671A808E7A0034FCE9 /* ReleaseNotes.txt */, - 4448BC771A808E7A0034FCE9 /* UnitTests-Info.plist */, - ); - path = HTTPFetcher; - sourceTree = ""; - }; - 4448BC571A808E7A0034FCE9 /* Products */ = { - isa = PBXGroup; - children = ( - 4448BCC71A808E7A0034FCE9 /* libGTMHTTPFetcher.a */, - 4448BCC91A808E7A0034FCE9 /* UnitTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 4448BC781A808E7A0034FCE9 /* JSON */ = { - isa = PBXGroup; - children = ( - 4448BC791A808E7A0034FCE9 /* JSON.h */, - 4448BC7A1A808E7A0034FCE9 /* NSObject+SBJSON.h */, - 4448BC7B1A808E7A0034FCE9 /* NSObject+SBJSON.m */, - 4448BC7C1A808E7A0034FCE9 /* NSString+SBJSON.h */, - 4448BC7D1A808E7A0034FCE9 /* NSString+SBJSON.m */, - 4448BC7E1A808E7A0034FCE9 /* SBJsonBase.h */, - 4448BC7F1A808E7A0034FCE9 /* SBJsonBase.m */, - 4448BC801A808E7A0034FCE9 /* SBJsonParser.h */, - 4448BC811A808E7A0034FCE9 /* SBJsonParser.m */, - 4448BC821A808E7A0034FCE9 /* SBJsonWriter.h */, - 4448BC831A808E7A0034FCE9 /* SBJsonWriter.m */, - ); - path = JSON; - sourceTree = ""; - }; - 4448BC841A808E7A0034FCE9 /* Source */ = { - isa = PBXGroup; - children = ( - 4448BCD81A80901D0034FCE9 /* Touch */, - 4448BC851A808E7A0034FCE9 /* GTMOAuth2.xcodeproj */, - 4448BC881A808E7A0034FCE9 /* GTMOAuth2Authentication.h */, - 4448BC891A808E7A0034FCE9 /* GTMOAuth2Authentication.m */, - 4448BC8A1A808E7A0034FCE9 /* GTMOAuth2SignIn.h */, - 4448BC8B1A808E7A0034FCE9 /* GTMOAuth2SignIn.m */, - 4448BC8C1A808E7A0034FCE9 /* Mac */, - 4448BC911A808E7A0034FCE9 /* ReleaseNotes.txt */, - ); - path = Source; - sourceTree = ""; - }; - 4448BC861A808E7A0034FCE9 /* Products */ = { - isa = PBXGroup; - children = ( - 4448BCCF1A808E7A0034FCE9 /* libOAuthTouch2.a */, - 4448BCD11A808E7A0034FCE9 /* libOAuthTouch2NG.a */, - ); - name = Products; - sourceTree = ""; - }; - 4448BC8C1A808E7A0034FCE9 /* Mac */ = { - isa = PBXGroup; - children = ( - 4448BC8D1A808E7A0034FCE9 /* GTMOAuth2Framework-Info.plist */, - 4448BC8E1A808E7A0034FCE9 /* GTMOAuth2Window.xib */, - 4448BC8F1A808E7A0034FCE9 /* GTMOAuth2WindowController.h */, - 4448BC901A808E7A0034FCE9 /* GTMOAuth2WindowController.m */, - ); - path = Mac; - sourceTree = ""; - }; - 4448BCD81A80901D0034FCE9 /* Touch */ = { - isa = PBXGroup; - children = ( - 4448BCD91A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.h */, - 4448BCDA1A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.m */, - 4448BCDB1A80901D0034FCE9 /* GTMOAuth2ViewTouch.xib */, - ); - path = Touch; - sourceTree = ""; - }; - 44A8439B1ADB9C0A009C7226 /* src */ = { - isa = PBXGroup; - children = ( - 44A8439C1ADB9C0A009C7226 /* com */, - ); - name = src; - path = ../Shared/src; - sourceTree = ""; - }; - 44A8439C1ADB9C0A009C7226 /* com */ = { - isa = PBXGroup; - children = ( - 44A8439D1ADB9C0A009C7226 /* pacoapp */, - ); - path = com; - sourceTree = ""; - }; - 44A8439D1ADB9C0A009C7226 /* pacoapp */ = { - isa = PBXGroup; - children = ( - 44A8439E1ADB9C0A009C7226 /* paco */, - ); - path = pacoapp; - sourceTree = ""; - }; - 44A8439E1ADB9C0A009C7226 /* paco */ = { - isa = PBXGroup; - children = ( - 44A8439F1ADB9C0A009C7226 /* shared */, - ); - path = paco; - sourceTree = ""; - }; - 44A8439F1ADB9C0A009C7226 /* shared */ = { - isa = PBXGroup; - children = ( - 44A843A01ADB9C0A009C7226 /* comm */, - 44A843A31ADB9C0A009C7226 /* model2 */, - 44A843BB1ADB9C0A009C7226 /* scheduling */, - 44A843C11ADB9C0A009C7226 /* util */, - ); - path = shared; - sourceTree = ""; - }; - 44A843A01ADB9C0A009C7226 /* comm */ = { - isa = PBXGroup; - children = ( - 44A843A11ADB9C0A009C7226 /* ExperimentEditOutcome.java */, - 44A843A21ADB9C0A009C7226 /* Outcome.java */, - ); - path = comm; - sourceTree = ""; - }; - 44A843A31ADB9C0A009C7226 /* model2 */ = { - isa = PBXGroup; - children = ( - 44A843A41ADB9C0A009C7226 /* ActionTrigger.java */, - 44A843A51ADB9C0A009C7226 /* EventInterface.java */, - 44A843A61ADB9C0A009C7226 /* EventStore.java */, - 44A843A71ADB9C0A009C7226 /* ExperimentDAO.java */, - 44A843A81ADB9C0A009C7226 /* ExperimentDAOCore.java */, - 44A843A91ADB9C0A009C7226 /* ExperimentGroup.java */, - 44A843AA1ADB9C0A009C7226 /* ExperimentQueryResult.java */, - 44A843AB1ADB9C0A009C7226 /* ExperimentValidator.java */, - 44A843AC1ADB9C0A009C7226 /* Feedback.java */, - 44A843AD1ADB9C0A009C7226 /* Input2.java */, - A678C2741B703955003F0D27 /* ModelBase.java */, - 44A843AE1ADB9C0A009C7226 /* InterruptCue.java */, - 44A843AF1ADB9C0A009C7226 /* InterruptTrigger.java */, - 44A843B01ADB9C0A009C7226 /* ListMaker.java */, - 44A843B11ADB9C0A009C7226 /* MinimumBufferable.java */, - 44A843B21ADB9C0A009C7226 /* PacoAction.java */, - 44A843B31ADB9C0A009C7226 /* PacoActionAllOthers.java */, - 44A843B41ADB9C0A009C7226 /* PacoNotificationAction.java */, - 44A843B51ADB9C0A009C7226 /* Schedule.java */, - 44A843B61ADB9C0A009C7226 /* ScheduleTrigger.java */, - 44A843B71ADB9C0A009C7226 /* SignalTime.java */, - 44A843B81ADB9C0A009C7226 /* Validatable.java */, - 44A843B91ADB9C0A009C7226 /* ValidationMessage.java */, - 44A843BA1ADB9C0A009C7226 /* Validator.java */, - ); - path = model2; - sourceTree = ""; - }; - 44A843BB1ADB9C0A009C7226 /* scheduling */ = { - isa = PBXGroup; - children = ( - 44A843BC1ADB9C0A009C7226 /* ActionScheduleGenerator.java */, - 44A843BD1ADB9C0A009C7226 /* ActionSpecification.java */, - 44A843BE1ADB9C0A009C7226 /* EsmGenerator2.java */, - 44A843BF1ADB9C0A009C7226 /* EsmSignalStore.java */, - 44A843C01ADB9C0A009C7226 /* NonESMSignalGenerator.java */, - ); - path = scheduling; - sourceTree = ""; - }; - 44A843C11ADB9C0A009C7226 /* util */ = { - isa = PBXGroup; - children = ( - 44A843C21ADB9C0A009C7226 /* ExperimentHelper.java */, - 44A843C31ADB9C0A009C7226 /* SchedulePrinter.java */, - 44A843C41ADB9C0A009C7226 /* TimeUtil.java */, - ); - path = util; - sourceTree = ""; - }; - A633A9741B5DA0970046436D /* src */ = { - isa = PBXGroup; - children = ( - A633A9751B5DA0970046436D /* com */, - A633A99E1B5DA0970046436D /* readme.md */, - ); - name = src; - path = ../../Shared/src; - sourceTree = ""; - }; - A633A9751B5DA0970046436D /* com */ = { - isa = PBXGroup; - children = ( - A633A9761B5DA0970046436D /* pacoapp */, - ); - path = com; - sourceTree = ""; - }; - A633A9761B5DA0970046436D /* pacoapp */ = { - isa = PBXGroup; - children = ( - A633A9771B5DA0970046436D /* paco */, - ); - path = pacoapp; - sourceTree = ""; - }; - A633A9771B5DA0970046436D /* paco */ = { - isa = PBXGroup; - children = ( - A633A9781B5DA0970046436D /* shared */, - ); - path = paco; - sourceTree = ""; - }; - A633A9781B5DA0970046436D /* shared */ = { - isa = PBXGroup; - children = ( - A633A9791B5DA0970046436D /* comm */, - A633A97C1B5DA0970046436D /* model2 */, - A633A9941B5DA0970046436D /* scheduling */, - A633A99A1B5DA0970046436D /* util */, - ); - path = shared; - sourceTree = ""; - }; - A633A9791B5DA0970046436D /* comm */ = { - isa = PBXGroup; - children = ( - A633A97A1B5DA0970046436D /* ExperimentEditOutcome.java */, - A633A97B1B5DA0970046436D /* Outcome.java */, - ); - path = comm; - sourceTree = ""; - }; - A633A97C1B5DA0970046436D /* model2 */ = { - isa = PBXGroup; - children = ( - A633A97D1B5DA0970046436D /* ActionTrigger.java */, - A633A97E1B5DA0970046436D /* EventInterface.java */, - A633A97F1B5DA0970046436D /* EventStore.java */, - A633A9801B5DA0970046436D /* ExperimentDAO.java */, - A633A9811B5DA0970046436D /* ExperimentDAOCore.java */, - A633A9821B5DA0970046436D /* ExperimentGroup.java */, - A633A9831B5DA0970046436D /* ExperimentQueryResult.java */, - A633A9841B5DA0970046436D /* ExperimentValidator.java */, - A633A9851B5DA0970046436D /* Feedback.java */, - A633A9861B5DA0970046436D /* Input2.java */, - A633A9871B5DA0970046436D /* InterruptCue.java */, - A633A9881B5DA0970046436D /* InterruptTrigger.java */, - A633A9891B5DA0970046436D /* ListMaker.java */, - A633A98A1B5DA0970046436D /* MinimumBufferable.java */, - A678C2E41B716283003F0D27 /* ModelBase.java */, - A633A98B1B5DA0970046436D /* PacoAction.java */, - A633A98C1B5DA0970046436D /* PacoActionAllOthers.java */, - A633A98D1B5DA0970046436D /* PacoNotificationAction.java */, - A633A98E1B5DA0970046436D /* Schedule.java */, - A633A98F1B5DA0970046436D /* ScheduleTrigger.java */, - A633A9901B5DA0970046436D /* SignalTime.java */, - A633A9911B5DA0970046436D /* Validatable.java */, - A633A9921B5DA0970046436D /* ValidationMessage.java */, - A633A9931B5DA0970046436D /* Validator.java */, - ); - path = model2; - sourceTree = ""; - }; - A633A9941B5DA0970046436D /* scheduling */ = { - isa = PBXGroup; - children = ( - A633A9951B5DA0970046436D /* ActionScheduleGenerator.java */, - A633A9961B5DA0970046436D /* ActionSpecification.java */, - A633A9971B5DA0970046436D /* EsmGenerator2.java */, - A633A9981B5DA0970046436D /* EsmSignalStore.java */, - A633A9991B5DA0970046436D /* NonESMSignalGenerator.java */, - ); - path = scheduling; - sourceTree = ""; - }; - A633A99A1B5DA0970046436D /* util */ = { + 4E3FFB9EF2A09E0E4F8D8E9A /* Pods */ = { isa = PBXGroup; children = ( - A633A99B1B5DA0970046436D /* ExperimentHelper.java */, - A633A99C1B5DA0970046436D /* SchedulePrinter.java */, - A633A99D1B5DA0970046436D /* TimeUtil.java */, + 9D60D437C62D01DB8DA47FFA /* Pods-Paco.debug.xcconfig */, + B8B04486F837EC6A07859438 /* Pods-Paco.release.xcconfig */, ); - path = util; - sourceTree = ""; - }; - A670746F1B62E6DF00017D36 /* modal2 */ = { - isa = PBXGroup; - children = ( - ); - name = modal2; - sourceTree = ""; - }; - A6ABFA941B742BA700F90598 /* aho-corasick */ = { - isa = PBXGroup; - children = ( - A6ABFA951B742BA700F90598 /* ITAhoCorasickContainer.h */, - A6ABFA961B742BA700F90598 /* ITAhoCorasickContainer.m */, - ); - path = "aho-corasick"; - sourceTree = ""; - }; - A6ABFA981B742BE800F90598 /* serializer */ = { - isa = PBXGroup; - children = ( - A6ABFA991B742BE800F90598 /* categories */, - A6ABFAA01B742BE800F90598 /* PacoSerializer.h */, - A6ABFAA11B742BE800F90598 /* PacoSerializer.m */, - ); - path = serializer; - sourceTree = ""; - }; - A6ABFA991B742BE800F90598 /* categories */ = { - isa = PBXGroup; - children = ( - A6ABFA9A1B742BE800F90598 /* NSMutableDictionary+ITExtension.h */, - A6ABFA9B1B742BE800F90598 /* NSMutableDictionary+ITExtension.m */, - A6ABFA9C1B742BE800F90598 /* NSObject+ITNDescription.h */, - A6ABFA9D1B742BE800F90598 /* NSObject+ITNDescription.m */, - A6ABFA9E1B742BE800F90598 /* NSObject+J2objcKVO.h */, - A6ABFA9F1B742BE800F90598 /* NSObject+J2objcKVO.m */, - ); - path = categories; + name = Pods; sourceTree = ""; }; C5C4F5D417B1738E009E9F18 /* jcnotificationbannerpresenter */ = { @@ -1958,12 +1238,14 @@ isa = PBXNativeTarget; buildConfigurationList = 31977200163F0733000AC06B /* Build configuration list for PBXNativeTarget "Paco" */; buildPhases = ( + 9EE300EE5E584EA2BA9D7BC8 /* [CP] Check Pods Manifest.lock */, 319771C0163F0733000AC06B /* Sources */, 319771C1163F0733000AC06B /* Frameworks */, 319771C2163F0733000AC06B /* Resources */, + D20EC8846F25838C3B206789 /* [CP] Embed Pods Frameworks */, + FF6711621A40FDBEB880F61A /* [CP] Copy Pods Resources */, ); buildRules = ( - 44F9DDF71ADB5D840098BECB /* PBXBuildRule */, ); dependencies = ( 36000C3617C6B0A800A8A9E7 /* PBXTargetDependency */, @@ -1983,7 +1265,6 @@ 319771EC163F0733000AC06B /* ShellScript */, ); buildRules = ( - A6D9AA8F1B59AA5C00595C06 /* PBXBuildRule */, ); dependencies = ( 319771F4163F0733000AC06B /* PBXTargetDependency */, @@ -2004,7 +1285,8 @@ ORGANIZATIONNAME = Paco; TargetAttributes = { 319771C3163F0733000AC06B = { - DevelopmentTeam = 7JRXRM6LRK; + DevelopmentTeam = J7M7JW942W; + ProvisioningStyle = Automatic; }; 319771ED163F0733000AC06B = { DevelopmentTeam = J7M7JW942W; @@ -2025,14 +1307,6 @@ projectDirPath = ""; projectReferences = ( { - ProductGroup = 4448BC571A808E7A0034FCE9 /* Products */; - ProjectRef = 4448BC561A808E7A0034FCE9 /* GTMHTTPFetcher.xcodeproj */; - }, - { - ProductGroup = 4448BC861A808E7A0034FCE9 /* Products */; - ProjectRef = 4448BC851A808E7A0034FCE9 /* GTMOAuth2.xcodeproj */; - }, - { ProductGroup = 36000C1617C6AEA900A8A9E7 /* Products */; ProjectRef = 36000C1517C6AEA900A8A9E7 /* ParseKit.xcodeproj */; }, @@ -2102,34 +1376,6 @@ remoteRef = 36000C2F17C6AEA900A8A9E7 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; - 4448BCC71A808E7A0034FCE9 /* libGTMHTTPFetcher.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = libGTMHTTPFetcher.a; - remoteRef = 4448BCC61A808E7A0034FCE9 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 4448BCC91A808E7A0034FCE9 /* UnitTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = UnitTests.xctest; - remoteRef = 4448BCC81A808E7A0034FCE9 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 4448BCCF1A808E7A0034FCE9 /* libOAuthTouch2.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = libOAuthTouch2.a; - remoteRef = 4448BCCE1A808E7A0034FCE9 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 4448BCD11A808E7A0034FCE9 /* libOAuthTouch2NG.a */ = { - isa = PBXReferenceProxy; - fileType = archive.ar; - path = libOAuthTouch2NG.a; - remoteRef = 4448BCD01A808E7A0034FCE9 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ @@ -2137,21 +1383,15 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - 44A843E71ADB9C2F009C7226 /* j2objcprefixes.properties in Resources */, - 4448BCDD1A80901D0034FCE9 /* GTMOAuth2ViewTouch.xib in Resources */, 36B8EBD617568E29004CF035 /* calculator.png in Resources */, 7FB660901AA8C352008D2327 /* PacoTitleView.xib in Resources */, 36B8EBD717568E29004CF035 /* current_experiments_disabled.png in Resources */, 36B8EBD817568E29004CF035 /* current_experiments_focused.png in Resources */, 36488BB518C8FB2E004517E2 /* incompatible@2x.png in Resources */, 36B8EBD917568E29004CF035 /* current_experiments_normal.png in Resources */, - 4448BCBE1A808E7A0034FCE9 /* GTMOAuth2Framework-Info.plist in Resources */, 36B8EBDA17568E29004CF035 /* current_experiments_pressed.png in Resources */, 36B8EBDE17568E29004CF035 /* experiment_disabled.png in Resources */, 36B8EBDF17568E29004CF035 /* experiment_focused.png in Resources */, - 7FB660811AA8C305008D2327 /* paco32@3x.png in Resources */, - 4448BCAA1A808E7A0034FCE9 /* ReleaseNotes.txt in Resources */, - 4448BCB61A808E7A0034FCE9 /* UnitTests-Info.plist in Resources */, 36B8EBE017568E29004CF035 /* experiment_normal.png in Resources */, 36B8EBE117568E29004CF035 /* experiment_pressed.png in Resources */, 36B8EBE217568E29004CF035 /* feedback_disabled.png in Resources */, @@ -2163,7 +1403,6 @@ 36B8EBE617568E29004CF035 /* find_experiments_disabled.png in Resources */, 36B8EBE717568E29004CF035 /* find_experiments_focused.png in Resources */, 36B8EBE817568E29004CF035 /* find_experiments_normal.png in Resources */, - A67076101B62F26A00017D36 /* DerivedSources in Resources */, 36B8EBE917568E29004CF035 /* find_experiments_pressed.png in Resources */, E480BE161896F3C700662432 /* InfoPlist.strings in Resources */, 36B8EBF217568E29004CF035 /* paco32.png in Resources */, @@ -2171,7 +1410,6 @@ 36B8EBF517568E29004CF035 /* question.png in Resources */, 7FB660801AA8C305008D2327 /* paco32@2x.png in Resources */, E480BE201896F3E100662432 /* Localizable.strings in Resources */, - A6701D611B73D48C00229432 /* joda in Resources */, 36B8EBF817568E29004CF035 /* smile_icon1.png in Resources */, 36B8EBF917568E29004CF035 /* smile_icon1_re.png in Resources */, 36B8EBFA17568E29004CF035 /* smile_icon2.png in Resources */, @@ -2185,9 +1423,7 @@ 36B8EC1017568E29004CF035 /* uicheckbox_checked.png in Resources */, 36B8EC1117568E29004CF035 /* uicheckbox_unchecked.png in Resources */, C567E89017A03FDE00267A26 /* deepbark_trial.mp3 in Resources */, - 4448BCC11A808E7A0034FCE9 /* ReleaseNotes.txt in Resources */, 36000C5917CD1AF600A8A9E7 /* Test_999999999.plist in Resources */, - 4448BCBF1A808E7A0034FCE9 /* GTMOAuth2Window.xib in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2196,7 +1432,6 @@ buildActionMask = 2147483647; files = ( 36B8EC3D17568E40004CF035 /* InfoPlist.strings in Resources */, - A67076111B62F26A00017D36 /* DerivedSources in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2216,6 +1451,51 @@ shellPath = /bin/sh; shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n"; }; + 9EE300EE5E584EA2BA9D7BC8 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + D20EC8846F25838C3B206789 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Paco/Pods-Paco-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + FF6711621A40FDBEB880F61A /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-Paco/Pods-Paco-resources.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -2233,7 +1513,6 @@ 7F8531D91A37BE680028BA23 /* JCNotificationBannerView.m in Sources */, 36B8EB6D17568DAF004CF035 /* PacoDateUtility.m in Sources */, 36B8EB6E17568DAF004CF035 /* main.m in Sources */, - 44A843DE1ADB9C0A009C7226 /* ActionScheduleGenerator.java in Sources */, 36B8EB6F17568DAF004CF035 /* PacoAppDelegate.m in Sources */, 36B8EB7017568DAF004CF035 /* PacoEditScheduleViewController.m in Sources */, 36B8EB7117568DAF004CF035 /* PacoByWeekOrMonthSelectionView.m in Sources */, @@ -2241,58 +1520,31 @@ 36B8EB7317568DAF004CF035 /* PacoDayOfWeekSelectionView.m in Sources */, 36B8EB7417568DAF004CF035 /* PacoESMFrequencySelectionView.m in Sources */, 36B8EB7517568DAF004CF035 /* PacoESMIncludeWeekendsSelectionView.m in Sources */, - 4448BCA71A808E7A0034FCE9 /* GTMHTTPUploadFetcher.m in Sources */, 36B8EB7617568DAF004CF035 /* PacoESMPeriodSelectionView.m in Sources */, - 4448BCA51A808E7A0034FCE9 /* GTMHTTPFetcherService.m in Sources */, 36B8EB7717568DAF004CF035 /* PacoFirstDayOfMonthSelectionView.m in Sources */, 36B8EB7817568DAF004CF035 /* PacoRepeatRateSelectionView.m in Sources */, 7F8531D41A37BE680028BA23 /* JCNotificationBanner.m in Sources */, 36C4A34918A4DFEC00D8FE59 /* DDTTYLogger.m in Sources */, - 44A843CD1ADB9C0A009C7226 /* ExperimentQueryResult.java in Sources */, 36B8EB7917568DAF004CF035 /* PacoScheduleEditView.m in Sources */, - 44A843DD1ADB9C0A009C7226 /* Validator.java in Sources */, 7F8531D81A37BE680028BA23 /* JCNotificationBannerPresenterSmokeStyle.m in Sources */, 36B8EB7A17568DAF004CF035 /* PacoTimeSelectionView.m in Sources */, 3612A269185FE7AA00DEADD1 /* PacoTimeEditView.m in Sources */, - 44A843D01ADB9C0A009C7226 /* Input2.java in Sources */, 7F8531D61A37BE680028BA23 /* JCNotificationBannerPresenterIOS7Style.m in Sources */, 36B8EB7C17568DAF004CF035 /* PacoConsentViewController.m in Sources */, - 44A843CC1ADB9C0A009C7226 /* ExperimentGroup.java in Sources */, 365B3C2E1836EF41003D57A7 /* UIImage+Paco.m in Sources */, - 4448BCA61A808E7A0034FCE9 /* GTMHTTPFetchHistory.m in Sources */, 36B8EB7D17568DAF004CF035 /* PacoExperimentDetailsViewController.m in Sources */, - A6ABFA971B742BA700F90598 /* ITAhoCorasickContainer.m in Sources */, - 4448BCA11A808E7A0034FCE9 /* GTMGatherInputStream.m in Sources */, 36B8EB7E17568DAF004CF035 /* PacoFindMyExperimentsViewController.m in Sources */, 7F8531D71A37BE680028BA23 /* JCNotificationBannerPresenterIOSStyle.m in Sources */, - 44A843D91ADB9C0A009C7226 /* ScheduleTrigger.java in Sources */, - 44A843DA1ADB9C0A009C7226 /* SignalTime.java in Sources */, 36B8EB8017568DAF004CF035 /* PacoMainViewController.m in Sources */, 36B8EB8117568DAF004CF035 /* PacoMenuButton.m in Sources */, - 44A843E11ADB9C0A009C7226 /* EsmSignalStore.java in Sources */, - 44A843D71ADB9C0A009C7226 /* PacoNotificationAction.java in Sources */, 36B8EB8217568DAF004CF035 /* PacoQuestionScreenViewController.m in Sources */, 36B8EB8317568DAF004CF035 /* PacoQuestionView.m in Sources */, E4E8F352183B21500022613A /* PacoContactUsViewController.m in Sources */, - 4448BCA81A808E7A0034FCE9 /* GTMMIMEDocument.m in Sources */, 36B8EB8417568DAF004CF035 /* PacoRunningExperimentsViewController.m in Sources */, - 44A843E21ADB9C0A009C7226 /* NonESMSignalGenerator.java in Sources */, - A6ABFAA31B742BE800F90598 /* NSObject+ITNDescription.m in Sources */, 36B8EB8517568DAF004CF035 /* PacoCheckboxView.m in Sources */, - 4448BCA91A808E7A0034FCE9 /* GTMReadMonitorInputStream.m in Sources */, 36B8EB8817568DAF004CF035 /* PacoLayout.m in Sources */, - 4448BCBC1A808E7A0034FCE9 /* GTMOAuth2Authentication.m in Sources */, - 44A843CA1ADB9C0A009C7226 /* ExperimentDAO.java in Sources */, - 4448BCB71A808E7A0034FCE9 /* NSObject+SBJSON.m in Sources */, - 44A843D41ADB9C0A009C7226 /* MinimumBufferable.java in Sources */, - 44A843C71ADB9C0A009C7226 /* ActionTrigger.java in Sources */, - A6ABFAA21B742BE800F90598 /* NSMutableDictionary+ITExtension.m in Sources */, - 44A843DB1ADB9C0A009C7226 /* Validatable.java in Sources */, - 4448BCB81A808E7A0034FCE9 /* NSString+SBJSON.m in Sources */, - 44A843CE1ADB9C0A009C7226 /* ExperimentValidator.java in Sources */, 363C99F11815FF8200D806F6 /* NSMutableArray+Paco.m in Sources */, 36B8EB8917568DAF004CF035 /* PacoLoadingTableCell.m in Sources */, - 44A843E01ADB9C0A009C7226 /* EsmGenerator2.java in Sources */, 36A8201C18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m in Sources */, 367233D41803956E006611E6 /* UILocalNotification+Paco.m in Sources */, 365D20EF1820622A0097F379 /* PacoScheduleGenerator+ESM.m in Sources */, @@ -2301,82 +1553,48 @@ 36B8EB8B17568DAF004CF035 /* PacoTableCell.m in Sources */, 36B8EB8C17568DAF004CF035 /* PacoTableTextCell.m in Sources */, 36417BE8180DCA9600335B74 /* NSCalendar+Paco.m in Sources */, - 4448BCBD1A808E7A0034FCE9 /* GTMOAuth2SignIn.m in Sources */, 36B8EB8D17568DAF004CF035 /* PacoTableView.m in Sources */, - 44A843C81ADB9C0A009C7226 /* EventInterface.java in Sources */, - 44A843D51ADB9C0A009C7226 /* PacoAction.java in Sources */, - 44A843C51ADB9C0A009C7226 /* ExperimentEditOutcome.java in Sources */, 7F8531DA1A37BE680028BA23 /* JCNotificationBannerViewController.m in Sources */, E462379218F9F1E900610F56 /* PacoDatePickerView.m in Sources */, - 4448BCA21A808E7A0034FCE9 /* GTMHTTPFetcher.m in Sources */, - 44A843DC1ADB9C0A009C7226 /* ValidationMessage.java in Sources */, - 4448BCA41A808E7A0034FCE9 /* GTMHTTPFetcherLogViewController.m in Sources */, - 36B8EC2D17568E33004CF035 /* GTMNSString+URLArguments.m in Sources */, 365D20FA1820695E0097F379 /* PacoUtility.m in Sources */, - 4448BCC01A808E7A0034FCE9 /* GTMOAuth2WindowController.m in Sources */, 36C4A33E18A4DEEE00D8FE59 /* DDFileLogger.m in Sources */, - 44A843D31ADB9C0A009C7226 /* ListMaker.java in Sources */, E4F9A79818899F39006A2803 /* PacoStepperView.m in Sources */, - 36B8EC3317568E33004CF035 /* GoogleAppEngineAuth.m in Sources */, - 36B8EC3417568E33004CF035 /* GoogleClientLogin.m in Sources */, - 44A843CB1ADB9C0A009C7226 /* ExperimentDAOCore.java in Sources */, 36946B05177A37CF005E0C04 /* PacoExperimentFeedback.m in Sources */, 7F8531DB1A37BE680028BA23 /* JCNotificationBannerViewIOS7Style.m in Sources */, 36C4A33F18A4DEEE00D8FE59 /* DDLog.m in Sources */, - A6ABFAA51B742BE800F90598 /* PacoSerializer.m in Sources */, 366F46B318CF82C200789A54 /* PacoPublicExperimentController.m in Sources */, 36946B08177A385A005E0C04 /* PacoExperimentInput.m in Sources */, - 4448BCDC1A80901D0034FCE9 /* GTMOAuth2ViewControllerTouch.m in Sources */, - 4448BCBB1A808E7A0034FCE9 /* SBJsonWriter.m in Sources */, - A6ABFAA41B742BE800F90598 /* NSObject+J2objcKVO.m in Sources */, 361A118B18F30CC9000E9CA2 /* UIColor+Paco.m in Sources */, - 4448BCA31A808E7A0034FCE9 /* GTMHTTPFetcherLogging.m in Sources */, - 44A843C91ADB9C0A009C7226 /* EventStore.java in Sources */, 36946B0B177A3968005E0C04 /* PacoExperimentSchedule.m in Sources */, 361A11A318F5A89A000E9CA2 /* UIFont+Paco.m in Sources */, - 44A843D11ADB9C0A009C7226 /* InterruptCue.java in Sources */, - 44A843D81ADB9C0A009C7226 /* Schedule.java in Sources */, 36946B0E177A55BA005E0C04 /* PacoExperimentDefinition.m in Sources */, 36946B14177A5782005E0C04 /* PacoExperiment.m in Sources */, - 44A843C61ADB9C0A009C7226 /* Outcome.java in Sources */, - 44A843E31ADB9C0A009C7226 /* ExperimentHelper.java in Sources */, 7F8531D51A37BE680028BA23 /* JCNotificationBannerPresenter.m in Sources */, 368C2EE1178DFFBA00546918 /* PacoAlertView.m in Sources */, 36488BB818C90D9A004517E2 /* PacoScheduleGenerator+Weekly.m in Sources */, 366F469D18CF127E00789A54 /* PacoScheduleGenerator+MonthlyByDayOfMonth.m in Sources */, 369EC80018467C2B00A1EFE4 /* PacoLoadingView.m in Sources */, - 4448BCBA1A808E7A0034FCE9 /* SBJsonParser.m in Sources */, E48622A2188FEE17000B5044 /* PacoSubtitleTableCell.m in Sources */, - 44A843CF1ADB9C0A009C7226 /* Feedback.java in Sources */, 36488BBE18CA598C004517E2 /* PacoPublicDefinitionLoader.m in Sources */, 36A8201818B556CC00FE83A5 /* PacoScheduleGenerator+Daily.m in Sources */, 36488BCC18CA6BAF004517E2 /* PacoEnumerator.m in Sources */, - 44A843D61ADB9C0A009C7226 /* PacoActionAllOthers.java in Sources */, E440AB3B19140E0800D6FD09 /* PacoOpenSourceLibViewController.m in Sources */, 366F46A118CF12FB00789A54 /* PacoScheduleGenerator+MonthlyByDayOfWeek.m in Sources */, 363E210817AAD028007DE3CE /* PacoEvent.m in Sources */, 36BD6D15194A390D00CD50A8 /* PacoEditScheduleAfterJoinController.m in Sources */, - 44A843DF1ADB9C0A009C7226 /* ActionSpecification.java in Sources */, 363E210B17AAD05B007DE3CE /* PacoEventManager.m in Sources */, 36488B8718BFDC46004517E2 /* PacoTriggerSignal.m in Sources */, 363E211317AF8420007DE3CE /* Reachability.m in Sources */, 363E211617AF88BB007DE3CE /* PacoEventUploader.m in Sources */, 365D20E7181B198D0097F379 /* NSString+Paco.m in Sources */, 36C4A33D18A4DEEE00D8FE59 /* DDASLLogger.m in Sources */, - 44A843E51ADB9C0A009C7226 /* TimeUtil.java in Sources */, 363E211A17B5B13F007DE3CE /* PacoExpressionExecutor.m in Sources */, - 4448BCB91A808E7A0034FCE9 /* SBJsonBase.m in Sources */, 363E211D17B5B1F6007DE3CE /* PacoInputEvaluator.m in Sources */, 7F8531DC1A37BE680028BA23 /* JCNotificationBannerViewIOSStyle.m in Sources */, - 36AD6CDD17C420F800B93855 /* SSKeychain.m in Sources */, 7F8531DD1A37BE680028BA23 /* JCNotificationBannerWindow.m in Sources */, - 44A843E41ADB9C0A009C7226 /* SchedulePrinter.java in Sources */, - 36AD6CDE17C420F800B93855 /* SSKeychainQuery.m in Sources */, 367233E1180619A5006611E6 /* PacoScheduleGenerator.m in Sources */, 36AD6CE217C4440000B93855 /* NSError+Paco.m in Sources */, - A678C2751B703955003F0D27 /* ModelBase.java in Sources */, 7F8531DE1A37BE680028BA23 /* JCNotificationCenter.m in Sources */, - 44A843D21ADB9C0A009C7226 /* InterruptTrigger.java in Sources */, 361AB05617DA77000053C313 /* PacoNotificationManager.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -2385,88 +1603,50 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - A678C2761B7042D3003F0D27 /* DerivedSources in Sources */, - A633A9AC1B5DA0970046436D /* InterruptTrigger.java in Sources */, 36A8201D18B5576400FE83A5 /* PacoScheduleGenerator+Weekdays.m in Sources */, - A633A9B61B5DA0970046436D /* ValidationMessage.java in Sources */, - A633A9A71B5DA0970046436D /* ExperimentQueryResult.java in Sources */, 36B5A4FB18282E46004DB894 /* PacoScheduleGeneratorWeeklyESMTests.m in Sources */, - A633A9AB1B5DA0970046436D /* InterruptCue.java in Sources */, 365D20EA181B1B000097F379 /* PacoNSStringCategoryTests.m in Sources */, 36B8EC3C17568E40004CF035 /* PacoTests.m in Sources */, 367233E418061FD6006611E6 /* PacoScheduleGeneratorTests.m in Sources */, - A678C2E51B716283003F0D27 /* ModelBase.java in Sources */, 363C9A431816F4A600D806F6 /* PacoNSMutableArrayCategoryTests.m in Sources */, 36AD6CEB17C5977E00B93855 /* PacoEvaluatorTests.m in Sources */, - A633A9B21B5DA0970046436D /* Schedule.java in Sources */, - A676C7381B6043DE00F37572 /* Pacoj2Objc2JsonTests.m in Sources */, - A633A9C21B5DA1B70046436D /* PacoJ2OBJCTests.m in Sources */, - A633A9AD1B5DA0970046436D /* ListMaker.java in Sources */, - A633A9A31B5DA0970046436D /* EventStore.java in Sources */, 365D20F01820622A0097F379 /* PacoScheduleGenerator+ESM.m in Sources */, 3662927D1821C10800FC647A /* PacoExperimentScheduleTests.m in Sources */, - A633A9C01B5DA0970046436D /* readme.md in Sources */, - A633A9A11B5DA0970046436D /* ActionTrigger.java in Sources */, 36488BB918C90D9A004517E2 /* PacoScheduleGenerator+Weekly.m in Sources */, 36D33C8F17D579F600AC30B9 /* PacoExpressionExecutor.m in Sources */, 36417BE9180DCA9600335B74 /* NSCalendar+Paco.m in Sources */, 36417BEB180DCA9600335B74 /* NSDate+Paco.m in Sources */, - A633A9B91B5DA0970046436D /* ActionSpecification.java in Sources */, - A633A9AF1B5DA0970046436D /* PacoAction.java in Sources */, 368F4DA317ECE9ED00CFC2E4 /* PacoDateUtilityTests.m in Sources */, 36B5A4F218282CBC004DB894 /* PacoScheduleGeneratorDailyESMTests.m in Sources */, - A633A9A41B5DA0970046436D /* ExperimentDAO.java in Sources */, 366292861821C2EF00FC647A /* PacoUtilityTests.m in Sources */, 366F46A218CF12FB00789A54 /* PacoScheduleGenerator+MonthlyByDayOfWeek.m in Sources */, - A633A9AA1B5DA0970046436D /* Input2.java in Sources */, 365D20DD181B18CD0097F379 /* PacoNSErrorCategoryTests.m in Sources */, 36F02D34180DE16B0027395F /* PacoNSDateCategoryTests.m in Sources */, - A633A9BF1B5DA0970046436D /* TimeUtil.java in Sources */, 366F469E18CF127E00789A54 /* PacoScheduleGenerator+MonthlyByDayOfMonth.m in Sources */, - A633A9B01B5DA0970046436D /* PacoActionAllOthers.java in Sources */, - A633A9BE1B5DA0970046436D /* SchedulePrinter.java in Sources */, - A633A9BB1B5DA0970046436D /* EsmSignalStore.java in Sources */, 36A8201918B556CC00FE83A5 /* PacoScheduleGenerator+Daily.m in Sources */, 365D20FB1820695E0097F379 /* PacoUtility.m in Sources */, - A633A9B11B5DA0970046436D /* PacoNotificationAction.java in Sources */, 36D33C9717D57A5B00AC30B9 /* PacoAppDelegate.m in Sources */, 361A118C18F30CC9000E9CA2 /* UIColor+Paco.m in Sources */, 36BC10DD17FE09E8001EA9DD /* PacoIOSLocalNotificationTests.m in Sources */, - A633A99F1B5DA0970046436D /* ExperimentEditOutcome.java in Sources */, - A633A9B51B5DA0970046436D /* Validatable.java in Sources */, 36488BCD18CA6BAF004517E2 /* PacoEnumerator.m in Sources */, - A633A9BC1B5DA0970046436D /* NonESMSignalGenerator.java in Sources */, - A633A9A61B5DA0970046436D /* ExperimentGroup.java in Sources */, 361A11A618F85B7B000E9CA2 /* PacoScheduleGeneratorDailyTests.m in Sources */, - A633A9A91B5DA0970046436D /* Feedback.java in Sources */, 367233DC1803958D006611E6 /* UILocalNotification+Paco.m in Sources */, 361A11A418F5A89A000E9CA2 /* UIFont+Paco.m in Sources */, - A633A9B81B5DA0970046436D /* ActionScheduleGenerator.java in Sources */, 36D424A017E64917003BCD61 /* PacoESMDateTests.m in Sources */, 365B3C2F1836EF41003D57A7 /* UIImage+Paco.m in Sources */, - A633A9B41B5DA0970046436D /* SignalTime.java in Sources */, 365D20E8181B198D0097F379 /* NSString+Paco.m in Sources */, 36F02D33180DE16B0027395F /* PacoNSCalendarCategoryTests.m in Sources */, 3647925F181711D100409E87 /* PacoNotificationManagerTests.m in Sources */, 367233E2180619A5006611E6 /* PacoScheduleGenerator.m in Sources */, - A633A9B71B5DA0970046436D /* Validator.java in Sources */, - A633A9A01B5DA0970046436D /* Outcome.java in Sources */, - A633A9A21B5DA0970046436D /* EventInterface.java in Sources */, - A633A9B31B5DA0970046436D /* ScheduleTrigger.java in Sources */, 3640613018230DA700DA5EB7 /* PacoExperimentTests.m in Sources */, 36B5A4FD18282EA5004DB894 /* PacoScheduleGeneratorMonthlyESMTests.m in Sources */, - A633A9BD1B5DA0970046436D /* ExperimentHelper.java in Sources */, 3647926818171D7600409E87 /* PacoSchedulerTests.m in Sources */, 36488B8818BFDC46004517E2 /* PacoTriggerSignal.m in Sources */, - A633A9AE1B5DA0970046436D /* MinimumBufferable.java in Sources */, - A633A9BA1B5DA0970046436D /* EsmGenerator2.java in Sources */, 36488BBF18CA598C004517E2 /* PacoPublicDefinitionLoader.m in Sources */, 36D8B54F17F153A100F7698E /* PacoClientTests.m in Sources */, 363C99F21815FF8200D806F6 /* NSMutableArray+Paco.m in Sources */, 36F3EFE818FC645500ABF242 /* PacoESMDailyGeneratorWithCache.m in Sources */, - A633A9A51B5DA0970046436D /* ExperimentDAOCore.java in Sources */, 367233DE1803AEE9006611E6 /* PacoNotificationCategoryTests.m in Sources */, - A633A9A81B5DA0970046436D /* ExperimentValidator.java in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -2524,8 +1704,8 @@ CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "iPhone Developer: Tom Pennings (3962CV8FL3)"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Tom Pennings (3962CV8FL3)"; + CODE_SIGN_IDENTITY = "iPhone Distribution"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Paco Developers (NW2F476Z8Y)"; COPY_PHASE_STRIP = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; @@ -2539,15 +1719,13 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = "ParseKit/include/**"; - IPHONEOS_DEPLOYMENT_TARGET = 6.0; - LIBRARY_SEARCH_PATHS = "../Shared/j2objc/lib/**"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; ONLY_ACTIVE_ARCH = YES; - OTHER_LDFLAGS = ""; PROVISIONING_PROFILE = "6FF1CA60-7E74-4967-9810-F69E1FEC48AB"; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "6FF1CA60-7E74-4967-9810-F69E1FEC48AB"; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; - USER_HEADER_SEARCH_PATHS = "ParseKit/include/** ../Shared/j2objc/include/** ${DERIVED_FILE_DIR}"; + USER_HEADER_SEARCH_PATHS = "ParseKit/include/**"; }; name = Debug; }; @@ -2560,8 +1738,8 @@ CLANG_ENABLE_OBJC_ARC = YES; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "iPhone Developer: Tom Pennings (3962CV8FL3)"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Tom Pennings (3962CV8FL3)"; + CODE_SIGN_IDENTITY = "iPhone Distribution"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer: Paco Developers (NW2F476Z8Y)"; COPY_PHASE_STRIP = YES; ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; @@ -2569,74 +1747,74 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_VARIABLE = YES; HEADER_SEARCH_PATHS = "ParseKit/include/**"; - IPHONEOS_DEPLOYMENT_TARGET = 6.0; - LIBRARY_SEARCH_PATHS = "../Shared/j2objc/lib/**"; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + ONLY_ACTIVE_ARCH = NO; OTHER_CFLAGS = "-DNS_BLOCK_ASSERTIONS=1"; - OTHER_LDFLAGS = ""; PROVISIONING_PROFILE = "6FF1CA60-7E74-4967-9810-F69E1FEC48AB"; "PROVISIONING_PROFILE[sdk=iphoneos*]" = "6FF1CA60-7E74-4967-9810-F69E1FEC48AB"; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; - USER_HEADER_SEARCH_PATHS = "ParseKit/include/** ../Shared/j2objc/include/** ${DERIVED_FILE_DIR}"; + USER_HEADER_SEARCH_PATHS = "ParseKit/include/**"; VALIDATE_PRODUCT = YES; }; name = Release; }; 31977201163F0733000AC06B /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 9D60D437C62D01DB8DA47FFA /* Pods-Paco.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=*]" = ""; + CODE_SIGN_IDENTITY = "iPhone Developer: Paco Developers (NW2F476Z8Y)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEVELOPMENT_TEAM = J7M7JW942W; + ENTITLEMENTS_REQUIRED = Yes; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/DerivedData/Paco/Build/Products/Debug-iphonesimulator/AppAuth", + "$(PROJECT_DIR)/DerivedData/Paco/Build/Products/Debug-iphonesimulator/GTMAppAuth", + "$(PROJECT_DIR)/DerivedData/Paco/Build/Products/Debug-iphonesimulator/GTMSessionFetcher", + ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Paco/source/Paco-Prefix.pch"; INFOPLIST_FILE = "Paco/config/Paco-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - LIBRARY_SEARCH_PATHS = ../Shared/j2objc/lib; - OTHER_LDFLAGS = ( - "-ObjC", - "-all_load", - "-ljre_emul", - "-ljsr305", - "-lguava", - "-ljoda_convert", - "-ljoda_time", - ); + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + OTHER_LDFLAGS = ""; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE = "5bc68275-45ab-4004-bb18-abf78da5fbdb"; - "PROVISIONING_PROFILE[sdk=iphoneos*]" = "5bc68275-45ab-4004-bb18-abf78da5fbdb"; - TARGETED_DEVICE_FAMILY = 1; - USER_HEADER_SEARCH_PATHS = "ParseKit/include/** ../Shared/j2objc/include/** ${DERIVED_FILE_DIR}/**"; + PROVISIONING_PROFILE = ""; + "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; + TARGETED_DEVICE_FAMILY = "1,2"; WRAPPER_EXTENSION = app; }; name = Debug; }; 31977202163F0733000AC06B /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = B8B04486F837EC6A07859438 /* Pods-Paco.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; - CODE_SIGN_IDENTITY = "iPhone Developer"; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + CODE_SIGN_IDENTITY = "iPhone Developer: Paco Developers (NW2F476Z8Y)"; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEVELOPMENT_TEAM = J7M7JW942W; + ENTITLEMENTS_REQUIRED = Yes; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/DerivedData/Paco/Build/Products/Debug-iphonesimulator/AppAuth", + "$(PROJECT_DIR)/DerivedData/Paco/Build/Products/Debug-iphonesimulator/GTMAppAuth", + "$(PROJECT_DIR)/DerivedData/Paco/Build/Products/Debug-iphonesimulator/GTMSessionFetcher", + ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Paco/source/Paco-Prefix.pch"; INFOPLIST_FILE = "Paco/config/Paco-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - LIBRARY_SEARCH_PATHS = ../Shared/j2objc/lib; - OTHER_LDFLAGS = ( - "-ObjC", - "-all_load", - "-ljre_emul", - "-ljsr305", - "-lguava", - "-ljoda_convert", - "-ljoda_time", - ); + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + OTHER_LDFLAGS = ""; + "OTHER_LDFLAGS[arch=*]" = ""; PRODUCT_NAME = "$(TARGET_NAME)"; - PROVISIONING_PROFILE = "5bc68275-45ab-4004-bb18-abf78da5fbdb"; - TARGETED_DEVICE_FAMILY = 1; - USER_HEADER_SEARCH_PATHS = "ParseKit/include/** ../Shared/j2objc/include/** ${DERIVED_FILE_DIR}/**"; + PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; + TARGETED_DEVICE_FAMILY = "1,2"; WRAPPER_EXTENSION = app; }; name = Release; @@ -2644,7 +1822,6 @@ 31977204163F0733000AC06B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/Paco.app/Paco"; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -2655,28 +1832,16 @@ ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Paco/source/Paco-Prefix.pch"; - HEADER_SEARCH_PATHS = ( - "$(inherited)", - "/Users/northropo/Project/paco/Paco-iOS/DerivedData", - ); INFOPLIST_FILE = "PacoTests/resources/PacoTests-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - LIBRARY_SEARCH_PATHS = "$(inherited)"; - OTHER_LDFLAGS = ( - "-framework", - XCTest, - ); PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; TEST_HOST = "$(BUNDLE_LOADER)"; - USER_HEADER_SEARCH_PATHS = "$(inherited)/**"; }; name = Debug; }; 31977205163F0733000AC06B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/Paco.app/Paco"; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -2687,21 +1852,10 @@ ); GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Paco/source/Paco-Prefix.pch"; - HEADER_SEARCH_PATHS = ( - "$(inherited)", - "/Users/northropo/Project/paco/Paco-iOS/DerivedData", - ); INFOPLIST_FILE = "PacoTests/resources/PacoTests-Info.plist"; - IPHONEOS_DEPLOYMENT_TARGET = 7.0; - LIBRARY_SEARCH_PATHS = "$(inherited)"; - OTHER_LDFLAGS = ( - "-framework", - XCTest, - ); PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; TEST_HOST = "$(BUNDLE_LOADER)"; - USER_HEADER_SEARCH_PATHS = "$(inherited)/**"; }; name = Release; }; diff --git a/Paco-iOS/Paco.xcworkspace/contents.xcworkspacedata b/Paco-iOS/Paco.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..c9034a92f --- /dev/null +++ b/Paco-iOS/Paco.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Paco-iOS/Paco.xcworkspace/xcuserdata/bobevans.xcuserdatad/UserInterfaceState.xcuserstate b/Paco-iOS/Paco.xcworkspace/xcuserdata/bobevans.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 000000000..dc0e1c919 Binary files /dev/null and b/Paco-iOS/Paco.xcworkspace/xcuserdata/bobevans.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/AppIcon.appiconset/Contents.json b/Paco-iOS/Paco/config/Images.xcassets/AppIcon.appiconset/Contents.json index c3796c8bf..1beb0d131 100644 --- a/Paco-iOS/Paco/config/Images.xcassets/AppIcon.appiconset/Contents.json +++ b/Paco-iOS/Paco/config/Images.xcassets/AppIcon.appiconset/Contents.json @@ -1,27 +1,68 @@ { "images" : [ { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "icon_ios7_settings_58.png", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "icon_ios7_spotlight_80.png", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { "size" : "60x60", "idiom" : "iphone", "filename" : "icon_ios7_iphone_120.png", "scale" : "2x" }, { - "size" : "76x76", + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { "idiom" : "ipad", - "filename" : "icon_ios7_ipad_76.png", + "size" : "20x20", "scale" : "1x" }, { - "size" : "76x76", "idiom" : "ipad", - "filename" : "icon_ios7_ipad_152.png", + "size" : "20x20", "scale" : "2x" }, { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_ios7_spotlight_80.png", + "size" : "29x29", + "idiom" : "ipad", + "filename" : "icon_ios7_settings_29.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "icon_ios7_settings_58.png", "scale" : "2x" }, { @@ -37,21 +78,20 @@ "scale" : "2x" }, { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_ios7_settings_58.png", - "scale" : "2x" + "size" : "76x76", + "idiom" : "ipad", + "filename" : "icon_ios7_ipad_76.png", + "scale" : "1x" }, { - "size" : "29x29", + "size" : "76x76", "idiom" : "ipad", - "filename" : "icon_ios7_settings_29.png", - "scale" : "1x" + "filename" : "icon_ios7_ipad_152.png", + "scale" : "2x" }, { - "size" : "29x29", "idiom" : "ipad", - "filename" : "icon_ios7_settings_58.png", + "size" : "83.5x83.5", "scale" : "2x" } ], diff --git a/Paco-iOS/Paco/config/Images.xcassets/Contents.json b/Paco-iOS/Paco/config/Images.xcassets/Contents.json new file mode 100644 index 000000000..da4a164c9 --- /dev/null +++ b/Paco-iOS/Paco/config/Images.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Contents.json b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Contents.json index b68f4a649..7c667b5ee 100644 --- a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Contents.json +++ b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Contents.json @@ -1,55 +1,163 @@ { + "info" : { + "author" : "xcode", + "version" : 1 + }, "images" : [ { "orientation" : "portrait", + "filename" : "Default.png", + "idiom" : "iphone", + "scale" : "1x", + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "minimum-system-version" : "7.0", + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default-568h@2x.png", + "idiom" : "iphone", + "subtype" : "retina4", + "scale" : "2x", + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default-568h@2x.png", + "idiom" : "iphone", + "subtype" : "retina4", + "scale" : "2x", + "minimum-system-version" : "7.0", + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default~ipad.png", + "idiom" : "ipad", + "scale" : "1x", + "extent" : "to-status-bar" + }, + { + "orientation" : "portrait", + "filename" : "Default~ipad@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "extent" : "to-status-bar" + }, + { + "orientation" : "landscape", + "filename" : "Default~ipad~landscape.png", "idiom" : "ipad", - "filename" : "splash_ios_tablet_768x1024.png", + "scale" : "1x", + "extent" : "to-status-bar" + }, + { + "orientation" : "landscape", + "filename" : "Default~ipad~landscape@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "extent" : "to-status-bar", + "size" : "83.5x83.5" + }, + { + "orientation" : "portrait", + "filename" : "Default~ipad~nostatusbar.png", + "idiom" : "ipad", + "scale" : "1x", "minimum-system-version" : "7.0", - "extent" : "full-screen", - "scale" : "1x" + "extent" : "full-screen" }, { "orientation" : "portrait", + "filename" : "Default~ipad~nostatusbar.png", "idiom" : "ipad", - "filename" : "splash_ios_tablet_768x1024@2x.png", + "scale" : "1x", + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default~ipad~nostatusbar@2x.png", + "idiom" : "ipad", + "scale" : "2x", "minimum-system-version" : "7.0", - "extent" : "full-screen", - "scale" : "2x" + "extent" : "full-screen" + }, + { + "orientation" : "portrait", + "filename" : "Default~ipad~nostatusbar@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "extent" : "full-screen" }, { "orientation" : "landscape", + "filename" : "Default~ipad~landscape~nostatusbar.png", "idiom" : "ipad", - "filename" : "splash_ios_tablet_1024x768.png", + "scale" : "1x", "minimum-system-version" : "7.0", - "extent" : "full-screen", - "scale" : "1x" + "extent" : "full-screen" }, { "orientation" : "landscape", + "filename" : "Default~ipad~landscape~nostatusbar.png", "idiom" : "ipad", - "filename" : "splash_ios_tablet_1024x768@2x.png", + "scale" : "1x", + "extent" : "full-screen" + }, + { + "orientation" : "landscape", + "filename" : "Default~ipad~landscape~nostatusbar@2x.png", + "idiom" : "ipad", + "scale" : "2x", "minimum-system-version" : "7.0", - "extent" : "full-screen", - "scale" : "2x" + "extent" : "full-screen" + }, + { + "orientation" : "landscape", + "filename" : "Default~ipad~landscape~nostatusbar@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "extent" : "full-screen" }, { "orientation" : "portrait", + "filename" : "Default-Portrait-736h@3x.png", "idiom" : "iphone", - "filename" : "splash_ios_mobile_640x960.png", - "minimum-system-version" : "7.0", - "scale" : "2x" + "subtype" : "736h", + "scale" : "3x", + "minimum-system-version" : "8.0", + "extent" : "full-screen" + }, + { + "orientation" : "landscape", + "filename" : "Default-Landscape-736h@3x.png", + "idiom" : "iphone", + "subtype" : "736h", + "scale" : "3x", + "minimum-system-version" : "8.0", + "extent" : "full-screen" }, { "orientation" : "portrait", + "filename" : "Default-667h@2x.png", "idiom" : "iphone", - "filename" : "splash_ios_mobile_640x1136.png", - "minimum-system-version" : "7.0", - "subtype" : "retina4", - "scale" : "2x" + "subtype" : "667h", + "scale" : "2x", + "minimum-system-version" : "8.0", + "extent" : "full-screen" } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file + ] +} diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-568h@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-568h@2x.png new file mode 100644 index 000000000..fe07e7791 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-568h@2x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-667h@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-667h@2x.png new file mode 100644 index 000000000..4a2069e20 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-667h@2x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h@3x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h@3x.png new file mode 100644 index 000000000..6fa36fe4a Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-Landscape-736h@3x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-Portrait-736h@3x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-Portrait-736h@3x.png new file mode 100644 index 000000000..1e2e69dbc Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default-Portrait-736h@3x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default.png new file mode 100644 index 000000000..d131c9c6f Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default@2x.png new file mode 100644 index 000000000..2a243d9d9 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default@2x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad.png new file mode 100644 index 000000000..e0519e212 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad@2x.png new file mode 100644 index 000000000..bb561d20f Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad@2x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape.png new file mode 100644 index 000000000..d75b34409 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape@2x.png new file mode 100644 index 000000000..7b1172c24 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape@2x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape~nostatusbar.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape~nostatusbar.png new file mode 100644 index 000000000..5f2676989 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape~nostatusbar.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape~nostatusbar@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape~nostatusbar@2x.png new file mode 100644 index 000000000..356d8a5df Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~landscape~nostatusbar@2x.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~nostatusbar.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~nostatusbar.png new file mode 100644 index 000000000..74aa404be Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~nostatusbar.png differ diff --git a/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~nostatusbar@2x.png b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~nostatusbar@2x.png new file mode 100644 index 000000000..faf862e58 Binary files /dev/null and b/Paco-iOS/Paco/config/Images.xcassets/LaunchImage.launchimage/Default~ipad~nostatusbar@2x.png differ diff --git a/Paco-iOS/Paco/config/Paco-Info.plist b/Paco-iOS/Paco/config/Paco-Info.plist index d3948cb24..26feca8b2 100644 --- a/Paco-iOS/Paco/config/Paco-Info.plist +++ b/Paco-iOS/Paco/config/Paco-Info.plist @@ -21,13 +21,32 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.1.7 + 1.1.8 CFBundleSignature ???? + CFBundleURLTypes + + + CFBundleTypeRole + Editor + CFBundleURLSchemes + + com.googleusercontent.apps.619519633889-f79aogqhj44eut1u75e8jaa5eav8p3eu + + + CFBundleVersion - 1.1.7.1 + 1.1.8.2 + LSApplicationCategoryType + LSRequiresIPhoneOS + NSCameraUsageDescription + Used to add picture survey responses + NSLocationWhenInUseUsageDescription + This app will display your current location + NSPhotoLibraryUsageDescription + Used to allow the user to attach a photo from their library as a survey response. UIBackgroundModes fetch @@ -36,6 +55,8 @@ armv7 + UIRequiresFullScreen + UISupportedInterfaceOrientations UIInterfaceOrientationPortrait diff --git a/Paco-iOS/Paco/source/PacoAppDelegate.h b/Paco-iOS/Paco/source/PacoAppDelegate.h index d2d145899..8f1b26d64 100644 --- a/Paco-iOS/Paco/source/PacoAppDelegate.h +++ b/Paco-iOS/Paco/source/PacoAppDelegate.h @@ -16,6 +16,7 @@ #import @class PacoMainViewController; +@protocol OIDAuthorizationFlowSession; @interface PacoAppDelegate : UIResponder @@ -29,4 +30,12 @@ - (void)processNotificationIfNeeded; +/*! @brief The authorization flow session which receives the return URL from + \SFSafariViewController. + @discussion We need to store this in the app delegate as it's that delegate which receives the + incoming URL on UIApplicationDelegate.application:openURL:options:. This property will be + nil, except when an authorization flow is in progress. + */ +@property(nonatomic, strong, nullable) id currentAuthorizationFlow; + @end diff --git a/Paco-iOS/Paco/source/PacoAppDelegate.m b/Paco-iOS/Paco/source/PacoAppDelegate.m index 27148b284..5541ea948 100644 --- a/Paco-iOS/Paco/source/PacoAppDelegate.m +++ b/Paco-iOS/Paco/source/PacoAppDelegate.m @@ -15,8 +15,9 @@ #import "PacoAppDelegate.h" -#import "GoogleAppEngineAuth.h" -#import "GTMOAuth2ViewControllerTouch.h" +#import "AppAuth.h" +//#import "GoogleAppEngineAuth.h" +//#import "GTMOAuth2ViewControllerTouch.h" #import "PacoClient.h" #import "UIColor+Paco.h" #import "PacoMainViewController.h" @@ -149,7 +150,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( } else { self.viewController = [[PacoMainViewController alloc] initWithNibName:nil bundle:nil]; } - + self.viewController.stillAuthenticating = _currentAuthorizationFlow; self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:self.viewController]; [self.window makeKeyAndVisible]; @@ -175,7 +176,7 @@ - (void)application:(UIApplication *)application performFetchWithCompletionHandl - (void)applicationDidBecomeActive:(UIApplication *)application { DDLogInfo(@"========== Application applicationDidBecomeActive =========="); - [[PacoClient sharedInstance] uploadPendingEventsInBackground]; +// [[PacoClient sharedInstance] uploadPendingEventsInBackground]; [[NSNotificationCenter defaultCenter] postNotificationName:kPacoNotificationAppBecomeActive object:nil]; @@ -218,4 +219,24 @@ - (void)applicationWillEnterForeground:(UIApplication *)application { [[PacoClient sharedInstance] executeRoutineMajorTaskIfNeeded]; } +#pragma GTMAppAuth +/*! @brief Handles inbound URLs. Checks if the URL matches the redirect URI for a pending + AppAuth authorization request. + */ +- (BOOL)application:(UIApplication *)app + openURL:(NSURL *)url + options:(NSDictionary *)options { + // Sends the URL to the current authorization flow (if any) which will process it if it relates to + // an authorization response. + if ([_currentAuthorizationFlow resumeAuthorizationFlowWithURL:url]) { + _currentAuthorizationFlow = nil; + return YES; + } + + // Your additional URL handling (if any) goes here. + + return NO; +} + + @end diff --git a/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.h b/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.h index 285e9aacd..4049bf9fa 100644 --- a/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.h +++ b/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.h @@ -17,17 +17,23 @@ -@class GTMOAuth2Authentication; +@class GTMFetcherAuthorizationProtocol; +@class GTMAppAuthFetcherAuthorization; +@class OIDAuthState; +@class OIDServiceConfiguration; + @interface PacoAuthenticator : NSObject -@property(nonatomic, readonly, retain) GTMOAuth2Authentication *auth; +@property(nonatomic, readonly, retain) GTMAppAuthFetcherAuthorization *auth; - (id)initWithFirstLaunchFlag:(BOOL)firstLaunch; - (void)reAuthenticateWithBlock:(void(^)(NSError*))completionBlock; -- (void)authenticateWithOAuth2WithCompletionHandler:(void (^)(NSError *))completionHandler; +//- (void)authenticateWithOAuth2WithCompletionHandler:(void (^)(NSError *))completionHandler; + +- (void)authenticateWithGTMAppAuthWithCompletionHandler:(void (^)(NSError *))completionHandler; - (BOOL)isLoggedIn; diff --git a/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.m b/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.m index f80f07004..173de5ebc 100644 --- a/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.m +++ b/Paco-iOS/Paco/source/core/authentication/PacoAuthenticator.m @@ -15,21 +15,46 @@ #import "PacoAuthenticator.h" -#import "GTMOAuth2Authentication.h" -#import "GTMOAuth2SignIn.h" -#import "GTMOAuth2ViewControllerTouch.h" +#import +#import +#import "GTMAppAuthFetcherAuthorization.h" +#import "GTMOAuth2KeychainCompatibility.h" +#import "PacoAppDelegate.h" + #import "PacoClient.h" -#import "SSKeychain.h" +NSString * const gtmAppAuthKeyChainName = @"PacoGTMAppAuthKeychain"; +NSString * const oldKeyChainName = @"PacoKeychain2"; + +/*! @brief The OIDC issuer from which the configuration will be discovered. + */ +static NSString *const kIssuer = @"https://accounts.google.com"; -NSString* const kPacoService = @"com.google.paco"; +/*! @brief The OAuth client ID. + @discussion For Google, register your client at + https://console.developers.google.com/apis/credentials?project=_ + The client should be registered with the "iOS" type. + */ +static NSString *const kClientID = @"619519633889-f79aogqhj44eut1u75e8jaa5eav8p3eu.apps.googleusercontent.com"; +/*! @brief The OAuth redirect URI for the client @c kClientID. + @discussion With Google, the scheme of the redirect URI is the reverse DNS notation of the + client ID. This scheme must be registered as a scheme in the project's Info + property list ("CFBundleURLTypes" plist key). Any path component will work, we use + 'oauthredirect' here to help disambiguate from any other use of this scheme. + */ +static NSString *const kRedirectURI = +@"com.googleusercontent.apps.619519633889-f79aogqhj44eut1u75e8jaa5eav8p3eu:/oauthredirect"; + +/*! @brief @c NSCoding key for the authState property. + */ +static NSString *const kExampleAuthorizerKey = @"authorization"; typedef void (^PacoAuthenticationBlock)(NSError *); @interface PacoAuthenticator () -@property(nonatomic, readwrite, retain) GTMOAuth2ViewControllerTouch *authUI; -@property(nonatomic, readwrite, retain) GTMOAuth2Authentication *auth; +//@property(nonatomic, readwrite, retain) GTMOAuth2ViewControllerTouch *authUI; +@property(nonatomic, readwrite, retain) GTMAppAuthFetcherAuthorization *auth; @property(nonatomic, readwrite, copy) PacoAuthenticationBlock completionHandler; @property(nonatomic, readwrite, assign) BOOL userLoggedIn; @@ -52,41 +77,26 @@ - (id)initWithFirstLaunchFlag:(BOOL)firstLaunch { #pragma mark - log in status - (NSString*)fetchUserEmailFromKeyChain { - NSArray* accounts = [SSKeychain accountsForService:kPacoService]; - if (0 == [accounts count]) { + GTMAppAuthFetcherAuthorization *authorization = [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:gtmAppAuthKeyChainName]; + if (!authorization) { NSLog(@"No email stored in Keychain"); return nil; } - NSAssert([accounts count] == 1, @"should only have one account!"); - NSDictionary* accountDict = accounts[0]; - NSString* email = accountDict[kSSKeychainAccountKey]; - NSLog(@"Fetched an email from Keychain"); - return email; + return authorization.userEmail; } - (BOOL)isUserAccountStored { NSString* email = [self fetchUserEmailFromKeyChain]; - NSString* pwd = [SSKeychain passwordForService:kPacoService account:email]; - if ([email length] > 0 && [pwd length] > 0) { - return YES; - } - return NO; + return [email length] > 0; } - (BOOL)hasAccountInKeyChain { - NSArray* accounts = [SSKeychain accountsForService:kPacoService]; - return [accounts count] > 0; + GTMAppAuthFetcherAuthorization *authorization = [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:gtmAppAuthKeyChainName]; + return authorization; } - (void)deleteAllAccountsFromKeyChain { - NSArray* accounts = [NSArray arrayWithArray:[SSKeychain accountsForService:kPacoService]]; - for (NSDictionary* accountDict in accounts) { - NSString* email = accountDict[kSSKeychainAccountKey]; - BOOL success = [SSKeychain deletePasswordForService:kPacoService account:email]; - if (!success) { - NSLog(@"[ERROR] Failed to delete password and account in keychain!"); - } - } + [GTMAppAuthFetcherAuthorization removeAuthorizationFromKeychainForName:gtmAppAuthKeyChainName]; } - (void)deleteAccount { @@ -94,13 +104,9 @@ - (void)deleteAccount { if ([self hasAccountInKeyChain]) { [self deleteAllAccountsFromKeyChain]; } - // Remove auth from keychain to prevent future auto sign-in as (null). - [GTMOAuth2ViewControllerTouch removeAuthFromKeychainForName:@"PacoKeychain2"]; - [GTMOAuth2ViewControllerTouch revokeTokenForGoogleAuthentication:self.auth]; } -- (BOOL)isLoggedIn -{ +- (BOOL)isLoggedIn { return self.userLoggedIn; } @@ -117,70 +123,102 @@ - (void)invalidateCurrentAccount { } - (void)reAuthenticateWithBlock:(void(^)(NSError*))completionBlock { - [self authenticateWithOAuth2WithCompletionHandler:completionBlock]; + [self authenticateWithGTMAppAuthWithCompletionHandler:completionBlock]; } +#pragma mark - GTMAppAuth -#pragma mark - OAuth2 +- (void)authenticateWithGTMAppAuthWithCompletionHandler:(void (^)(NSError *))completionHandler { + // Attempt to deserialize from Keychain in GTMAppAuth format. + GTMAppAuthFetcherAuthorization *authorization = [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:gtmAppAuthKeyChainName]; + self.auth = authorization; -- (void)authenticateWithOAuth2WithCompletionHandler:(void (^)(NSError *))completionHandler { - // Standard OAuth2 login flow. - // See: https://code.google.com/apis/console/#project:406945030854:access - - NSString *scopes = @"https://www.googleapis.com/auth/userinfo.email"; - NSString *clientId = @"1051938716780.apps.googleusercontent.com"; - - // ispiro: Apparently the clientSecret parameter can be empty and auth still succeeds. - NSString *clientSecret = @""; - GTMOAuth2Authentication *keychainAuth = - [GTMOAuth2ViewControllerTouch - authForGoogleFromKeychainForName:@"PacoKeychain2" - clientID:clientId - clientSecret:clientSecret]; - if (keychainAuth && (keychainAuth.parameters)[@"refresh_token"]) { - self.auth = keychainAuth; + // If no data found in the new format, try to deserialize data from GTMOAuth2 + if (!authorization) { + // Tries to load the data serialized by GTMOAuth2 using old keychain name. + // If you created a new client id, be sure to use the *previous* client id and secret here. + authorization = + [GTMOAuth2KeychainCompatibility authForGoogleFromKeychainForName:oldKeyChainName + clientID:@"1051938716780.apps.googleusercontent.com" + clientSecret:@""]; + if (authorization) { + // Remove previously stored GTMOAuth2-formatted data. + [GTMOAuth2KeychainCompatibility removeAuthFromKeychainForName:oldKeyChainName]; + // Serialize to Keychain in GTMAppAuth format. + [GTMAppAuthFetcherAuthorization saveAuthorization:(GTMAppAuthFetcherAuthorization *)authorization + toKeychainForName:gtmAppAuthKeyChainName]; + if (completionHandler) { + completionHandler(nil); + } + } else { + NSURL *issuer = [NSURL URLWithString:kIssuer]; + NSURL *redirectURI = [NSURL URLWithString:kRedirectURI]; + + NSLog(@"Fetching configuration for issuer: %@", issuer); + + // discovers endpoints + [OIDAuthorizationService + discoverServiceConfigurationForIssuer:issuer + completion:^(OIDServiceConfiguration *_Nullable configuration, NSError *_Nullable error) { + + if (!configuration) { + NSLog(@"Error retrieving discovery document: %@", [error localizedDescription]); + self.auth = nil; + return; + } + + NSLog(@"Got configuration", nil); + + // builds authentication request + OIDAuthorizationRequest *request = + [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + scopes:@[OIDScopeEmail] + redirectURL:redirectURI + responseType:OIDResponseTypeCode + additionalParameters:nil]; + // performs authentication request + PacoAppDelegate *appDelegate = (PacoAppDelegate *)[[UIApplication sharedApplication] delegate]; + NSLog(@"Initiating authorization request with scope: %@", request.scope); + + UIViewController *controller = [UIApplication sharedApplication].keyWindow.rootViewController; + + appDelegate.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + presentingViewController:controller + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + if (authState) { + GTMAppAuthFetcherAuthorization *authorization = + [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState]; + + self.auth = authorization; + NSLog(@"Got authorization tokens. ", nil); //authState.lastTokenResponse.accessToken); + [GTMAppAuthFetcherAuthorization saveAuthorization:(GTMAppAuthFetcherAuthorization *)authorization + toKeychainForName:gtmAppAuthKeyChainName]; + NSLog(@"PACO OAUTH2 LOGIN AUTH SUCCEEDED [%@]", authorization.authState.refreshToken); + self.userLoggedIn = YES; + if (completionHandler) { + completionHandler(nil); + } + + } else { + self.auth = nil; + NSLog(@"Authorization error: %@", [error localizedDescription]); + NSLog(@"PACO OAUTH2 LOGIN AUTH FAILED [%@]", error); + self.userLoggedIn = NO; + } + }]; + }]; + + } + } else { + self.auth = authorization; if (completionHandler) { completionHandler(nil); } - return; } - - - _authUI = [[GTMOAuth2ViewControllerTouch alloc] - initWithScope:scopes - clientID:clientId - clientSecret:clientSecret - keychainItemName:@"PacoKeychain2" - completionHandler:^(GTMOAuth2ViewControllerTouch *viewController, - GTMOAuth2Authentication *auth, - NSError *error) { - BOOL result = [GTMOAuth2ViewControllerTouch saveParamsToKeychainForName:@"PacoKeychain2" - authentication:auth]; - assert(result); - // TODO(ispiro): If user presses cancel at the final screen, assert will fail. Should return to splash screen. - self.auth = auth; - if (auth && !error) { - [SSKeychain setPassword:@"" - forService:kPacoService - account:auth.userEmail]; - NSLog(@"PACO OAUTH2 LOGIN AUTH SUCCEEDED [%@]", auth.tokenURL.absoluteString); - self.userLoggedIn = YES; - } else { - NSLog(@"PACO OAUTH2 LOGIN AUTH FAILED [%@]", error); - self.userLoggedIn = NO; - } - if (completionHandler) { - completionHandler(nil); - } - // TODO(ispiro): Find a way to hide this window faster. - [[UIApplication sharedApplication].keyWindow.rootViewController - dismissViewControllerAnimated:NO completion:^{}]; - }]; - [[UIApplication sharedApplication].keyWindow.rootViewController - presentViewController:_authUI animated:NO completion:^{ - self.authUI = nil; - }]; } @end diff --git a/Paco-iOS/Paco/source/core/client/PacoClient.m b/Paco-iOS/Paco/source/core/client/PacoClient.m index b58f41576..c03495938 100644 --- a/Paco-iOS/Paco/source/core/client/PacoClient.m +++ b/Paco-iOS/Paco/source/core/client/PacoClient.m @@ -496,7 +496,7 @@ - (void)loginWithOAuth2CompletionHandler:(void (^)(NSError *))completionHandler completionHandler(nil); } }else{ - [self.authenticator authenticateWithOAuth2WithCompletionHandler:^(NSError *error) { + [self.authenticator authenticateWithGTMAppAuthWithCompletionHandler:^(NSError *error) { if (!error) { // Authorize the service. self.service.authenticator = self.authenticator; diff --git a/Paco-iOS/Paco/source/core/model/PacoExperimentInput.m b/Paco-iOS/Paco/source/core/model/PacoExperimentInput.m index f708b0a3e..d9eaa76bd 100644 --- a/Paco-iOS/Paco/source/core/model/PacoExperimentInput.m +++ b/Paco-iOS/Paco/source/core/model/PacoExperimentInput.m @@ -144,7 +144,7 @@ + (ResponseEnumType)responseEnumTypeFromString:(NSString*)responseTypeString { enumType = ResponseEnumTypePhoto; } else { - NSAssert1(NO, @"[ERROR]responseType %@ is not implemented!", responseTypeString); + //NSAssert1(NO, @"[ERROR]responseType %@ is not implemented!", responseTypeString); } return enumType; } diff --git a/Paco-iOS/Paco/source/core/scheduling/PacoNotificationManager.m b/Paco-iOS/Paco/source/core/scheduling/PacoNotificationManager.m index c3d8656de..cbb9c577e 100644 --- a/Paco-iOS/Paco/source/core/scheduling/PacoNotificationManager.m +++ b/Paco-iOS/Paco/source/core/scheduling/PacoNotificationManager.m @@ -111,7 +111,19 @@ - (void)handleRespondedNotification:(UILocalNotification*)notification { if (0 == [notifications count]) { return; } - [notifications removeObject:notification]; + + //The passed notification object is identical to but not the same + //as the fired notification object. + //Therefore removeObject fails to remove the notification from the array. + //Since at this point, the array is already filtered by experimentId, we + //can just use the predicate to remove the fired notification object. + + NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fireDate == %@", notification.fireDate]; + NSArray *filteredArray = [notifications filteredArrayUsingPredicate:predicate]; + id firstFoundObject = nil; + firstFoundObject = filteredArray.count > 0 ? filteredArray.firstObject : nil; + [notifications removeObject:firstFoundObject]; + (self.notificationDict)[experimentId] = notifications; DDLogInfo(@"New Notification Dict: %@", [self.notificationDict pacoDescriptionForNotificationDict]); [self saveNotificationsToCache]; diff --git a/Paco-iOS/Paco/source/core/service/PacoService.m b/Paco-iOS/Paco/source/core/service/PacoService.m index e9c788143..d7e880e94 100644 --- a/Paco-iOS/Paco/source/core/service/PacoService.m +++ b/Paco-iOS/Paco/source/core/service/PacoService.m @@ -15,10 +15,6 @@ #import "PacoService.h" - -#import "GTMHTTPFetcher.h" -#import "GTMHTTPFetcherLogging.h" -#import "GTMOAuth2Authentication.h" #import "PacoAuthenticator.h" #import "PacoDateUtility.h" #import "PacoModel.h" @@ -28,6 +24,10 @@ #import "PacoExperimentDefinition.h" #import "PacoEvent.h" +#import "GTMSessionFetcher.h" +#import "GTMSessionFetcherService.h" +#import "OIDError.h" + @implementation PacoService @@ -41,17 +41,6 @@ + (NSString *)stringFromData:(NSData *)data { return converted; } -- (void)authenticateRequest:(NSMutableURLRequest *)request - withFetcher:(GTMHTTPFetcher *)fetcher { - if (self.authenticator.auth) { - // OAuth2 - [fetcher setAuthorizer:self.authenticator.auth]; - - } else { - DDLogError(@"Error authenticating request."); - } -} - - (void)executePacoServiceCall:(NSMutableURLRequest *)request completionHandler:(void (^)(id, NSError *))completionHandler { NSString *version = [[NSBundle mainBundle] infoDictionary][(NSString*)kCFBundleVersionKey]; @@ -59,34 +48,42 @@ - (void)executePacoServiceCall:(NSMutableURLRequest *)request [request setValue:@"iOS" forHTTPHeaderField:@"http.useragent"]; [request setValue:version forHTTPHeaderField:@"paco.version"]; [request setValue:@"3.0" forHTTPHeaderField:@"pacoProtocol"]; - - // Authenticate - [GTMHTTPFetcher setLoggingEnabled:YES]; - GTMHTTPFetcher *fetcher = [[GTMHTTPFetcher alloc] initWithRequest:request]; - [self authenticateRequest:request withFetcher:fetcher]; - fetcher.delegateQueue = [NSOperationQueue mainQueue]; - - // Fetch + + + // Creates a GTMSessionFetcherService with the authorization. + // Normally you would save this service object and re-use it for all REST API calls. + GTMSessionFetcherService *fetcherService = [[GTMSessionFetcherService alloc] init]; + fetcherService.authorizer = self.authenticator.auth; + + GTMSessionFetcher *fetcher = [fetcherService fetcherWithRequest:request]; + [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { - if (error) { - DDLogError(@"Service Call Failed [%@]", error); - } - // Convert to string and return. - id jsonObj = nil; - NSError *jsonError = nil; - if ([data length]) { - jsonObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; - if (jsonError) { - DDLogError(@"JSON PARSE ERROR = %@\n", jsonError); - DDLogError(@"PROBABLY AN AUTH ERROR"); - - [[PacoClient sharedInstance] invalidateUserAccount]; - } + if (error) { + if ([error.domain isEqual:OIDOAuthTokenErrorDomain]) { + //self.authenticator.auth = nil; + NSLog(@"Authorization error during token refresh, clearing state. %@", + error); + // Other errors are assumed transient. + } else { + NSLog(@"Transient error during token refresh. %@", error); } - if (completionHandler) { - completionHandler(jsonObj, error ? error : jsonError); + return; + } + + id jsonObj = nil; + NSError *jsonError = nil; + if ([data length]) { + jsonObj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; + if (jsonError) { + DDLogError(@"JSON PARSE ERROR = %@\n", jsonError); + DDLogError(@"JSON dump: %@\n", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); } - }]; + } + if (completionHandler) { + completionHandler(jsonObj, error ? error : jsonError); + } + + }]; } //http request to load paginated experiment definitions @@ -233,7 +230,7 @@ - (void)submitEventList:(NSArray*)eventList withCompletionBlock:(void (^)(NSArra NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData - timeoutInterval:25]; + timeoutInterval:120]; [request setHTTPMethod:@"POST"]; // Serialize to JSON for the request body. diff --git a/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.h b/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.h index 71d091d20..835ffc296 100644 --- a/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.h +++ b/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.h @@ -18,4 +18,5 @@ @interface PacoMainViewController : UIViewController +@property BOOL stillAuthenticating; @end diff --git a/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.m b/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.m index cb7743f35..87f2419af 100644 --- a/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.m +++ b/Paco-iOS/Paco/source/ui/MainScreen/PacoMainViewController.m @@ -23,7 +23,6 @@ #import "PacoClient.h" #import "PacoContactUsViewController.h" #import "PacoWebViewController.h" -#import "GoogleClientLogin.h" #import "JCNotificationCenter.h" #import "JCNotificationBannerPresenterSmokeStyle.h" #import "PacoPublicExperimentController.h" @@ -139,21 +138,25 @@ - (void)viewDidLoad { [view setNeedsLayout]; - [[PacoClient sharedInstance] loginWithCompletionBlock:^(NSError *error) { - NSString* message = [self welcomeMessage]; - if (error) { - message = [GoogleClientLogin descriptionForError:error.domain]; - if (0 == [message length]) {//just in case - message = NSLocalizedString(@"Something went wrong, please try again.", nil); + if (!_stillAuthenticating) { + [[PacoClient sharedInstance] loginWithCompletionBlock:^(NSError *error) { + NSString* message = [self welcomeMessage]; + if (error) { + if (0 == [error.description length]) {//just in case + message = NSLocalizedString(@"Something went wrong, please try again.", nil); + } + } else { + //[[PacoClient sharedInstance] uploadPendingEventsInBackground]; } - } - [JCNotificationCenter sharedCenter].presenter = [JCNotificationBannerPresenterSmokeStyle new]; - JCNotificationBanner* banner = [[JCNotificationBanner alloc] initWithTitle:@"" - message:message - timeout:3. - tapHandler:nil]; - [[JCNotificationCenter sharedCenter] enqueueNotification:banner]; - }]; + [JCNotificationCenter sharedCenter].presenter = [JCNotificationBannerPresenterSmokeStyle new]; + JCNotificationBanner* banner = [[JCNotificationBanner alloc] initWithTitle:@"" + message:message + timeout:3. + tapHandler:nil]; + [[JCNotificationCenter sharedCenter] enqueueNotification:banner]; + }]; + } + } - (NSString*)welcomeMessage { diff --git a/Paco-iOS/Paco/source/ui/OpenSourceLibScreen/PacoOpenSourceLibViewController.m b/Paco-iOS/Paco/source/ui/OpenSourceLibScreen/PacoOpenSourceLibViewController.m index 3225068aa..6e8fe9322 100644 --- a/Paco-iOS/Paco/source/ui/OpenSourceLibScreen/PacoOpenSourceLibViewController.m +++ b/Paco-iOS/Paco/source/ui/OpenSourceLibScreen/PacoOpenSourceLibViewController.m @@ -76,15 +76,13 @@ - (void)viewDidLoad { - (void)loadCreditsTableView { self.creditsArray = @[@"Google-Toolbox-For-Mac", - @"TouchEngine", - @"SSKeyChain", + @"CocoaPods", @"JCNotificationBannerPresenter", @"CocoaLumberjack", @"ParseKit"]; self.urlArray = @[@"https://code.google.com/p/google-toolbox-for-mac/", - @"https://code.google.com/p/touchengine/", - @"https://github.com/soffes/sskeychain", + @"https://cocoapods.org", @"https://github.com/jcoleman/JCNotificationBannerPresenter", @"https://github.com/CocoaLumberjack/CocoaLumberjack", @"https://code.google.com/p/parsekit/source/detail?r=1543"]; diff --git a/Paco-iOS/Paco/source/ui/QuestionScreen/PacoQuestionView.m b/Paco-iOS/Paco/source/ui/QuestionScreen/PacoQuestionView.m index 3b0c43f1f..c913d9c6e 100644 --- a/Paco-iOS/Paco/source/ui/QuestionScreen/PacoQuestionView.m +++ b/Paco-iOS/Paco/source/ui/QuestionScreen/PacoQuestionView.m @@ -18,6 +18,7 @@ #import #import #import +#import #import "PacoCheckboxView.h" #import "UIColor+Paco.h" @@ -29,6 +30,7 @@ #import "UIImage+Paco.h" #import "PacoClient.h" + static const int kInvalidIndex = -1; static NSString* const kPlaceHolderString = @""; @@ -417,6 +419,12 @@ - (void)setupUIForQuestion { } self.map.delegate = self; [self addSubview:self.map]; + //if (UIDevice.currentDevice().systemVersion.floatValue>=8.0) { + //---request for foreground location use--- + // location.requestWhenInUseAuthorization() + //} + + //lm.startUpdatingLocation() } else if (self.question.responseEnumType == ResponseEnumTypePhoto) { if ([self.question.text length] == 0) { self.questionText.text = NSLocalizedString(@"Attach a photo.", nil); diff --git a/Paco-iOS/Paco/sourceImages/assets/splash_ios_tablet_1024x768@2x.png b/Paco-iOS/Paco/sourceImages/assets/splash_ios_tablet_1024x768@2x.png new file mode 100755 index 000000000..423662019 Binary files /dev/null and b/Paco-iOS/Paco/sourceImages/assets/splash_ios_tablet_1024x768@2x.png differ diff --git a/Paco-iOS/Paco/sourceImages/icons/icon_ios7_ipad_152.png b/Paco-iOS/Paco/sourceImages/icons/icon_ios7_ipad_152.png new file mode 100755 index 000000000..500d1f716 Binary files /dev/null and b/Paco-iOS/Paco/sourceImages/icons/icon_ios7_ipad_152.png differ diff --git a/Paco-iOS/ParseKit/ParseKit.xcodeproj/project.pbxproj b/Paco-iOS/ParseKit/ParseKit.xcodeproj/project.pbxproj index 43f9bc46d..6ceafdd0c 100644 --- a/Paco-iOS/ParseKit/ParseKit.xcodeproj/project.pbxproj +++ b/Paco-iOS/ParseKit/ParseKit.xcodeproj/project.pbxproj @@ -4918,6 +4918,7 @@ isa = XCBuildConfiguration; buildSettings = { DEBUG_INFORMATION_FORMAT = dwarf; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 5.0; @@ -4931,6 +4932,7 @@ isa = XCBuildConfiguration; buildSettings = { DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 5.0; diff --git a/Paco-iOS/Podfile b/Paco-iOS/Podfile new file mode 100644 index 000000000..8ce26e2c4 --- /dev/null +++ b/Paco-iOS/Podfile @@ -0,0 +1,9 @@ +platform :ios, '9.0' +use_frameworks! +inhibit_all_warnings! + +target 'Paco' do + pod 'AppAuth' + pod 'GTMAppAuth' + pod 'GTMSessionFetcher' +end diff --git a/Paco-iOS/Podfile.lock b/Paco-iOS/Podfile.lock new file mode 100644 index 000000000..d8a5d07a9 --- /dev/null +++ b/Paco-iOS/Podfile.lock @@ -0,0 +1,24 @@ +PODS: + - AppAuth (0.7.1) + - GTMAppAuth (0.5.0): + - AppAuth (~> 0.7.0) + - GTMSessionFetcher (~> 1.1) + - GTMSessionFetcher (1.1.9): + - GTMSessionFetcher/Full (= 1.1.9) + - GTMSessionFetcher/Core (1.1.9) + - GTMSessionFetcher/Full (1.1.9): + - GTMSessionFetcher/Core (= 1.1.9) + +DEPENDENCIES: + - AppAuth + - GTMAppAuth + - GTMSessionFetcher + +SPEC CHECKSUMS: + AppAuth: c56d352b0d50bb34dbb302d7ba50b20aa6b6ae89 + GTMAppAuth: 4b7bdc1fefdf6a49f3d9fc1aa6123f0c7e9b6660 + GTMSessionFetcher: 5c046c76a1f859bc9c187e918f18e4fc7bb57b5e + +PODFILE CHECKSUM: c665a47779f733e33fedc48ca8e7aafbb602f3d3 + +COCOAPODS: 1.2.1 diff --git a/Paco-iOS/Pods/AppAuth/LICENSE b/Paco-iOS/Pods/AppAuth/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Paco-iOS/Pods/AppAuth/README.md b/Paco-iOS/Pods/AppAuth/README.md new file mode 100644 index 000000000..82e9fbf13 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/README.md @@ -0,0 +1,327 @@ +# AppAuth for iOS and macOS + +[![Build Status](https://www.bitrise.io/app/8e4dbca635a964dc.svg?token=8rT4oJnhjUuFWH-QvXuJzg&branch=master)](https://www.bitrise.io/app/8e4dbca635a964dc) + +AppAuth for iOS and macOS is a client SDK for communicating with [OAuth 2.0] +(https://tools.ietf.org/html/rfc6749) and [OpenID Connect] +(http://openid.net/specs/openid-connect-core-1_0.html) providers. It strives to +directly map the requests and responses of those specifications, while following +the idiomatic style of the implementation language. In addition to mapping the +raw protocol flows, convenience methods are available to assist with common +tasks like performing an action with fresh tokens. + +It follows the best practices set out in [OAuth 2.0 for Native Apps] +(https://tools.ietf.org/html/draft-ietf-oauth-native-apps) +including using `SFSafariViewController` on iOS for the auth request. For this +reason, `UIWebView` is explicitly *not* supported due to usability and security +reasons. + +It also supports the [PKCE](https://tools.ietf.org/html/rfc7636) extension to +OAuth which was created to secure authorization codes in public clients when +custom URI scheme redirects are used. The library is friendly to other +extensions (standard or otherwise) with the ability to handle additional params +in all protocol requests and responses. + +## Specification + +### iOS + +#### Supported Versions + +AppAuth supports iOS 7 and above. + +iOS 9+ uses the in-app browser tab pattern +(via `SFSafariViewController`), and falls back to the system browser (mobile +Safari) on earlier versions. + +#### Authorization Server Requirements + +Both Custom URI Schemes (all supported versions of iOS) and Universal Links +(iOS 9+) can be used with the library. + +In general, AppAuth can work with any Authorization Server (AS) that supports +[native apps](https://tools.ietf.org/html/draft-ietf-oauth-native-apps), +either through custom URI scheme redirects, or universal links. +AS's that assume all clients are web-based or require clients to maintain +confidentiality of the client secrets may not work well. + +### macOS + +#### Supported Versions + +AppAuth supports macOS (OS X) 10.8 and above. + +#### Authorization Server Requirements + +AppAuth for macOS supports both custom schemes, a loopback HTTP redirects +via a small embedded server. + +In general, AppAuth can work with any Authorization Server (AS) that supports +[native apps](https://tools.ietf.org/html/draft-ietf-oauth-native-apps), +either through custom URI scheme, or loopback HTTP redirects. +AS's that assume all clients are web-based or require clients to maintain +confidentiality of the client secrets may not work well. + +## Try + +Want to try out AppAuth? Just run: + + pod try AppAuth + +Follow the instructions in [Example/README.md](Example/README.md) to configure +with your own OAuth client (you need to update 3 configuration points with your +client info to try the demo). + +## Setup + +If you use [CocoaPods](https://guides.cocoapods.org/using/getting-started.html), +simply add: + + pod 'AppAuth' + +To your `Podfile` and run `pod install`. Otherwise, add `AppAuth.xcodeproj` +into your workspace. + +## Auth Flow + +AppAuth supports both manual interaction with the Authorization Server +where you need to perform your own token exchanges, as well as convenience +methods that perform some of this logic for you. This example uses the +convenience method which returns either an `OIDAuthState` object, or an error. + +`OIDAuthState` is a class that keeps track of the authorization and token +requests and responses, and provides a convenience method to call an API with +fresh tokens. This is the only object that you need to serialize to retain the +authorization state of the session. + +### Configuration + +You can configure AppAuth by specifying the endpoints directly: + +```objc +NSURL *authorizationEndpoint = + [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/v2/auth"]; +NSURL *tokenEndpoint = + [NSURL URLWithString:@"https://www.googleapis.com/oauth2/v4/token"]; + +OIDServiceConfiguration *configuration = + [[OIDServiceConfiguration alloc] + initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint]; + +// perform the auth request... +``` + +Or through discovery: + +```objc +NSURL *issuer = [NSURL URLWithString:@"https://accounts.google.com"]; + +[OIDAuthorizationService discoverServiceConfigurationForIssuer:issuer + completion:^(OIDServiceConfiguration *_Nullable configuration, + NSError *_Nullable error) { + + if (!configuration) { + NSLog(@"Error retrieving discovery document: %@", + [error localizedDescription]); + return; + } + + // perform the auth request... +}]; +``` + +### Authorizing – iOS + +First you need to have a property in your AppDelegate to hold the session, in +order to continue the authorization flow from the redirect. + +```objc +// property of the app's AppDelegate +@property(nonatomic, strong, nullable) + id currentAuthorizationFlow; +``` + +And your main class, a property to store the auth state: + +```objc +// property of the containing class +@property(nonatomic, strong, nullable) OIDAuthState *authState; +``` + +Then, initiate the authorization request. By using the +`authStateByPresentingAuthorizationRequest` convenience method, the token +exchange will be performed automatically, and everything will be protected with +PKCE (if the server supports it). AppAuth also allows you to perform these +requests manually. See the `authNoCodeExchange` method in the included Example +app for a demonstration. + +```objc +// builds authentication request +OIDAuthorizationRequest *request = + [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + scopes:@[OIDScopeOpenID, + OIDScopeProfile] + redirectURL:KRedirectURI + responseType:OIDResponseTypeCode + additionalParameters:nil]; + +// performs authentication request +AppDelegate *appDelegate = + (AppDelegate *)[UIApplication sharedApplication].delegate; +appDelegate.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + presentingViewController:self + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + if (authState) { + NSLog(@"Got authorization tokens. Access token: %@", + authState.lastTokenResponse.accessToken); + [self setAuthState:authState]; + } else { + NSLog(@"Authorization error: %@", [error localizedDescription]); + [self setAuthState:nil]; + } +}]; +``` + +*Handling the Redirect* + +The authorization response URL is returned to the app via the iOS openURL +app delegate method, so you need to pipe this through to the current +authorization session (created in the previous session). + +```objc +- (BOOL)application:(UIApplication *)app + openURL:(NSURL *)url + options:(NSDictionary *)options { + // Sends the URL to the current authorization flow (if any) which will + // process it if it relates to an authorization response. + if ([_currentAuthorizationFlow resumeAuthorizationFlowWithURL:url]) { + _currentAuthorizationFlow = nil; + return YES; + } + + // Your additional URL handling (if any) goes here. + + return NO; +} +``` + +### Authorizing – MacOS + +On macOS, the most popular way to get the authorization response redirect is to +start a local HTTP server on the loopback interface (limited to incoming +requests from the user's machine only). When the authorization is complete, the +user is redirected to that local server, and the authorization response can be +processed by the app. AppAuth takes care of managing the local HTTP server +lifecycle for you. + +> #### :bulb: Alternative: Custom URI Schemes +> Custom URI schemes are also supported on macOS, but some browsers display +> an interstitial which reduces the usability. For an example on using custom +> URI schemes with macOS, See `Example-Mac`. + +To receive the authorization response using a local HTTP server, first you need +to have an instance variable in your main class to retain the HTTP redirect +handler. + +```objc +OIDRedirectHTTPHandler *_redirectHTTPHandler; +``` + +Then, as the port used by the local HTTP server varies, you need to start it +before building the authorization request in order to get the exact redirect +URI to use. + +```objc +static NSString *const kSuccessURLString = + @"http://openid.github.io/AppAuth-iOS/redirect/"; +NSURL *successURL = [NSURL URLWithString:kSuccessURLString]; + +// Starts a loopback HTTP redirect listener to receive the code. This needs to be started first, +// as the exact redirect URI (including port) must be passed in the authorization request. +_redirectHTTPHandler = [[OIDRedirectHTTPHandler alloc] initWithSuccessURL:successURL]; +NSURL *redirectURI = [_redirectHTTPHandler startHTTPListener:nil]; +``` + +Then, initiate the authorization request. By using the +`authStateByPresentingAuthorizationRequest` convenience method, the token +exchange will be performed automatically, and everything will be protected with +PKCE (if the server supports it). By assigning the return value to the +`OIDRedirectHTTPHandler`'s `currentAuthorizationFlow`, the authorization will +continue automatically once the user makes their choice. + +```objc +// builds authentication request +OIDAuthorizationRequest *request = + [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + clientSecret:kClientSecret + scopes:@[ OIDScopeOpenID ] + redirectURL:redirectURI + responseType:OIDResponseTypeCode + additionalParameters:nil]; +// performs authentication request +__weak __typeof(self) weakSelf = self; +_redirectHTTPHandler.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + // Brings this app to the foreground. + [[NSRunningApplication currentApplication] + activateWithOptions:(NSApplicationActivateAllWindows | + NSApplicationActivateIgnoringOtherApps)]; + + // Processes the authorization response. + if (authState) { + NSLog(@"Got authorization tokens. Access token: %@", + authState.lastTokenResponse.accessToken); + } else { + NSLog(@"Authorization error: %@", error.localizedDescription); + } + [weakSelf setAuthState:authState]; +}]; +``` + +### Making API Calls + +AppAuth gives you the raw token information, if you need it. However we +recommend that users of the `OIDAuthState` convenience wrapper use the provided +`performActionWithFreshTokens:` method to perform their API calls to avoid +needing to worry about token freshness. + +```objc +[_authState performActionWithFreshTokens:^(NSString *_Nonnull accessToken, + NSString *_Nonnull idToken, + NSError *_Nullable error) { + if (error) { + NSLog(@"Error fetching fresh tokens: %@", [error localizedDescription]); + return; + } + + // perform your API request using the tokens +}]; +``` + +## API Documentation + +Browse the [API documentation] +(http://openid.github.io/AppAuth-iOS/docs/latest/annotated.html). + +## Included Samples + +You can try out the iOS sample included in the source distribution by opening +`Example/Example.xcworkspace`. You can easily convert the Example +workspace to a Pod workspace by deleting the `AppAuth` project, and +[configuring the pod](#setup). You can also +[try out the sample via CocoaPods](#try). Be sure to follow the instructions in +[Example/README.md](Example/README.md) to configure your own OAuth client ID +for use with the example. + +You can try out the macOS sample included in the source distribution by +executing `pod install` in the `Example-Mac` folder, then opening +`Example-Mac.xcworkspace`. Be sure to follow the instructions in +[Example-Mac/README.md](Example-Mac/README.md) to configure your own OAuth +client ID for use with the example. diff --git a/Paco-iOS/Pods/AppAuth/Source/AppAuth.h b/Paco-iOS/Pods/AppAuth/Source/AppAuth.h new file mode 100644 index 000000000..d3e9e39a7 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/AppAuth.h @@ -0,0 +1,81 @@ +/*! @file AppAuth.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthState.h" +#import "OIDAuthStateChangeDelegate.h" +#import "OIDAuthStateErrorDelegate.h" +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationService.h" +#import "OIDAuthorizationUICoordinator.h" +#import "OIDError.h" +#import "OIDErrorUtilities.h" +#import "OIDGrantTypes.h" +#import "OIDResponseTypes.h" +#import "OIDScopes.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDTokenUtilities.h" + +#if TARGET_OS_TV +#elif TARGET_OS_WATCH +#elif TARGET_OS_IOS +#import "OIDAuthState+IOS.h" +#import "OIDAuthorizationService+IOS.h" +#import "OIDAuthorizationUICoordinatorIOS.h" +#elif TARGET_OS_MAC +#import "OIDAuthState+Mac.h" +#import "OIDAuthorizationService+Mac.h" +#import "OIDAuthorizationUICoordinatorMac.h" +#import "OIDRedirectHTTPHandler.h" +#else +#error "Platform Undefined" +#endif + + +/*! @mainpage AppAuth for iOS and macOS + + @section introduction Introduction + + AppAuth for iOS and macOS is a client SDK for communicating with [OAuth 2.0] + (https://tools.ietf.org/html/rfc6749) and [OpenID Connect] + (http://openid.net/specs/openid-connect-core-1_0.html) providers. It strives to + directly map the requests and responses of those specifications, while following + the idiomatic style of the implementation language. In addition to mapping the + raw protocol flows, convenience methods are available to assist with common + tasks like performing an action with fresh tokens. + + It follows the best practices set out in [OAuth 2.0 for Native Apps] + (https://tools.ietf.org/html/draft-ietf-oauth-native-apps) + including using `SFSafariViewController` for the auth request. For this reason, + `UIWebView` is explicitly *not* supported due to usability and security reasons. + + It also supports the [PKCE](https://tools.ietf.org/html/rfc7636) extension to + OAuth which was created to secure authorization codes in public clients when + custom URI scheme redirects are used. The library is friendly to other + extensions (standard or otherwise) with the ability to handle additional params + in all protocol requests and responses. + + Homepage: http://openid.github.io/AppAuth-iOS/
+ API Documentation: http://openid.github.io/AppAuth-iOS/docs/latest
+ Git Repository: https://github.com/openid/AppAuth-iOS
+ + */ diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthState.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthState.h new file mode 100644 index 000000000..9ba5836d6 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthState.h @@ -0,0 +1,238 @@ +/*! @file OIDAuthState.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ +#import + +@class OIDAuthorizationRequest; +@class OIDAuthorizationResponse; +@class OIDAuthState; +@class OIDTokenResponse; +@class OIDTokenRequest; +@protocol OIDAuthorizationFlowSession; +@protocol OIDAuthorizationUICoordinator; +@protocol OIDAuthStateChangeDelegate; +@protocol OIDAuthStateErrorDelegate; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a block used to call an action with a fresh access token. + @param accessToken A valid access token if available. + @param idToken A valid ID token if available. + @param error The error if an error occurred. + */ +typedef void (^OIDAuthStateAction)(NSString *_Nullable accessToken, + NSString *_Nullable idToken, + NSError *_Nullable error); + +/*! @brief The method called when the @c + OIDAuthState.authStateByPresentingAuthorizationRequest:presentingViewController:callback: + method has completed or failed. + @param authState The auth state, if the authorization request succeeded. + @param error The error if an error occurred. + */ +typedef void (^OIDAuthStateAuthorizationCallback)(OIDAuthState *_Nullable authState, + NSError *_Nullable error); + +/*! @brief A convenience class that retains the auth state between @c OIDAuthorizationResponse%s + and @c OIDTokenResponse%s. + */ +@interface OIDAuthState : NSObject + +/*! @brief The most recent refresh token received from the server. + @discussion Rather than using this property directly, you should call + @c OIDAuthState.performActionWithFreshTokens:. + @remarks refresh_token + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/*! @brief The scope of the current authorization grant. + @discussion This represents the latest scope returned by the server and may be a subset of the + scope that was initially granted. + @remarks scope + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief The most recent authorization response used to update the authorization state. For the + implicit flow, this will contain the latest access token. + */ +@property(nonatomic, readonly) OIDAuthorizationResponse *lastAuthorizationResponse; + +/*! @brief The most recent token response used to update this authorization state. This will + contain the latest access token. + */ +@property(nonatomic, readonly, nullable) OIDTokenResponse *lastTokenResponse; + +/*! @brief The authorization error that invalidated this @c OIDAuthState. + @discussion The authorization error encountered by @c OIDAuthState or set by the user via + @c OIDAuthState.updateWithAuthorizationError: that invalidated this @c OIDAuthState. + Authorization errors from @c OIDAuthState will always have a domain of + @c ::OIDOAuthAuthorizationErrorDomain or @c ::OIDOAuthTokenErrorDomain. Note: that after + unarchiving the @c OIDAuthState object, the \NSError_userInfo property of this error will + be nil. + */ +@property(nonatomic, readonly, nullable) NSError *authorizationError; + +/*! @brief Returns YES if the authorization state is not known to be invalid. + @discussion Returns YES if no OAuth errors have been received, and the last call resulted in a + successful access token or id token. This does not mean that the access is fresh - just + that it was valid the last time it was used. Note that network and other transient errors + do not invalidate the authorized state. If NO, you should authenticate the user again, + using a fresh authorization request. Invalid @c OIDAuthState objects may still be useful in + that case, to hint at the previously authorized user and streamline the re-authentication + experience. + */ +@property(nonatomic, readonly) BOOL isAuthorized; + +/*! @brief The @c OIDAuthStateChangeDelegate delegate. + @discussion Use the delegate to observe state changes (and update storage) as well as error + states. + */ +@property(nonatomic, weak, nullable) id stateChangeDelegate; + +/*! @brief The @c OIDAuthStateErrorDelegate delegate. + @discussion Use the delegate to observe state changes (and update storage) as well as error + states. + */ +@property(nonatomic, weak, nullable) id errorDelegate; + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + and performing the authorization code exchange in the case of code flow requests. + @param authorizationRequest The authorization request to present. + @param UICoordinator Generic authorization UI coordinator that can present an authorization + request. + @param callback The method called when the request has completed or failed. + @return A @c OIDAuthorizationFlowSession instance which will terminate when it + receives a @c OIDAuthorizationFlowSession.cancel message, or after processing a + @c OIDAuthorizationFlowSession.resumeAuthorizationFlowWithURL: message. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + UICoordinator:(id)UICoordinator + callback:(OIDAuthStateAuthorizationCallback)callback; + +/*! @internal + @brief Unavailable. Please use @c initWithAuthorizationResponse:. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief Creates an auth state from an authorization response. + @param response The authorization response. + */ +- (nullable instancetype)initWithAuthorizationResponse: + (OIDAuthorizationResponse *)authorizationResponse; + +/*! @brief Creates an auth state from an authorization response. + @param response The authorization response. + */ +- (nullable instancetype)initWithAuthorizationResponse: + (OIDAuthorizationResponse *)authorizationResponse + tokenResponse:(nullable OIDTokenResponse *)tokenResponse; + +/*! @brief Updates the authorization state based on a new authorization response. + @param authorizationResponse The new authorization response to update the state with. + @param error Any error encountered when performing the authorization request. Errors in the + domain @c ::OIDOAuthAuthorizationErrorDomain are reflected in the auth state, other errors + are assumed to be transient, and ignored. + @discussion Typically called with the response from an incremental authorization request, + or if using the implicit flow. Will clear the @c #lastTokenResponse property. + */ +- (void)updateWithAuthorizationResponse:(nullable OIDAuthorizationResponse *)authorizationResponse + error:(nullable NSError *)error; + +/*! @brief Updates the authorization state based on a new token response. + @param tokenResponse The new token response to update the state from. + @param error Any error encountered when performing the authorization request. Errors in the + domain @c ::OIDOAuthTokenErrorDomain are reflected in the auth state, other errors + are assumed to be transient, and ignored. + @discussion Typically called with the response from an authorization code exchange, or a token + refresh. + */ +- (void)updateWithTokenResponse:(nullable OIDTokenResponse *)tokenResponse + error:(nullable NSError *)error; + +/*! @brief Updates the authorization state based on an authorization error. + @param authorizationError The authorization error. + @discussion Call this method if you receive an authorization error during an API call to + invalidate the authentication state of this @c OIDAuthState. Don't call with errors + unrelated to authorization, such as transient network errors. + The OIDAuthStateErrorDelegate.authState:didEncounterAuthorizationError: method of + @c #errorDelegate will be called with the error. + You may optionally use the convenience method + OIDErrorUtilities.resourceServerAuthorizationErrorWithCode:errorResponse:underlyingError: + to create \NSError objects for use here. + The latest error received is stored in @c #authorizationError. Note: that after unarchiving + this object, the \NSError_userInfo property of this error will be nil. + */ +- (void)updateWithAuthorizationError:(NSError *)authorizationError; + +/*! @brief Calls the block with a valid access token (refreshing it first, if needed), or if a + refresh was needed and failed, with the error that caused it to fail. + @param action The block to execute with a fresh token. This block will be executed on the main + thread. + */ +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action; + +/*! @brief Calls the block with a valid access token (refreshing it first, if needed), or if a + refresh was needed and failed, with the error that caused it to fail. + @param action The block to execute with a fresh token. This block will be executed on the main + thread. + @param additionalRefreshParameters Additional parameters for the token request if token is + refreshed. + */ +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action + additionalRefreshParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Forces a token refresh the next time @c OIDAuthState.performActionWithFreshTokens: is + called, even if the current tokens are considered valid. + */ +- (void)setNeedsTokenRefresh; + +/*! @brief Creates a token request suitable for refreshing an access token. + @return A @c OIDTokenRequest suitable for using a refresh token to obtain a new access token. + @discussion After performing the refresh, call @c OIDAuthState.updateWithTokenResponse:error: + to update the authorization state based on the response. Rather than doing the token refresh + yourself, you should use @c OIDAuthState.performActionWithFreshTokens:. + @see https://tools.ietf.org/html/rfc6749#section-1.5 + */ +- (nullable OIDTokenRequest *)tokenRefreshRequest; + +/*! @brief Creates a token request suitable for refreshing an access token. + @param additionalParameters Additional parameters for the token request. + @return A @c OIDTokenRequest suitable for using a refresh token to obtain a new access token. + @discussion After performing the refresh, call @c OIDAuthState.updateWithTokenResponse:error: + to update the authorization state based on the response. Rather than doing the token refresh + yourself, you should use @c OIDAuthState.performActionWithFreshTokens:. + @see https://tools.ietf.org/html/rfc6749#section-1.5 + */ +- (nullable OIDTokenRequest *)tokenRefreshRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters; + +/*! @brief Deprecated, use @c OIDAuthState.performActionWithFreshTokens:. + @discussion Calls the block with a valid access token (refreshing it first, if needed), or if a + refresh was needed and failed, with the error that caused it to fail. + @param action The block to execute with a fresh token. This block will be executed on the main + thread. + @deprecated Use @c OIDAuthState.performActionWithFreshTokens: which is equivalent. + */ +- (void)withFreshTokensPerformAction:(OIDAuthStateAction)action + __deprecated_msg("Use OIDAuthState.performActionWithFreshTokens:"); + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthState.m b/Paco-iOS/Pods/AppAuth/Source/OIDAuthState.m new file mode 100644 index 000000000..337c94c73 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthState.m @@ -0,0 +1,499 @@ +/*! @file OIDAuthState.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthState.h" + +#import "OIDAuthStateChangeDelegate.h" +#import "OIDAuthStateErrorDelegate.h" +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationService.h" +#import "OIDDefines.h" +#import "OIDError.h" +#import "OIDErrorUtilities.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" + +/*! @brief Key used to encode the @c refreshToken property for @c NSSecureCoding. + */ +static NSString *const kRefreshTokenKey = @"refreshToken"; + +/*! @brief Key used to encode the @c scope property for @c NSSecureCoding. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c lastAuthorizationResponse property for @c NSSecureCoding. + */ +static NSString *const kLastAuthorizationResponseKey = @"lastAuthorizationResponse"; + +/*! @brief Key used to encode the @c lastTokenResponse property for @c NSSecureCoding. + */ +static NSString *const kLastTokenResponseKey = @"lastTokenResponse"; + +/*! @brief Key used to encode the @c lastOAuthError property for @c NSSecureCoding. + */ +static NSString *const kAuthorizationErrorKey = @"authorizationError"; + +/*! @brief The exception thrown when a developer tries to create a refresh request from an + authorization request with no authorization code. + */ +static NSString *const kRefreshTokenRequestException = + @"Attempted to create a token refresh request from a token response with no refresh token."; + +/*! @brief Number of seconds the access token is refreshed before it actually expires. + */ +static const NSUInteger kExpiryTimeTolerance = 60; + +@interface OIDAuthState () + +/*! @brief The access token generated by the authorization server. + @discussion Rather than using this property directly, you should call + @c OIDAuthState.withFreshTokenPerformAction:. + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/*! @brief The approximate expiration date & time of the access token. + @discussion Rather than using this property directly, you should call + @c OIDAuthState.withFreshTokenPerformAction:. + */ +@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate; + +/*! @brief ID Token value associated with the authenticated session. + @discussion Rather than using this property directly, you should call + OIDAuthState.withFreshTokenPerformAction:. + */ +@property(nonatomic, readonly, nullable) NSString *idToken; + +/*! @brief Private method, called when the internal state changes. + */ +- (void)didChangeState; + +@end + + +@implementation OIDAuthState { + /*! @brief Array of pending actions (use @c _pendingActionsSyncObject to synchronize access). + */ + NSMutableArray *_pendingActions; + + /*! @brief Object for synchronizing access to @c pendingActions. + */ + id _pendingActionsSyncObject; + + /*! @brief If YES, tokens will be refreshed on the next API call regardless of expiry. + */ + BOOL _needsTokenRefresh; +} + +#pragma mark - Convenience initializers + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + UICoordinator:(id)UICoordinator + callback:(OIDAuthStateAuthorizationCallback)callback { + // presents the authorization request + id authFlowSession = [OIDAuthorizationService + presentAuthorizationRequest:authorizationRequest + UICoordinator:UICoordinator + callback:^(OIDAuthorizationResponse *_Nullable authorizationResponse, + NSError *_Nullable authorizationError) { + // inspects response and processes further if needed (e.g. authorization + // code exchange) + if (authorizationResponse) { + if ([authorizationRequest.responseType + isEqualToString:OIDResponseTypeCode]) { + // if the request is for the code flow (NB. not hybrid), assumes the + // code is intended for this client, and performs the authorization + // code exchange + OIDTokenRequest *tokenExchangeRequest = + [authorizationResponse tokenExchangeRequest]; + [OIDAuthorizationService + performTokenRequest:tokenExchangeRequest + callback:^(OIDTokenResponse *_Nullable tokenResponse, + NSError *_Nullable tokenError) { + OIDAuthState *authState; + if (tokenResponse) { + authState = [[OIDAuthState alloc] + initWithAuthorizationResponse: + authorizationResponse + tokenResponse:tokenResponse]; + } + callback(authState, tokenError); + }]; + } else { + // implicit or hybrid flow (hybrid flow assumes code is not for this + // client) + OIDAuthState *authState = [[OIDAuthState alloc] + initWithAuthorizationResponse:authorizationResponse]; + callback(authState, authorizationError); + } + } else { + callback(nil, authorizationError); + } + }]; + return authFlowSession; +} + +#pragma mark - Initializers + +- (nullable instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithAuthorizationResponse:tokenResponse:)); + +/*! @brief Creates an auth state from an authorization response. + @param response The authorization response. + */ +- (nullable instancetype)initWithAuthorizationResponse: + (OIDAuthorizationResponse *)authorizationResponse { + return [self initWithAuthorizationResponse:authorizationResponse tokenResponse:nil]; +} + + +/*! @brief Designated initializer. + @param response The authorization response. + @discussion Creates an auth state from an authorization response and token response. + */ +- (nullable instancetype)initWithAuthorizationResponse: + (OIDAuthorizationResponse *)authorizationResponse + tokenResponse:(nullable OIDTokenResponse *)tokenResponse { + self = [super init]; + if (self) { + _pendingActionsSyncObject = [[NSObject alloc] init]; + [self updateWithAuthorizationResponse:authorizationResponse error:nil]; + + if (tokenResponse) { + [self updateWithTokenResponse:tokenResponse error:nil]; + } + } + return self; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, isAuthorized: %@, refreshToken: \"%@\", " + "scope: \"%@\", accessToken: \"%@\", " + "accessTokenExpirationDate: %@, idToken: \"%@\", " + "lastAuthorizationResponse: %@, lastTokenResponse: %@, " + "authorizationError: %@>", + NSStringFromClass([self class]), + self, + (self.isAuthorized) ? @"YES" : @"NO", + _refreshToken, + _scope, + self.accessToken, + self.accessTokenExpirationDate, + self.idToken, + _lastAuthorizationResponse, + _lastTokenResponse, + _authorizationError]; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + _lastAuthorizationResponse = [aDecoder decodeObjectOfClass:[OIDAuthorizationResponse class] + forKey:kLastAuthorizationResponseKey]; + _lastTokenResponse = [aDecoder decodeObjectOfClass:[OIDTokenResponse class] + forKey:kLastTokenResponseKey]; + self = [self initWithAuthorizationResponse:_lastAuthorizationResponse + tokenResponse:_lastTokenResponse]; + if (self) { + _authorizationError = + [aDecoder decodeObjectOfClass:[NSError class] forKey:kAuthorizationErrorKey]; + _scope = [aDecoder decodeObjectOfClass:[NSString class] forKey:kScopeKey]; + _refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_lastAuthorizationResponse forKey:kLastAuthorizationResponseKey]; + [aCoder encodeObject:_lastTokenResponse forKey:kLastTokenResponseKey]; + if (_authorizationError) { + NSError *codingSafeAuthorizationError = [NSError errorWithDomain:_authorizationError.domain + code:_authorizationError.code + userInfo:nil]; + [aCoder encodeObject:codingSafeAuthorizationError forKey:kAuthorizationErrorKey]; + } + [aCoder encodeObject:_scope forKey:kScopeKey]; + [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey]; +} + +#pragma mark - Private convenience getters + +- (NSString *)accessToken { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.accessToken + : _lastAuthorizationResponse.accessToken; +} + +- (NSString *)tokenType { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.tokenType + : _lastAuthorizationResponse.tokenType; +} + +- (NSDate *)accessTokenExpirationDate { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.accessTokenExpirationDate + : _lastAuthorizationResponse.accessTokenExpirationDate; +} + +- (NSString *)idToken { + if (_authorizationError) { + return nil; + } + return _lastTokenResponse ? _lastTokenResponse.idToken + : _lastAuthorizationResponse.idToken; +} + +#pragma mark - Getters + +- (BOOL)isAuthorized { + return !self.authorizationError && (self.accessToken || self.idToken || self.refreshToken); +} + +#pragma mark - Updating the state + +- (void)updateWithAuthorizationResponse:(nullable OIDAuthorizationResponse *)authorizationResponse + error:(nullable NSError *)error { + // If the error is an OAuth authorization error, updates the state. Other errors are ignored. + if (error.domain == OIDOAuthAuthorizationErrorDomain) { + [self updateWithAuthorizationError:error]; + return; + } + if (!authorizationResponse) { + return; + } + + _lastAuthorizationResponse = authorizationResponse; + + // clears the last token response and refresh token as these now relate to an old authorization + // that is no longer relevant + _lastTokenResponse = nil; + _refreshToken = nil; + _authorizationError = nil; + + // if the response's scope is nil, it means that it equals that of the request + // see: https://tools.ietf.org/html/rfc6749#section-5.1 + _scope = (authorizationResponse.scope) ? authorizationResponse.scope + : authorizationResponse.request.scope; + + [self didChangeState]; +} + +- (void)updateWithTokenResponse:(nullable OIDTokenResponse *)tokenResponse + error:(nullable NSError *)error { + if (_authorizationError) { + // Calling updateWithTokenResponse while in an error state probably means the developer obtained + // a new token and did the exchange without also calling updateWithAuthorizationResponse. + // Attempts to handle gracefully, but warns the developer that this is unexpected. + NSLog(@"OIDAuthState:updateWithTokenResponse should not be called in an error state [%@] call" + "updateWithAuthorizationResponse with the result of the fresh authorization response" + "first", + _authorizationError); + + _authorizationError = nil; + } + + // If the error is an OAuth authorization error, updates the state. Other errors are ignored. + if (error.domain == OIDOAuthTokenErrorDomain) { + [self updateWithAuthorizationError:error]; + return; + } + if (!tokenResponse) { + return; + } + + _lastTokenResponse = tokenResponse; + + // updates the scope and refresh token if they are present on the TokenResponse. + // according to the spec, these may be changed by the server, including when refreshing the + // access token. See: https://tools.ietf.org/html/rfc6749#section-5.1 and + // https://tools.ietf.org/html/rfc6749#section-6 + if (tokenResponse.scope) { + _scope = tokenResponse.scope; + } + if (tokenResponse.refreshToken) { + _refreshToken = tokenResponse.refreshToken; + } + + [self didChangeState]; +} + +- (void)updateWithAuthorizationError:(NSError *)oauthError { + _authorizationError = oauthError; + + [self didChangeState]; + + [_errorDelegate authState:self didEncounterAuthorizationError:oauthError]; +} + +#pragma mark - OAuth Requests + +- (OIDTokenRequest *)tokenRefreshRequest { + return [self tokenRefreshRequestWithAdditionalParameters:nil]; +} + +- (OIDTokenRequest *)tokenRefreshRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters { + + // TODO: Add unit test to confirm exception is thrown when expected + + if (!_refreshToken) { + [OIDErrorUtilities raiseException:kRefreshTokenRequestException]; + } + return [[OIDTokenRequest alloc] + initWithConfiguration:_lastAuthorizationResponse.request.configuration + grantType:OIDGrantTypeRefreshToken + authorizationCode:nil + redirectURL:_lastAuthorizationResponse.request.redirectURL + clientID:_lastAuthorizationResponse.request.clientID + clientSecret:_lastAuthorizationResponse.request.clientSecret + scope:_lastAuthorizationResponse.request.scope + refreshToken:_refreshToken + codeVerifier:nil + additionalParameters:additionalParameters]; +} + +#pragma mark - Stateful Actions + +- (void)didChangeState { + [_stateChangeDelegate didChangeState:self]; +} + +- (void)setNeedsTokenRefresh { + _needsTokenRefresh = YES; +} + +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action { + [self performActionWithFreshTokens:action additionalRefreshParameters:nil]; +} + +- (void)performActionWithFreshTokens:(OIDAuthStateAction)action + additionalRefreshParameters: + (nullable NSDictionary *)additionalParameters { + if ([self isTokenFresh]) { + // access token is valid within tolerance levels, perform action + dispatch_async(dispatch_get_main_queue(), ^() { + action(self.accessToken, self.idToken, nil); + }); + return; + } + + if (!_refreshToken) { + // no refresh token available and token has expired + NSError *tokenRefreshError = [ + OIDErrorUtilities errorWithCode:OIDErrorCodeTokenRefreshError + underlyingError:nil + description:@"Unable to refresh expired token without a refresh token."]; + dispatch_async(dispatch_get_main_queue(), ^() { + action(nil, nil, tokenRefreshError); + }); + return; + } + + // access token is expired, first refresh the token, then perform action + NSAssert(_pendingActionsSyncObject, @"_pendingActionsSyncObject cannot be nil"); + @synchronized(_pendingActionsSyncObject) { + // if a token is already in the process of being refreshed, adds to pending actions + if (_pendingActions) { + [_pendingActions addObject:action]; + return; + } + + // creates a list of pending actions, starting with this one + _pendingActions = [NSMutableArray arrayWithObject:action]; + } + + // refresh the tokens + OIDTokenRequest *tokenRefreshRequest = + [self tokenRefreshRequestWithAdditionalParameters:additionalParameters]; + [OIDAuthorizationService performTokenRequest:tokenRefreshRequest + callback:^(OIDTokenResponse *_Nullable response, + NSError *_Nullable error) { + dispatch_async(dispatch_get_main_queue(), ^() { + // update OIDAuthState based on response + if (response) { + _needsTokenRefresh = NO; + [self updateWithTokenResponse:response error:nil]; + } else { + if (error.domain == OIDOAuthTokenErrorDomain) { + _needsTokenRefresh = NO; + [self updateWithAuthorizationError:error]; + } else { + if ([_errorDelegate respondsToSelector: + @selector(authState:didEncounterTransientError:)]) { + [_errorDelegate authState:self didEncounterTransientError:error]; + } + } + } + + // nil the pending queue and process everything that was queued up + NSArray *actionsToProcess; + @synchronized(_pendingActionsSyncObject) { + actionsToProcess = _pendingActions; + _pendingActions = nil; + } + for (OIDAuthStateAction actionToProcess in actionsToProcess) { + actionToProcess(self.accessToken, self.idToken, error); + } + }); + }]; +} + +#pragma mark - Deprecated + +- (void)withFreshTokensPerformAction:(OIDAuthStateAction)action { + [self performActionWithFreshTokens:action additionalRefreshParameters:nil]; +} + +#pragma mark - + +/*! @fn isTokenFresh + @brief Determines whether a token refresh request must be made to refresh the tokens. + */ +- (BOOL)isTokenFresh { + if (_needsTokenRefresh) { + // forced refresh + return NO; + } + + if (!self.accessTokenExpirationDate) { + // if there is no expiration time but we have an access token, it is assumed to never expire + return !!self.accessToken; + } + + // has the token expired? + BOOL tokenFresh = [self.accessTokenExpirationDate timeIntervalSinceNow] > kExpiryTimeTolerance; + return tokenFresh; +} + +@end + + diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthStateChangeDelegate.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthStateChangeDelegate.h new file mode 100644 index 000000000..2570df131 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthStateChangeDelegate.h @@ -0,0 +1,39 @@ +/*! @file OIDAuthStateChangeDelegate.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthState; + +NS_ASSUME_NONNULL_BEGIN + +/*! @protocol OIDAuthStateChangeDelegate + @brief Delegate of the OIDAuthState used to monitor various changes in state. + */ +@protocol OIDAuthStateChangeDelegate + +/*! @brief Called when the authorization state changes and any backing storage needs to be updated. + @param state The @c OIDAuthState that changed. + @discussion If you are storing the authorization state, you should update the storage when the + state changes. + */ +- (void)didChangeState:(OIDAuthState *)state; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthStateErrorDelegate.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthStateErrorDelegate.h new file mode 100644 index 000000000..91a9b1cd0 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthStateErrorDelegate.h @@ -0,0 +1,62 @@ +/*! @file OIDAuthStateErrorDelegate.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthState; + +NS_ASSUME_NONNULL_BEGIN + +/*! @protocol OIDAuthStateErrorDelegate + @brief Delegate of the OIDAuthState used to monitor errors. + */ +@protocol OIDAuthStateErrorDelegate + +/*! @brief Called when an authentication occurs, which indicates the auth session is invalid. + @param state The @c OIDAuthState on which the error occurred. + @param error The authorization error. + @discussion This is a hard error (not a transient network issue) that indicates a problem with + the authorization. You should stop using the @c OIDAuthState when such an error is + encountered. If the \NSError_code is @c ::OIDErrorCodeOAuthInvalidGrant then + the session may be recoverable with user interaction (i.e. re-authentication). In all cases + you should consider the user unauthorized, and remove locally cached resources that require + that authorization. @c OIDAuthState will call this method automatically if it encounters + an OAuth error (that is, an HTTP 400 response with a valid OAuth error response) during + authorization or token refresh (such as performed automatically when using + @c OIDAuthState.performActionWithFreshTokens:). You can signal authorization errors with + @c OIDAuthState.updateWithAuthorizationError:. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +- (void)authState:(OIDAuthState *)state didEncounterAuthorizationError:(NSError *)error; + +@optional + +/*! @brief Called when a network or other transient error occurs. + @param state The @c OIDAuthState on which the error occurred. + @param error The transient error. + @discussion This is a soft error, typically network related. The @c OIDAuthState is likely + still valid, and should not be discarded. Retry the request using an incremental backoff + strategy. This is only called when using the @c OIDAuthState convenience methods such as + @c OIDAuthState.performActionWithFreshTokens:. If you are refreshing the tokens yourself + outside of @c OIDAuthState class, it will never be called. + */ +- (void)authState:(OIDAuthState *)state didEncounterTransientError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationRequest.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationRequest.h new file mode 100644 index 000000000..3e283672a --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationRequest.h @@ -0,0 +1,233 @@ +/*! @file OIDAuthorizationRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +// These files only declare string constants useful for constructing a @c OIDAuthorizationRequest, +// so they are imported here for convenience. +#import "OIDResponseTypes.h" +#import "OIDScopes.h" + +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The @c code_challenge_method value for the S256 code challenge. + @see https://tools.ietf.org/html/rfc7636#section-4.3 + */ +extern NSString *const OIDOAuthorizationRequestCodeChallengeMethodS256; + + +/*! @brief Represents an authorization request. + @see https://tools.ietf.org/html/rfc6749#section-4 + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + */ +@interface OIDAuthorizationRequest : NSObject + +/*! @brief The service's configuration. + @remarks This configuration specifies how to connect to a particular OAuth provider. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @brief The expected response type. + @remarks response_type + @discussion Generally 'code' if pure OAuth, otherwise a space-delimited list of of response + types including 'code', 'token', and 'id_token' for OpenID Connect. + @see https://tools.ietf.org/html/rfc6749#section-3.1.1 + @see http://openid.net/specs/openid-connect-core-1_0.html#rfc.section.3 + */ +@property(nonatomic, readonly) NSString *responseType; + +/*! @brief The client identifier. + @remarks client_id + @see https://tools.ietf.org/html/rfc6749#section-2.2 + */ +@property(nonatomic, readonly) NSString *clientID; + +/*! @brief The client secret. + @remarks client_secret + @discussion The client secret is used to prove that identity of the client when exchaning an + authorization code for an access token. + The client secret is not passed in the authorizationRequestURL. It is only used when + exchanging the authorization code for an access token. + @see https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +@property(nonatomic, readonly, nullable) NSString *clientSecret; + +/*! @brief The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief The client's redirect URI. + @remarks redirect_uri + @see https://tools.ietf.org/html/rfc6749#section-3.1.2 + */ +@property(nonatomic, readonly, nullable) NSURL *redirectURL; + +/*! @brief An opaque value used by the client to maintain state between the request and callback. + @remarks state + @discussion If this value is not explicitly set, this library will automatically add state and + perform appropriate validation of the state in the authorization response. It is recommended + that the default implementation of this parameter be used wherever possible. Typically used + to prevent CSRF attacks, as recommended in RFC6819 Section 5.3.5. + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + @see https://tools.ietf.org/html/rfc6819#section-5.3.5 + */ +@property(nonatomic, readonly, nullable) NSString *state; + +/*! @brief The PKCE code verifier. + @remarks code_verifier + @discussion The code verifier itself is not included in the authorization request that is sent + on the wire, but needs to be in the token exchange request. + @c OIDAuthorizationResponse.tokenExchangeRequest will create a @c OIDTokenRequest that + includes this parameter automatically. + @see https://tools.ietf.org/html/rfc7636#section-4.1 + */ +@property(nonatomic, readonly, nullable) NSString *codeVerifier; + +/*! @brief The PKCE code challenge, derived from #codeVerifier. + @remarks code_challenge + @see https://tools.ietf.org/html/rfc7636#section-4.2 + */ +@property(nonatomic, readonly, nullable) NSString *codeChallenge; + +/*! @brief The method used to compute the @c #codeChallenge + @remarks code_challenge_method + @see https://tools.ietf.org/html/rfc7636#section-4.3 + */ +@property(nonatomic, readonly, nullable) NSString *codeChallengeMethod; + +/*! @brief The client's additional authorization parameters. + @see https://tools.ietf.org/html/rfc6749#section-3.1 + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalParameters; + +/*! @internal + @brief Unavailable. Please use + @c initWithConfiguration:clientId:scopes:redirectURL:additionalParameters:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Creates an authorization request with opinionated defaults (a secure @c state, and + PKCE with S256 as the @c code_challenge_method). + @param configuration The service's configuration. + @param clientID The client identifier. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param additionalParameters The client's additional authorization parameters. + @remarks This convenience initializer generates a state parameter and PKCE challenges + automatically. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Creates an authorization request with opinionated defaults (a secure @c state, and + PKCE with S256 as the @c code_challenge_method). + @param configuration The service's configuration. + @param clientID The client identifier. + @param clientSecret The client secret. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param additionalParameters The client's additional authorization parameters. + @remarks This convenience initializer generates a state parameter and PKCE challenges + automatically. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param clientID The client identifier. + @param scope A scope string per the OAuth2 spec (a space-delimited set of scopes). + @param redirectURL The client's redirect URI. + @param responseType The expected response type. + @param state An opaque value used by the client to maintain state between the request and + callback. + @param codeVerifier The PKCE code verifier. See @c OIDAuthorizationRequest.generateCodeVerifier. + @param codeChallenge The PKCE code challenge, calculated from the code verifier such as with + @c OIDAuthorizationRequest.codeChallengeS256ForVerifier:. + @param codeChallengeMethod The PKCE code challenge method. + ::OIDOAuthorizationRequestCodeChallengeMethodS256 when + @c OIDAuthorizationRequest.codeChallengeS256ForVerifier: is used to create the code + challenge. + @param additionalParameters The client's additional authorization parameters. + */ +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + redirectURL:(nullable NSURL *)redirectURL + responseType:(NSString *)responseType + state:(nullable NSString *)state + codeVerifier:(nullable NSString *)codeVerifier + codeChallenge:(nullable NSString *)codeChallenge + codeChallengeMethod:(nullable NSString *)codeChallengeMethod + additionalParameters:(nullable NSDictionary *)additionalParameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Constructs the request URI by adding the request parameters to the query component of the + authorization endpoint URI using the "application/x-www-form-urlencoded" format. + @return A URL representing the authorization request. + @see https://tools.ietf.org/html/rfc6749#section-4.1.1 + */ +- (NSURL *)authorizationRequestURL; + +/*! @brief Generates an OAuth state param using a random source. + @return The generated state. + @see https://tools.ietf.org/html/rfc6819#section-5.3.5 + */ ++ (nullable NSString *)generateState; + +/*! @brief Constructs a PKCE-compliant code verifier. + @return The generated code verifier. + @see https://tools.ietf.org/html/rfc7636#section-4.1 + */ ++ (nullable NSString *)generateCodeVerifier; + +/*! @brief Creates a PKCE S256 codeChallenge from the codeVerifier. + @param codeVerifier The code verifier from which the code challenge will be derived. + @return The generated code challenge. + @details Generate a secure code verifier to pass into this method with + @c OIDAuthorizationRequest.generateCodeVerifier. The matching @c #codeChallengeMethod for + @c #codeChallenge%s created by this method is + ::OIDOAuthorizationRequestCodeChallengeMethodS256. + @see https://tools.ietf.org/html/rfc7636#section-4.1 + */ ++ (nullable NSString *)codeChallengeS256ForVerifier:(nullable NSString *)codeVerifier; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationRequest.m b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationRequest.m new file mode 100644 index 000000000..e3deb1e71 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationRequest.m @@ -0,0 +1,300 @@ +/*! @file OIDAuthorizationRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationRequest.h" + +#import "OIDDefines.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDTokenUtilities.h" +#import "OIDURLQueryComponent.h" + +/*! @brief The key for the @c configuration property for @c NSSecureCoding + */ +static NSString *const kConfigurationKey = @"configuration"; + +/*! @brief Key used to encode the @c responseType property for @c NSSecureCoding, and on the URL + request. + */ +static NSString *const kResponseTypeKey = @"response_type"; + +/*! @brief Key used to encode the @c clientID property for @c NSSecureCoding, and on the URL + request. + */ +static NSString *const kClientIDKey = @"client_id"; + +/*! @brief Key used to encode the @c clientSecret property for @c NSSecureCoding. + */ +static NSString *const kClientSecretKey = @"client_secret"; + +/*! @brief Key used to encode the @c scope property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c redirectURL property for @c NSSecureCoding, and on the URL + request. + */ +static NSString *const kRedirectURLKey = @"redirect_uri"; + +/*! @brief Key used to encode the @c state property for @c NSSecureCoding, and on the URL request. + */ +static NSString *const kStateKey = @"state"; + +/*! @brief Key used to encode the @c codeVerifier property for @c NSSecureCoding. + */ +static NSString *const kCodeVerifierKey = @"code_verifier"; + +/*! @brief Key used to send the @c codeChallenge on the URL request. + */ +static NSString *const kCodeChallengeKey = @"code_challenge"; + +/*! @brief Key used to send the @c codeChallengeMethod on the URL request. + */ +static NSString *const kCodeChallengeMethodKey = @"code_challenge_method"; + +/*! @brief Key used to encode the @c additionalParameters property for + @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Number of random bytes generated for the @ state. + */ +static NSUInteger const kStateSizeBytes = 32; + +/*! @brief Number of random bytes generated for the @ codeVerifier. + */ +static NSUInteger const kCodeVerifierBytes = 32; + +NSString *const OIDOAuthorizationRequestCodeChallengeMethodS256 = @"S256"; + +@implementation OIDAuthorizationRequest + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER( + @selector(initWithConfiguration: + clientId: + scopes: + redirectURL: + responseType: + additionalParameters:) + ); + +- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + state:(nullable NSString *)state + codeVerifier:(nullable NSString *)codeVerifier + codeChallenge:(nullable NSString *)codeChallenge + codeChallengeMethod:(nullable NSString *)codeChallengeMethod + additionalParameters:(nullable NSDictionary *)additionalParameters +{ + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _clientID = [clientID copy]; + _clientSecret = [clientSecret copy]; + _scope = [scope copy]; + _redirectURL = [redirectURL copy]; + _responseType = [responseType copy]; + _state = [state copy]; + _codeVerifier = [codeVerifier copy]; + _codeChallenge = [codeChallenge copy]; + _codeChallengeMethod = [codeChallengeMethod copy]; + + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + } + return self; +} + +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + clientSecret:(NSString *)clientSecret + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters { + + // generates PKCE code verifier and challenge + NSString *codeVerifier = [[self class] generateCodeVerifier]; + NSString *codeChallenge = [[self class] codeChallengeS256ForVerifier:codeVerifier]; + + return [self initWithConfiguration:configuration + clientId:clientID + clientSecret:clientSecret + scope:[OIDScopeUtilities scopesWithArray:scopes] + redirectURL:redirectURL + responseType:responseType + state:[[self class] generateState] + codeVerifier:codeVerifier + codeChallenge:codeChallenge + codeChallengeMethod:OIDOAuthorizationRequestCodeChallengeMethodS256 + additionalParameters:additionalParameters]; +} + +- (instancetype) + initWithConfiguration:(OIDServiceConfiguration *)configuration + clientId:(NSString *)clientID + scopes:(nullable NSArray *)scopes + redirectURL:(NSURL *)redirectURL + responseType:(NSString *)responseType + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + clientId:clientID + clientSecret:nil + scopes:scopes + redirectURL:redirectURL + responseType:responseType + additionalParameters:additionalParameters]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDServiceConfiguration *configuration = + [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] + forKey:kConfigurationKey]; + NSString *responseType = [aDecoder decodeObjectOfClass:[NSString class] forKey:kResponseTypeKey]; + NSString *clientID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientIDKey]; + NSString *clientSecret = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientSecretKey]; + NSString *scope = [aDecoder decodeObjectOfClass:[NSString class] forKey:kScopeKey]; + NSURL *redirectURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kRedirectURLKey]; + NSString *state = [aDecoder decodeObjectOfClass:[NSString class] forKey:kStateKey]; + NSString *codeVerifier = [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeVerifierKey]; + NSString *codeChallenge = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeChallengeKey]; + NSString *codeChallengeMethod = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeChallengeMethodKey]; + NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class] + ]]; + NSDictionary *additionalParameters = + [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses + forKey:kAdditionalParametersKey]; + + self = [self initWithConfiguration:configuration + clientId:clientID + clientSecret:clientSecret + scope:scope + redirectURL:redirectURL + responseType:responseType + state:state + codeVerifier:codeVerifier + codeChallenge:codeChallenge + codeChallengeMethod:codeChallengeMethod + additionalParameters:additionalParameters]; + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_configuration forKey:kConfigurationKey]; + [aCoder encodeObject:_responseType forKey:kResponseTypeKey]; + [aCoder encodeObject:_clientID forKey:kClientIDKey]; + [aCoder encodeObject:_clientSecret forKey:kClientSecretKey]; + [aCoder encodeObject:_scope forKey:kScopeKey]; + [aCoder encodeObject:_redirectURL forKey:kRedirectURLKey]; + [aCoder encodeObject:_state forKey:kStateKey]; + [aCoder encodeObject:_codeVerifier forKey:kCodeVerifierKey]; + [aCoder encodeObject:_codeChallenge forKey:kCodeChallengeKey]; + [aCoder encodeObject:_codeChallengeMethod forKey:kCodeChallengeMethodKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, request: %@>", + NSStringFromClass([self class]), + self, + self.authorizationRequestURL]; +} + +#pragma mark - State and PKCE verifier/challenge generation Methods + ++ (nullable NSString *)generateCodeVerifier { + return [OIDTokenUtilities randomURLSafeStringWithSize:kCodeVerifierBytes]; +} + ++ (nullable NSString *)generateState { + return [OIDTokenUtilities randomURLSafeStringWithSize:kStateSizeBytes]; +} + ++ (nullable NSString *)codeChallengeS256ForVerifier:(NSString *)codeVerifier { + if (!codeVerifier) { + return nil; + } + // generates the code_challenge per spec https://tools.ietf.org/html/rfc7636#section-4.2 + // code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier))) + // NB. the ASCII conversion on the code_verifier entropy was done at time of generation. + NSData *sha256Verifier = [OIDTokenUtilities sha265:codeVerifier]; + return [OIDTokenUtilities encodeBase64urlNoPadding:sha256Verifier]; +} + +#pragma mark - + +- (NSURL *)authorizationRequestURL { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + // Required parameters. + [query addParameter:kResponseTypeKey value:_responseType]; + [query addParameter:kClientIDKey value:_clientID]; + + // Add any additional parameters the client has specified. + [query addParameters:_additionalParameters]; + + // Add optional parameters, as applicable. + if (_redirectURL) { + [query addParameter:kRedirectURLKey value:_redirectURL.absoluteString]; + } + if (_scope) { + [query addParameter:kScopeKey value:_scope]; + } + if (_state) { + [query addParameter:kStateKey value:_state]; + } + if (_codeChallenge) { + [query addParameter:kCodeChallengeKey value:_codeChallenge]; + } + if (_codeChallengeMethod) { + [query addParameter:kCodeChallengeMethodKey value:_codeChallengeMethod]; + } + + // Construct the URL: + return [query URLByReplacingQueryInURL:_configuration.authorizationEndpoint]; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationResponse.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationResponse.h new file mode 100644 index 000000000..79d59baa4 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationResponse.h @@ -0,0 +1,128 @@ +/*! @file OIDAuthorizationResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorizationRequest; +@class OIDTokenRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the response to an authorization request. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2 + @see https://tools.ietf.org/html/rfc6749#section-5.1 + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@interface OIDAuthorizationResponse : NSObject + +/*! @brief The request which was serviced. + */ +@property(nonatomic, readonly) OIDAuthorizationRequest *request; + +/*! @brief The authorization code generated by the authorization server. + @discussion Set when the response_type requested includes 'code'. + @remarks code + */ +@property(nonatomic, readonly, nullable) NSString *authorizationCode; + +/*! @brief REQUIRED if the "state" parameter was present in the client authorization request. The + exact value received from the client. + @remarks state + */ +@property(nonatomic, readonly, nullable) NSString *state; + +/*! @brief The access token generated by the authorization server. + @discussion Set when the response_type requested includes 'token'. + @remarks access_token + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/*! @brief The approximate expiration date & time of the access token. + @discussion Set when the response_type requested includes 'token'. + @remarks expires_in + @seealso OIDAuthorizationResponse.accessToken + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate; + +/*! @brief Typically "Bearer" when present. Otherwise, another token_type value that the Client has + negotiated with the Authorization Server. + @discussion Set when the response_type requested includes 'token'. + @remarks token_type + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *tokenType; + +/*! @brief ID Token value associated with the authenticated session. + @discussion Set when the response_type requested includes 'id_token'. + @remarks id_token + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *idToken; + +/*! @brief The scope of the access token. OPTIONAL, if identical to the scopes requested, otherwise, + REQUIRED. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief Additional parameters returned from the authorization server. + */ +@property(nonatomic, readonly, nullable) + NSDictionary *> *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithParameters:. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the Authorization Server. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (nullable instancetype)initWithRequest:(OIDAuthorizationRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Creates a token request suitable for exchanging an authorization code for an access + token. + @return A @c OIDTokenRequest suitable for exchanging an authorization code for an access + token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (nullable OIDTokenRequest *)tokenExchangeRequest; + +/*! @brief Creates a token request suitable for exchanging an authorization code for an access + token. + @param additionalParameters Additional parameters for the token request. + @return A @c OIDTokenRequest suitable for exchanging an authorization code for an access + token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (nullable OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters: + (nullable NSDictionary *)additionalParameters; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationResponse.m b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationResponse.m new file mode 100644 index 000000000..0738412dd --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationResponse.m @@ -0,0 +1,209 @@ +/*! @file OIDAuthorizationResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationResponse.h" + +#import "OIDAuthorizationRequest.h" +#import "OIDDefines.h" +#import "OIDError.h" +#import "OIDFieldMapping.h" +#import "OIDTokenRequest.h" + +/*! @brief The key for the @c authorizationCode property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kAuthorizationCodeKey = @"code"; + +/*! @brief The key for the @c state property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kStateKey = @"state"; + +/*! @brief The key for the @c accessToken property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kAccessTokenKey = @"access_token"; + +/*! @brief The key for the @c accessTokenExpirationDate property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kExpiresInKey = @"expires_in"; + +/*! @brief The key for the @c tokenType property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kTokenTypeKey = @"token_type"; + +/*! @brief The key for the @c idToken property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kIDTokenKey = @"id_token"; + +/*! @brief The key for the @c scope property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +/*! @brief The exception thrown when a developer tries to create a token exchange request from an + authorization request with no authorization code. + */ +static NSString *const kTokenExchangeRequestException = + @"Attempted to create a token exchange request from an authorization response with no " + "authorization code."; + +@implementation OIDAuthorizationResponse + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[kStateKey] = + [[OIDFieldMapping alloc] initWithName:@"_state" type:[NSString class]]; + fieldMap[kAuthorizationCodeKey] = + [[OIDFieldMapping alloc] initWithName:@"_authorizationCode" type:[NSString class]]; + fieldMap[kAccessTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessToken" type:[NSString class]]; + fieldMap[kExpiresInKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessTokenExpirationDate" + type:[NSDate class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]]; + }]; + fieldMap[kTokenTypeKey] = + [[OIDFieldMapping alloc] initWithName:@"_tokenType" type:[NSString class]]; + fieldMap[kIDTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_idToken" type:[NSString class]]; + fieldMap[kScopeKey] = + [[OIDFieldMapping alloc] initWithName:@"_scope" type:[NSString class]]; + }); + return fieldMap; +} + +#pragma mark - Initializers + +- (nullable instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:)); + +- (nullable instancetype)initWithRequest:(OIDAuthorizationRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super init]; + if (self) { + _request = [request copy]; + NSDictionary *> *additionalParameters = + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:parameters + instance:self]; + _additionalParameters = additionalParameters; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDAuthorizationRequest *request = + [aDecoder decodeObjectOfClass:[OIDAuthorizationRequest class] forKey:kRequestKey]; + self = [self initWithRequest:request parameters:@{ }]; + if (self) { + [OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self]; + _additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes] + forKey:kAdditionalParametersKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_request forKey:kRequestKey]; + [OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, authorizationCode: %@, state: \"%@\", accessToken: " + "\"%@\", accessTokenExpirationDate: %@, tokenType: %@, " + "idToken: \"%@\", scope: \"%@\", additionalParameters: %@, " + "request: %@>", + NSStringFromClass([self class]), + self, + _authorizationCode, + _state, + _accessToken, + _accessTokenExpirationDate, + _tokenType, + _idToken, + _scope, + _additionalParameters, + _request]; +} + +#pragma mark - + +- (OIDTokenRequest *)tokenExchangeRequest { + return [self tokenExchangeRequestWithAdditionalParameters:nil]; +} + +- (OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters: + (NSDictionary *)additionalParameters { + // TODO: add a unit test to confirm exception is thrown when expected and the request is created + // with the correct parameters. + if (!_authorizationCode) { + [NSException raise:kTokenExchangeRequestException + format:kTokenExchangeRequestException]; + } + return [[OIDTokenRequest alloc] initWithConfiguration:_request.configuration + grantType:OIDGrantTypeAuthorizationCode + authorizationCode:_authorizationCode + redirectURL:_request.redirectURL + clientID:_request.clientID + clientSecret:_request.clientSecret + scope:_scope + refreshToken:nil + codeVerifier:_request.codeVerifier + additionalParameters:additionalParameters]; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationService.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationService.h new file mode 100644 index 000000000..c71409220 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationService.h @@ -0,0 +1,156 @@ +/*! @file OIDAuthorizationService.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorization; +@class OIDAuthorizationRequest; +@class OIDAuthorizationResponse; +@class OIDServiceConfiguration; +@class OIDTokenRequest; +@class OIDTokenResponse; +@protocol OIDAuthorizationFlowSession; +@protocol OIDAuthorizationUICoordinator; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the type of block used as a callback for creating a service configuration from + a remote OpenID Connect Discovery document. + @param configuration The service configuration, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDDiscoveryCallback)(OIDServiceConfiguration *_Nullable configuration, + NSError *_Nullable error); + +/*! @brief Represents the type of block used as a callback for various methods of + @c OIDAuthorizationService. + @param authorizationResponse The authorization response, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDAuthorizationCallback)(OIDAuthorizationResponse *_Nullable authorizationResponse, + NSError *_Nullable error); + +/*! @brief Represents the type of block used as a callback for various methods of + @c OIDAuthorizationService. + @param tokenResponse The token response, if available. + @param error The error if an error occurred. + */ +typedef void (^OIDTokenCallback)(OIDTokenResponse *_Nullable tokenResponse, + NSError *_Nullable error); + +/*! @brief Represents the type of dictionary used to specify additional querystring parameters + when making authorization or token endpoint requests. + */ +typedef NSDictionary *_Nullable OIDTokenEndpointParameters; + +/*! @brief Performs various OAuth and OpenID Connect related calls via the user agent or + \NSURLSession. + */ +@interface OIDAuthorizationService : NSObject + +/*! @brief The service's configuration. + @remarks Each authorization service is initialized with a configuration. This configuration + specifies how to connect to a particular OAuth provider. Clients should use separate + authorization service instances for each provider they wish to integrate with. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief Convenience method for creating an authorization service configuration from an OpenID + Connect compliant issuer URL. + @param issuerURL The service provider's OpenID Connect issuer. + @param completion A block which will be invoked when the authorization service configuration has + been created, or when an error has occurred. + @see https://openid.net/specs/openid-connect-discovery-1_0.html + */ ++ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL + completion:(OIDDiscoveryCallback)completion; + + +/*! @brief Convenience method for creating an authorization service configuration from an OpenID + Connect compliant identity provider's discovery document. + @param discoveryURL The URL of the service provider's OpenID Connect discovery document. + @param completion A block which will be invoked when the authorization service configuration has + been created, or when an error has occurred. + @see https://openid.net/specs/openid-connect-discovery-1_0.html + */ ++ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL + completion:(OIDDiscoveryCallback)completion; + +/*! @brief Perform an authorization flow using a generic flow shim. + @param request The authorization request. + @param UICoordinator Generic authorization UI coordinator that can present an authorization + request. + @param callback The method called when the request has completed or failed. + @return A @c OIDAuthorizationFlowSession instance which will terminate when it + receives a @c OIDAuthorizationFlowSession.cancel message, or after processing a + @c OIDAuthorizationFlowSession.resumeAuthorizationFlowWithURL: message. + */ ++ (id) + presentAuthorizationRequest:(OIDAuthorizationRequest *)request + UICoordinator:(id)UICoordinator + callback:(OIDAuthorizationCallback)callback; + +/*! @brief Performs a token request. + @param request The token request. + @param callback The method called when the request has completed or failed. + */ ++ (void)performTokenRequest:(OIDTokenRequest *)request callback:(OIDTokenCallback)callback; + +@end + +/*! @brief Represents an in-flight authorization flow session. + */ +@protocol OIDAuthorizationFlowSession + +/*! @brief Cancels the code flow session, invoking the request's callback with a cancelled error. + @remarks Has no effect if called more than once, or after a + @c OIDAuthorizationFlowSession.resumeAuthorizationFlowWithURL: message was received. Will + cause an error with code: @c ::OIDErrorCodeProgramCanceledAuthorizationFlow to be passed to + the @c callback block passed to + @c OIDAuthorizationService.presentAuthorizationRequest:presentingViewController:callback: + */ +- (void)cancel; + +/*! @brief Clients should call this method with the result of the authorization code flow if it + becomes available. + @param URL The redirect URL invoked by the authorization server. + @discussion When the URL represented a valid authorization response, implementations + should clean up any left-over UI state from the authorization, for example by + closing the \SFSafariViewController or looback HTTP listener if those were used. + The completion block of the pending authorization request should then be invoked. + @remarks Has no effect if called more than once, or after a @c cancel message was received. + @return YES if the passed URL matches the expected redirect URL and was consumed, NO otherwise. + */ +- (BOOL)resumeAuthorizationFlowWithURL:(NSURL *)URL; + +/*! @brief @c OIDAuthorizationUICoordinator or clients should call this method when the + authorization flow failed with a non-OAuth error. + @param error The error that is the reason for the failure of this authorization flow. + @remarks Has no effect if called more than once, or after a @c cancel message was received. + */ +- (void)failAuthorizationFlowWithError:(NSError *)error; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationService.m b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationService.m new file mode 100644 index 000000000..b9b2f2f72 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationService.m @@ -0,0 +1,354 @@ +/*! @file OIDAuthorizationService.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationService.h" + +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationUICoordinator.h" +#import "OIDDefines.h" +#import "OIDErrorUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDURLQueryComponent.h" + +/*! @brief Path appended to an OpenID Connect issuer for discovery + @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig + */ +static NSString *const kOpenIDConfigurationWellKnownPath = @".well-known/openid-configuration"; + +/*! @brief The state authorization parameter. + */ +static NSString *const kStateParameter = @"state"; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDAuthorizationFlowSessionImplementation : NSObject + +- (instancetype)init NS_UNAVAILABLE; + +- (nullable instancetype)initWithRequest:(OIDAuthorizationRequest *)request + NS_DESIGNATED_INITIALIZER; + +@end + +@implementation OIDAuthorizationFlowSessionImplementation { + OIDAuthorizationRequest *_request; + id _UICoordinator; + OIDAuthorizationCallback _pendingauthorizationFlowCallback; +} + +- (nullable instancetype)initWithRequest:(OIDAuthorizationRequest *)request { + self = [super init]; + if (self) { + _request = [request copy]; + } + return self; +} + +- (void)presentAuthorizationWithCoordinator:(id)UICoordinator + callback:(OIDAuthorizationCallback)authorizationFlowCallback { + _UICoordinator = UICoordinator; + _pendingauthorizationFlowCallback = authorizationFlowCallback; + NSURL *URL = [_request authorizationRequestURL]; + BOOL authorizationFlowStarted = [_UICoordinator presentAuthorizationWithURL:URL session:self]; + if (!authorizationFlowStarted) { + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError + underlyingError:nil + description:@"Unable to open Safari."]; + [self didFinishWithResponse:nil error:safariError]; + } +} + +- (void)cancel { + [_UICoordinator dismissAuthorizationAnimated:YES + completion:^{ + NSError *error = [OIDErrorUtilities + errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow + underlyingError:nil + description:nil]; + [self didFinishWithResponse:nil error:error]; + }]; +} + +- (BOOL)shouldHandleURL:(NSURL *)URL { + NSURL *standardizedURL = [URL standardizedURL]; + NSURL *standardizedRedirectURL = [_request.redirectURL standardizedURL]; + + return OIDIsEqualIncludingNil(standardizedURL.scheme, standardizedRedirectURL.scheme) && + OIDIsEqualIncludingNil(standardizedURL.user, standardizedRedirectURL.user) && + OIDIsEqualIncludingNil(standardizedURL.password, standardizedRedirectURL.password) && + OIDIsEqualIncludingNil(standardizedURL.host, standardizedRedirectURL.host) && + OIDIsEqualIncludingNil(standardizedURL.port, standardizedRedirectURL.port) && + OIDIsEqualIncludingNil(standardizedURL.path, standardizedRedirectURL.path); +} + +- (BOOL)resumeAuthorizationFlowWithURL:(NSURL *)URL { + // rejects URLs that don't match redirect (these may be completely unrelated to the authorization) + if (![self shouldHandleURL:URL]) { + return NO; + } + // checks for an invalid state + if (!_pendingauthorizationFlowCallback) { + [NSException raise:OIDOAuthExceptionInvalidAuthorizationFlow + format:@"%@", OIDOAuthExceptionInvalidAuthorizationFlow, nil]; + } + + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] initWithURL:URL]; + + NSError *error; + OIDAuthorizationResponse *response = nil; + + // checks for an OAuth error response as per RFC6749 Section 4.1.2.1 + if (query.dictionaryValue[OIDOAuthErrorFieldError]) { + error = [OIDErrorUtilities OAuthErrorWithDomain:OIDOAuthAuthorizationErrorDomain + OAuthResponse:query.dictionaryValue + underlyingError:nil]; + } + + // verifies that the state in the response matches the state in the request, or both are nil + if (!OIDIsEqualIncludingNil(_request.state, query.dictionaryValue[kStateParameter])) { + NSMutableDictionary *userInfo = [query.dictionaryValue mutableCopy]; + userInfo[NSLocalizedDescriptionKey] = + [NSString stringWithFormat:@"State mismatch, expecting %@ but got %@ in authorization " + "response %@", + _request.state, + response.state, + response]; + response = nil; + error = [NSError errorWithDomain:OIDOAuthAuthorizationErrorDomain + code:OIDErrorCodeOAuthAuthorizationClientError + userInfo:userInfo]; + } + + // no error, should be a valid OAuth 2.0 response + if (!error) { + response = [[OIDAuthorizationResponse alloc] initWithRequest:_request + parameters:query.dictionaryValue]; + } + + [_UICoordinator dismissAuthorizationAnimated:YES + completion:^{ + [self didFinishWithResponse:response error:error]; + }]; + + return YES; +} + +- (void)failAuthorizationFlowWithError:(NSError *)error { + [self didFinishWithResponse:nil error:error]; +} + +/*! @brief Invokes the pending callback and performs cleanup. + @param response The authorization response, if any to return to the callback. + @param error The error, if any, to return to the callback. + */ +- (void)didFinishWithResponse:(nullable OIDAuthorizationResponse *)response + error:(nullable NSError *)error { + OIDAuthorizationCallback callback = _pendingauthorizationFlowCallback; + _pendingauthorizationFlowCallback = nil; + _UICoordinator = nil; + if (callback) { + callback(response, error); + } +} + +@end + +@implementation OIDAuthorizationService + ++ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL + completion:(OIDDiscoveryCallback)completion { + NSURL *fullDiscoveryURL = + [issuerURL URLByAppendingPathComponent:kOpenIDConfigurationWellKnownPath]; + + return [[self class] discoverServiceConfigurationForDiscoveryURL:fullDiscoveryURL + completion:completion]; +} + ++ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL + completion:(OIDDiscoveryCallback)completion { + + NSURLSession *session = [NSURLSession sharedSession]; + NSURLSessionDataTask *task = + [session dataTaskWithURL:discoveryURL + completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { + // If we got any sort of error, just report it. + if (error || !data) { + error = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:error.localizedDescription]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + + NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response; + + // Check for non-200 status codes. + // https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse + if (urlResponse.statusCode != 200) { + NSError *URLResponseError = [OIDErrorUtilities HTTPErrorWithHTTPResponse:urlResponse + data:data]; + error = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:URLResponseError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + + // Construct an OIDServiceDiscovery with the received JSON. + OIDServiceDiscovery *discovery = + [[OIDServiceDiscovery alloc] initWithJSONData:data error:&error]; + if (error || !discovery) { + error = [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(nil, error); + }); + return; + } + + // Create our service configuration with the discovery document and return it. + OIDServiceConfiguration *configuration = + [[OIDServiceConfiguration alloc] initWithDiscoveryDocument:discovery]; + dispatch_async(dispatch_get_main_queue(), ^{ + completion(configuration, nil); + }); + }]; + [task resume]; +} + +#pragma mark - Authorization Endpoint + ++ (id) + presentAuthorizationRequest:(OIDAuthorizationRequest *)request + UICoordinator:(id)UICoordinator + callback:(OIDAuthorizationCallback)callback { + OIDAuthorizationFlowSessionImplementation *flowSession = + [[OIDAuthorizationFlowSessionImplementation alloc] initWithRequest:request]; + [flowSession presentAuthorizationWithCoordinator:UICoordinator callback:callback]; + return flowSession; +} + +#pragma mark - Token Endpoint + ++ (void)performTokenRequest:(OIDTokenRequest *)request callback:(OIDTokenCallback)callback { + NSURLRequest *URLRequest = [request URLRequest]; + NSURLSession *session = [NSURLSession sharedSession]; + [[session dataTaskWithRequest:URLRequest + completionHandler:^(NSData *_Nullable data, + NSURLResponse *_Nullable response, + NSError *_Nullable error) { + if (error) { + // A network error or server error occurred. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeNetworkError + underlyingError:error + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + NSHTTPURLResponse *HTTPURLResponse = (NSHTTPURLResponse *)response; + NSInteger statusCode = HTTPURLResponse.statusCode; + if (statusCode != 200) { + // A server error occurred. + NSError *serverError = + [OIDErrorUtilities HTTPErrorWithHTTPResponse:HTTPURLResponse data:data]; + + // HTTP 400 may indicate an RFC6749 Section 5.2 error response. + // HTTP 429 may occur during polling for device-flow requests for the slow_down error + // https://tools.ietf.org/html/draft-ietf-oauth-device-flow-03#section-3.5 + if (statusCode == 400 || statusCode == 429) { + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonDeserializationError]; + + // if the HTTP 400 response parses as JSON and has an 'error' key, it's an OAuth error + // these errors are special as they indicate a problem with the authorization grant + if (json[OIDOAuthErrorFieldError]) { + NSError *oauthError = + [OIDErrorUtilities OAuthErrorWithDomain:OIDOAuthTokenErrorDomain + OAuthResponse:json + underlyingError:serverError]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, oauthError); + }); + return; + } + } + + // not an OAuth error, just a generic server error + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeServerError + underlyingError:serverError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + NSError *jsonDeserializationError; + NSDictionary *> *json = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonDeserializationError]; + if (jsonDeserializationError) { + // A problem occurred deserializing the response/JSON. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONDeserializationError + underlyingError:jsonDeserializationError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + OIDTokenResponse *tokenResponse = + [[OIDTokenResponse alloc] initWithRequest:request parameters:json]; + if (!tokenResponse) { + // A problem occurred constructing the token response from the JSON. + NSError *returnedError = + [OIDErrorUtilities errorWithCode:OIDErrorCodeTokenResponseConstructionError + underlyingError:jsonDeserializationError + description:nil]; + dispatch_async(dispatch_get_main_queue(), ^{ + callback(nil, returnedError); + }); + return; + } + + // Success + dispatch_async(dispatch_get_main_queue(), ^{ + callback(tokenResponse, nil); + }); + }] resume]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationUICoordinator.h b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationUICoordinator.h new file mode 100644 index 000000000..a20de6b78 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDAuthorizationUICoordinator.h @@ -0,0 +1,51 @@ +/*! @file OIDAuthorizationUICoordinator.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@protocol OIDAuthorizationFlowSession; + +NS_ASSUME_NONNULL_BEGIN + +/*! @protocol OIDAuthorizationUICoordinator + @brief An authorization UI coordinator that presents an authorization request. Clients may + provide custom implementations of an authorization UI coordinator to customize the way the + authorization request is presented to the user. + */ +@protocol OIDAuthorizationUICoordinator + +/*! @brief Presents the authorization UI for the given URL. + @param URL The URL that should be used when presenting the authorization UI. + @param session The @c OIDAuthorizationFlowSession instance that initiates presenting the + authorization UI. Concrete implementations of a @c OIDAuthorizationUICoordinator may call + resumeAuthorizationFlowWithURL or failAuthorizationFlowWithError on session to either + resume or fail the authorization. + @return YES If the authorization UI was successfully presented to the user. + */ +- (BOOL)presentAuthorizationWithURL:(NSURL *)URL session:(id)session; + +/*! @brief Dimisses the authorization UI and calls completion when the dismiss operation ends. + @param animated Wheter or not the dismiss operation should be animated. + @remarks Has no effect if no authorization UI is presented. + @param completion The block to be called when the dismiss operations ends + */ +- (void)dismissAuthorizationAnimated:(BOOL)animated completion:(void (^)(void))completion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDDefines.h b/Paco-iOS/Pods/AppAuth/Source/OIDDefines.h new file mode 100644 index 000000000..0dccf842a --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDDefines.h @@ -0,0 +1,44 @@ +/*! @file OIDDefines.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +/*! @def OIDIsEqualIncludingNil(x, y) + @brief Returns YES if x and y are equal by reference or value. + @discussion NOTE: parameters may be evaluated multiple times. Be careful if using this check + with expressions - especially if the expressions have side effects. + @param x An object. + @param y An object. + */ +#define OIDIsEqualIncludingNil(x, y) (((x) == (y)) || [(x) isEqual:(y)]) + +/*! @def OID_UNAVAILABLE_USE_INITIALIZER(designatedInitializer) + @brief Provides a template implementation for init-family methods which have been marked as + NS_UNAVILABLE. Stops the compiler from giving a warning when it's the super class' + designated initializer, and gives callers useful feedback telling them what the + new designated initializer is. + @remarks Takes a SEL as a parameter instead of a string so that we get compiler warnings if the + designated intializer's signature changes. + @param designatedInitializer A SEL referencing the designated initializer. + */ +#define OID_UNAVAILABLE_USE_INITIALIZER(designatedInitializer) { \ + NSString *reason = [NSString stringWithFormat:@"Called: %@\nDesignated Initializer:%@", \ + NSStringFromSelector(_cmd), \ + NSStringFromSelector(designatedInitializer)]; \ + @throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." \ + reason:reason \ + userInfo:nil]; \ +} diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDError.h b/Paco-iOS/Pods/AppAuth/Source/OIDError.h new file mode 100644 index 000000000..01afbfcb4 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDError.h @@ -0,0 +1,318 @@ +/*! @file OIDError.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The error domain for all NSErrors returned from the AppAuth library. + */ +extern NSString *const OIDGeneralErrorDomain; + +/*! @brief The error domain for OAuth specific errors on the authorization endpoint. + @discussion This error domain is used when the server responds to an authorization request + with an explicit OAuth error, as defined by RFC6749 Section 4.1.2.1. If the authorization + response is invalid and not explicitly an error response, another error domain will be used. + The error response parameter dictionary is available in the + \NSError_userInfo dictionary using the @c ::OIDOAuthErrorResponseErrorKey key. + The \NSError_code will be one of the @c ::OIDErrorCodeOAuthAuthorization enum values. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ +extern NSString *const OIDOAuthAuthorizationErrorDomain; + +/*! @brief The error domain for OAuth specific errors on the token endpoint. + @discussion This error domain is used when the server responds with HTTP 400 and an OAuth error, + as defined RFC6749 Section 5.2. If an HTTP 400 response does not parse as an OAuth error + (i.e. no 'error' field is present or the JSON is invalid), another error domain will be + used. The entire OAuth error response dictionary is available in the \NSError_userInfo + dictionary using the @c ::OIDOAuthErrorResponseErrorKey key. Unlike transient network + errors, errors in this domain invalidate the authentication state, and either indicate a + client error or require user interaction (i.e. reauthentication) to resolve. + The \NSError_code will be one of the @c ::OIDErrorCodeOAuthToken enum values. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthTokenErrorDomain; + +/*! @brief The error domain for authorization errors encountered out of band on the resource server. + */ +extern NSString *const OIDResourceServerAuthorizationErrorDomain; + +/*! @brief An error domain representing received HTTP errors. + */ +extern NSString *const OIDHTTPErrorDomain; + +/*! @brief An error key for the original OAuth error response (if any). + */ +extern NSString *const OIDOAuthErrorResponseErrorKey; + +/*! @brief The key of the 'error' response field in a RFC6749 Section 5.2 response. + @remark error + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthErrorFieldError; + +/*! @brief The key of the 'error_description' response field in a RFC6749 Section 5.2 response. + @remark error_description + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthErrorFieldErrorDescription; + +/*! @brief The key of the 'error_uri' response field in a RFC6749 Section 5.2 response. + @remark error_uri + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +extern NSString *const OIDOAuthErrorFieldErrorURI; + +/*! @brief The various error codes returned from the AppAuth library. + */ +typedef NS_ENUM(NSInteger, OIDErrorCode) { + /*! @brief Indicates a problem parsing an OpenID Connect Service Discovery document. + */ + OIDErrorCodeInvalidDiscoveryDocument = -2, + + /*! @brief Indicates the user manually canceled the OAuth authorization code flow. + */ + OIDErrorCodeUserCanceledAuthorizationFlow = -3, + + /*! @brief Indicates an OAuth authorization flow was programmatically cancelled. + */ + OIDErrorCodeProgramCanceledAuthorizationFlow = -4, + + /*! @brief Indicates a network error or server error occurred. + */ + OIDErrorCodeNetworkError = -5, + + /*! @brief Indicates a server error occurred. + */ + OIDErrorCodeServerError = -6, + + /*! @brief Indicates a problem occurred deserializing the response/JSON. + */ + OIDErrorCodeJSONDeserializationError = -7, + + /*! @brief Indicates a problem occurred constructing the token response from the JSON. + */ + OIDErrorCodeTokenResponseConstructionError = -8, + + /*! @brief @c UIApplication.openURL: returned NO when attempting to open the authorization + request in mobile Safari. + */ + OIDErrorCodeSafariOpenError = -9, + + /*! @brief @c NSWorkspace.openURL returned NO when attempting to open the authorization + request in the default browser. + */ + OIDErrorCodeBrowserOpenError = -10, + + /*! @brief Indicates a problem when trying to refresh the tokens. + */ + OIDErrorCodeTokenRefreshError = -11, + + +}; + +/*! @brief Enum of all possible OAuth error codes as defined by RFC6749 + @discussion Used by @c ::OIDErrorCodeOAuthAuthorization and @c ::OIDErrorCodeOAuthToken + which define endpoint-specific subsets of OAuth codes. Those enum types are down-castable + to this one. + @see https://tools.ietf.org/html/rfc6749#section-11.4 + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuth) { + + /*! @remarks invalid_request + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidRequest = -2, + + /*! @remarks unauthorized_client + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthUnauthorizedClient = -3, + + /*! @remarks access_denied + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAccessDenied = -4, + + /*! @remarks unsupported_response_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthUnsupportedResponseType = -5, + + /*! @remarks invalid_scope + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidScope = -6, + + /*! @remarks server_error + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthServerError = -7, + + /*! @remarks temporarily_unavailable + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthTemporarilyUnavailable = -8, + + /*! @remarks invalid_client + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidClient = -9, + + /*! @remarks invalid_grant + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthInvalidGrant = -10, + + /*! @remarks unsupported_grant_type + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthUnsupportedGrantType = -11, + + /*! @brief An authorization error occurring on the client rather than the server. For example, + due to a state mismatch or misconfiguration. Should be treated as an unrecoverable + authorization error. + */ + OIDErrorCodeOAuthClientError = -0xEFFF, + + /*! @brief An OAuth error not known to this library + @discussion Indicates an OAuth error as per RFC6749, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. Such errors are assumed to invalidate the + authentication state + */ + OIDErrorCodeOAuthOther = -0xF000, +}; + +/*! @brief The error codes for the @c ::OIDOAuthAuthorizationErrorDomain error domain + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuthAuthorization) { + /*! @remarks invalid_request + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationInvalidRequest = OIDErrorCodeOAuthInvalidRequest, + + /*! @remarks unauthorized_client + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationUnauthorizedClient = OIDErrorCodeOAuthUnauthorizedClient, + + /*! @remarks access_denied + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationAccessDenied = + OIDErrorCodeOAuthAccessDenied, + + /*! @remarks unsupported_response_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationUnsupportedResponseType = + OIDErrorCodeOAuthUnsupportedResponseType, + + /*! @brief Indicates a network error or server error occurred. + @remarks invalid_scope + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationAuthorizationInvalidScope = OIDErrorCodeOAuthInvalidScope, + + /*! @brief Indicates a server error occurred. + @remarks server_error + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationServerError = OIDErrorCodeOAuthServerError, + + /*! @remarks temporarily_unavailable + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationTemporarilyUnavailable = OIDErrorCodeOAuthTemporarilyUnavailable, + + /*! @brief An authorization error occurring on the client rather than the server. For example, + due to a state mismatch or client misconfiguration. Should be treated as an unrecoverable + authorization error. + */ + OIDErrorCodeOAuthAuthorizationClientError = OIDErrorCodeOAuthClientError, + + /*! @brief An authorization OAuth error not known to this library + @discussion this indicates an OAuth error as per RFC6749, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. We assume such errors are not transient. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + */ + OIDErrorCodeOAuthAuthorizationOther = OIDErrorCodeOAuthOther, +}; + + +/*! @brief The error codes for the @c ::OIDOAuthTokenErrorDomain error domain + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ +typedef NS_ENUM(NSInteger, OIDErrorCodeOAuthToken) { + /*! @remarks invalid_request + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidRequest = OIDErrorCodeOAuthInvalidRequest, + + /*! @remarks invalid_client + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidClient = OIDErrorCodeOAuthInvalidClient, + + /*! @remarks invalid_grant + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidGrant = OIDErrorCodeOAuthInvalidGrant, + + /*! @remarks unauthorized_client + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenUnauthorizedClient = OIDErrorCodeOAuthUnauthorizedClient, + + /*! @remarks unsupported_grant_type + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenUnsupportedGrantType = OIDErrorCodeOAuthUnsupportedGrantType, + + /*! @remarks invalid_scope + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenInvalidScope = OIDErrorCodeOAuthInvalidScope, + + /*! @brief An unrecoverable token error occurring on the client rather than the server. + */ + OIDErrorCodeOAuthTokenClientError = OIDErrorCodeOAuthClientError, + + /*! @brief A token endpoint OAuth error not known to this library + @discussion this indicates an OAuth error as per RFC6749, but the error code was not in our + list. It could be a custom error code, or one from an OAuth extension. See the "error" key + of the \NSError_userInfo property. We assume such errors are not transient. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ + OIDErrorCodeOAuthTokenOther = OIDErrorCodeOAuthOther, +}; + +/*! @brief The exception text for the exception which occurs when a + @c OIDAuthorizationFlowSession receives a message after it has already completed. + */ +extern NSString *const OIDOAuthExceptionInvalidAuthorizationFlow; + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDError.m b/Paco-iOS/Pods/AppAuth/Source/OIDError.m new file mode 100644 index 000000000..4342af4c6 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDError.m @@ -0,0 +1,40 @@ +/*! @file OIDError.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDError.h" + +NSString *const OIDGeneralErrorDomain = @"org.openid.appauth.general"; + +NSString *const OIDOAuthTokenErrorDomain = @"org.openid.appauth.oauth_token"; + +NSString *const OIDOAuthAuthorizationErrorDomain = @"org.openid.appauth.oauth_authorization"; + +NSString *const OIDResourceServerAuthorizationErrorDomain = @"org.openid.appauth.resourceserver"; + +NSString *const OIDHTTPErrorDomain = @"org.openid.appauth.remote-http"; + +NSString *const OIDOAuthExceptionInvalidAuthorizationFlow = @"An OAuth redirect was sent to a " + "OIDAuthorizationFlowSession after it already completed."; + +NSString *const OIDOAuthErrorResponseErrorKey = @"OIDOAuthErrorResponseErrorKey"; + +NSString *const OIDOAuthErrorFieldError = @"error"; + +NSString *const OIDOAuthErrorFieldErrorDescription = @"error_description"; + +NSString *const OIDOAuthErrorFieldErrorURI = @"error_uri"; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDErrorUtilities.h b/Paco-iOS/Pods/AppAuth/Source/OIDErrorUtilities.h new file mode 100644 index 000000000..fb98a5579 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDErrorUtilities.h @@ -0,0 +1,107 @@ +/*! @file OIDErrorUtilities.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDError.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Convenience methods for creating standardized \NSError instances. + */ +@interface OIDErrorUtilities : NSObject + +/*! @brief Creates a standard \NSError from an @c ::OIDErrorCode and custom user info. + Automatically populates the localized error description. + @param code The error code. + @param underlyingError The underlying error which occurred, if applicable. + @param description A custom description, if applicable. + @return An \NSError representing the error code. + */ ++ (nullable NSError *)errorWithCode:(OIDErrorCode)code + underlyingError:(nullable NSError *)underlyingError + description:(nullable NSString *)description; + +/*! @brief Creates a standard \NSError from an @c ::OIDErrorCode and custom user info. + Automatically populates the localized error description. + @param OAuthErrorDomain The OAuth error domain. Must be @c ::OIDOAuthAuthorizationErrorDomain or + @c ::OIDOAuthTokenErrorDomain. + @param errorResponse The dictionary from an OAuth error response (as per RFC6749 Section 5.2). + @param underlyingError The underlying error which occurred, if applicable. + @return An \NSError representing the OAuth error. + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ ++ (nullable NSError *)OAuthErrorWithDomain:(NSString *)OAuthErrorDomain + OAuthResponse:(NSDictionary *)errorResponse + underlyingError:(nullable NSError *)underlyingError; + +/*! @brief Creates a \NSError indicating that the resource server responded with an authorization + error. + @param code Your error code. + @param errorResponse The resource server error response, if any. + @param underlyingError The underlying error which occurred, if applicable. + @return An \NSError representing the authorization error from the resource server. + */ ++ (nullable NSError *)resourceServerAuthorizationErrorWithCode:(NSInteger)code + errorResponse:(nullable NSDictionary *)errorResponse + underlyingError:(nullable NSError *)underlyingError; + + +/*! @brief Creates a standard \NSError from an \NSHTTPURLResponse. Automatically + populates the localized error description with the response data associated with the + \NSHTTPURLResponse, if available. + @param HTTPURLResponse The response which indicates an error occurred. + @param data The response data associated with the response which should be converted to an + @c NSString assuming a UTF-8 encoding, if available. + @return An \NSError representing the error. + */ ++ (nullable NSError *)HTTPErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPURLResponse + data:(nullable NSData *)data; + +/*! @brief Raises an exception with the given name as both the name, and the message. + @param name The name of the exception. + */ ++ (void)raiseException:(NSString *)name; + +/*! @brief Raises an exception with the given name and message. + @param name The name of the exception. + @param message The message of the exception. + */ ++ (void)raiseException:(NSString *)name message:(NSString *)message; + +/*! @brief Converts an OAuth error code into an @c ::OIDErrorCodeOAuth error code. + @param errorCode The OAuth error code. + @discussion Returns @c ::OIDErrorCodeOAuthOther if the string is not in AppAuth's list. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ ++ (OIDErrorCodeOAuth)OAuthErrorCodeFromString:(NSString *)errorCode; + +/*! @brief Returns true if the given error domain is an OAuth error domain. + @param errorDomain The error domain to test. + @discussion An OAuth error domain is used for errors returned per RFC6749 sections 4.1.2.1 and + 5.2. Other errors, such as network errors can also occur but they will not have an OAuth + error domain. + @see https://tools.ietf.org/html/rfc6749#section-4.1.2.1 + @see https://tools.ietf.org/html/rfc6749#section-5.2 + */ ++ (BOOL)isOAuthErrorDomain:(NSString*)errorDomain; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDErrorUtilities.m b/Paco-iOS/Pods/AppAuth/Source/OIDErrorUtilities.m new file mode 100644 index 000000000..126f9c1b8 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDErrorUtilities.m @@ -0,0 +1,160 @@ +/*! @file OIDErrorUtilities.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDErrorUtilities.h" + +@implementation OIDErrorUtilities + ++ (nullable NSError *)errorWithCode:(OIDErrorCode)code + underlyingError:(NSError *)underlyingError + description:(NSString *)description { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + if (description) { + userInfo[NSLocalizedDescriptionKey] = description; + } + // TODO: Populate localized description based on code. + NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain + code:code + userInfo:userInfo]; + return error; +} + ++ (BOOL)isOAuthErrorDomain:(NSString *)errorDomain { + return errorDomain == OIDOAuthAuthorizationErrorDomain + || errorDomain == OIDOAuthTokenErrorDomain; +} + ++ (nullable NSError *)resourceServerAuthorizationErrorWithCode:(NSInteger)code + errorResponse:(nullable NSDictionary *)errorResponse + underlyingError:(nullable NSError *)underlyingError { + // builds the userInfo dictionary with the full OAuth response and other information + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (errorResponse) { + userInfo[OIDOAuthErrorResponseErrorKey] = errorResponse; + } + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + NSError *error = [NSError errorWithDomain:OIDResourceServerAuthorizationErrorDomain + code:code + userInfo:userInfo]; + return error; +} + ++ (nullable NSError *)OAuthErrorWithDomain:(NSString *)oAuthErrorDomain + OAuthResponse:(NSDictionary *)errorResponse + underlyingError:(NSError *)underlyingError { + // not a valid OAuth error + if (![self isOAuthErrorDomain:oAuthErrorDomain] + || !errorResponse + || !errorResponse[OIDOAuthErrorFieldError]) { + return [[self class] errorWithCode:OIDErrorCodeNetworkError + underlyingError:underlyingError + description:underlyingError.localizedDescription]; + } + + // builds the userInfo dictionary with the full OAuth response and other information + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + userInfo[OIDOAuthErrorResponseErrorKey] = errorResponse; + if (underlyingError) { + userInfo[NSUnderlyingErrorKey] = underlyingError; + } + + NSString *oauthErrorCodeString = errorResponse[OIDOAuthErrorFieldError]; + NSString *oauthErrorMessage = errorResponse[OIDOAuthErrorFieldErrorDescription]; + NSString *oauthErrorURI = errorResponse[OIDOAuthErrorFieldErrorURI]; + + // builds the error description, using the information supplied by the server if possible + NSMutableString *description = [NSMutableString string]; + [description appendString:oauthErrorCodeString]; + if (oauthErrorMessage) { + [description appendString:@": "]; + [description appendString:oauthErrorMessage]; + } + if (oauthErrorURI) { + if ([description length] > 0) { + [description appendString:@" - "]; + } + [description appendString:oauthErrorURI]; + } + if ([description length] == 0) { + // backup description + [description appendFormat:@"OAuth error: %@ - https://tools.ietf.org/html/rfc6749#section-5.2", + oauthErrorCodeString]; + } + userInfo[NSLocalizedDescriptionKey] = description; + + // looks up the error code based on the "error" response param + OIDErrorCodeOAuth code = [[self class] OAuthErrorCodeFromString:oauthErrorCodeString]; + + NSError *error = [NSError errorWithDomain:oAuthErrorDomain + code:code + userInfo:userInfo]; + return error; +} + ++ (nullable NSError *)HTTPErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPURLResponse + data:(nullable NSData *)data { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (data) { + NSString *serverResponse = + [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (serverResponse) { + userInfo[NSLocalizedDescriptionKey] = serverResponse; + } + } + NSError *serverError = + [NSError errorWithDomain:OIDHTTPErrorDomain + code:HTTPURLResponse.statusCode + userInfo:userInfo]; + return serverError; +} + ++ (OIDErrorCodeOAuth)OAuthErrorCodeFromString:(NSString *)errorCode { + NSDictionary *errorCodes = @{ + @"invalid_request": @(OIDErrorCodeOAuthInvalidRequest), + @"unauthorized_client": @(OIDErrorCodeOAuthUnauthorizedClient), + @"access_denied": @(OIDErrorCodeOAuthAccessDenied), + @"unsupported_response_type": @(OIDErrorCodeOAuthUnsupportedResponseType), + @"invalid_scope": @(OIDErrorCodeOAuthInvalidScope), + @"server_error": @(OIDErrorCodeOAuthServerError), + @"temporarily_unavailable": @(OIDErrorCodeOAuthTemporarilyUnavailable), + @"invalid_client": @(OIDErrorCodeOAuthInvalidClient), + @"invalid_grant": @(OIDErrorCodeOAuthInvalidGrant), + @"unsupported_grant_type": @(OIDErrorCodeOAuthUnsupportedGrantType), + }; + NSNumber *code = errorCodes[errorCode]; + if (code) { + return [code integerValue]; + } else { + return OIDErrorCodeOAuthOther; + } +} + ++ (void)raiseException:(NSString *)name { + [[self class] raiseException:name message:name]; +} + ++ (void)raiseException:(NSString *)name message:(NSString *)message { + [NSException raise:name format:@"%@", message]; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDFieldMapping.h b/Paco-iOS/Pods/AppAuth/Source/OIDFieldMapping.h new file mode 100644 index 000000000..0775ddef1 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDFieldMapping.h @@ -0,0 +1,116 @@ +/*! @file OIDFieldMapping.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a function which transforms incoming source values into instance variable + values. + */ +typedef _Nullable id(^OIDFieldMappingConversionFunction)(NSObject *_Nullable value); + +/*! @brief Describes the mapping of a key/value pair to an iVar with an optional conversion + function. + */ +@interface OIDFieldMapping : NSObject + +/*! @brief The name of the instance variable the field should be mapped to. + */ +@property(nonatomic, readonly) NSString *name; + +/*! @brief The type of the instance variable. + */ +@property(nonatomic, readonly) Class expectedType; + +/*! @brief An optional conversion function which specifies a transform from the incoming data to the + instance variable value. + */ +@property(nonatomic, readonly, nullable) OIDFieldMappingConversionFunction conversion; + +/*! @internal + @brief Unavailable. Please use initWithName:type:conversion:. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief The designated initializer. + @param name The name of the instance variable the field should be mapped to. + @param type The type of the instance variable. + @param conversion An optional conversion function which specifies a transform from the incoming + data to the instance variable value. Used during the process performed by + @c OIDFieldMapping.remainingParametersWithMap:parameters:instance: but not during + encoding/decoding, since the encoded and decoded values should already be of the type + specified by the @c type parameter. + */ +- (nullable instancetype)initWithName:(NSString *)name + type:(Class)type + conversion:(nullable OIDFieldMappingConversionFunction)conversion + NS_DESIGNATED_INITIALIZER; + +/*! @brief A convenience initializer. + @param name The name of the instance variable the field should be mapped to. + @param type The type of the instance variable. + */ +- (nullable instancetype)initWithName:(NSString *)name + type:(Class)type; + +/*! @brief Performs a mapping of key/value pairs in an incoming parameters dictionary to instance + variables, returning a dictionary of parameter key/values which didn't map to instance + variables. + @param map A mapping of incoming keys to instance variables. + @param parameters Incoming key value pairs to map to an instance's variables. + @param instance The instance whose variables should be set based on the mapping. + @return A dictionary of parameter key/values which didn't map to instance variables. + */ ++ (NSDictionary *> *)remainingParametersWithMap: + (NSDictionary *)map + parameters:(NSDictionary *> *)parameters + instance:(id)instance; + +/*! @brief This helper method for @c NSCoding implementations performs a serialization of fields + defined in a field mapping. + @param aCoder An @c NSCoder instance to serialize instance variable values to. + @param map A mapping of keys to instance variables. + @param instance The instance whose variables should be serialized based on the mapping. + */ ++ (void)encodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance; + +/*! @brief This helper method for @c NSCoding implementations performs a deserialization of + fields defined in a field mapping. + @param aCoder An @c NSCoder instance from which to deserialize instance variable values from. + @param map A mapping of keys to instance variables. + @param instance The instance whose variables should be deserialized based on the mapping. + */ ++ (void)decodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance; + +/*! @brief Returns an @c NSSet of classes suitable for deserializing JSON content in an + @c NSSecureCoding context. + */ ++ (NSSet *)JSONTypes; + +/*! @brief Returns a function for converting an @c NSString to an @c NSURL. + */ ++ (OIDFieldMappingConversionFunction)URLConversion; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDFieldMapping.m b/Paco-iOS/Pods/AppAuth/Source/OIDFieldMapping.m new file mode 100644 index 000000000..dacac8226 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDFieldMapping.m @@ -0,0 +1,112 @@ +/*! @file OIDFieldMapping.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDFieldMapping.h" + +#import "OIDDefines.h" + +@implementation OIDFieldMapping + +- (nullable instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithName:type:conversion:)); + +- (nullable instancetype)initWithName:(NSString *)name + type:(Class)type { + return [self initWithName:name type:type conversion:nil]; +} + +- (nullable instancetype)initWithName:(NSString *)name + type:(Class)type + conversion:(nullable OIDFieldMappingConversionFunction)conversion { + self = [super init]; + if (self) { + _name = [name copy]; + _expectedType = type; + _conversion = conversion; + } + return self; +} + ++ (NSDictionary *> *)remainingParametersWithMap: + (NSDictionary *)map + parameters:(NSDictionary *> *)parameters + instance:(id)instance { + NSMutableDictionary *additionalParameters = [NSMutableDictionary dictionary]; + for (NSString *key in parameters) { + NSObject *value = [parameters[key] copy]; + OIDFieldMapping *mapping = map[key]; + // If the field doesn't appear in the mapping, we add it to the additional parameters + // dictionary. + if (!mapping) { + additionalParameters[key] = value; + continue; + } + // If the field mapping specifies a conversion function, apply the conversion to the value. + if (mapping.conversion) { + value = mapping.conversion(value); + } + // Check the type of the value and make sure it matches the type we expected. If it doesn't we + // add the value to the additional parameters dictionary but don't assign the instance variable. + if (![value isKindOfClass:mapping.expectedType]) { + additionalParameters[key] = value; + continue; + } + // Assign the instance variable. + [instance setValue:value forKey:mapping.name]; + } + return additionalParameters; +} + ++ (void)encodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance { + for (NSString *key in map) { + id value = [instance valueForKey:map[key].name]; + [aCoder encodeObject:value forKey:key]; + } +} + ++ (void)decodeWithCoder:(NSCoder *)aCoder + map:(NSDictionary *)map + instance:(id)instance { + for (NSString *key in map) { + OIDFieldMapping *mapping = map[key]; + id value = [aCoder decodeObjectOfClass:mapping.expectedType forKey:key]; + [instance setValue:value forKey:mapping.name]; + } +} + ++ (NSSet *)JSONTypes { + return [NSSet setWithArray:@[ + [NSDictionary class], + [NSArray class], + [NSString class], + [NSNumber class] + ]]; +} + ++ (OIDFieldMappingConversionFunction)URLConversion { + return ^id _Nullable(NSObject *_Nullable value) { + if ([value isKindOfClass:[NSString class]]) { + return [NSURL URLWithString:(NSString *)value]; + } + return value; + }; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDGrantTypes.h b/Paco-iOS/Pods/AppAuth/Source/OIDGrantTypes.h new file mode 100644 index 000000000..6e6500473 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDGrantTypes.h @@ -0,0 +1,40 @@ +/*! @file OIDGrantTypes.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +/*! @brief For exchanging an authorization code for an access token. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +extern NSString *const OIDGrantTypeAuthorizationCode; + +/*! @brief For refreshing an access token with a refresh token. + @see https://tools.ietf.org/html/rfc6749#section-6 + */ +extern NSString *const OIDGrantTypeRefreshToken; + +/*! @brief For obtaining an access token with a username and password. + @see https://tools.ietf.org/html/rfc6749#section-4.3.2 + */ +extern NSString *const OIDGrantTypePassword; + +/*! @brief For obtaining an access token from the token endpoint using client credentials. + @see https://tools.ietf.org/html/rfc6749#section-3.2.1 + @see https://tools.ietf.org/html/rfc6749#section-4.4.2 + */ +extern NSString *const OIDGrantTypeClientCredentials; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDGrantTypes.m b/Paco-iOS/Pods/AppAuth/Source/OIDGrantTypes.m new file mode 100644 index 000000000..2b1934370 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDGrantTypes.m @@ -0,0 +1,27 @@ +/*! @file OIDGrantTypes.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDGrantTypes.h" + +NSString *const OIDGrantTypeAuthorizationCode = @"authorization_code"; + +NSString *const OIDGrantTypeRefreshToken = @"refresh_token"; + +NSString *const OIDGrantTypePassword = @"password"; + +NSString *const OIDGrantTypeClientCredentials = @"client_credentials"; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDResponseTypes.h b/Paco-iOS/Pods/AppAuth/Source/OIDResponseTypes.h new file mode 100644 index 000000000..405ef9381 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDResponseTypes.h @@ -0,0 +1,31 @@ +/*! @file OIDResponseTypes.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +/*! @brief A constant for the standard OAuth2 Response Type of 'code'. + */ +extern NSString *const OIDResponseTypeCode; + +/*! @brief A constant for the standard OAuth2 Response Type of 'token'. + */ +extern NSString *const OIDResponseTypeToken; + +/*! @brief A constant for the standard OAuth2 Response Type of 'id_token'. + */ +extern NSString *const OIDResponseTypeIDToken; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDResponseTypes.m b/Paco-iOS/Pods/AppAuth/Source/OIDResponseTypes.m new file mode 100644 index 000000000..78eaf187e --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDResponseTypes.m @@ -0,0 +1,25 @@ +/*! @file OIDResponseTypes.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDResponseTypes.h" + +NSString *const OIDResponseTypeCode = @"code"; + +NSString *const OIDResponseTypeToken = @"token"; + +NSString *const OIDResponseTypeIDToken = @"id_token"; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDScopeUtilities.h b/Paco-iOS/Pods/AppAuth/Source/OIDScopeUtilities.h new file mode 100644 index 000000000..c0a5190cb --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDScopeUtilities.h @@ -0,0 +1,48 @@ +/*! @file OIDScopeUtilities.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides convenience methods for dealing with scope strings. + */ +@interface OIDScopeUtilities : NSObject + +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Converts an array of scope strings to a single scope string per the OAuth 2 spec. + @param scopes An array of scope strings. + @return A space-delimited string of scopes. + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ ++ (NSString *)scopesWithArray:(NSArray *)scopes; + +/*! @brief Converts an OAuth 2 spec-compliant scope string to an array of scopes. + @param scopes An OAuth 2 spec-compliant scope string. + @return An array of scope strings. + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ ++ (NSArray *)scopesArrayWithString:(NSString *)scopes; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDScopeUtilities.m b/Paco-iOS/Pods/AppAuth/Source/OIDScopeUtilities.m new file mode 100644 index 000000000..a0bcb8c85 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDScopeUtilities.m @@ -0,0 +1,58 @@ +/*! @file OIDScopeUtilities.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDScopeUtilities.h" + +@implementation OIDScopeUtilities + +/*! @brief A character set with the characters NOT allowed in a scope name. + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ ++ (NSCharacterSet *)disallowedScopeCharacters { + static NSCharacterSet *disallowedCharacters; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSMutableCharacterSet *allowedCharacters; + allowedCharacters = + [NSMutableCharacterSet characterSetWithRange:NSMakeRange(0x23, 0x5B - 0x23 + 1)]; + [allowedCharacters addCharactersInRange:NSMakeRange(0x5D, 0x7E - 0x5D + 1)]; + [allowedCharacters addCharactersInString:@"\x21"]; + disallowedCharacters = [allowedCharacters invertedSet]; + }); + return disallowedCharacters; +} + ++ (NSString *)scopesWithArray:(NSArray *)scopes { +#if !defined(NS_BLOCK_ASSERTIONS) + NSCharacterSet *disallowedCharacters = [self disallowedScopeCharacters]; + for (NSString *scope in scopes) { + NSAssert(scope.length, @"Found illegal empty scope string."); + NSAssert([scope rangeOfCharacterFromSet:disallowedCharacters].location == NSNotFound, + @"Found illegal character in scope string."); + } +#endif // !defined(NS_BLOCK_ASSERTIONS) + + NSString *scopeString = [scopes componentsJoinedByString:@" "]; + return scopeString; +} + ++ (NSArray *)scopesArrayWithString:(NSString *)scopes { + return [scopes componentsSeparatedByString:@" "]; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDScopes.h b/Paco-iOS/Pods/AppAuth/Source/OIDScopes.h new file mode 100644 index 000000000..da8bb189f --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDScopes.h @@ -0,0 +1,46 @@ +/*! @file OIDScopes.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +/*! @brief Scope that indicates this request is an OpenID Connect request. + @see http://openid.net/specs/openid-connect-core-1_0.html#AuthRequestValidation + */ +extern NSString *const OIDScopeOpenID; + +/*! @brief This scope value requests access to the End-User's default profile Claims, which are: + name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, + website, gender, birthdate, zoneinfo, locale, and updated_at. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopeProfile; + +/*! @brief This scope value requests access to the email and email_verified Claims. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopeEmail; + +/*! @brief This scope value requests access to the address Claim. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopeAddress; + +/*! @brief This scope value requests access to the phone_number and phone_number_verified Claims. + @see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims + */ +extern NSString *const OIDScopePhone; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDScopes.m b/Paco-iOS/Pods/AppAuth/Source/OIDScopes.m new file mode 100644 index 000000000..62dd707ec --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDScopes.m @@ -0,0 +1,29 @@ +/*! @file OIDScopes.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDScopes.h" + +NSString *const OIDScopeOpenID = @"openid"; + +NSString *const OIDScopeProfile = @"profile"; + +NSString *const OIDScopeEmail = @"email"; + +NSString *const OIDScopeAddress = @"address"; + +NSString *const OIDScopePhone = @"phone"; diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDServiceConfiguration.h b/Paco-iOS/Pods/AppAuth/Source/OIDServiceConfiguration.h new file mode 100644 index 000000000..0d823b27c --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDServiceConfiguration.h @@ -0,0 +1,68 @@ +/*! @file OIDServiceConfiguration.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDServiceConfiguration; +@class OIDServiceDiscovery; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The type of block called when a @c OIDServiceConfiguration has been created + by loading a @c OIDServiceDiscovery from an @c NSURL. + */ +typedef void (^OIDServiceConfigurationCreated) + (OIDServiceConfiguration *_Nullable serviceConfiguration, + NSError *_Nullable error); + +/*! @brief Represents the information needed to construct a @c OIDAuthorizationService. + */ +@interface OIDServiceConfiguration : NSObject + +/*! @brief The authorization endpoint URI. + */ +@property(nonatomic, readonly) NSURL *authorizationEndpoint; + +/*! @brief The token exchange and refresh endpoint URI. + */ +@property(nonatomic, readonly) NSURL *tokenEndpoint; + +/*! @brief The discovery document. + */ +@property(nonatomic, readonly, nullable) OIDServiceDiscovery *discoveryDocument; + +/*! @internal + @brief Unavailable. Please use @c initWithAuthorizationEndpoint:tokenEndpoint: or + @c initWithDiscoveryDocument:. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @param authorizationEndpoint The authorization endpoint URI. + @param tokenEndpoint The token exchange and refresh endpoint URI. + */ +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint; + +/*! @param discoveryDocument The discovery document from which to extract the required OAuth + configuration. + */ +- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *)discoveryDocument; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDServiceConfiguration.m b/Paco-iOS/Pods/AppAuth/Source/OIDServiceConfiguration.m new file mode 100644 index 000000000..13530bb66 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDServiceConfiguration.m @@ -0,0 +1,132 @@ +/*! @file OIDServiceConfiguration.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDServiceConfiguration.h" + +#import "OIDDefines.h" +#import "OIDErrorUtilities.h" +#import "OIDServiceDiscovery.h" + +/*! @brief The key for the @c authorizationEndpoint property. + */ +static NSString *const kAuthorizationEndpointKey = @"authorizationEndpoint"; + +/*! @brief The key for the @c tokenEndpoint property. + */ +static NSString *const kTokenEndpointKey = @"tokenEndpoint"; + +/*! @brief The key for the @c discoveryDocument property. + */ +static NSString *const kDiscoveryDocumentKey = @"discoveryDocument"; + +NS_ASSUME_NONNULL_BEGIN + +@interface OIDServiceConfiguration () + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + discoveryDocument:(nullable OIDServiceDiscovery *)discoveryDocument + NS_DESIGNATED_INITIALIZER; + +@end + +@implementation OIDServiceConfiguration + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithAuthorizationEndpoint:tokenEndpoint:)); + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint + discoveryDocument:(nullable OIDServiceDiscovery *)discoveryDocument { + + self = [super init]; + if (self) { + _authorizationEndpoint = [authorizationEndpoint copy]; + _tokenEndpoint = [tokenEndpoint copy]; + _discoveryDocument = [discoveryDocument copy]; + } + return self; +} + +- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint + tokenEndpoint:(NSURL *)tokenEndpoint { + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + discoveryDocument:nil]; +} + +- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *) discoveryDocument { + return [self initWithAuthorizationEndpoint:discoveryDocument.authorizationEndpoint + tokenEndpoint:discoveryDocument.tokenEndpoint + discoveryDocument:discoveryDocument]; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSURL *authorizationEndpoint = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kAuthorizationEndpointKey]; + NSURL *tokenEndpoint = [aDecoder decodeObjectOfClass:[NSURL class] + forKey:kTokenEndpointKey]; + // We don't accept nil authorizationEndpoints or tokenEndpoints. + if (!authorizationEndpoint || !tokenEndpoint) { + return nil; + } + + OIDServiceDiscovery *discoveryDocument = [aDecoder decodeObjectOfClass:[OIDServiceDiscovery class] + forKey:kDiscoveryDocumentKey]; + + return [self initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint + discoveryDocument:discoveryDocument]; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_authorizationEndpoint forKey:kAuthorizationEndpointKey]; + [aCoder encodeObject:_tokenEndpoint forKey:kTokenEndpointKey]; + [aCoder encodeObject:_discoveryDocument forKey:kDiscoveryDocumentKey]; +} + +#pragma mark - description + +- (NSString *)description { + return [NSString stringWithFormat: + @"OIDServiceConfiguration authorizationEndpoint: %@, tokenEndpoint: %@, " + "discoveryDocument: [%@]", + _authorizationEndpoint, + _tokenEndpoint, + _discoveryDocument]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDServiceDiscovery.h b/Paco-iOS/Pods/AppAuth/Source/OIDServiceDiscovery.h new file mode 100644 index 000000000..d0dbad207 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDServiceDiscovery.h @@ -0,0 +1,352 @@ +/*! @file OIDServiceDiscovery.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents an OpenID Connect 1.0 Discovery Document + @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +@interface OIDServiceDiscovery : NSObject + +/*! @brief The decoded OpenID Connect 1.0 Discovery Document as a dictionary. + */ +@property(nonatomic, readonly) NSDictionary *discoveryDictionary; + +/*! @brief REQUIRED. URL using the @c https scheme with no query or fragment component that the OP + asserts as its Issuer Identifier. If Issuer discovery is supported, this value MUST be + identical to the issuer value returned by WebFinger. This also MUST be identical to the + @c iss Claim value in ID Tokens issued from this Issuer. + @remarks issuer + @seealso https://openid.net/specs/openid-connect-discovery-1_0.html#IssuerDiscovery + */ +@property(nonatomic, readonly) NSURL *issuer; + +/*! @brief REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint. + @remarks authorization_endpoint + @seealso http://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint + */ +@property(nonatomic, readonly) NSURL *authorizationEndpoint; + +/*! @brief URL of the OP's OAuth 2.0 Token Endpoint. This is REQUIRED unless only the Implicit Flow + is used. + @remarks token_endpoint + @seealso http://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint + */ +@property(nonatomic, readonly) NSURL *tokenEndpoint; + +/*! @brief RECOMMENDED. URL of the OP's UserInfo Endpoint. This URL MUST use the https scheme and + MAY contain port, path, and query parameter components. + @remarks userinfo_endpoint + @seealso http://openid.net/specs/openid-connect-core-1_0.html#UserInfo + */ +@property(nonatomic, readonly, nullable) NSURL *userinfoEndpoint; + +/*! @brief REQUIRED. URL of the OP's JSON Web Key Set document. This contains the signing key(s) the + RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's + encryption key(s), which are used by RPs to encrypt requests to the Server. When both + signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED + for all keys in the referenced JWK Set to indicate each key's intended usage. Although some + algorithms allow the same key to be used for both signatures and encryption, doing so is NOT + RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 + representations of keys provided. When used, the bare key values MUST still be present and + MUST match those in the certificate. + @remarks jwks_uri + @seealso http://tools.ietf.org/html/rfc7517 + */ +@property(nonatomic, readonly) NSURL *jwksURL; + +/*! @brief RECOMMENDED. URL of the OP's Dynamic Client Registration Endpoint. + @remarks registration_endpoint + @seealso http://openid.net/specs/openid-connect-registration-1_0.html + */ +@property(nonatomic, readonly, nullable) NSURL *registrationEndpoint; + +/*! @brief RECOMMENDED. JSON array containing a list of the OAuth 2.0 [RFC6749] scope values that + this server supports. The server MUST support the openid scope value. Servers MAY choose not + to advertise some supported scope values even when this parameter is used, although those + defined in [OpenID.Core] SHOULD be listed, if supported. + @remarks scopes_supported + @seealso http://tools.ietf.org/html/rfc6749#section-3.3 + */ +@property(nonatomic, readonly, nullable) NSArray *scopesSupported; + +/*! @brief REQUIRED. JSON array containing a list of the OAuth 2.0 @c response_type values that this + OP supports. Dynamic OpenID Providers MUST support the @c code, @c id_token, and the token + @c id_token Response Type values. + @remarks response_types_supported + */ +@property(nonatomic, readonly) NSArray *responseTypesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the OAuth 2.0 @c response_mode values that this + OP supports, as specified in OAuth 2.0 Multiple Response Type Encoding Practices. If + omitted, the default for Dynamic OpenID Providers is @c ["query", "fragment"]. + @remarks response_modes_supported + @seealso http://openid.net/specs/oauth-v2-multiple-response-types-1_0.html + */ +@property(nonatomic, readonly, nullable) NSArray *responseModesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the OAuth 2.0 Grant Type values that this OP + supports. Dynamic OpenID Providers MUST support the @c authorization_code and @c implicit + Grant Type values and MAY support other Grant Types. If omitted, the default value is + @c ["authorization_code", "implicit"]. + @remarks grant_types_supported + */ +@property(nonatomic, readonly, nullable) NSArray *grantTypesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the Authentication Context Class References + that this OP supports. + @remarks acr_values_supported + */ +@property(nonatomic, readonly, nullable) NSArray *acrValuesSupported; + +/*! @brief REQUIRED. JSON array containing a list of the Subject Identifier types that this OP + supports. Valid types include @c pairwise and @c public. + @remarks subject_types_supported + */ +@property(nonatomic, readonly) NSArray *subjectTypesSupported; + +/*! @brief REQUIRED. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the OP for the ID Token to encode the Claims in a JWT. The algorithm @c RS256 + MUST be included. The value @c none MAY be supported, but MUST NOT be used unless the + Response Type used returns no ID Token from the Authorization Endpoint (such as when using + the Authorization Code Flow). + @remarks id_token_signing_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly) NSArray *IDTokenSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c alg values) + supported by the OP for the ID Token to encode the Claims in a JWT. + @remarks id_token_encryption_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *IDTokenEncryptionAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c enc values) + supported by the OP for the ID Token to encode the Claims in a JWT. + @remarks id_token_encryption_enc_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *IDTokenEncryptionEncodingValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the UserInfo Endpoint to encode the Claims in a JWT. The value none MAY be + included. + @remarks userinfo_signing_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7515 + @seealso https://tools.ietf.org/html/rfc7518 + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *userinfoSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (alg values) + supported by the UserInfo Endpoint to encode the Claims in a JWT. + @remarks userinfo_encryption_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7516 + @seealso https://tools.ietf.org/html/rfc7518 + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *userinfoEncryptionAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c enc values) + supported by the UserInfo Endpoint to encode the Claims in a JWT. + @remarks userinfo_encryption_enc_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *userinfoEncryptionEncodingValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the OP for Request Objects, which are described in Section 6.1 of OpenID + Connect Core 1.0. These algorithms are used both when the Request Object is passed by value + (using the request parameter) and when it is passed by reference (using the @c request_uri + parameter). Servers SHOULD support @c none and @c RS256. + @remarks request_object_signing_alg_values_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + */ +@property(nonatomic, readonly, nullable) + NSArray *requestObjectSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c alg values) + supported by the OP for Request Objects. These algorithms are used both when the Request + Object is passed by value and when it is passed by reference. + @remarks request_object_encryption_alg_values_supported + */ +@property(nonatomic, readonly, nullable) + NSArray *requestObjectEncryptionAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWE encryption algorithms (@c enc values) + supported by the OP for Request Objects. These algorithms are used both when the Request + Object is passed by value and when it is passed by reference. + @remarks request_object_encryption_enc_values_supported + */ +@property(nonatomic, readonly, nullable) + NSArray *requestObjectEncryptionEncodingValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of Client Authentication methods supported by this + Token Endpoint. The options are @c client_secret_post, @c client_secret_basic, + @c client_secret_jwt, and @c private_key_jwt, as described in Section 9 of OpenID Connect + Core 1.0. Other authentication methods MAY be defined by extensions. If omitted, the default + is @c client_secret_basic -- the HTTP Basic Authentication Scheme specified in Section 2.3.1 + of OAuth 2.0. + @remarks token_endpoint_auth_methods_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + @seealso http://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +@property(nonatomic, readonly, nullable) NSArray *tokenEndpointAuthMethodsSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the JWS signing algorithms (@c alg values) + supported by the Token Endpoint for the signature on the JWT used to authenticate the Client + at the Token Endpoint for the @c private_key_jwt and @c client_secret_jwt authentication + methods. Servers SHOULD support @c RS256. The value @c none MUST NOT be used. + @remarks token_endpoint_auth_signing_alg_values_supported + @seealso https://tools.ietf.org/html/rfc7519 + */ +@property(nonatomic, readonly, nullable) + NSArray *tokenEndpointAuthSigningAlgorithmValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the @c display parameter values that the OpenID + Provider supports. These values are described in Section 3.1.2.1 of OpenID Connect Core 1.0. + @remarks display_values_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + */ +@property(nonatomic, readonly, nullable) NSArray *displayValuesSupported; + +/*! @brief OPTIONAL. JSON array containing a list of the Claim Types that the OpenID Provider + supports. These Claim Types are described in Section 5.6 of OpenID Connect Core 1.0. Values + defined by this specification are @c normal, @c aggregated, and @c distributed. If omitted, + the implementation supports only @c normal Claims. + @remarks claim_types_supported + @seealso http://openid.net/specs/openid-connect-core-1_0.html + */ +@property(nonatomic, readonly, nullable) NSArray *claimTypesSupported; + +/*! @brief RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the + OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, + this might not be an exhaustive list. + @remarks claims_supported + */ +@property(nonatomic, readonly, nullable) NSArray *claimsSupported; + +/*! @brief OPTIONAL. URL of a page containing human-readable information that developers might want + or need to know when using the OpenID Provider. In particular, if the OpenID Provider does + not support Dynamic Client Registration, then information on how to register Clients needs + to be provided in this documentation. + @remarks service_documentation + */ +@property(nonatomic, readonly, nullable) NSURL *serviceDocumentation; + +/*! @brief OPTIONAL. Languages and scripts supported for values in Claims being returned, + represented as a JSON array of BCP47 language tag values. Not all languages and scripts are + necessarily supported for all Claim values. + @remarks claims_locales_supported + @seealso http://tools.ietf.org/html/rfc5646 + */ +@property(nonatomic, readonly, nullable) NSArray *claimsLocalesSupported; + +/*! @brief OPTIONAL. Languages and scripts supported for the user interface, represented as a JSON + array of BCP47 language tag values. + @remarks ui_locales_supported + @seealso http://tools.ietf.org/html/rfc5646 + */ +@property(nonatomic, readonly, nullable) NSArray *UILocalesSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP supports use of the claims parameter, + with @c true indicating support. If omitted, the default value is @c false. + @remarks claims_parameter_supported + */ +@property(nonatomic, readonly) BOOL claimsParameterSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP supports use of the request parameter, + with @c true indicating support. If omitted, the default value is @c false. + @remarks request_parameter_supported + */ +@property(nonatomic, readonly) BOOL requestParameterSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP supports use of the @c request_uri + parameter, with true indicating support. If omitted, the default value is @c true. + @remarks request_uri_parameter_supported + */ +@property(nonatomic, readonly) BOOL requestURIParameterSupported; + +/*! @brief OPTIONAL. Boolean value specifying whether the OP requires any @c request_uri values used + to be pre-registered using the @c request_uris registration parameter. Pre-registration is + REQUIRED when the value is @c true. If omitted, the default value is @c false. + @remarks require_request_uri_registration + */ +@property(nonatomic, readonly) BOOL requireRequestURIRegistration; + +/*! @brief OPTIONAL. URL that the OpenID Provider provides to the person registering the Client to + read about the OP's requirements on how the Relying Party can use the data provided by the + OP. The registration process SHOULD display this URL to the person registering the Client if + it is given. + @remarks op_policy_uri + */ +@property(nonatomic, readonly, nullable) NSURL *OPPolicyURI; + +/*! @brief OPTIONAL. URL that the OpenID Provider provides to the person registering the Client to + read about OpenID Provider's terms of service. The registration process SHOULD display this + URL to the person registering the Client if it is given. + @remarks op_tos_uri + */ +@property(nonatomic, readonly, nullable) NSURL *OPTosURI; + +/*! @internal + @brief Unavailable. Please use @c initWithDictionary:error:, @c initWithJSON:error, or the + @c serviceDiscoveryWithURL:callback: factory method. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief Decodes a OpenID Connect Discovery 1.0 JSON document. + @param serviceDiscoveryJSON An OpenID Connect Service Discovery document. + @param error If a required field is missing from the dictionary, an error with domain + @c ::OIDGeneralErrorDomain and code @c ::OIDErrorCodeInvalidDiscoveryDocument will be + returned. + */ +- (nullable instancetype)initWithJSON:(NSString *)serviceDiscoveryJSON + error:(NSError **_Nullable)error; + +/*! @brief Decodes a OpenID Connect Discovery 1.0 JSON document. + @param serviceDiscoveryJSONData An OpenID Connect Service Discovery document. + @param error If a required field is missing from the dictionary, an error with domain + @c ::OIDGeneralErrorDomain and code @c ::OIDErrorCodeInvalidDiscoveryDocument will be + returned. + */ +- (nullable instancetype)initWithJSONData:(NSData *)serviceDiscoveryJSONData + error:(NSError **_Nullable)error; + +/*! @brief Designated initializer. The dictionary keys should match the keys defined in the OpenID + Connect Discovery 1.0 standard for OpenID Provider Metadata. + @param serviceDiscoveryDictionary A dictionary representing an OpenID Connect Service Discovery + document. + @param error If a required field is missing from the dictionary, an error with domain + @c ::OIDGeneralErrorDomain and code @c ::OIDErrorCodeInvalidDiscoveryDocument will be + returned. + */ +- (nullable instancetype)initWithDictionary:(NSDictionary *)serviceDiscoveryDictionary + error:(NSError **_Nullable)error NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDServiceDiscovery.m b/Paco-iOS/Pods/AppAuth/Source/OIDServiceDiscovery.m new file mode 100644 index 000000000..4159327b8 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDServiceDiscovery.m @@ -0,0 +1,350 @@ +/*! @file OIDServiceDiscovery.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDServiceDiscovery.h" + +#import "OIDDefines.h" +#import "OIDErrorUtilities.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! Field keys associated with an OpenID Connect Discovery Document. */ +static NSString *const kIssuerKey = @"issuer"; +static NSString *const kAuthorizationEndpointKey = @"authorization_endpoint"; +static NSString *const kTokenEndpointKey = @"token_endpoint"; +static NSString *const kUserinfoEndpointKey = @"userinfo_endpoint"; +static NSString *const kJWKSURLKey = @"jwks_uri"; +static NSString *const kRegistrationEndpointKey = @"registration_endpoint"; +static NSString *const kScopesSupportedKey = @"scopes_supported"; +static NSString *const kResponseTypesSupportedKey = @"response_types_supported"; +static NSString *const kResponseModesSupportedKey = @"response_modes_supported"; +static NSString *const kGrantTypesSupportedKey = @"grant_types_supported"; +static NSString *const kACRValuesSupportedKey = @"acr_values_supported"; +static NSString *const kSubjectTypesSupportedKey = @"subject_types_supported"; +static NSString *const kIDTokenSigningAlgorithmValuesSupportedKey = + @"id_token_signing_alg_values_supported"; +static NSString *const kIDTokenEncryptionAlgorithmValuesSupportedKey = + @"id_token_encryption_alg_values_supported"; +static NSString *const kIDTokenEncryptionEncodingValuesSupportedKey = + @"id_token_encryption_enc_values_supported"; +static NSString *const kUserinfoSigningAlgorithmValuesSupportedKey = + @"userinfo_signing_alg_values_supported"; +static NSString *const kUserinfoEncryptionAlgorithmValuesSupportedKey = + @"userinfo_encryption_alg_values_supported"; +static NSString *const kUserinfoEncryptionEncodingValuesSupportedKey = + @"userinfo_encryption_enc_values_supported"; +static NSString *const kRequestObjectSigningAlgorithmValuesSupportedKey = + @"request_object_signing_alg_values_supported"; +static NSString *const kRequestObjectEncryptionAlgorithmValuesSupportedKey = + @"request_object_encryption_alg_values_supported"; +static NSString *const kRequestObjectEncryptionEncodingValuesSupported = + @"request_object_encryption_enc_values_supported"; +static NSString *const kTokenEndpointAuthMethodsSupportedKey = + @"token_endpoint_auth_methods_supported"; +static NSString *const kTokenEndpointAuthSigningAlgorithmValuesSupportedKey = + @"token_endpoint_auth_signing_alg_values_supported"; +static NSString *const kDisplayValuesSupportedKey = @"display_values_supported"; +static NSString *const kClaimTypesSupportedKey = @"claim_types_supported"; +static NSString *const kClaimsSupportedKey = @"claims_supported"; +static NSString *const kServiceDocumentationKey = @"service_documentation"; +static NSString *const kClaimsLocalesSupportedKey = @"claims_locales_supported"; +static NSString *const kUILocalesSupportedKey = @"ui_locales_supported"; +static NSString *const kClaimsParameterSupportedKey = @"claims_parameter_supported"; +static NSString *const kRequestParameterSupportedKey = @"request_parameter_supported"; +static NSString *const kRequestURIParameterSupportedKey = @"request_uri_parameter_supported"; +static NSString *const kRequireRequestURIRegistrationKey = @"require_request_uri_registration"; +static NSString *const kOPPolicyURIKey = @"op_policy_uri"; +static NSString *const kOPTosURIKey = @"op_tos_uri"; + +@implementation OIDServiceDiscovery { + NSDictionary *_discoveryDictionary; +} + +- (nullable instancetype)init OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithDictionary:error:)); + +- (nullable instancetype)initWithJSON:(NSString *)serviceDiscoveryJSON error:(NSError **)error { + NSData *jsonData = [serviceDiscoveryJSON dataUsingEncoding:NSUTF8StringEncoding]; + return [self initWithJSONData:jsonData error:error]; +} + +- (nullable instancetype)initWithJSONData:(NSData *)serviceDiscoveryJSONData + error:(NSError **_Nullable)error { + NSError *jsonError; + NSDictionary *json = + [NSJSONSerialization JSONObjectWithData:serviceDiscoveryJSONData options:0 error:&jsonError]; + if (!json || jsonError) { + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeJSONDeserializationError + underlyingError:jsonError + description:nil]; + return nil; + } + return [self initWithDictionary:json error:error]; +} + +- (nullable instancetype)initWithDictionary:(NSDictionary *)serviceDiscoveryDictionary + error:(NSError **_Nullable)error { + if (![[self class] dictionaryHasRequiredFields:serviceDiscoveryDictionary error:error]) { + return nil; + } + self = [super init]; + if (self) { + _discoveryDictionary = [serviceDiscoveryDictionary copy]; + } + return self; +} + +#pragma mark - + +/*! @brief Checks to see if the specified dictionary contains the required fields. + @discussion This test is not meant to provide semantic analysis of the document (eg. fields + where the value @c none is not an allowed option would not cause this method to fail if + their value was @c none.) We are just testing to make sure we can meet the nullability + contract we promised in the header. + */ ++ (BOOL)dictionaryHasRequiredFields:(NSDictionary *)dictionary + error:(NSError **_Nullable)error { + static NSString *const kMissingFieldErrorText = @"Missing field: %@"; + static NSString *const kInvalidURLFieldErrorText = @"Invalid URL: %@"; + + NSArray *requiredFields = @[ + kIssuerKey, + kAuthorizationEndpointKey, + kTokenEndpointKey, + kJWKSURLKey, + kResponseTypesSupportedKey, + kSubjectTypesSupportedKey, + kIDTokenSigningAlgorithmValuesSupportedKey + ]; + + for (NSString *field in requiredFields) { + if (!dictionary[field]) { + if (error) { + NSString *errorText = [NSString stringWithFormat:kMissingFieldErrorText, field]; + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeInvalidDiscoveryDocument + underlyingError:nil + description:errorText]; + } + return NO; + } + } + + // Check required URL fields are valid URLs. + NSArray *requiredURLFields = @[ + kIssuerKey, + kTokenEndpointKey, + kJWKSURLKey + ]; + + for (NSString *field in requiredURLFields) { + if (![NSURL URLWithString:dictionary[field]]) { + if (error) { + NSString *errorText = [NSString stringWithFormat:kInvalidURLFieldErrorText, field]; + *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeInvalidDiscoveryDocument + underlyingError:nil + description:errorText]; + } + return NO; + } + } + + return YES; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + NSError *error; + NSDictionary *dictionary = [[NSDictionary alloc] initWithCoder:aDecoder]; + self = [self initWithDictionary:dictionary error:&error]; + if (error) { + return nil; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [_discoveryDictionary encodeWithCoder:aCoder]; +} + +#pragma mark - Properties + +- (NSDictionary *)discoveryDictionary { + return _discoveryDictionary; +} + +- (NSURL *)issuer { + return [NSURL URLWithString:_discoveryDictionary[kIssuerKey]]; +} + +- (NSURL *)authorizationEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kAuthorizationEndpointKey]]; +} + +- (NSURL *)tokenEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kTokenEndpointKey]]; +} + +- (nullable NSURL *)userinfoEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kUserinfoEndpointKey]]; +} + +- (NSURL *)jwksURL { + return [NSURL URLWithString:_discoveryDictionary[kJWKSURLKey]]; +} + +- (nullable NSURL *)registrationEndpoint { + return [NSURL URLWithString:_discoveryDictionary[kRegistrationEndpointKey]]; +} + +- (nullable NSArray *)scopesSupported { + return _discoveryDictionary[kScopesSupportedKey]; +} + +- (NSArray *)responseTypesSupported { + return _discoveryDictionary[kResponseTypesSupportedKey]; +} + +- (nullable NSArray *)responseModesSupported { + return _discoveryDictionary[kResponseModesSupportedKey]; +} + +- (nullable NSArray *)grantTypesSupported { + return _discoveryDictionary[kGrantTypesSupportedKey]; +} + +- (nullable NSArray *)acrValuesSupported { + return _discoveryDictionary[kACRValuesSupportedKey]; +} + +- (NSArray *)subjectTypesSupported { + return _discoveryDictionary[kSubjectTypesSupportedKey]; +} + +- (NSArray *) IDTokenSigningAlgorithmValuesSupported { + return _discoveryDictionary[kIDTokenSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)IDTokenEncryptionAlgorithmValuesSupported { + return _discoveryDictionary[kIDTokenEncryptionAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)IDTokenEncryptionEncodingValuesSupported { + return _discoveryDictionary[kIDTokenEncryptionEncodingValuesSupportedKey]; +} + +- (nullable NSArray *)userinfoSigningAlgorithmValuesSupported { + return _discoveryDictionary[kUserinfoSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)userinfoEncryptionAlgorithmValuesSupported { + return _discoveryDictionary[kUserinfoEncryptionAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)userinfoEncryptionEncodingValuesSupported { + return _discoveryDictionary[kUserinfoEncryptionEncodingValuesSupportedKey]; +} + +- (nullable NSArray *)requestObjectSigningAlgorithmValuesSupported { + return _discoveryDictionary[kRequestObjectSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *) requestObjectEncryptionAlgorithmValuesSupported { + return _discoveryDictionary[kRequestObjectEncryptionAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *) requestObjectEncryptionEncodingValuesSupported { + return _discoveryDictionary[kRequestObjectEncryptionEncodingValuesSupported]; +} + +- (nullable NSArray *)tokenEndpointAuthMethodsSupported { + return _discoveryDictionary[kTokenEndpointAuthMethodsSupportedKey]; +} + +- (nullable NSArray *)tokenEndpointAuthSigningAlgorithmValuesSupported { + return _discoveryDictionary[kTokenEndpointAuthSigningAlgorithmValuesSupportedKey]; +} + +- (nullable NSArray *)displayValuesSupported { + return _discoveryDictionary[kDisplayValuesSupportedKey]; +} + +- (nullable NSArray *)claimTypesSupported { + return _discoveryDictionary[kClaimTypesSupportedKey]; +} + +- (nullable NSArray *)claimsSupported { + return _discoveryDictionary[kClaimsSupportedKey]; +} + +- (nullable NSURL *)serviceDocumentation { + return [NSURL URLWithString:_discoveryDictionary[kServiceDocumentationKey]]; +} + +- (nullable NSArray *)claimsLocalesSupported { + return _discoveryDictionary[kClaimsLocalesSupportedKey]; +} + +- (nullable NSArray *)UILocalesSupported { + return _discoveryDictionary[kUILocalesSupportedKey]; +} + +- (BOOL)claimsParameterSupported { + return [_discoveryDictionary[kClaimsParameterSupportedKey] boolValue]; +} + +- (BOOL)requestParameterSupported { + return [_discoveryDictionary[kRequestParameterSupportedKey] boolValue]; +} + +- (BOOL)requestURIParameterSupported { + // Default is true/YES. + if (!_discoveryDictionary[kRequestURIParameterSupportedKey]) { + return YES; + } + return [_discoveryDictionary[kRequestURIParameterSupportedKey] boolValue]; +} + +- (BOOL)requireRequestURIRegistration { + return [_discoveryDictionary[kRequireRequestURIRegistrationKey] boolValue]; +} + +- (nullable NSURL *)OPPolicyURI { + return [NSURL URLWithString:_discoveryDictionary[kOPPolicyURIKey]]; +} + +- (nullable NSURL *)OPTosURI { + return [NSURL URLWithString:_discoveryDictionary[kOPTosURIKey]]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDTokenRequest.h b/Paco-iOS/Pods/AppAuth/Source/OIDTokenRequest.h new file mode 100644 index 000000000..c252b99a2 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDTokenRequest.h @@ -0,0 +1,158 @@ +/*! @file OIDTokenRequest.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +// This file only declares string constants useful for constructing a @c OIDTokenRequest, so it is +// imported here for convenience. +#import "OIDGrantTypes.h" + +@class OIDAuthorizationResponse; +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents a token request. + @see https://tools.ietf.org/html/rfc6749#section-3.2 + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@interface OIDTokenRequest : NSObject + +/*! @brief The service's configuration. + @remarks This configuration specifies how to connect to a particular OAuth provider. + Configurations may be created manually, or via an OpenID Connect Discovery Document. + */ +@property(nonatomic, readonly) OIDServiceConfiguration *configuration; + +/*! @brief The type of token being sent to the token endpoint, i.e. "authorization_code" for the + authorization code exchange, or "refresh_token" for an access token refresh request. + @remarks grant_type + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + @see https://www.google.com/url?sa=D&q=https%3A%2F%2Ftools.ietf.org%2Fhtml%2Frfc6749%23section-6 + */ +@property(nonatomic, readonly) NSString *grantType; + +/*! @brief The authorization code received from the authorization server. + @remarks code + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@property(nonatomic, readonly, nullable) NSString *authorizationCode; + +/*! @brief The client's redirect URI. + @remarks redirect_uri + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@property(nonatomic, readonly) NSURL *redirectURL; + +/*! @brief The client identifier. + @remarks client_id + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@property(nonatomic, readonly) NSString *clientID; + +/*! @brief The client secret. + @remarks client_secret + @see https://tools.ietf.org/html/rfc6749#section-2.3.1 + */ +@property(nonatomic, readonly, nullable) NSString *clientSecret; + +/*! @brief The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-3.3 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief The refresh token, which can be used to obtain new access tokens using the same + authorization grant. + @remarks refresh_token + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/*! @brief The PKCE code verifier used to redeem the authorization code. + @remarks code_verifier + @see https://tools.ietf.org/html/rfc7636#section-4.3 + */ +@property(nonatomic, readonly, nullable) NSString *codeVerifier; + +/*! @brief The client's additional token request parameters. + */ +@property(nonatomic, readonly, nullable) NSDictionary *additionalParameters; + +/*! @internal + @brief Unavailable. Please use + initWithConfiguration:grantType:code:redirectURL:clientID:additionalParameters:. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @param configuration The service's configuration. + @param grantType the type of token being sent to the token endpoint, i.e. "authorization_code" + for the authorization code exchange, or "refresh_token" for an access token refresh request. + @see OIDGrantTypes.h + @param code The authorization code received from the authorization server. + @param redirectURL The client's redirect URI. + @param clientID The client identifier. + @param scopes An array of scopes to combine into a single scope string per the OAuth2 spec. + @param refreshToken The refresh token. + @param additionalParameters The client's additional token request parameters. + */ +- (nullable instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters; + +/*! @brief Designated initializer. + @param configuration The service's configuration. + @param grantType the type of token being sent to the token endpoint, i.e. "authorization_code" + for the authorization code exchange, or "refresh_token" for an access token refresh request. + @see OIDGrantTypes.h + @param code The authorization code received from the authorization server. + @param redirectURL The client's redirect URI. + @param clientID The client identifier. + @param scope The value of the scope parameter is expressed as a list of space-delimited, + case-sensitive strings. + @param refreshToken The refresh token. + @param additionalParameters The client's additional token request parameters. + */ +- (nullable instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters + NS_DESIGNATED_INITIALIZER; + +/*! @brief Constructs an @c NSURLRequest representing the token request. + @return An @c NSURLRequest representing the token request. + */ +- (NSURLRequest *)URLRequest; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDTokenRequest.m b/Paco-iOS/Pods/AppAuth/Source/OIDTokenRequest.m new file mode 100644 index 000000000..8f4eb959a --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDTokenRequest.m @@ -0,0 +1,274 @@ +/*! @file OIDTokenRequest.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTokenRequest.h" + +#import "OIDDefines.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDURLQueryComponent.h" + +/*! @brief The key for the @c configuration property for @c NSSecureCoding + */ +static NSString *const kConfigurationKey = @"configuration"; + +/*! @brief Key used to encode the @c grantType property for @c NSSecureCoding + */ +static NSString *const kGrantTypeKey = @"grant_type"; + +/*! @brief The key for the @c authorizationCode property for @c NSSecureCoding. + */ +static NSString *const kAuthorizationCodeKey = @"code"; + +/*! @brief Key used to encode the @c clientID property for @c NSSecureCoding + */ +static NSString *const kClientIDKey = @"client_id"; + +/*! @brief Key used to encode the @c clientSecret property for @c NSSecureCoding + */ +static NSString *const kClientSecretKey = @"client_secret"; + +/*! @brief Key used to encode the @c redirectURL property for @c NSSecureCoding + */ +static NSString *const kRedirectURLKey = @"redirect_uri"; + +/*! @brief Key used to encode the @c scopes property for @c NSSecureCoding + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c refreshToken property for @c NSSecureCoding + */ +static NSString *const kRefreshTokenKey = @"refresh_token"; + +/*! @brief Key used to encode the @c codeVerifier property for @c NSSecureCoding and to build the + request URL. + */ +static NSString *const kCodeVerifierKey = @"code_verifier"; + +/*! @brief Key used to encode the @c additionalParameters property for + @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +@implementation OIDTokenRequest + +- (instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER( + @selector(initWithConfiguration: + grantType: + authorizationCode: + redirectURL: + clientID: + clientSecret: + scope: + refreshToken: + codeVerifier: + additionalParameters:) + ); + +- (nullable instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scopes:(nullable NSArray *)scopes + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters { + return [self initWithConfiguration:configuration + grantType:grantType + authorizationCode:code + redirectURL:redirectURL + clientID:clientID + clientSecret:clientSecret + scope:[OIDScopeUtilities scopesWithArray:scopes] + refreshToken:refreshToken + codeVerifier:(NSString *)codeVerifier + additionalParameters:additionalParameters]; +} + +- (nullable instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration + grantType:(NSString *)grantType + authorizationCode:(nullable NSString *)code + redirectURL:(NSURL *)redirectURL + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret + scope:(nullable NSString *)scope + refreshToken:(nullable NSString *)refreshToken + codeVerifier:(nullable NSString *)codeVerifier + additionalParameters:(nullable NSDictionary *)additionalParameters { + self = [super init]; + if (self) { + _configuration = [configuration copy]; + _grantType = [grantType copy]; + _authorizationCode = [code copy]; + _redirectURL = [redirectURL copy]; + _clientID = [clientID copy]; + _clientSecret = [clientSecret copy]; + _scope = [scope copy]; + _refreshToken = [refreshToken copy]; + _codeVerifier = [codeVerifier copy]; + _additionalParameters = + [[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES]; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDServiceConfiguration *configuration = + [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] + forKey:kConfigurationKey]; + NSString *grantType = [aDecoder decodeObjectOfClass:[NSString class] forKey:kGrantTypeKey]; + NSString *code = [aDecoder decodeObjectOfClass:[NSString class] forKey:kAuthorizationCodeKey]; + NSString *clientID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientIDKey]; + NSString *clientSecret = [aDecoder decodeObjectOfClass:[NSString class] forKey:kClientSecretKey]; + NSString *scope = [aDecoder decodeObjectOfClass:[NSString class] forKey:kScopeKey]; + NSString *refreshToken = [aDecoder decodeObjectOfClass:[NSString class] forKey:kRefreshTokenKey]; + NSString *codeVerifier = [aDecoder decodeObjectOfClass:[NSString class] forKey:kCodeVerifierKey]; + NSURL *redirectURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kRedirectURLKey]; + NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[ + [NSDictionary class], + [NSString class] + ]]; + NSDictionary *additionalParameters = + [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses + forKey:kAdditionalParametersKey]; + self = [self initWithConfiguration:configuration + grantType:grantType + authorizationCode:code + redirectURL:redirectURL + clientID:clientID + clientSecret:clientSecret + scope:scope + refreshToken:refreshToken + codeVerifier:codeVerifier + additionalParameters:additionalParameters]; + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_configuration forKey:kConfigurationKey]; + [aCoder encodeObject:_grantType forKey:kGrantTypeKey]; + [aCoder encodeObject:_authorizationCode forKey:kAuthorizationCodeKey]; + [aCoder encodeObject:_clientID forKey:kClientIDKey]; + [aCoder encodeObject:_clientSecret forKey:kClientSecretKey]; + [aCoder encodeObject:_redirectURL forKey:kRedirectURLKey]; + [aCoder encodeObject:_scope forKey:kScopeKey]; + [aCoder encodeObject:_refreshToken forKey:kRefreshTokenKey]; + [aCoder encodeObject:_codeVerifier forKey:kCodeVerifierKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + NSURLRequest *request = self.URLRequest; + NSString *requestBody = + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding]; + return [NSString stringWithFormat:@"<%@: %p, request: >", + NSStringFromClass([self class]), + self, + request.URL, + requestBody]; +} + +#pragma mark - + +/*! @brief Constructs the request URI. + @return A URL representing the token request. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (NSURL *)tokenRequestURL { + return _configuration.tokenEndpoint; +} + +/*! @brief Constructs the request body data by combining the request parameters using the + "application/x-www-form-urlencoded" format. + @return The data to pass to the token request URL. + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +- (NSData *)tokenRequestBody { + OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init]; + + // Add parameters, as applicable. + if (_grantType) { + [query addParameter:kGrantTypeKey value:_grantType]; + } + if (_scope) { + [query addParameter:kScopeKey value:_scope]; + } + if (_clientID) { + [query addParameter:kClientIDKey value:_clientID]; + } + if (_clientSecret) { + [query addParameter:kClientSecretKey value:_clientSecret]; + } + if (_redirectURL) { + [query addParameter:kRedirectURLKey value:_redirectURL.absoluteString]; + } + if (_refreshToken) { + [query addParameter:kRefreshTokenKey value:_refreshToken]; + } + if (_authorizationCode) { + [query addParameter:kAuthorizationCodeKey value:_authorizationCode]; + } + if (_codeVerifier) { + [query addParameter:kCodeVerifierKey value:_codeVerifier]; + } + + // Add any additional parameters the client has specified. + [query addParameters:_additionalParameters]; + + // Construct the body string: + NSString *bodyString = [query URLEncodedParameters]; + NSData *body = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; + return body; +} + +- (NSURLRequest *)URLRequest { + static NSString *const kHTTPPost = @"POST"; + static NSString *const kHTTPContentTypeHeaderKey = @"Content-Type"; + static NSString *const kHTTPContentTypeHeaderValue = + @"application/x-www-form-urlencoded; charset=UTF-8"; + + NSURL *tokenRequestURL = [self tokenRequestURL]; + NSMutableURLRequest *URLRequest = [[NSURLRequest requestWithURL:tokenRequestURL] mutableCopy]; + URLRequest.HTTPMethod = kHTTPPost; + [URLRequest setValue:kHTTPContentTypeHeaderValue forHTTPHeaderField:kHTTPContentTypeHeaderKey]; + URLRequest.HTTPBody = [self tokenRequestBody]; + return URLRequest; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDTokenResponse.h b/Paco-iOS/Pods/AppAuth/Source/OIDTokenResponse.h new file mode 100644 index 000000000..5a7cf550d --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDTokenResponse.h @@ -0,0 +1,102 @@ +/*! @file OIDTokenResponse.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDTokenRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Represents the response to an token request. + @see https://tools.ietf.org/html/rfc6749#section-3.2 + @see https://tools.ietf.org/html/rfc6749#section-4.1.3 + */ +@interface OIDTokenResponse : NSObject + +/*! @brief The request which was serviced. + */ +@property(nonatomic, readonly) OIDTokenRequest *request; + +/*! @brief The access token generated by the authorization server. + @discussion Set when the response_type requested includes 'token'. + @remarks access_token + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *accessToken; + +/*! @brief The approximate expiration date & time of the access token. + @remarks expires_in + @seealso OIDTokenResponse.accessToken + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate; + +/*! @brief Typically "Bearer" when present. Otherwise, another token_type value that the Client has + negotiated with the Authorization Server. + @discussion Set when the response_type requested includes 'token'. + @remarks token_type + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *tokenType; + +/*! @brief ID Token value associated with the authenticated session. + @discussion Set when the response_type requested includes 'id_token'. + @remarks id_token + @see http://openid.net/specs/openid-connect-core-1_0.html#IDToken + @see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse + */ +@property(nonatomic, readonly, nullable) NSString *idToken; + +/*! @brief The refresh token, which can be used to obtain new access tokens using the same + authorization grant + @remarks refresh_token + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *refreshToken; + +/*! @brief The scope of the access token. OPTIONAL, if identical to the scopes requested, otherwise, + REQUIRED. + @remarks scope + @see https://tools.ietf.org/html/rfc6749#section-5.1 + */ +@property(nonatomic, readonly, nullable) NSString *scope; + +/*! @brief Additional parameters returned from the token server. + */ +@property(nonatomic, readonly, nullable) + NSDictionary *> *additionalParameters; + +/*! @internal + @brief Unavailable. Please use initWithParameters:. + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief Designated initializer. + @param request The serviced request. + @param parameters The decoded parameters returned from the Authorization Server. + @remarks Known parameters are extracted from the @c parameters parameter and the normative + properties are populated. Non-normative parameters are placed in the + @c #additionalParameters dictionary. + */ +- (nullable instancetype)initWithRequest:(OIDTokenRequest *)request + parameters:(NSDictionary *> *)parameters + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDTokenResponse.m b/Paco-iOS/Pods/AppAuth/Source/OIDTokenResponse.m new file mode 100644 index 000000000..2ad1a24a6 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDTokenResponse.m @@ -0,0 +1,168 @@ +/*! @file OIDTokenResponse.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTokenResponse.h" + +#import "OIDDefines.h" +#import "OIDFieldMapping.h" +#import "OIDTokenRequest.h" + +/*! @brief Key used to encode the @c request property for @c NSSecureCoding + */ +static NSString *const kRequestKey = @"request"; + +/*! @brief The key for the @c accessToken property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kAccessTokenKey = @"access_token"; + +/*! @brief The key for the @c accessTokenExpirationDate property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kExpiresInKey = @"expires_in"; + +/*! @brief The key for the @c tokenType property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kTokenTypeKey = @"token_type"; + +/*! @brief The key for the @c idToken property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kIDTokenKey = @"id_token"; + +/*! @brief The key for the @c refreshToken property in the incoming parameters and for + @c NSSecureCoding. + */ +static NSString *const kRefreshTokenKey = @"refresh_token"; + +/*! @brief The key for the @c scope property in the incoming parameters and for @c NSSecureCoding. + */ +static NSString *const kScopeKey = @"scope"; + +/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding + */ +static NSString *const kAdditionalParametersKey = @"additionalParameters"; + +@implementation OIDTokenResponse + +/*! @brief Returns a mapping of incoming parameters to instance variables. + @return A mapping of incoming parameters to instance variables. + */ ++ (NSDictionary *)fieldMap { + static NSMutableDictionary *fieldMap; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + fieldMap = [NSMutableDictionary dictionary]; + fieldMap[kAccessTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessToken" type:[NSString class]]; + fieldMap[kExpiresInKey] = + [[OIDFieldMapping alloc] initWithName:@"_accessTokenExpirationDate" + type:[NSDate class] + conversion:^id _Nullable(NSObject *_Nullable value) { + if (![value isKindOfClass:[NSNumber class]]) { + return value; + } + NSNumber *valueAsNumber = (NSNumber *)value; + return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]]; + }]; + fieldMap[kTokenTypeKey] = + [[OIDFieldMapping alloc] initWithName:@"_tokenType" type:[NSString class]]; + fieldMap[kIDTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_idToken" type:[NSString class]]; + fieldMap[kRefreshTokenKey] = + [[OIDFieldMapping alloc] initWithName:@"_refreshToken" type:[NSString class]]; + fieldMap[kScopeKey] = + [[OIDFieldMapping alloc] initWithName:@"_scope" type:[NSString class]]; + }); + return fieldMap; +} + +#pragma mark - Initializers + +- (nullable instancetype)init + OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:)); + +- (nullable instancetype)initWithRequest:(OIDTokenRequest *)request + parameters:(NSDictionary *> *)parameters { + self = [super init]; + if (self) { + _request = [request copy]; + NSDictionary *> *additionalParameters = + [OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap] + parameters:parameters + instance:self]; + _additionalParameters = additionalParameters; + } + return self; +} + +#pragma mark - NSCopying + +- (instancetype)copyWithZone:(nullable NSZone *)zone { + // The documentation for NSCopying specifically advises us to return a reference to the original + // instance in the case where instances are immutable (as ours is): + // "Implement NSCopying by retaining the original instead of creating a new copy when the class + // and its contents are immutable." + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDTokenRequest *request = + [aDecoder decodeObjectOfClass:[OIDTokenRequest class] forKey:kRequestKey]; + self = [self initWithRequest:request parameters:@{ }]; + if (self) { + [OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self]; + _additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes] + forKey:kAdditionalParametersKey]; + } + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self]; + [aCoder encodeObject:_request forKey:kRequestKey]; + [aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey]; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, accessToken: \"%@\", accessTokenExpirationDate: %@, " + "tokenType: %@, idToken: \"%@\", refreshToken: \"%@\", " + "scope: \"%@\", additionalParameters: %@, request: %@>", + NSStringFromClass([self class]), + self, + _accessToken, + _accessTokenExpirationDate, + _tokenType, + _idToken, + _refreshToken, + _scope, + _additionalParameters, + _request]; +} + +#pragma mark - + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDTokenUtilities.h b/Paco-iOS/Pods/AppAuth/Source/OIDTokenUtilities.h new file mode 100644 index 000000000..f13d937b0 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDTokenUtilities.h @@ -0,0 +1,55 @@ +/*! @file OIDTokenUtilities.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides data encoding/decoding methods, random string generators, etc. + */ +@interface OIDTokenUtilities : NSObject + +/*! @internal + @brief Unavailable. This class should not be initialized. + */ +- (instancetype)init NS_UNAVAILABLE; + +/*! @brief Base64url-nopadding encodes the given data. + @param data The input data. + @return The base64url encoded data as a NSString. + @discussion Base64url-nopadding is used in several identity specs such as PKCE and + OpenID Connect. + */ ++ (NSString *)encodeBase64urlNoPadding:(NSData *)data; + +/*! @brief Generates a URL-safe string of random data. + @param size The number of random bytes to encode. NB. the length of the output string will be + greater than the number of random bytes, due to the URL-safe encoding. + @return Random data encoded with base64url. + */ ++ (nullable NSString *)randomURLSafeStringWithSize:(NSUInteger)size; + +/*! @brief SHA256 hashes the input string. + @param inputString The input string. + @return The SHA256 data. + */ ++ (NSData *)sha265:(NSString *)inputString; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDTokenUtilities.m b/Paco-iOS/Pods/AppAuth/Source/OIDTokenUtilities.m new file mode 100644 index 000000000..fa08ddcb5 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDTokenUtilities.m @@ -0,0 +1,51 @@ +/*! @file OIDTokenUtilities.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDTokenUtilities.h" + +#import + +@implementation OIDTokenUtilities + ++ (NSString *)encodeBase64urlNoPadding:(NSData *)data { + NSString *base64string = [data base64EncodedStringWithOptions:0]; + // converts base64 to base64url + base64string = [base64string stringByReplacingOccurrencesOfString:@"+" withString:@"-"]; + base64string = [base64string stringByReplacingOccurrencesOfString:@"/" withString:@"_"]; + // strips padding + base64string = [base64string stringByReplacingOccurrencesOfString:@"=" withString:@""]; + return base64string; +} + ++ (nullable NSString *)randomURLSafeStringWithSize:(NSUInteger)size { + NSMutableData *randomData = [NSMutableData dataWithLength:size]; + int result = SecRandomCopyBytes(kSecRandomDefault, randomData.length, randomData.mutableBytes); + if (result != 0) { + return nil; + } + return [[self class] encodeBase64urlNoPadding:randomData]; +} + ++ (NSData *)sha265:(NSString *)inputString { + NSData *verifierData = [inputString dataUsingEncoding:NSUTF8StringEncoding]; + NSMutableData *sha256Verifier = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH]; + CC_SHA256(verifierData.bytes, (CC_LONG)verifierData.length, sha256Verifier.mutableBytes); + return sha256Verifier; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDURLQueryComponent.h b/Paco-iOS/Pods/AppAuth/Source/OIDURLQueryComponent.h new file mode 100644 index 000000000..69f8c6eed --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDURLQueryComponent.h @@ -0,0 +1,79 @@ +/*! @file OIDURLQueryComponent.h + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +@class OIDAuthorizationRequest; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief If set to YES, will force the iOS 7-only code for @c OIDURLQueryComponent to be used, + even on non-iOS 7 devices and simulators. Useful for testing the iOS 7 code paths on the + simulator. Defaults to NO. + */ +extern BOOL gOIDURLQueryComponentForceIOS7Handling; + +/*! @brief A utility class for creating and parsing URL query components. + */ +@interface OIDURLQueryComponent : NSObject + +/*! @brief The parameter names in the query. + */ +@property(nonatomic, readonly) NSArray *parameters; + +/*! @brief The parameters represented as a dictionary. + @remarks All values are @c NSString except for parameters which contain multiple values, in + which case the value is an @c NSArray *. + */ +@property(nonatomic, readonly) NSDictionary *> *dictionaryValue; + +/*! @brief Creates an @c OIDURLQueryComponent by parsing the query string in a URL. + @param URL The URL from which to extract a query component. + */ +- (nullable instancetype)initWithURL:(NSURL *)URL; + +/*! @brief The value (or values) for a named parameter in the query. + @param parameter The parameter name. Case sensitive. + @return The value (or values) for a named parameter in the query. + */ +- (NSArray *)valuesForParameter:(NSString *)parameter; + +/*! @brief Adds a parameter value to the query. + @param parameter The name of the parameter. Case sensitive. + @param value The value to add. + */ +- (void)addParameter:(NSString *)parameter value:(NSString *)value; + +/*! @brief Adds multiple parameters with associated values to the query. + @param parameters The parameter name value pairs to add to the query. + */ +- (void)addParameters:(NSDictionary *)parameters; + +/*! @param URL The URL to add the query component to. + @return The original URL with the query component replaced by the parameters from this query. + */ +- (NSURL *)URLByReplacingQueryInURL:(NSURL *)URL; + +/*! @brief Builds an x-www-form-urlencoded string representing the parameters. + @return The x-www-form-urlencoded string representing the parameters. + */ +- (NSString *)URLEncodedParameters; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/OIDURLQueryComponent.m b/Paco-iOS/Pods/AppAuth/Source/OIDURLQueryComponent.m new file mode 100644 index 000000000..2ed290a44 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/OIDURLQueryComponent.m @@ -0,0 +1,197 @@ +/*! @file OIDURLQueryComponent.m + @brief AppAuth iOS SDK + @copyright + Copyright 2015 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDURLQueryComponent.h" + +BOOL gOIDURLQueryComponentForceIOS7Handling = NO; + +/*! @brief String representing the set of characters that are valid for the URL query + (per @ NSCharacterSet.URLQueryAllowedCharacterSet), but are disallowed in URL query + parameters and values. + */ +static NSString *const kQueryStringParamAdditionalDisallowedCharacters = @"=&+"; + +@implementation OIDURLQueryComponent { + /*! @brief A dictionary of parameter names and values representing the contents of the query. + */ + NSMutableDictionary *> *_parameters; +} + +- (nullable instancetype)init { + self = [super init]; + if (self) { + _parameters = [NSMutableDictionary dictionary]; + } + return self; +} + +- (nullable instancetype)initWithURL:(NSURL *)URL { + self = [self init]; + if (self) { + if (!gOIDURLQueryComponentForceIOS7Handling && [NSURLQueryItem class]) { + // If NSURLQueryItem is available, use it for deconstructing the new URL. (iOS 8+) + NSURLComponents *components = + [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + NSArray *queryItems = components.queryItems; + for (NSURLQueryItem *queryItem in queryItems) { + [self addParameter:queryItem.name value:queryItem.value]; + } + } else { + // Fallback for iOS 7 + NSString *query = URL.query; + NSArray *queryParts = [query componentsSeparatedByString:@"&"]; + for (NSString *queryPart in queryParts) { + NSRange equalsRange = [queryPart rangeOfString:@"="]; + if (equalsRange.location == NSNotFound) { + continue; + } + NSString *name = [queryPart substringToIndex:equalsRange.location]; + name = name.stringByRemovingPercentEncoding; + NSString *value = [queryPart substringFromIndex:equalsRange.location + equalsRange.length]; + value = value.stringByRemovingPercentEncoding; + [self addParameter:name value:value]; + } + } + } + return self; +} + +- (NSArray *)parameters { + return _parameters.allKeys; +} + +- (NSDictionary *> *)dictionaryValue { + // This method will flatten arrays in our @c _parameters' values if only one value exists. + NSMutableDictionary *> *values = [NSMutableDictionary dictionary]; + for (NSString *parameter in _parameters.allKeys) { + NSArray *value = _parameters[parameter]; + if (value.count == 1) { + values[parameter] = [value.firstObject copy]; + } else { + values[parameter] = [value copy]; + } + } + return values; +} + +- (NSArray *)valuesForParameter:(NSString *)parameter { + return _parameters[parameter]; +} + +- (void)addParameter:(NSString *)parameter value:(NSString *)value { + NSMutableArray *parameterValues = _parameters[parameter]; + if (!parameterValues) { + parameterValues = [NSMutableArray array]; + _parameters[parameter] = parameterValues; + } + [parameterValues addObject:value]; +} + +- (void)addParameters:(NSDictionary *)parameters { + for (NSString *parameterName in parameters.allKeys) { + [self addParameter:parameterName value:parameters[parameterName]]; + } +} + +/*! @brief Builds a query items array that can be set to @c NSURLComponents.queryItems + @discussion The parameter names and values are NOT URL encoded. + @return An array of unencoded @c NSURLQueryItem objects. + */ +- (NSMutableArray *)queryItems { + NSMutableArray *queryParameters = [NSMutableArray array]; + for (NSString *parameterName in _parameters.allKeys) { + NSArray *values = _parameters[parameterName]; + for (NSString *value in values) { + NSURLQueryItem *item = [NSURLQueryItem queryItemWithName:parameterName value:value]; + [queryParameters addObject:item]; + } + } + return queryParameters; +} + +/*! @brief Builds a query string that can be set to @c NSURLComponents.percentEncodedQuery + @discussion This string is percent encoded, and shouldn't be used with + @c NSURLComponents.query. + @return An percentage encoded query string. + */ +- (NSString *)percentEncodedQueryString { + NSMutableArray *parameterizedValues = [NSMutableArray array]; + + // Starts with the standard URL-allowed character set. + NSMutableCharacterSet *allowedParamCharacters = + [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + // Removes additional characters we don't want to see in the query component. + [allowedParamCharacters removeCharactersInString:kQueryStringParamAdditionalDisallowedCharacters]; + + for (NSString *parameterName in _parameters.allKeys) { + NSString *encodedParameterName = + [parameterName stringByAddingPercentEncodingWithAllowedCharacters:allowedParamCharacters]; + + NSArray *values = _parameters[parameterName]; + for (NSString *value in values) { + NSString *encodedValue = + [value stringByAddingPercentEncodingWithAllowedCharacters:allowedParamCharacters]; + NSString *parameterizedValue = + [NSString stringWithFormat:@"%@=%@", encodedParameterName, encodedValue]; + [parameterizedValues addObject:parameterizedValue]; + } + } + + NSString *queryString = [parameterizedValues componentsJoinedByString:@"&"]; + return queryString; +} + +- (NSString *)URLEncodedParameters { + // If NSURLQueryItem is available, uses it for constructing the encoded parameters. (iOS 8+) + if (!gOIDURLQueryComponentForceIOS7Handling && [NSURLQueryItem class]) { + NSURLComponents *components = [[NSURLComponents alloc] init]; + components.queryItems = [self queryItems]; + NSString *encodedQuery = components.percentEncodedQuery; + // NSURLComponents.percentEncodedQuery creates a validly escaped URL query component, but + // doesn't encode the '+' leading to potential ambiguity with application/x-www-form-urlencoded + // encoding. Percent encodes '+' to avoid this ambiguity. + encodedQuery = [encodedQuery stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]; + return encodedQuery; + } + + // else, falls back to building query string manually (iOS 7) + return [self percentEncodedQueryString]; +} + +- (NSURL *)URLByReplacingQueryInURL:(NSURL *)URL { + NSURLComponents *components = + [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; + + // Replaces encodedQuery component + NSString *queryString = [self URLEncodedParameters]; + components.percentEncodedQuery = queryString; + + NSURL *URLWithParameters = components.URL; + return URLWithParameters; +} + +#pragma mark - NSObject overrides + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, parameters: %@>", + NSStringFromClass([self class]), + self, + _parameters]; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthState+IOS.h b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthState+IOS.h new file mode 100644 index 000000000..80f162587 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthState+IOS.h @@ -0,0 +1,46 @@ +/*! @file OIDAuthState+IOS.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDAuthState.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief iOS specific convenience methods for @c OIDAuthState. + */ +@interface OIDAuthState (IOS) + +/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request + and performing the authorization code exchange in the case of code flow requests. + @param authorizationRequest The authorization request to present. + @param presentingViewController The view controller from which to present the + @c SFSafariViewController. + @param callback The method called when the request has completed or failed. + @return A @c OIDAuthorizationFlowSession instance which will terminate when it + receives a @c OIDAuthorizationFlowSession.cancel message, or after processing a + @c OIDAuthorizationFlowSession.resumeAuthorizationFlowWithURL: message. + */ ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthStateAuthorizationCallback)callback; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthState+IOS.m b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthState+IOS.m new file mode 100644 index 000000000..3e32a8be9 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthState+IOS.m @@ -0,0 +1,36 @@ +/*! @file OIDAuthState+IOS.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthState+IOS.h" + +#import "OIDAuthorizationUICoordinatorIOS.h" + +@implementation OIDAuthState (IOS) + ++ (id) + authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthStateAuthorizationCallback)callback { + OIDAuthorizationUICoordinatorIOS *coordinator = [[OIDAuthorizationUICoordinatorIOS alloc] + initWithPresentingViewController:presentingViewController]; + return [self authStateByPresentingAuthorizationRequest:authorizationRequest + UICoordinator:coordinator + callback:callback]; +} + +@end diff --git a/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationService+IOS.h b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationService+IOS.h new file mode 100644 index 000000000..3d76340e8 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationService+IOS.h @@ -0,0 +1,44 @@ +/*! @file OIDAuthorizationService+IOS.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDAuthorizationService.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Provides iOS specific authorization request handling. + */ +@interface OIDAuthorizationService (IOS) + +/*! @brief Perform an authorization flow using \SFSafariViewController. + @param request The authorization request. + @param presentingViewController The view controller from which to present the + \SFSafariViewController. + @param callback The method called when the request has completed or failed. + @return A @c OIDAuthorizationFlowSession instance which will terminate when it + receives a @c OIDAuthorizationFlowSession.cancel message, or after processing a + @c OIDAuthorizationFlowSession.resumeAuthorizationFlowWithURL: message. + */ ++ (id) + presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthorizationCallback)callback; +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationService+IOS.m b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationService+IOS.m new file mode 100644 index 000000000..2a8d6da86 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationService+IOS.m @@ -0,0 +1,38 @@ +/*! @file OIDAuthorizationService+IOS.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationService+IOS.h" + +#import "OIDAuthorizationUICoordinatorIOS.h" + +NS_ASSUME_NONNULL_BEGIN + +@implementation OIDAuthorizationService (IOS) + ++ (id) + presentAuthorizationRequest:(OIDAuthorizationRequest *)request + presentingViewController:(UIViewController *)presentingViewController + callback:(OIDAuthorizationCallback)callback { + OIDAuthorizationUICoordinatorIOS *coordinator = [[OIDAuthorizationUICoordinatorIOS alloc] + initWithPresentingViewController:presentingViewController]; + return [self presentAuthorizationRequest:request UICoordinator:coordinator callback:callback]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationUICoordinatorIOS.h b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationUICoordinatorIOS.h new file mode 100644 index 000000000..57c0d25d1 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationUICoordinatorIOS.h @@ -0,0 +1,66 @@ +/*! @file OIDAuthorizationUICoordinator.h + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +#import "OIDAuthorizationUICoordinator.h" + +@class SFSafariViewController; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Allows library consumers to bootstrap an @c SFSafariViewController as they see fit. + @remarks Useful for customizing tint colors and presentation styles. + */ +@protocol OIDSafariViewControllerFactory + +/*! @brief Creates and returns a new @c SFSafariViewController. + @param URL The URL which the @c SFSafariViewController should load initially. + */ +- (SFSafariViewController *)safariViewControllerWithURL:(NSURL *)URL; + +@end + +/*! @brief An iOS specific authorization UI Coordinator that uses a \SFSafariViewController to + present an authorization request. + */ +@interface OIDAuthorizationUICoordinatorIOS : NSObject + +/*! @brief Allows library consumers to change the @c OIDSafariViewControllerFactory used to create + new instances of @c SFSafariViewController. + @remarks Useful for customizing tint colors and presentation styles. + @param factory The @c OIDSafariViewControllerFactory to use for creating new instances of + @c SFSafariViewController. + */ ++ (void)setSafariViewControllerFactory:(id)factory; + +/*! @internal + @brief Unavailable. Please use @c initWithPresentingViewController: + */ +- (nullable instancetype)init NS_UNAVAILABLE; + +/*! @brief The designated initializer. + @param parentViewController The view controller from which to present the + \SFSafariViewController. + */ +- (nullable instancetype)initWithPresentingViewController:(UIViewController *)parentViewController + NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationUICoordinatorIOS.m b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationUICoordinatorIOS.m new file mode 100644 index 000000000..6bb2ac270 --- /dev/null +++ b/Paco-iOS/Pods/AppAuth/Source/iOS/OIDAuthorizationUICoordinatorIOS.m @@ -0,0 +1,154 @@ +/*! @file OIDAuthorizationUICoordinatorIOS.m + @brief AppAuth iOS SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "OIDAuthorizationUICoordinatorIOS.h" + +#import + +#import "OIDAuthorizationService.h" +#import "OIDErrorUtilities.h" + +NS_ASSUME_NONNULL_BEGIN + +/** @brief The global/shared Safari view controller factory. Responsible for creating all new + instances of @c SFSafariViewController. + */ +static id __nullable gSafariViewControllerFactory; + +/** @brief The default @c OIDSafariViewControllerFactory which creates new instances of + @c SFSafariViewController using known best practices. + */ +@interface OIDDefaultSafariViewControllerFactory : NSObject +@end + +@interface OIDAuthorizationUICoordinatorIOS () +@end + +@implementation OIDAuthorizationUICoordinatorIOS { + UIViewController *_presentingViewController; + + BOOL _authorizationFlowInProgress; + __weak id _session; + __weak SFSafariViewController *_safariVC; +} + +/** @brief Obtains the current @c OIDSafariViewControllerFactory; creating a new default instance if + required. + */ ++ (id)safariViewControllerFactory { + if (!gSafariViewControllerFactory) { + gSafariViewControllerFactory = [[OIDDefaultSafariViewControllerFactory alloc] init]; + } + return gSafariViewControllerFactory; +} + ++ (void)setSafariViewControllerFactory:(id)factory { + NSAssert(factory, @"Parameter: |factory| must be non-nil."); + gSafariViewControllerFactory = factory; +} + +- (nullable instancetype)initWithPresentingViewController: + (UIViewController *)presentingViewController { + self = [super init]; + if (self) { + _presentingViewController = presentingViewController; + } + return self; +} + +- (BOOL)presentAuthorizationWithURL:(NSURL *)URL session:(id)session { + if (_authorizationFlowInProgress) { + // TODO: Handle errors as authorization is already in progress. + return NO; + } + + _authorizationFlowInProgress = YES; + _session = session; + if ([SFSafariViewController class]) { + SFSafariViewController *safariVC = + [[[self class] safariViewControllerFactory] safariViewControllerWithURL:URL]; + safariVC.delegate = self; + _safariVC = safariVC; + [_presentingViewController presentViewController:safariVC animated:YES completion:nil]; + return YES; + } + BOOL openedSafari = [[UIApplication sharedApplication] openURL:URL]; + if (!openedSafari) { + [self cleanUp]; + NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError + underlyingError:nil + description:@"Unable to open Safari."]; + [session failAuthorizationFlowWithError:safariError]; + } + return openedSafari; +} + +- (void)dismissAuthorizationAnimated:(BOOL)animated completion:(void (^)(void))completion { + if (!_authorizationFlowInProgress) { + // Ignore this call if there is no authorization flow in progress. + return; + } + SFSafariViewController *safariVC = _safariVC; + [self cleanUp]; + if (safariVC) { + [safariVC dismissViewControllerAnimated:YES completion:completion]; + } else { + if (completion) completion(); + } +} + +- (void)cleanUp { + // The weak references to |_safariVC| and |_session| are set to nil to avoid accidentally using + // them while not in an authorization flow. + _safariVC = nil; + _session = nil; + _authorizationFlowInProgress = NO; +} + +#pragma mark - SFSafariViewControllerDelegate + +- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller { + if (controller != _safariVC) { + // Ignore this call if the safari view controller do not match. + return; + } + if (!_authorizationFlowInProgress) { + // Ignore this call if there is no authorization flow in progress. + return; + } + id session = _session; + [self cleanUp]; + NSError *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeProgramCanceledAuthorizationFlow + underlyingError:nil + description:nil]; + [session failAuthorizationFlowWithError:error]; +} + +@end + +@implementation OIDDefaultSafariViewControllerFactory + +- (SFSafariViewController *)safariViewControllerWithURL:(NSURL *)URL { + SFSafariViewController *safariViewController = + [[SFSafariViewController alloc] initWithURL:URL entersReaderIfAvailable:NO]; + return safariViewController; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMAppAuth/LICENSE b/Paco-iOS/Pods/GTMAppAuth/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Paco-iOS/Pods/GTMAppAuth/README.md b/Paco-iOS/Pods/GTMAppAuth/README.md new file mode 100644 index 000000000..b3105126c --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/README.md @@ -0,0 +1,372 @@ +# GTMAppAuth for iOS and macOS + +GTMAppAuth enables you to use [AppAuth](http://openid.github.io/AppAuth-iOS) +with the +[Google Toolbox for Mac - Session Fetcher](https://github.com/google/gtm-session-fetcher) +and +[Google APIs Client Library for Objective-C For REST](https://github.com/google/google-api-objectivec-client-for-rest) +libraries by providing an implementation of `GTMFetcherAuthorizationProtocol` +for authorizing requests with AppAuth. + +GTMAppAuth is an alternative authorizer to GTMOAuth2. The key differentiator is +the use of the user's default browser for the authorization, which is more +secure, more usable (the user's session can be reused) and follows modern OAuth +[best practices for native apps](https://tools.ietf.org/html/draft-ietf-oauth-native-apps). +Compatibility methods for GTMOAuth2 are offered allowing you to migrate +from GTMOAuth2 to GTMAppAuth preserving previously serialized authorizations +(so users shouldn't need to re-authenticate). + +## Setup + +If you use [CocoaPods](https://guides.cocoapods.org/using/getting-started.html), +simply add: + + pod 'GTMAppAuth' + +To your `Podfile` and run `pod install`. + +## Usage + +### Configuration + +To configure GTMAppAuth with the OAuth endpoints for Google, you can use the +convenience method: + +```objc +OIDServiceConfiguration *configuration = + [GTMAppAuthFetcherAuthorization configurationForGoogle]; +``` + +Alternatively, you can configure GTMAppAuth by specifying the endpoints +directly: + +```objc +NSURL *authorizationEndpoint = + [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/v2/auth"]; +NSURL *tokenEndpoint = + [NSURL URLWithString:@"https://www.googleapis.com/oauth2/v4/token"]; + +OIDServiceConfiguration *configuration = + [[OIDServiceConfiguration alloc] + initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint]; + +// perform the auth request... +``` + +Or through discovery: + +```objc +NSURL *issuer = [NSURL URLWithString:@"https://accounts.google.com"]; + +[OIDAuthorizationService discoverServiceConfigurationForIssuer:issuer + completion:^(OIDServiceConfiguration *_Nullable configuration, + NSError *_Nullable error) { + if (!configuration) { + NSLog(@"Error retrieving discovery document: %@", + [error localizedDescription]); + return; + } + + // perform the auth request... +}]; +``` + +### Authorizing + +First, you need to have a way for your UIApplicationDelegate to continue the +authorization flow session from the incoming redirect URI. Typically you could +store the in-progress OIDAuthorizationFlowSession instance in a property: + +```objc +// property of the app's UIApplicationDelegate +@property(nonatomic, nullable) + id currentAuthorizationFlow; +``` + +And in a location accessible by all controllers that need authorization, a +property to store the authorization state: + +```objc +// property of the containing class +@property(nonatomic, nullable) GTMAppAuthFetcherAuthorization *authorization; +``` + +Then, initiate the authorization request. By using the +`authStateByPresentingAuthorizationRequest` method, the OAuth token +exchange will be performed automatically, and everything will be protected with +PKCE (if the server supports it). + +```objc +// builds authentication request +OIDAuthorizationRequest *request = + [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration + clientId:kClientID + clientSecret:kClientSecret + scopes:@[OIDScopeOpenID, OIDScopeProfile] + redirectURL:redirectURI + responseType:OIDResponseTypeCode + additionalParameters:nil]; +// performs authentication request +self.appDelegate.currentAuthorizationFlow = + [OIDAuthState authStateByPresentingAuthorizationRequest:request + callback:^(OIDAuthState *_Nullable authState, + NSError *_Nullable error) { + if (authState) { + // Creates the GTMAppAuthFetcherAuthorization from the OIDAuthState. + GTMAppAuthFetcherAuthorization *authorization = + [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState]; + + self.authorization = authorization; + NSLog(@"Got authorization tokens. Access token: %@", + authState.lastTokenResponse.accessToken); + } else { + NSLog(@"Authorization error: %@", [error localizedDescription]); + self.authorization = nil; + } +}]; +``` + +### Handling the Redirect + +The authorization response URL is returned to the app via the platform-specific +application delegate method, so you need to pipe this through to the current +authorization session (created in the previous session). + +#### macOS Custom URI Scheme Redirect Example + +```objc +- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + // Other app initialization code ... + + // Register for GetURL events. + NSAppleEventManager *appleEventManager = + [NSAppleEventManager sharedAppleEventManager]; + [appleEventManager setEventHandler:self + andSelector:@selector(handleGetURLEvent:withReplyEvent:) + forEventClass:kInternetEventClass + andEventID:kAEGetURL]; +} + +- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event + withReplyEvent:(NSAppleEventDescriptor *)replyEvent { + NSString *URLString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; + NSURL *URL = [NSURL URLWithString:URLString]; + [_currentAuthorizationFlow resumeAuthorizationFlowWithURL:URL]; +} +``` + +#### iOS Custom URI Scheme Redirect Example + +```objc +- (BOOL)application:(UIApplication *)app + openURL:(NSURL *)url + options:(NSDictionary *)options { + // Sends the URL to the current authorization flow (if any) which will + // process it if it relates to an authorization response. + if ([_currentAuthorizationFlow resumeAuthorizationFlowWithURL:url]) { + _currentAuthorizationFlow = nil; + return YES; + } + + // Your additional URL handling (if any) goes here. + + return NO; +} +``` + +### Making API Calls + +The goal of GTMAppAuth is to enable you to authorize HTTP requests with fresh +tokens following the Session Fetcher pattern, which you can do like so: + +```objc +// Creates a GTMSessionFetcherService with the authorization. +// Normally you would save this service object and re-use it for all REST API calls. +GTMSessionFetcherService *fetcherService = [[GTMSessionFetcherService alloc] init]; +fetcherService.authorizer = self.authorization; + +// Creates a fetcher for the API call. +NSURL *userinfoEndpoint = [NSURL URLWithString:@"https://www.googleapis.com/oauth2/v3/userinfo"]; +GTMSessionFetcher *fetcher = [fetcherService fetcherWithURL:userinfoEndpoint]; +[fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + // Checks for an error. + if (error) { + // OIDOAuthTokenErrorDomain indicates an issue with the authorization. + if ([error.domain isEqual:OIDOAuthTokenErrorDomain]) { + self.authorization = nil; + NSLog(@"Authorization error during token refresh, clearing state. %@", + error); + // Other errors are assumed transient. + } else { + NSLog(@"Transient error during token refresh. %@", error); + } + return; + } + + // Parses the JSON response. + NSError *jsonError = nil; + id jsonDictionaryOrArray = + [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError]; + + // JSON error. + if (jsonError) { + NSLog(@"JSON decoding error %@", jsonError); + return; + } + + // Success response! + NSLog(@"Success: %@", jsonDictionaryOrArray); +}]; +``` + +### Serialization + +You can easily serialize `GTMAppAuthFetcherAuthorization` objects using the +included Keychain category. + +```objc +// Serialize to Keychain +[GTMAppAuthFetcherAuthorization saveAuthorization:_authorization + toKeychainForName:kGTMAppAuthExampleAuthorizerKey]; + +// Deserialize from Keychain +GTMAppAuthFetcherAuthorization* authorization = + [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kGTMAppAuthExampleAuthorizerKey]; + +// Remove from Keychain +[GTMAppAuthFetcherAuthorization + removeAuthorizationFromKeychainForName:kGTMAppAuthExampleAuthorizerKey]; +``` + +### GTMOAuth2-compatible Serialization + +To assist the migration from GTMOAuth2 to GTMAppAuth, GTMOAuth2-compatible +serialization methods are provided in `GTMOAuth2KeychainCompatibility`. + +```objc +// Deserialize from Keychain +GTMAppAuthFetcherAuthorization *auth = + [GTMOAuth2KeychainCompatibility authForGoogleFromKeychainForName:kKeychainItemName + clientID:clientID + clientSecret:clientSecret]; + +// Remove from Keychain +[GTMOAuth2KeychainCompatibility removeAuthFromKeychainForName:kKeychainItemName]; +``` + +You can also serialize to GTMOAuth2 format, though this is discouraged (you +should serialize in GTMAppAuth format as described above). + +```objc +// Serialize to Keychain +[GTMOAuth2KeychainCompatibility saveAuthToKeychainForName:kKeychainItemName + authentication:authorization]; +``` + +## Included Samples + +Try out one of the included samples `Example-Mac` and `Example-iOS`. In the +folder run `pod install`, then open the `xcworkspace` file. + +Be sure to follow the instructions in +[Example-iOS/README.md](Example-iOS/README.md) or +[Example-macOS/README.md](Example-macOS/README.md) to configure your own OAuth +client ID for use with the example. + +## Differences with GTMOAuth2 + +### Authorization Method + +GTMAppAuth uses the browser to present the authorization request, while +GTMOAuth2 uses an embedded web-view. Migrating to GTMAppAuth will require you +to change how you authorize the user. Follow the instructions above to get the +authorization. You can then create a `GTMAppAuthFetcherAuthorization` object +with the `initWithAuthState:authState` initializer. + +Once you have the `GTMAppAuthFetcherAuthorization` you can continue to make REST +calls as before. + +### Error Handling + +GTMAppAuth's error handling is also different. There are no notifications, +instead you need to inspect NSError in the callback. If the error domain is +`OIDOAuthTokenErrorDomain`, it indicates an authorization error, you should +clear your authorization state and consider prompting the user to authorize +again. Other errors are generally considered transient, meaning that you should +retry the request after a delay. + +### Serialization + +The serialization format is different between GTMOAuth2 and GTMAppAuth, though +we have methods to help you migrate from one to the other without losing any +data. + +## Migrating from GTMOAuth2 + +### OAuth Client Registration + +Typically, GTMOAuth2 clients are registered with Google as type "Other". This is +correct for macOS, but on iOS clients should be registered with the type "iOS". + +If you're migrating an iOS client, in the *same project as your existing client*, +[register a new iOS client](https://console.developers.google.com/apis/credentials?project=_) +to be used with GTMAppAuth. + +### Changing your Authorization Flows + +Both GTMOAuth2 and GTMAppAuth support the `GTMFetcherAuthorizationProtocol` +allowing you to use the authorization with the session fetcher. Where you +previously had a property like `GTMOAuth2Authentication *authorization` change the +type to reference the protocol instead, i.e.: +`id authorization`. This allows you to switch +the authorization implementation under the hood to GTMAppAuth. + +Then, follow the instructions above to replace authorization request +(where you ask the user to grant access) with the GTMAppAuth approach. If you +created a new OAuth client, use that for these requests. + +### Serialization & Migrating Existing Grants + +GTMAppAuth has a different way to serialize the authorization. Change how you +serialize your `authorization` object using the new methods, e.g.: + +```objc +// Serialize to Keychain +[GTMAppAuthFetcherAuthorization saveAuthorization:(GTMAppAuthFetcherAuthorization *)authorization + toKeychainForName:kNewKeychainName]; +``` + +Be sure to use a *new* name for the keychain. Don't reuse your existing one! + +For deserializing, we can preserve all existing grants (so users who authorized +your app in GTMOAuth2 don't have to authorize it again). Remember that when +deserializing the old data you need to use your *old* keychain name, and +the old client id and client secret (if those changed). Pay particular care to +use the old details when deserializing the GTMOAuth2 keychain, and the new +details for all other GTMAppAuth calls. + +Keychain migration example: + +```objc +// Attempt to deserialize from Keychain in GTMAppAuth format. +id authorization = + [GTMAppAuthFetcherAuthorization authorizationFromKeychainForName:kNewKeychainName]; + +// If no data found in the new format, try to deserialize data from GTMOAuth2 +if (!authorization) { + // Tries to load the data serialized by GTMOAuth2 using old keychain name. + // If you created a new client id, be sure to use the *previous* client id and secret here. + authorization = + [GTMOAuth2KeychainCompatibility authForGoogleFromKeychainForName:kPreviousKeychainName + clientID:kPreviousClientID + clientSecret:kPreviousClientSecret]; + if (authorization) { + // Remove previously stored GTMOAuth2-formatted data. + [GTMOAuth2KeychainCompatibility removeAuthFromKeychainForName:kPreviousKeychainName]; + // Serialize to Keychain in GTMAppAuth format. + [GTMAppAuthFetcherAuthorization saveAuthorization:(GTMAppAuthFetcherAuthorization *)authorization + toKeychainForName:kNewKeychainName]; + } +} +``` diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuth.h b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuth.h new file mode 100644 index 000000000..644349ebb --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuth.h @@ -0,0 +1,30 @@ +/*! @file GTMAppAuth.h + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMAppAuthFetcherAuthorization.h" +#import "GTMAppAuthFetcherAuthorization+Keychain.h" + +#if TARGET_OS_TV +#elif TARGET_OS_WATCH +#elif TARGET_OS_IOS +#import "GTMOAuth2KeychainCompatibility.h" +#elif TARGET_OS_MAC +#import "GTMOAuth2KeychainCompatibility.h" +#else +#warn "Platform Undefined" +#endif diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization+Keychain.h b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization+Keychain.h new file mode 100644 index 000000000..69956322e --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization+Keychain.h @@ -0,0 +1,52 @@ +/*! @file GTMAppAuthFetcherAuthorization+Keychain.h + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMAppAuthFetcherAuthorization.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Category to support serialization and deserialization of + @c GTMAppAuthFetcherAuthorization in the format used by GTMAppAuth. + */ +@interface GTMAppAuthFetcherAuthorization (Keychain) + +/*! @brief Attempts to create a @c GTMAppAuthFetcherAuthorization from data stored in the keychain + in GTMAppAuth format. + @param keychainItemName The keychain name. + @return A @c GTMAppAuthFetcherAuthorization object, or nil. + */ ++ (nullable GTMAppAuthFetcherAuthorization *) + authorizationFromKeychainForName:(NSString *)keychainItemName; + +/*! @brief Removes a stored authorization state. + @param keychainItemName The keychain name. + @return YES the tokens were removed successfully (or didn't exist). + */ ++ (BOOL)removeAuthorizationFromKeychainForName:(NSString *)keychainItemName; + +/*! @brief Saves the authorization state to the keychain, in GTMAppAuth format. + @param auth The authorization to save. + @param keychainItemName The keychain name. + @return YES when the state was saved successfully. + */ ++ (BOOL)saveAuthorization:(GTMAppAuthFetcherAuthorization *)auth + toKeychainForName:(NSString *)keychainItemName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization+Keychain.m b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization+Keychain.m new file mode 100644 index 000000000..9fd76ef55 --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization+Keychain.m @@ -0,0 +1,46 @@ +/*! @file GTMAppAuthFetcherAuthorization+Keychain.m + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMAppAuthFetcherAuthorization+Keychain.h" + +#import "GTMKeychain.h" + +@implementation GTMAppAuthFetcherAuthorization (Keychain) + ++ (GTMAppAuthFetcherAuthorization *)authorizationFromKeychainForName:(NSString *)keychainItemName { + NSData *passwordData = [GTMKeychain passwordDataFromKeychainForName:keychainItemName]; + if (!passwordData) { + return nil; + } + GTMAppAuthFetcherAuthorization *authorization = (GTMAppAuthFetcherAuthorization *) + [NSKeyedUnarchiver unarchiveObjectWithData:passwordData]; + return authorization; +} + ++ (BOOL)removeAuthorizationFromKeychainForName:(NSString *)keychainItemName { + return [GTMKeychain removePasswordFromKeychainForName:keychainItemName]; +} + ++ (BOOL)saveAuthorization:(GTMAppAuthFetcherAuthorization *)auth + toKeychainForName:(NSString *)keychainItemName { + NSData *authorizationData = [NSKeyedArchiver archivedDataWithRootObject:auth]; + return [GTMKeychain savePasswordDataToKeychainForName:keychainItemName + passwordData:authorizationData]; +} + +@end diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization.h b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization.h new file mode 100644 index 000000000..2dc443953 --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization.h @@ -0,0 +1,133 @@ +/*! @file GTMAppAuthFetcherAuthorization.h + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#ifndef GTMAPPAUTH_USER_IMPORTS +#import +#else // GTMAPPAUTH_USER_IMPORTS +#import "GTMSessionFetcher.h" +#endif // GTMAPPAUTH_USER_IMPORTS + +@class OIDAuthState; +@class OIDServiceConfiguration; + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief The userInfo key for the @c NSURLRequest. + */ +extern NSString *const GTMAppAuthFetcherAuthorizationErrorRequestKey; + +/*! @brief The error domain for errors specific to the session fetcher authorization. + */ +extern NSString *const GTMAppAuthFetcherAuthorizationErrorDomain; + +/*! @brief Enum of all possible error codes in the @c ::GTMAppAuthFetcherAuthorizationErrorDomain + domain. + @discussion Note that these are GTMAppAuth-specific errors. When AppAuth errors are encountered, + those are returned instead. + */ +typedef NS_ENUM(NSInteger, GTMAppAuthFetcherAuthorizationError) { + GTMAppAuthFetcherAuthorizationErrorUnauthorizableRequest = -1004 +}; + +typedef void (^GTMAppAuthFetcherAuthorizationCompletion)(NSError *_Nullable error); + +/*! @brief An implementation of the @c GTMFetcherAuthorizationProtocol protocol for the AppAuth + library. + @discussion Enables you to use AppAuth with the GTM Session Fetcher library. + */ +@interface GTMAppAuthFetcherAuthorization : NSObject + +/*! @brief The AppAuth authentication state. + */ +@property(nonatomic, readonly) OIDAuthState *authState; + +/*! @brief Service identifier, for example "Google"; not used for authentication. + @discussion The provider name is just for allowing stored authorization to be associated + with the authorizing service. + */ +@property(nullable, nonatomic, readonly) NSString *serviceProvider; + +/*! @brief User ID from the ID Token. + * @discussion Note: Never send this value to your backend as an authentication token, rather send + * an ID Token and validate it. + */ +@property(nullable, nonatomic, readonly) NSString *userID; + +/*! @brief Email verified status; not used for authentication. + @discussion The verified string can be checked with -boolValue. If the result is false, then + the email address is listed with the account on the server, but the address has not been + confirmed as belonging to the owner of the account. + */ +@property(nullable, nonatomic, readonly) NSString *userEmailIsVerified; + +/*! @brief Creates a new @c GTMAppAuthFetcherAuthorization using the given @c OIDAuthState from + AppAuth. + @param authState The authorization state. + */ +- (instancetype)initWithAuthState:(OIDAuthState *)authState; + +/*! @brief Creates a new @c GTMAppAuthFetcherAuthorization using the given @c OIDAuthState from + AppAuth. + @param authState The authorization state. + @param serviceProvider An optional string to describe the service. + @param userID An optional string of the user ID. + @param userEmail An optional string of the user's email address. + @param userEmailIsVerified An optional string representation of a boolean to indicate that the + email address has been verified. Pass @"true" for @c YES, or @"false" for @c NO. + @discussion Designated initializer. + */ +- (instancetype)initWithAuthState:(OIDAuthState *)authState + serviceProvider:(nullable NSString *)serviceProvider + userID:(nullable NSString *)userID + userEmail:(nullable NSString *)userEmail + userEmailIsVerified:(nullable NSString *)userEmailIsVerified + NS_DESIGNATED_INITIALIZER; + +#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT +/*! @brief Convenience method to return an @c OIDServiceConfiguration for Google. + @return A @c OIDServiceConfiguration object setup with Google OAuth endpoints. + */ ++ (OIDServiceConfiguration *)configurationForGoogle; +#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +/*! @brief Adds an authorization header to the given request, using the authorization state. + Refreshes the access token if needed. + @param request The request to authorize. + @param handler The block that is called after authorizing the request is attempted. If @c error + is non-nil, the authorization failed. Errors in the domain @c ::OIDOAuthTokenErrorDomain + indicate that the authorization itself is invalid, and will need to be re-obtained from the + user. Errors in the @c GTMAppAuthFetcherAuthorizationErrorDomain indicate another + unrecoverable errors. Errors in other domains may indicate a transitive error condition such + as a network error, and typically you do not need to reauthenticate the user on such errors. + @discussion The completion handler is scheduled on the main thread, unless the @c callbackQueue + property is set on the @c fetcherService in which case the handler is scheduled on that + queue. + */ +- (void)authorizeRequest:(nullable NSMutableURLRequest *)request + completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)handler; + +/*! @brief Returns YES if the authorization state is currently valid. + @discussion Note that this doesn't guarantee that a request will get a valid authorization, as + the authorization state could become invalid on on the next token refresh. + */ +- (BOOL)canAuthorize; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization.m b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization.m new file mode 100644 index 000000000..eff5dc95a --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMAppAuthFetcherAuthorization.m @@ -0,0 +1,518 @@ +/*! @file GTMAppAuthFetcherAuthorization.m + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMAppAuthFetcherAuthorization.h" + +#import "AppAuth.h" + +#define GTMOAuth2AssertValidSelector GTMBridgeAssertValidSelector + +/*! @brief Provides a template implementation for init-family methods which have been marked as + NS_UNAVILABLE. Stops the compiler from giving a warning when it's the super class' + designated initializer, and gives callers useful feedback telling them what the + new designated initializer is. + @remarks Takes a SEL as a parameter instead of a string so that we get compiler warnings if the + designated initializer's signature changes. + @param designatedInitializer A SEL referencing the designated initializer. + */ +#define GTM_UNAVAILABLE_USE_INITIALIZER(designatedInitializer) { \ + NSString *reason = [NSString stringWithFormat:@"Called: %@\nDesignated Initializer:%@", \ + NSStringFromSelector(_cmd), \ + NSStringFromSelector(designatedInitializer)]; \ + @throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." \ + reason:reason \ + userInfo:nil]; \ +} + +/*! @brief Key used to encode the @c authState property for @c NSSecureCoding. + */ +static NSString *const kAuthStateKey = @"authState"; + +/*! @brief Key used to encode the @c serviceProvider property for @c NSSecureCoding. + */ +static NSString *const kServiceProviderKey = @"serviceProvider"; + +/*! @brief Key used to encode the @c userID property for @c NSSecureCoding. + */ +static NSString *const kUserIDKey = @"userID"; + +/*! @brief Key used to encode the @c userEmail property for @c NSSecureCoding. + */ +static NSString *const kUserEmailKey = @"userEmail"; + +/*! @brief Key used to encode the @c userEmailIsVerified property for @c NSSecureCoding. + */ +static NSString *const kUserEmailIsVerifiedKey = @"userEmailIsVerified"; + +NSString *const GTMAppAuthFetcherAuthorizationErrorDomain = + @"kGTMAppAuthFetcherAuthorizationErrorDomain"; +NSString *const GTMAppAuthFetcherAuthorizationErrorRequestKey = @"request"; + +/*! @brief Internal wrapper class for requests needing authorization and their callbacks. + @discusssion Used to abstract away the detail of whether a callback or block is used. + */ +@interface GTMAppAuthFetcherAuthorizationArgs : NSObject + +/*! @brief The request to authorize. + * @discussion Not copied, as we are mutating the request. + */ +@property (nonatomic, strong) NSMutableURLRequest *request; + +/*! @brief The delegate on which @c selector is called on completion. + */ +@property (nonatomic, weak) id delegate; + +/*! @brief The selector called on the @c delegate object on completion. + */ +@property (nonatomic) SEL selector; + +/*! @brief The completion block when the block option was used. + */ +@property (nonatomic, strong) GTMAppAuthFetcherAuthorizationCompletion completionHandler; + +/*! @brief The error that happened during token refresh (if any). + */ +@property (nonatomic, strong) NSError *error; + ++ (GTMAppAuthFetcherAuthorizationArgs *)argsWithRequest:(NSMutableURLRequest *)req + delegate:(id)delegate + selector:(SEL)selector + completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)completionHandler; + +@end + +@implementation GTMAppAuthFetcherAuthorizationArgs + +@synthesize request = _request; +@synthesize delegate = _delegate; +@synthesize selector = _selector; +@synthesize completionHandler = _completionHandler; +@synthesize error = _error; + ++ (GTMAppAuthFetcherAuthorizationArgs *)argsWithRequest:(NSMutableURLRequest *)req + delegate:(id)delegate + selector:(SEL)selector + completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)completionHandler { + GTMAppAuthFetcherAuthorizationArgs *obj; + obj = [[GTMAppAuthFetcherAuthorizationArgs alloc] init]; + obj.request = req; + obj.delegate = delegate; + obj.selector = selector; + obj.completionHandler = completionHandler; + return obj; +} + +@end + +@implementation GTMAppAuthFetcherAuthorization { + /*! @brief Array of requests pending authorization headers. + */ + NSMutableArray *_authorizationQueue; +} + +@synthesize authState = _authState; +@synthesize serviceProvider = _serviceProvider; +@synthesize userID = _userID; +@synthesize userEmailIsVerified = _userEmailIsVerified; + +// GTMFetcherAuthorizationProtocol doesn't specify atomic/nonatomic for these properties. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wimplicit-atomic-properties" +@synthesize userEmail = _userEmail; +@synthesize shouldAuthorizeAllRequests = _shouldAuthorizeAllRequests; +@synthesize fetcherService = _fetcherService; +#pragma clang diagnostic pop + +#pragma mark - Initializers + +// Ignore warning about not calling the designated initializer. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wobjc-designated-initializers" +- (instancetype)init + GTM_UNAVAILABLE_USE_INITIALIZER(@selector(initWithAuthState:)); +#pragma clang diagnostic pop + +- (instancetype)initWithAuthState:(OIDAuthState *)authState { + return [self initWithAuthState:authState + serviceProvider:nil + userID:nil + userEmail:nil + userEmailIsVerified:nil]; +} + +- (instancetype)initWithAuthState:(OIDAuthState *)authState + serviceProvider:(nullable NSString *)serviceProvider + userID:(nullable NSString *)userID + userEmail:(nullable NSString *)userEmail + userEmailIsVerified:(nullable NSString *)userEmailIsVerified { + self = [super init]; + if (self) { + _authState = authState; + _authorizationQueue = [[NSMutableArray alloc] init]; + + _serviceProvider = [serviceProvider copy]; + _userID = [userID copy]; + _userEmail = [userEmail copy]; + _userEmailIsVerified = [userEmailIsVerified copy]; + + // Decodes the ID Token locally to extract the email address. + NSString *idToken = _authState.lastTokenResponse.idToken + ? : _authState.lastAuthorizationResponse.idToken; + if (idToken) { + NSDictionary *claimsDictionary = [[self class] extractIDTokenClaimsNoVerification:idToken]; + if (claimsDictionary) { + _userEmail = (NSString *)[claimsDictionary[@"email"] copy]; + _userEmailIsVerified = [(NSNumber *)claimsDictionary[@"email_verified"] stringValue]; + _userID = [claimsDictionary[@"sub"] copy]; + } + } + } + return self; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder { + OIDAuthState *authState = + [aDecoder decodeObjectOfClass:[OIDAuthState class] forKey:kAuthStateKey]; + NSString *serviceProvider = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kServiceProviderKey]; + NSString *userID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserIDKey]; + NSString *userEmail = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserEmailKey]; + NSString *userEmailIsVerified = + [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserEmailIsVerifiedKey]; + + self = [self initWithAuthState:authState + serviceProvider:serviceProvider + userID:userID + userEmail:userEmail + userEmailIsVerified:userEmailIsVerified]; + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:_authState forKey:kAuthStateKey]; + [aCoder encodeObject:_serviceProvider forKey:kServiceProviderKey]; + [aCoder encodeObject:_userID forKey:kUserIDKey]; + [aCoder encodeObject:_userEmail forKey:kUserEmailKey]; + [aCoder encodeObject:_userEmailIsVerified forKey:kUserEmailIsVerifiedKey]; +} + +# pragma mark - Convenience + +#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT ++ (OIDServiceConfiguration *)configurationForGoogle { + NSURL *authorizationEndpoint = + [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/v2/auth"]; + NSURL *tokenEndpoint = + [NSURL URLWithString:@"https://www.googleapis.com/oauth2/v4/token"]; + + OIDServiceConfiguration *configuration = + [[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:authorizationEndpoint + tokenEndpoint:tokenEndpoint]; + return configuration; +} +#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +# pragma mark - ID Token extraction + ++ (nullable NSDictionary *)extractIDTokenClaimsNoVerification:(NSString *)idToken { + NSArray *sections = [idToken componentsSeparatedByString:@"."]; + if (sections.count > 1) { + // Gets the JWT payload section. + NSMutableString *body = [sections[1] mutableCopy]; + + // Converts base64url to base64. + NSRange range = NSMakeRange(0, body.length); + [body replaceOccurrencesOfString:@"-" withString:@"+" options:NSLiteralSearch range:range]; + [body replaceOccurrencesOfString:@"_" withString:@"/" options:NSLiteralSearch range:range]; + + // Converts base64 no padding to base64 with padding + while (body.length % 4 != 0) { + [body appendString:@"="]; + } + + // Decodes base64 string. + NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:body options:0]; + + // Parses JSON. + NSError *error; + id object = [NSJSONSerialization JSONObjectWithData:decodedData options:0 error:&error]; + if (error) { + NSLog(@"Error %@ parsing token payload %@", error, body); + } + if ([object isKindOfClass:[NSDictionary class]]) { + return (NSDictionary *)object; + } + } + return nil; +} + +#pragma mark - GTMFetcherAuthorizationProtocol + +#pragma mark Authorizing Requests + +/*! @brief Authorizing with a completion block. + */ +- (void)authorizeRequest:(NSMutableURLRequest *)request + completionHandler:(GTMAppAuthFetcherAuthorizationCompletion)handler { + GTMAppAuthFetcherAuthorizationArgs *args = + [GTMAppAuthFetcherAuthorizationArgs argsWithRequest:request + delegate:nil + selector:NULL + completionHandler:handler]; + [self authorizeRequestArgs:args]; +} + +/*! @brief Authorizing with a callback selector. + @discussion Selector has the signature: + - (void)authentication:(GTMAppAuthFetcherAuthorization *)auth + request:(NSMutableURLRequest *)request + finishedWithError:(NSError *)error; + */ +- (void)authorizeRequest:(NSMutableURLRequest *)request + delegate:(id)delegate + didFinishSelector:(SEL)sel { + GTMOAuth2AssertValidSelector(delegate, sel, + @encode(GTMAppAuthFetcherAuthorization *), + @encode(NSMutableURLRequest *), + @encode(NSError *), 0); + + GTMAppAuthFetcherAuthorizationArgs *args; + args = [GTMAppAuthFetcherAuthorizationArgs argsWithRequest:request + delegate:delegate + selector:sel + completionHandler:nil]; + [self authorizeRequestArgs:args]; +} + +/*! @brief Internal routine common to delegate and block invocations to queue requests while + fresh tokens are obtained. + */ +- (void)authorizeRequestArgs:(GTMAppAuthFetcherAuthorizationArgs *)args { + // Adds requests to queue. + @synchronized(_authorizationQueue) { + [_authorizationQueue addObject:args]; + } + + // Obtains fresh tokens from AppAuth. + [_authState performActionWithFreshTokens:^(NSString *_Nullable accessToken, + NSString *_Nullable idToken, + NSError *_Nullable error) { + // Processes queue. + @synchronized(_authorizationQueue) { + for (GTMAppAuthFetcherAuthorizationArgs *fetcherArgs in _authorizationQueue) { + [self authorizeRequestImmediateArgs:fetcherArgs accessToken:accessToken error:error]; + } + [_authorizationQueue removeAllObjects]; + } + }]; +} + +/*! @brief Adds authorization headers to the given request, using the supplied access token, or + handles the error. + @param args The request argument group to authorize. + @param accessToken A currently valid access token. + @param error If accessToken is nil, the error which caused the token to be unavailable. + @return YES if the request was authorized with a valid access token. + */ +- (BOOL)authorizeRequestImmediateArgs:(GTMAppAuthFetcherAuthorizationArgs *)args + accessToken:(NSString *)accessToken + error:(NSError *)error { + // This authorization entry point never attempts to refresh the access token, + // but does call the completion routine + + NSMutableURLRequest *request = args.request; + + NSURL *requestURL = [request URL]; + NSString *scheme = [requestURL scheme]; + BOOL isAuthorizableRequest = + !requestURL + || (scheme && [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) + || [requestURL isFileURL] + || self.shouldAuthorizeAllRequests; + if (!isAuthorizableRequest) { + // Request is not https, a local file, or nil, so may be insecure + // + // The NSError will be created below +#if DEBUG + NSLog(@"Cannot authorize request with scheme %@ (%@)", scheme, request); +#endif + } + + // Get the access token. + if (isAuthorizableRequest && accessToken && accessToken.length > 0) { + if (request) { + // Adds the authorization header to the request. + NSString *value = [NSString stringWithFormat:@"%@ %@", @"Bearer", accessToken]; + [request setValue:value forHTTPHeaderField:@"Authorization"]; + } + + // We've authorized the request, even if the previous refresh + // failed with an error + args.error = nil; + } else { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (!userInfo) { + userInfo = [[NSMutableDictionary alloc] init]; + } + if (request) { + userInfo[GTMAppAuthFetcherAuthorizationErrorRequestKey] = request; + } + + if (!isAuthorizableRequest || !error) { + args.error = [NSError errorWithDomain:GTMAppAuthFetcherAuthorizationErrorDomain + code:GTMAppAuthFetcherAuthorizationErrorUnauthorizableRequest + userInfo:userInfo]; + } else { + // Passes through error domain & code from AppAuth, with additional userInfo args. + args.error = [NSError errorWithDomain:error.domain + code:error.code + userInfo:userInfo]; + } + } + + // Invoke any callbacks on the proper thread + if (args.delegate || args.completionHandler) { + // If the fetcher service provides a callback queue, we'll use that + // (or if it's nil, we'll use the main thread) for callbacks. + dispatch_queue_t callbackQueue = self.fetcherService.callbackQueue; + if (!callbackQueue) { + callbackQueue = dispatch_get_main_queue(); + } + dispatch_async(callbackQueue, ^{ + [self invokeCallbackArgs:args]; + }); + } + + BOOL didAuth = (args.error == nil); + return didAuth; +} + +/*! @brief Invokes the callback for the given authorization argument group. + @param args The request argument group to invoke following authorization or error. + */ +- (void)invokeCallbackArgs:(GTMAppAuthFetcherAuthorizationArgs *)args { + NSError *error = args.error; + id delegate = args.delegate; + SEL sel = args.selector; + + // If the selector callback method exists, invokes the selector. + if (delegate && sel) { + NSMutableURLRequest *request = args.request; + + NSMethodSignature *sig = [delegate methodSignatureForSelector:sel]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; + [invocation setSelector:sel]; + [invocation setTarget:delegate]; + GTMAppAuthFetcherAuthorization *authorization = self; + [invocation setArgument:&authorization atIndex:2]; + [invocation setArgument:&request atIndex:3]; + [invocation setArgument:&error atIndex:4]; + [invocation invoke]; + } + + // If a callback block exists, executes the block. + id handler = args.completionHandler; + if (handler) { + void (^authCompletionBlock)(NSError *) = handler; + authCompletionBlock(error); + } +} + +/*! @brief Removes all pending requests from the authorization queue. + */ +- (void)stopAuthorization { + @synchronized(_authorizationQueue) { + [_authorizationQueue removeAllObjects]; + } +} + +/*! @brief Attempts to remove a specific pending requests from the authorization queue. + @discussion Has no effect if the authorization already occurred. + */ +- (void)stopAuthorizationForRequest:(NSURLRequest *)request { + @synchronized(_authorizationQueue) { + NSUInteger argIndex = 0; + BOOL found = NO; + for (GTMAppAuthFetcherAuthorizationArgs *args in _authorizationQueue) { + // Checks pointer equality with given request, don't want to match equivalent requests. + if ([args request] == request) { + found = YES; + break; + } + argIndex++; + } + + if (found) { + [_authorizationQueue removeObjectAtIndex:argIndex]; + + // If the queue is now empty, go ahead and stop the fetcher. + if (_authorizationQueue.count == 0) { + [self stopAuthorization]; + } + } + } +} + +/*! @brief Returns YES if the given requests is in the pending authorization queue. + */ +- (BOOL)isAuthorizingRequest:(NSURLRequest *)request { + BOOL wasFound = NO; + @synchronized(_authorizationQueue) { + for (GTMAppAuthFetcherAuthorizationArgs *args in _authorizationQueue) { + // Checks pointer equality with given request, don't want to match equivalent requests. + if ([args request] == request) { + wasFound = YES; + break; + } + } + } + return wasFound; +} + +/*! @brief Returns YES if given request has an Authorization header. + */ +- (BOOL)isAuthorizedRequest:(NSURLRequest *)request { + NSString *authStr = [request valueForHTTPHeaderField:@"Authorization"]; + return (authStr.length > 0); +} + +/*! @brief Returns YES if the authorization state is currently valid. + @discussion Note that the state can become invalid immediately due to an error on token refresh. + */ +- (BOOL)canAuthorize { + return [_authState isAuthorized]; +} + +/*! @brief Forces a token refresh the next time a request is queued for authorization. + */ +- (BOOL)primeForRefresh { + if (_authState.refreshToken == nil) { + // Cannot refresh without a refresh token + return NO; + } + [_authState setNeedsTokenRefresh]; + return YES; +} + +@end diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMKeychain.h b/Paco-iOS/Pods/GTMAppAuth/Source/GTMKeychain.h new file mode 100644 index 000000000..760131908 --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMKeychain.h @@ -0,0 +1,62 @@ +/*! @file GTMKeychain.h + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Utility for saving and loading data to the keychain. + */ +@interface GTMKeychain : NSObject + +/*! @brief Saves the password string to the keychain with the given identifier. + @param keychainItemName Keychain name of the item. + @param password Password string to save. + @return YES when the password string was saved successfully. + */ ++ (BOOL)savePasswordToKeychainForName:(NSString *)keychainItemName password:(NSString *)password; + +/*! @brief Loads the password string from the keychain with the given identifier. + @param keychainItemName Keychain name of the item. + @return The password string at the given identifier, or nil. + */ ++ (nullable NSString *)passwordFromKeychainForName:(NSString *)keychainItemName; + +/*! @brief Saves the password data to the keychain with the given identifier. + @param keychainItemName Keychain name of the item. + @param passwordData Password data to save. + @return YES when the password data was saved successfully. + */ ++ (BOOL)savePasswordDataToKeychainForName:(NSString *)keychainItemName + passwordData:(NSData *)password; + +/*! @brief Loads the password data from the keychain with the given identifier. + @param keychainItemName Keychain name of the item. + @return The password data at the given identifier, or nil. + */ ++ (nullable NSData *)passwordDataFromKeychainForName:(NSString *)keychainItemName; + +/*! @brief Removes stored password string, such as when the user signs out. + @param keychainItemName Keychain name of the item. + @return YES if the password string was removed successfully (or didn't exist). + */ ++ (BOOL)removePasswordFromKeychainForName:(NSString *)keychainItemName; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.h b/Paco-iOS/Pods/GTMAppAuth/Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.h new file mode 100644 index 000000000..9fa123898 --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.h @@ -0,0 +1,135 @@ +/*! @file GTMOAuth2Compatibility.h + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMAppAuthFetcherAuthorization.h" + +NS_ASSUME_NONNULL_BEGIN + +/*! @brief Class to support serialization and deserialization of @c GTMAppAuthFetcherAuthorization + in the format used by GTMOAuth2. + @discussion The methods of this class are capable of serializing and deserializing auth + objects in a way compatible with the serialization in @c GTMOAuth2ViewControllerTouch and + @c GTMOAuth2WindowController in GTMOAuth2. + */ +@interface GTMOAuth2KeychainCompatibility : NSObject + +/*! @brief Encodes the given @c GTMAppAuthFetcherAuthorization in a GTMOAuth2 compatible persistence + string using URL param key/value encoding. + @param authorization The @c GTMAppAuthFetcherAuthorization to serialize in GTMOAuth2 format. + @return The GTMOAuth2 persistence representation of this object. + */ ++ (NSString *)persistenceResponseStringForAuthorization: + (GTMAppAuthFetcherAuthorization *)authorization; + +/*! @brief Attempts to create a @c GTMAppAuthFetcherAuthorization from data stored in the keychain + in GTMOAuth2 format, at the supplied keychain identifier. + @param keychainItemName The keychain name. + @param serviceProvider An optional string to describe the service. + @param tokenURL The OAuth token endpoint URL. + @param redirectURI The OAuth redirect URI used when obtaining the original authorization. + @param clientID The OAuth client id. + @param clientSecret The OAuth client secret. + @return A @c GTMAppAuthFetcherAuthorization object, or nil. + */ ++ (nullable GTMAppAuthFetcherAuthorization *) + authorizeFromKeychainForName:(NSString *)keychainItemName + serviceProvider:(nullable NSString *)serviceProvider + tokenURL:(NSURL *)tokenURL + redirectURI:(NSString *)redirectURI + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret; + +/*! @brief Attempts to create a @c GTMAppAuthFetcherAuthorization from a @c NSString + representation of the GTMOAuth2 keychain data. + @param persistenceString String representation of the GTMOAuth2 keychain data. + @param serviceProvider An optional string to describe the service. + @param tokenURL The OAuth token endpoint URL. + @param redirectURI The OAuth redirect URI used when obtaining the original authorization. + @param clientID The OAuth client id. + @param clientSecret The OAuth client secret. + @return A @c GTMAppAuthFetcherAuthorization object, or nil. + */ ++ (nullable GTMAppAuthFetcherAuthorization *) + authorizeFromPersistenceString:(NSString *)persistenceString + serviceProvider:(nullable NSString *)serviceProvider + tokenURL:(NSURL *)tokenURL + redirectURI:(NSString *)redirectURI + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret; + +/*! @brief Removes stored tokens, such as when the user signs out. + @param keychainItemName The keychain name. + @return YES the tokens were removed successfully (or didn't exist). + */ ++ (BOOL)removeAuthFromKeychainForName:(NSString *)keychainItemName; + +/*! @brief Saves the authorization state to the keychain, in a GTMOAuth2 compatible manner. + @param keychainItemName The keychain name. + @return YES when the state was saved successfully. + */ ++ (BOOL)saveAuthToKeychainForName:(NSString *)keychainItemName + authentication:(GTMAppAuthFetcherAuthorization *)auth + __attribute__((deprecated( + "Use GTMAppAuthFetcherAuthorization::saveAuthorization:toKeychainForName:"))); + +#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +/*! @brief Attempts to create a @c GTMAppAuthFetcherAuthorization from data stored in the keychain + in GTMOAuth2 format, at the supplied keychain identifier. Uses Google OAuth provider + information. + @param keychainItemName The keychain name. + @param clientID The OAuth client id. + @param clientSecret The OAuth client secret. + @return A @c GTMAppAuthFetcherAuthorization object, or nil. + */ ++ (nullable GTMAppAuthFetcherAuthorization *) + authForGoogleFromKeychainForName:(NSString *)keychainItemName + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret; + +/*! @brief Returns Google's OAuth 2.0 authorization endpoint. + @return Returns Google's OAuth 2.0 authorization endpoint. + */ ++ (NSURL *)googleAuthorizationURL; + +/*! @brief Returns Google's OAuth 2.0 token endpoint. + @return Returns Google's OAuth 2.0 token endpoint. + */ ++ (NSURL *)googleTokenURL; + +/*! @brief Returns Google's OAuth 2.0 revocation endpoint. + @return Returns Google's OAuth 2.0 revocation endpoint. + */ ++ (NSURL *)googleRevocationURL; + +/*! @brief Returns Google's OAuth 2.0 userinfo endpoint. + @return Returns Google's OAuth 2.0 userinfo endpoint. + */ ++ (NSURL *)googleUserInfoURL; + +/*! @brief Returns Google's native OOB redirect URI. + @discussion This is a legacy redirect URI that was used with WebViews. + @return Returns Google's native OOB redirect URI. + */ ++ (NSString *)nativeClientRedirectURI; + +#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +@end + +NS_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.m b/Paco-iOS/Pods/GTMAppAuth/Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.m new file mode 100644 index 000000000..514359978 --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.m @@ -0,0 +1,321 @@ +/*! @file GTMOAuth2Compatibility.m + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMOAuth2KeychainCompatibility.h" + +#import "AppAuth.h" +#import "GTMKeychain.h" + +// standard OAuth keys +static NSString *const kOAuth2AccessTokenKey = @"access_token"; +static NSString *const kOAuth2RefreshTokenKey = @"refresh_token"; +static NSString *const kOAuth2ScopeKey = @"scope"; +static NSString *const kOAuth2ErrorKey = @"error"; +static NSString *const kOAuth2TokenTypeKey = @"token_type"; +static NSString *const kOAuth2ExpiresInKey = @"expires_in"; +static NSString *const kOAuth2CodeKey = @"code"; +static NSString *const kOAuth2AssertionKey = @"assertion"; +static NSString *const kOAuth2RefreshScopeKey = @"refreshScope"; + +// additional persistent keys +static NSString *const kServiceProviderKey = @"serviceProvider"; +static NSString *const kUserIDKey = @"userID"; +static NSString *const kUserEmailKey = @"email"; +static NSString *const kUserEmailIsVerifiedKey = @"isVerified"; + +// URI indicating an installed app is signing in. This is described at +// +// https://developers.google.com/identity/protocols/OAuth2InstalledApp#formingtheurl +// +static NSString *const kOOBString = @"urn:ietf:wg:oauth:2.0:oob"; + +static NSString *const kGTMOAuth2ServiceProviderGoogle = @"Google"; + +@implementation GTMOAuth2KeychainCompatibility + +// This returns a "response string" that can be passed later to +// setKeysForResponseString: to reuse an old access token in a new auth object ++ (NSString *)persistenceResponseStringForAuthorization: + (GTMAppAuthFetcherAuthorization *)authorization { + NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; + + NSString *refreshToken = authorization.authState.refreshToken; + NSString *accessToken = authorization.authState.lastTokenResponse.accessToken; + + // Any nil values will not set a dictionary entry + [dict setValue:refreshToken forKey:kOAuth2RefreshTokenKey]; + [dict setValue:accessToken forKey:kOAuth2AccessTokenKey]; + [dict setValue:authorization.serviceProvider forKey:kServiceProviderKey]; + [dict setValue:authorization.userID forKey:kUserIDKey]; + [dict setValue:authorization.userEmail forKey:kUserEmailKey]; + [dict setValue:authorization.userEmailIsVerified forKey:kUserEmailIsVerifiedKey]; + [dict setValue:authorization.authState.scope forKey:kOAuth2ScopeKey]; + + NSString *result = [self encodedQueryParametersForDictionary:dict]; + return result; +} + ++ (GTMAppAuthFetcherAuthorization *)authorizeFromKeychainForName:(NSString *)keychainItemName + serviceProvider:(nullable NSString *)serviceProvider + tokenURL:(NSURL *)tokenURL + redirectURI:(NSString *)redirectURI + clientID:(NSString *)clientID + clientSecret:(nullable NSString *)clientSecret { + // Loads password string from keychain. + NSString *password = [GTMKeychain passwordFromKeychainForName:keychainItemName]; + + if (!password) { + return nil; + } + + GTMAppAuthFetcherAuthorization *authorization = + [self authorizeFromPersistenceString:password + serviceProvider:serviceProvider + tokenURL:tokenURL + redirectURI:redirectURI + clientID:clientID + clientSecret:clientSecret]; + return authorization; +} + ++ (GTMAppAuthFetcherAuthorization *)authorizeFromPersistenceString:(NSString *)persistenceString + serviceProvider:(NSString *)serviceProvider + tokenURL:(NSURL *)tokenURL + redirectURI:(NSString *)redirectURIString + clientID:(NSString *)clientID + clientSecret:(NSString *)clientSecret { + // Parses persistence data into NSDictionary. + NSDictionary *dict = [self dictionaryWithResponseString:persistenceString]; + + NSURL *redirectURI = (NSURL *)[NSURL URLWithString:redirectURIString]; + + // OIDAuthState is based on the request/response history. + // Creates history based on the data from the keychain, and client details passed in. + OIDServiceConfiguration *authConfig = + [[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:tokenURL tokenEndpoint:tokenURL]; + OIDAuthorizationRequest *authRequest = + [[OIDAuthorizationRequest alloc] initWithConfiguration:authConfig + clientId:clientID + clientSecret:clientSecret + scope:dict[kOAuth2ScopeKey] + redirectURL:redirectURI + responseType:@"token" + state:nil + codeVerifier:nil + codeChallenge:nil + codeChallengeMethod:nil + additionalParameters:nil]; + OIDAuthorizationResponse *authResponse = + [[OIDAuthorizationResponse alloc] initWithRequest:authRequest parameters:dict]; + OIDTokenRequest *tokenRequest = + [[OIDTokenRequest alloc] initWithConfiguration:authConfig + grantType:@"token" + authorizationCode:nil + redirectURL:redirectURI + clientID:clientID + clientSecret:clientSecret + scope:dict[kOAuth2ScopeKey] + refreshToken:dict[kOAuth2RefreshTokenKey] + codeVerifier:nil + additionalParameters:dict]; + OIDTokenResponse *tokenResponse = + [[OIDTokenResponse alloc] initWithRequest:tokenRequest parameters:dict]; + OIDAuthState *authState = [[OIDAuthState alloc] initWithAuthorizationResponse:authResponse + tokenResponse:tokenResponse]; + // We're not serializing the token expiry date, so the first refresh needs to be forced. + [authState setNeedsTokenRefresh]; + + GTMAppAuthFetcherAuthorization *authorizer = + [[GTMAppAuthFetcherAuthorization alloc] initWithAuthState:authState + serviceProvider:dict[kServiceProviderKey] + userID:dict[kUserIDKey] + userEmail:dict[kUserEmailKey] + userEmailIsVerified:dict[kUserEmailIsVerifiedKey]]; + return authorizer; +} + +#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + ++ (GTMAppAuthFetcherAuthorization *)authForGoogleFromKeychainForName:(NSString *)keychainItemName + clientID:(NSString *)clientID + clientSecret:(NSString *)clientSecret { + Class signInClass = self; + NSURL *tokenURL = [signInClass googleTokenURL]; + NSString *redirectURI = [signInClass nativeClientRedirectURI]; + + GTMAppAuthFetcherAuthorization *auth; + auth = [self authorizeFromKeychainForName:keychainItemName + serviceProvider:kGTMOAuth2ServiceProviderGoogle + tokenURL:tokenURL + redirectURI:redirectURI + clientID:clientID + clientSecret:clientSecret]; + return auth; +} + +#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +/*! @brief Removes stored tokens, such as when the user signs out. + @return YES the tokens were removed successfully (or didn't exist). + */ ++ (BOOL)removeAuthFromKeychainForName:(NSString *)keychainItemName { + return [GTMKeychain removePasswordFromKeychainForName:keychainItemName]; +} + +/*! @brief Saves the authorization state to the keychain, in a GTMOAuth2 compatible manner. + @return YES when the state was saved successfully. + */ ++ (BOOL)saveAuthToKeychainForName:(NSString *)keychainItemName + authentication:(GTMAppAuthFetcherAuthorization *)auth { + [self removeAuthFromKeychainForName:keychainItemName]; + NSString *password = [self persistenceResponseStringForAuthorization:auth]; + + return [GTMKeychain savePasswordToKeychainForName:keychainItemName password:password]; +} + +#pragma mark Utility Routines + ++ (NSString *)encodedQueryParametersForDictionary:(NSDictionary *)dict { + // Make a string like "cat=fluffy&dog=spot" + NSMutableString *result = [NSMutableString string]; + NSArray *sortedKeys = + [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; + NSString *joiner = @""; + for (NSString *key in sortedKeys) { + NSString *value = [dict objectForKey:key]; + NSString *encodedValue = [self encodedOAuthValueForString:value]; + NSString *encodedKey = [self encodedOAuthValueForString:key]; + [result appendFormat:@"%@%@=%@", joiner, encodedKey, encodedValue]; + joiner = @"&"; + } + return result; +} + ++ (NSString *)encodedOAuthValueForString:(NSString *)originalString { + // For parameters, we'll explicitly leave spaces unescaped now, and replace + // them with +'s + NSString *const kForceEscape = @"!*'();:@&=+$,/?%#[]"; + +#if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_9) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_7_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0) + // Builds targeting iOS 7/OS X 10.9 and higher only. + NSMutableCharacterSet *cs = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [cs removeCharactersInString:kForceEscape]; + + return [originalString stringByAddingPercentEncodingWithAllowedCharacters:cs]; +#else + // Builds targeting iOS 6/OS X 10.8. + CFStringRef escapedStr = NULL; + if (originalString) { + escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, + (CFStringRef)originalString, + NULL, + (CFStringRef)kForceEscape, + kCFStringEncodingUTF8); + } + + return (__bridge NSString *)escapedStr; +#endif +} + ++ (NSDictionary *)dictionaryWithResponseString:(NSString *)responseStr { + // Build a dictionary from a response string of the form + // "cat=fluffy&dog=spot". Missing or empty values are considered + // empty strings; keys and values are percent-decoded. + if (responseStr == nil) return nil; + + NSArray *items = [responseStr componentsSeparatedByString:@"&"]; + + NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithCapacity:items.count]; + + for (NSString *item in items) { + NSString *key; + NSString *value = @""; + + NSRange equalsRange = [item rangeOfString:@"="]; + if (equalsRange.location != NSNotFound) { + // The parameter has at least one '=' + key = [item substringToIndex:equalsRange.location]; + + // There are characters after the '=' + if (equalsRange.location + 1 < item.length) { + value = [item substringFromIndex:(equalsRange.location + 1)]; + } + } else { + // The parameter has no '=' + key = item; + } + + NSString *plainKey = [self unencodedOAuthParameterForString:key]; + NSString *plainValue = [self unencodedOAuthParameterForString:value]; + + [responseDict setObject:plainValue forKey:plainKey]; + } + + return responseDict; +} + ++ (NSString *)unencodedOAuthParameterForString:(NSString *)str { +#if (!TARGET_OS_IPHONE \ + && defined(MAC_OS_X_VERSION_10_9) \ + && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9) \ + || (TARGET_OS_IPHONE \ + && defined(__IPHONE_7_0) \ + && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_7_0) + // On iOS 7, -stringByRemovingPercentEncoding incorrectly returns nil for an empty string. + if (str != nil && [str length] == 0) return @""; + + NSString *plainStr = [str stringByRemovingPercentEncoding]; + return plainStr; +#else + NSString *plainStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + return plainStr; +#endif +} + +#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +// Endpoint URLs are available at https://accounts.google.com/.well-known/openid-configuration + ++ (NSURL *)googleAuthorizationURL { + NSString *str = @"https://accounts.google.com/o/oauth2/v2/auth"; + return (NSURL *)[NSURL URLWithString:str]; +} + ++ (NSURL *)googleTokenURL { + NSString *str = @"https://www.googleapis.com/oauth2/v4/token"; + return (NSURL *)[NSURL URLWithString:str]; +} + ++ (NSURL *)googleRevocationURL { + NSString *urlStr = @"https://accounts.google.com/o/oauth2/revoke"; + return (NSURL *)[NSURL URLWithString:urlStr]; +} + ++ (NSURL *)googleUserInfoURL { + NSString *urlStr = @"https://www.googleapis.com/oauth2/v3/userinfo"; + return (NSURL *)[NSURL URLWithString:urlStr]; +} + ++ (NSString *)nativeClientRedirectURI { + return kOOBString; +} + +#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT + +@end diff --git a/Paco-iOS/Pods/GTMAppAuth/Source/iOS/GTMKeychain_iOS.m b/Paco-iOS/Pods/GTMAppAuth/Source/iOS/GTMKeychain_iOS.m new file mode 100644 index 000000000..78025e22c --- /dev/null +++ b/Paco-iOS/Pods/GTMAppAuth/Source/iOS/GTMKeychain_iOS.m @@ -0,0 +1,287 @@ +/*! @file GTMKeychain_iOS.m + @brief GTMAppAuth SDK + @copyright + Copyright 2016 Google Inc. All Rights Reserved. + @copydetails + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "GTMKeychain.h" + +#import + +typedef NS_ENUM(NSInteger, GTMAppAuthFetcherAuthorizationGTMAppAuthGTMOAuth2KeychainError) { + GTMAppAuthGTMOAuth2KeychainErrorBadArguments = -1301, + GTMAppAuthGTMOAuth2KeychainErrorNoPassword = -1302 +}; + +/*! @brief Keychain helper class. + */ +@interface GTMAppAuthGTMOAuth2Keychain : NSObject + ++ (GTMAppAuthGTMOAuth2Keychain *)defaultKeychain; + +// OK to pass nil for the error parameter. +- (NSString *)passwordForService:(NSString *)service + account:(NSString *)account + error:(NSError **)error; + +- (NSData *)passwordDataForService:(NSString *)service + account:(NSString *)account + error:(NSError **)error; + +// OK to pass nil for the error parameter. +- (BOOL)removePasswordForService:(NSString *)service + account:(NSString *)account + error:(NSError **)error; + +// OK to pass nil for the error parameter. +// +// accessibility should be one of the constants for kSecAttrAccessible +// such as kSecAttrAccessibleWhenUnlocked +- (BOOL)setPassword:(NSString *)password + forService:(NSString *)service + accessibility:(CFTypeRef)accessibility + account:(NSString *)account + error:(NSError **)error; + +- (BOOL)setPasswordData:(NSData *)passwordData + forService:(NSString *)service + accessibility:(CFTypeRef)accessibility + account:(NSString *)account + error:(NSError **)error; + +// For unit tests: allow setting a mock object ++ (void)setDefaultKeychain:(GTMAppAuthGTMOAuth2Keychain *)keychain; + +@end + +NSString *const kGTMAppAuthFetcherAuthorizationGTMOAuth2ErrorDomain = @"com.google.GTMOAuth2"; +NSString *const kGTMAppAuthFetcherAuthorizationGTMOAuth2KeychainErrorDomain = + @"com.google.GTMOAuthKeychain"; +static NSString *const kGTMAppAuthFetcherAuthorizationGTMOAuth2AccountName = @"OAuth"; +static GTMAppAuthGTMOAuth2Keychain* gGTMAppAuthFetcherAuthorizationGTMOAuth2DefaultKeychain = nil; + +@implementation GTMKeychain + ++ (BOOL)removePasswordFromKeychainForName:(NSString *)keychainItemName { + GTMAppAuthGTMOAuth2Keychain *keychain = [GTMAppAuthGTMOAuth2Keychain defaultKeychain]; + return [keychain removePasswordForService:keychainItemName + account:kGTMAppAuthFetcherAuthorizationGTMOAuth2AccountName + error:nil]; +} + ++ (NSString *)passwordFromKeychainForName:(NSString *)keychainItemName { + GTMAppAuthGTMOAuth2Keychain *keychain = [GTMAppAuthGTMOAuth2Keychain defaultKeychain]; + NSError *error; + NSString *password = + [keychain passwordForService:keychainItemName + account:kGTMAppAuthFetcherAuthorizationGTMOAuth2AccountName + error:&error]; + return password; +} + ++ (BOOL)savePasswordToKeychainForName:(NSString *)keychainItemName password:(NSString *)password { + return [self savePasswordToKeychainForName:keychainItemName + password:password + accessibility:NULL + error:NULL]; +} + ++ (BOOL)savePasswordToKeychainForName:(NSString *)keychainItemName password:(NSString *)password + accessibility:(CFTypeRef)accessibility + error:(NSError **)error { + if (accessibility == NULL) { + accessibility = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly; + } + // make a response string containing the values we want to save + GTMAppAuthGTMOAuth2Keychain *keychain = [GTMAppAuthGTMOAuth2Keychain defaultKeychain]; + return [keychain setPassword:password + forService:keychainItemName + accessibility:accessibility + account:kGTMAppAuthFetcherAuthorizationGTMOAuth2AccountName + error:error]; +} + +/*! @brief Saves the password string to the keychain with the given identifier. + @param keychainItemName Keychain name of the item. + @param password Password string to save. + @return YES when the password string was saved successfully. + */ ++ (BOOL)savePasswordDataToKeychainForName:(NSString *)keychainItemName + passwordData:(NSData *)password { + CFTypeRef accessibility = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly; + // make a response string containing the values we want to save + GTMAppAuthGTMOAuth2Keychain *keychain = [GTMAppAuthGTMOAuth2Keychain defaultKeychain]; + return [keychain setPasswordData:password + forService:keychainItemName + accessibility:accessibility + account:kGTMAppAuthFetcherAuthorizationGTMOAuth2AccountName + error:NULL]; +} + +/*! @brief Loads the password string from the keychain with the given identifier. + @param keychainItemName Keychain name of the item. + @return The password string at the given identifier, or nil. + */ ++ (NSData *)passwordDataFromKeychainForName:(NSString *)keychainItemName { + GTMAppAuthGTMOAuth2Keychain *keychain = [GTMAppAuthGTMOAuth2Keychain defaultKeychain]; + NSError *error; + NSData *password = + [keychain passwordDataForService:keychainItemName + account:kGTMAppAuthFetcherAuthorizationGTMOAuth2AccountName + error:&error]; + return password; +} + +@end + +#pragma mark GTMAppAuthGTMOAuth2Keychain + +@implementation GTMAppAuthGTMOAuth2Keychain + ++ (GTMAppAuthGTMOAuth2Keychain *)defaultKeychain { + static dispatch_once_t onceToken; + dispatch_once (&onceToken, ^{ + gGTMAppAuthFetcherAuthorizationGTMOAuth2DefaultKeychain = [[self alloc] init]; + }); + return gGTMAppAuthFetcherAuthorizationGTMOAuth2DefaultKeychain; +} + + +// For unit tests: allow setting a mock object ++ (void)setDefaultKeychain:(GTMAppAuthGTMOAuth2Keychain *)keychain { + if (gGTMAppAuthFetcherAuthorizationGTMOAuth2DefaultKeychain != keychain) { + gGTMAppAuthFetcherAuthorizationGTMOAuth2DefaultKeychain = keychain; + } +} + +- (NSString *)keyForService:(NSString *)service account:(NSString *)account { + return [NSString stringWithFormat:@"com.google.GTMOAuth.%@%@", service, account]; +} + ++ (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account { + NSMutableDictionary *query = + [NSMutableDictionary dictionaryWithObjectsAndKeys:(id)kSecClassGenericPassword, (id)kSecClass, + @"OAuth", (id)kSecAttrGeneric, + account, (id)kSecAttrAccount, + service, (id)kSecAttrService, + nil]; + return query; +} + +- (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account { + return [[self class] keychainQueryForService:service account:account]; +} + +// iPhone +- (NSString *)passwordForService:(NSString *)service + account:(NSString *)account + error:(NSError **)error { + NSData *passwordData = [self passwordDataForService:service account:account error:error]; + if (!passwordData) { + return nil; + } + NSString *result = [[NSString alloc] initWithData:passwordData + encoding:NSUTF8StringEncoding]; + return result; +} + +// iPhone +- (NSData *)passwordDataForService:(NSString *)service + account:(NSString *)account + error:(NSError **)error { + OSStatus status = GTMAppAuthGTMOAuth2KeychainErrorBadArguments; + NSData *result = nil; + if (service.length > 0 && account.length > 0) { + CFDataRef passwordData = NULL; + NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account]; + [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData]; + [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit]; + + status = SecItemCopyMatching((CFDictionaryRef)keychainQuery, + (CFTypeRef *)&passwordData); + if (status == noErr && 0 < [(__bridge NSData *)passwordData length]) { + result = [(__bridge NSData *)passwordData copy]; + } + if (passwordData != NULL) { + CFRelease(passwordData); + } + } + if (status != noErr && error != NULL) { + *error = [NSError errorWithDomain:kGTMAppAuthFetcherAuthorizationGTMOAuth2KeychainErrorDomain + code:status + userInfo:nil]; + } + return result; +} + +// iPhone +- (BOOL)removePasswordForService:(NSString *)service + account:(NSString *)account + error:(NSError **)error { + OSStatus status = GTMAppAuthGTMOAuth2KeychainErrorBadArguments; + if (0 < [service length] && 0 < [account length]) { + NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account]; + status = SecItemDelete((CFDictionaryRef)keychainQuery); + } + if (status != noErr && error != NULL) { + *error = [NSError errorWithDomain:kGTMAppAuthFetcherAuthorizationGTMOAuth2KeychainErrorDomain + code:status + userInfo:nil]; + } + return status == noErr; +} + +// iPhone +- (BOOL)setPassword:(NSString *)password + forService:(NSString *)service + accessibility:(CFTypeRef)accessibility + account:(NSString *)account + error:(NSError **)error { + NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding]; + return [self setPasswordData:passwordData + forService:service + accessibility:accessibility + account:account + error:error]; +} + +- (BOOL)setPasswordData:(NSData *)passwordData + forService:(NSString *)service + accessibility:(CFTypeRef)accessibility + account:(NSString *)account + error:(NSError **)error { + OSStatus status = GTMAppAuthGTMOAuth2KeychainErrorBadArguments; + if (0 < [service length] && 0 < [account length]) { + [self removePasswordForService:service account:account error:nil]; + if (0 < [passwordData length]) { + NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account]; + [keychainQuery setObject:passwordData forKey:(id)kSecValueData]; + + if (accessibility != NULL) { + [keychainQuery setObject:(__bridge id)accessibility + forKey:(id)kSecAttrAccessible]; + } + status = SecItemAdd((CFDictionaryRef)keychainQuery, NULL); + } + } + if (status != noErr && error != NULL) { + *error = [NSError errorWithDomain:kGTMAppAuthFetcherAuthorizationGTMOAuth2KeychainErrorDomain + code:status + userInfo:nil]; + } + return status == noErr; +} + +@end diff --git a/Paco-iOS/Pods/GTMSessionFetcher/LICENSE b/Paco-iOS/Pods/GTMSessionFetcher/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Paco-iOS/Pods/GTMSessionFetcher/README.md b/Paco-iOS/Pods/GTMSessionFetcher/README.md new file mode 100644 index 000000000..478efde95 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/README.md @@ -0,0 +1,23 @@ +# Google Toolbox for Mac - Session Fetcher # + +**Project site**
+**Discussion group** + +[![Build Status](https://travis-ci.org/google/gtm-session-fetcher.svg?branch=master)](https://travis-ci.org/google/gtm-session-fetcher) + +`GTMSessionFetcher` makes it easy for Cocoa applications to perform http +operations. The fetcher is implemented as a wrapper on `NSURLSession`, so its +behavior is asynchronous and uses operating-system settings on iOS and Mac OS X. + +Features include: +- Simple to build; only one source/header file pair is required +- Simple to use: takes just two lines of code to fetch a request +- Supports upload and download sessions +- Flexible cookie storage +- Automatic retry on errors, with exponential backoff +- Support for generating multipart MIME upload streams +- Easy, convenient logging of http requests and responses +- Supports plug-in authentication such as with GTMAppAuth +- Easily testable; self-mocking +- Automatic rate limiting when created by the `GTMSessionFetcherService` factory class +- Fully independent of other projects diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMGatherInputStream.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMGatherInputStream.h new file mode 100644 index 000000000..ec3c0125d --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMGatherInputStream.h @@ -0,0 +1,52 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The GTMGatherInput stream is an input stream implementation that is to be +// instantiated with an NSArray of NSData objects. It works in the traditional +// scatter/gather vector I/O model. Rather than allocating a big NSData object +// to hold all of the data and performing a copy into that object, the +// GTMGatherInputStream will maintain a reference to the NSArray and read from +// each NSData in turn as the read method is called. You should not alter the +// underlying set of NSData objects until all read operations on this input +// stream have completed. + +#import + +#ifndef GTM_NONNULL + #if defined(__has_attribute) + #if __has_attribute(nonnull) + #define GTM_NONNULL(x) __attribute__((nonnull x)) + #else + #define GTM_NONNULL(x) + #endif + #else + #define GTM_NONNULL(x) + #endif +#endif + +// Avoid multiple declaration of this class. +// +// Note: This should match the declaration of GTMGatherInputStream in GTMMIMEDocument.m + +#ifndef GTM_GATHERINPUTSTREAM_DECLARED +#define GTM_GATHERINPUTSTREAM_DECLARED + +@interface GTMGatherInputStream : NSInputStream + ++ (NSInputStream *)streamWithArray:(NSArray *)dataArray GTM_NONNULL((1)); + +@end + +#endif // GTM_GATHERINPUTSTREAM_DECLARED diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMGatherInputStream.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMGatherInputStream.m new file mode 100644 index 000000000..0f65310ff --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMGatherInputStream.m @@ -0,0 +1,185 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMGatherInputStream.h" + +@implementation GTMGatherInputStream { + NSArray *_dataArray; // NSDatas that should be "gathered" and streamed. + NSUInteger _arrayIndex; // Index in the array of the current NSData. + long long _dataOffset; // Offset in the current NSData we are processing. + NSStreamStatus _streamStatus; + id __weak _delegate; // Stream delegate, defaults to self. +} + ++ (NSInputStream *)streamWithArray:(NSArray *)dataArray { + return [(GTMGatherInputStream *)[self alloc] initWithArray:dataArray]; +} + +- (instancetype)initWithArray:(NSArray *)dataArray { + self = [super init]; + if (self) { + _dataArray = dataArray; + _delegate = self; // An NSStream's default delegate should be self. + } + return self; +} + +#pragma mark - NSStream + +- (void)open { + _arrayIndex = 0; + _dataOffset = 0; + _streamStatus = NSStreamStatusOpen; +} + +- (void)close { + _streamStatus = NSStreamStatusClosed; +} + +- (id)delegate { + return _delegate; +} + +- (void)setDelegate:(id)delegate { + if (delegate == nil) { + _delegate = self; + } else { + _delegate = delegate; + } +} + +- (id)propertyForKey:(NSString *)key { + if ([key isEqual:NSStreamFileCurrentOffsetKey]) { + return @([self absoluteOffset]); + } + return nil; +} + +- (BOOL)setProperty:(id)property forKey:(NSString *)key { + if ([key isEqual:NSStreamFileCurrentOffsetKey]) { + NSNumber *absoluteOffsetNumber = property; + [self setAbsoluteOffset:absoluteOffsetNumber.longLongValue]; + return YES; + } + return NO; +} + +- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { +} + +- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { +} + +- (NSStreamStatus)streamStatus { + return _streamStatus; +} + +- (NSError *)streamError { + return nil; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len { + NSInteger bytesRead = 0; + NSUInteger bytesRemaining = len; + + // Read bytes from the currently-indexed array. + while ((bytesRemaining > 0) && (_arrayIndex < _dataArray.count)) { + NSData *data = [_dataArray objectAtIndex:_arrayIndex]; + + NSUInteger dataLen = data.length; + NSUInteger dataBytesLeft = dataLen - (NSUInteger)_dataOffset; + + NSUInteger bytesToCopy = MIN(bytesRemaining, dataBytesLeft); + NSRange range = NSMakeRange((NSUInteger) _dataOffset, bytesToCopy); + + [data getBytes:(buffer + bytesRead) range:range]; + + bytesRead += bytesToCopy; + _dataOffset += bytesToCopy; + bytesRemaining -= bytesToCopy; + + if (_dataOffset == (long long)dataLen) { + _dataOffset = 0; + _arrayIndex++; + } + } + if (_arrayIndex >= _dataArray.count) { + _streamStatus = NSStreamStatusAtEnd; + } + return bytesRead; +} + +- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len { + return NO; // We don't support this style of reading. +} + +- (BOOL)hasBytesAvailable { + // If we return no, the read never finishes, even if we've already delivered all the bytes. + return YES; +} + +#pragma mark - NSStreamDelegate + +- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { + id delegate = _delegate; + if (delegate != self) { + [delegate stream:self handleEvent:streamEvent]; + } +} + +#pragma mark - Private + +- (long long)absoluteOffset { + long long absoluteOffset = 0; + NSUInteger index = 0; + for (NSData *data in _dataArray) { + if (index >= _arrayIndex) { + break; + } + absoluteOffset += data.length; + ++index; + } + absoluteOffset += _dataOffset; + return absoluteOffset; +} + +- (void)setAbsoluteOffset:(long long)absoluteOffset { + if (absoluteOffset < 0) { + absoluteOffset = 0; + } + _arrayIndex = 0; + _dataOffset = absoluteOffset; + for (NSData *data in _dataArray) { + long long dataLen = (long long) data.length; + if (dataLen > _dataOffset) { + break; + } + _arrayIndex++; + _dataOffset -= dataLen; + } + if (_arrayIndex == _dataArray.count) { + if (_dataOffset > 0) { + _dataOffset = 0; + } + } +} + +@end diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMMIMEDocument.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMMIMEDocument.h new file mode 100644 index 000000000..451e13239 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMMIMEDocument.h @@ -0,0 +1,148 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This is a simple class to create or parse a MIME document. + +// To create a MIME document, allocate a new GTMMIMEDocument and start adding parts. +// When you are done adding parts, call generateInputStream or generateDispatchData. +// +// A good reference for MIME is http://en.wikipedia.org/wiki/MIME + +#import + +#ifndef GTM_NONNULL + #if defined(__has_attribute) + #if __has_attribute(nonnull) + #define GTM_NONNULL(x) __attribute__((nonnull x)) + #else + #define GTM_NONNULL(x) + #endif + #else + #define GTM_NONNULL(x) + #endif +#endif + +#ifndef GTM_DECLARE_GENERICS + #if __has_feature(objc_generics) + #define GTM_DECLARE_GENERICS 1 + #else + #define GTM_DECLARE_GENERICS 0 + #endif +#endif + +#ifndef GTM_NSArrayOf + #if GTM_DECLARE_GENERICS + #define GTM_NSArrayOf(value) NSArray + #define GTM_NSDictionaryOf(key, value) NSDictionary + #else + #define GTM_NSArrayOf(value) NSArray + #define GTM_NSDictionaryOf(key, value) NSDictionary + #endif // GTM_DECLARE_GENERICS +#endif // GTM_NSArrayOf + + +// GTMMIMEDocumentPart represents a part of a MIME document. +// +// +[GTMMIMEDocument MIMEPartsWithBoundary:data:] returns an array of these. +@interface GTMMIMEDocumentPart : NSObject + +@property(nonatomic, readonly) GTM_NSDictionaryOf(NSString *, NSString *) *headers; +@property(nonatomic, readonly) NSData *headerData; +@property(nonatomic, readonly) NSData *body; +@property(nonatomic, readonly) NSUInteger length; + ++ (instancetype)partWithHeaders:(NSDictionary *)headers body:(NSData *)body; + +@end + +@interface GTMMIMEDocument : NSObject + +// Get or set the unique boundary for the parts that have been added. +// +// When creating a MIME document from parts, this is typically calculated +// automatically after all parts have been added. +@property(nonatomic, copy) NSString *boundary; + +#pragma mark - Methods for Creating a MIME Document + ++ (instancetype)MIMEDocument; + +// Adds a new part to this mime document with the given headers and body. +// The headers keys and values should be NSStrings. +// Adding a part may cause the boundary string to change. +- (void)addPartWithHeaders:(GTM_NSDictionaryOf(NSString *, NSString *) *)headers + body:(NSData *)body GTM_NONNULL((1,2)); + +// An inputstream that can be used to efficiently read the contents of the MIME document. +// +// Any parameter may be null if the result is not wanted. +- (void)generateInputStream:(NSInputStream **)outStream + length:(unsigned long long *)outLength + boundary:(NSString **)outBoundary; + +// A dispatch_data_t with the contents of the MIME document. +// +// Note: dispatch_data_t is one-way toll-free bridged so the result +// may be cast directly to NSData *. +// +// Any parameter may be null if the result is not wanted. +- (void)generateDispatchData:(dispatch_data_t *)outDispatchData + length:(unsigned long long *)outLength + boundary:(NSString **)outBoundary; + +// Utility method for making a header section, including trailing newlines. ++ (NSData *)dataWithHeaders:(GTM_NSDictionaryOf(NSString *, NSString *) *)headers; + +#pragma mark - Methods for Parsing a MIME Document + +// Method for parsing out an array of MIME parts from a MIME document. +// +// Returns an array of GTMMIMEDocumentParts. Returns nil if no part can +// be found. ++ (GTM_NSArrayOf(GTMMIMEDocumentPart *) *)MIMEPartsWithBoundary:(NSString *)boundary + data:(NSData *)fullDocumentData; + +// Utility method for efficiently searching possibly discontiguous NSData +// for occurrences of target byte. This method does not "flatten" an NSData +// that is composed of discontiguous blocks. +// +// The byte offsets of non-overlapping occurrences of the target are returned as +// NSNumbers in the array. ++ (void)searchData:(NSData *)data + targetBytes:(const void *)targetBytes + targetLength:(NSUInteger)targetLength + foundOffsets:(GTM_NSArrayOf(NSNumber *) **)outFoundOffsets; + +// Utility method to parse header bytes into an NSDictionary. ++ (GTM_NSDictionaryOf(NSString *, NSString *) *)headersWithData:(NSData *)data; + +// ------ UNIT TESTING ONLY BELOW ------ + +// Internal methods, exposed for unit testing only. +- (void)seedRandomWith:(u_int32_t)seed; + ++ (NSUInteger)findBytesWithNeedle:(const unsigned char *)needle + needleLength:(NSUInteger)needleLength + haystack:(const unsigned char *)haystack + haystackLength:(NSUInteger)haystackLength + foundOffset:(NSUInteger *)foundOffset; + ++ (void)searchData:(NSData *)data + targetBytes:(const void *)targetBytes + targetLength:(NSUInteger)targetLength + foundOffsets:(GTM_NSArrayOf(NSNumber *) **)outFoundOffsets + foundBlockNumbers:(GTM_NSArrayOf(NSNumber *) **)outFoundBlockNumbers; + +@end diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMMIMEDocument.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMMIMEDocument.m new file mode 100644 index 000000000..7b21c30f9 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMMIMEDocument.m @@ -0,0 +1,629 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMMIMEDocument.h" + +// Avoid a hard dependency on GTMGatherInputStream. +#ifndef GTM_GATHERINPUTSTREAM_DECLARED +#define GTM_GATHERINPUTSTREAM_DECLARED + +@interface GTMGatherInputStream : NSInputStream + ++ (NSInputStream *)streamWithArray:(NSArray *)dataArray GTM_NONNULL((1)); + +@end +#endif // GTM_GATHERINPUTSTREAM_DECLARED + +// FindBytes +// +// Helper routine to search for the existence of a set of bytes (needle) within +// a presumed larger set of bytes (haystack). Can find the first part of the +// needle at the very end of the haystack. +// +// Returns the needle length on complete success, the number of bytes matched +// if a partial needle was found at the end of the haystack, and 0 on failure. +static NSUInteger FindBytes(const unsigned char *needle, NSUInteger needleLen, + const unsigned char *haystack, NSUInteger haystackLen, + NSUInteger *foundOffset); + +// SearchDataForBytes +// +// This implements the functionality of the +searchData: methods below. See the documentation +// for those methods. +static void SearchDataForBytes(NSData *data, const void *targetBytes, NSUInteger targetLength, + NSMutableArray *foundOffsets, NSMutableArray *foundBlockNumbers); + +@implementation GTMMIMEDocumentPart { + NSDictionary *_headers; + NSData *_headerData; // Header content including the ending "\r\n". + NSData *_bodyData; +} + +@synthesize headers = _headers, + headerData = _headerData, + body = _bodyData; + +@dynamic length; + ++ (instancetype)partWithHeaders:(NSDictionary *)headers body:(NSData *)body { + return [[self alloc] initWithHeaders:headers body:body]; +} + +- (instancetype)initWithHeaders:(NSDictionary *)headers body:(NSData *)body { + self = [super init]; + if (self) { + _bodyData = body; + _headers = headers; + } + return self; +} + +// Returns true if the part's header or data contain the given set of bytes. +// +// NOTE: We assume that the 'bytes' we are checking for do not contain "\r\n", +// so we don't need to check the concatenation of the header and body bytes. +- (BOOL)containsBytes:(const unsigned char *)bytes length:(NSUInteger)length { + // This uses custom search code rather than strcpy because the encoded data may contain + // null values. + NSData *headerData = self.headerData; + return (FindBytes(bytes, length, headerData.bytes, headerData.length, NULL) == length || + FindBytes(bytes, length, _bodyData.bytes, _bodyData.length, NULL) == length); +} + +- (NSData *)headerData { + if (!_headerData) { + _headerData = [GTMMIMEDocument dataWithHeaders:_headers]; + } + return _headerData; +} + +- (NSData *)body { + return _bodyData; +} + +- (NSUInteger)length { + return _headerData.length + _bodyData.length; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"%@ %p (headers %tu keys, body %tu bytes)", + [self class], self, _headers.count, _bodyData.length]; +} + +- (BOOL)isEqual:(GTMMIMEDocumentPart *)other { + if (self == other) return YES; + if (![other isKindOfClass:[GTMMIMEDocumentPart class]]) return NO; + return ((_bodyData == other->_bodyData || [_bodyData isEqual:other->_bodyData]) + && (_headers == other->_headers || [_headers isEqual:other->_headers])); +} + +- (NSUInteger)hash { + return _bodyData.hash | _headers.hash; +} + +@end + +@implementation GTMMIMEDocument { + NSMutableArray *_parts; // Ordered array of GTMMIMEDocumentParts. + unsigned long long _length; // Length in bytes of the document. + NSString *_boundary; + u_int32_t _randomSeed; // For testing. +} + ++ (instancetype)MIMEDocument { + return [[self alloc] init]; +} + +- (instancetype)init { + self = [super init]; + if (self) { + _parts = [[NSMutableArray alloc] init]; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"%@ %p (%tu parts)", + [self class], self, _parts.count]; +} + +#pragma mark - Joining Parts + +// Adds a new part to this mime document with the given headers and body. +- (void)addPartWithHeaders:(NSDictionary *)headers body:(NSData *)body { + GTMMIMEDocumentPart *part = [GTMMIMEDocumentPart partWithHeaders:headers body:body]; + [_parts addObject:part]; + _boundary = nil; +} + +// For unit testing only, seeds the random number generator so that we will +// have reproducible boundary strings. +- (void)seedRandomWith:(u_int32_t)seed { + _randomSeed = seed; + _boundary = nil; +} + +- (u_int32_t)random { + if (_randomSeed) { + // For testing only. + return _randomSeed++; + } else { + return arc4random(); + } +} + +// Computes the mime boundary to use. This should only be called +// after all the desired document parts have been added since it must compute +// a boundary that does not exist in the document data. +- (NSString *)boundary { + if (_boundary) { + return _boundary; + } + + // Use an easily-readable boundary string. + NSString *const kBaseBoundary = @"END_OF_PART"; + + _boundary = kBaseBoundary; + + // If the boundary isn't unique, append random numbers, up to 10 attempts; + // if that's still not unique, use a random number sequence instead, and call it good. + BOOL didCollide = NO; + + const int maxTries = 10; // Arbitrarily chosen maximum attempts. + for (int tries = 0; tries < maxTries; ++tries) { + + NSData *data = [_boundary dataUsingEncoding:NSUTF8StringEncoding]; + const void *dataBytes = data.bytes; + NSUInteger dataLen = data.length; + + for (GTMMIMEDocumentPart *part in _parts) { + didCollide = [part containsBytes:dataBytes length:dataLen]; + if (didCollide) break; + } + + if (!didCollide) break; // We're fine, no more attempts needed. + + // Try again with a random number appended. + _boundary = [NSString stringWithFormat:@"%@_%08x", kBaseBoundary, [self random]]; + } + + if (didCollide) { + // Fallback... two random numbers. + _boundary = [NSString stringWithFormat:@"%08x_tedborg_%08x", [self random], [self random]]; + } + return _boundary; +} + +- (void)setBoundary:(NSString *)str { + _boundary = [str copy]; +} + +// Internal method. +- (void)generateDataArray:(NSMutableArray *)dataArray + length:(unsigned long long *)outLength + boundary:(NSString **)outBoundary { + + // The input stream is of the form: + // --boundary + // [part_1_headers] + // [part_1_data] + // --boundary + // [part_2_headers] + // [part_2_data] + // --boundary-- + + // First we set up our boundary NSData objects. + NSString *boundary = self.boundary; + + NSString *mainBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary]; + NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary]; + + NSData *mainBoundaryData = [mainBoundary dataUsingEncoding:NSUTF8StringEncoding]; + NSData *endBoundaryData = [endBoundary dataUsingEncoding:NSUTF8StringEncoding]; + + // Now we add them all in proper order to our dataArray. + unsigned long long length = 0; + + for (GTMMIMEDocumentPart *part in _parts) { + [dataArray addObject:mainBoundaryData]; + [dataArray addObject:part.headerData]; + [dataArray addObject:part.body]; + + length += part.length + mainBoundaryData.length; + } + + [dataArray addObject:endBoundaryData]; + length += endBoundaryData.length; + + if (outLength) *outLength = length; + if (outBoundary) *outBoundary = boundary; +} + +- (void)generateInputStream:(NSInputStream **)outStream + length:(unsigned long long *)outLength + boundary:(NSString **)outBoundary { + NSMutableArray *dataArray = outStream ? [NSMutableArray array] : nil; + [self generateDataArray:dataArray + length:outLength + boundary:outBoundary]; + + if (outStream) { + Class streamClass = NSClassFromString(@"GTMGatherInputStream"); + NSAssert(streamClass != nil, @"GTMGatherInputStream not available."); + + *outStream = [streamClass streamWithArray:dataArray]; + } +} + +- (void)generateDispatchData:(dispatch_data_t *)outDispatchData + length:(unsigned long long *)outLength + boundary:(NSString **)outBoundary { + NSMutableArray *dataArray = outDispatchData ? [NSMutableArray array] : nil; + [self generateDataArray:dataArray + length:outLength + boundary:outBoundary]; + + if (outDispatchData) { + // Create an empty data accumulator. + dispatch_data_t dataAccumulator; + + dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + + for (NSData *partData in dataArray) { + __block NSData *immutablePartData = [partData copy]; + dispatch_data_t newDataPart = + dispatch_data_create(immutablePartData.bytes, immutablePartData.length, bgQueue, ^{ + // We want the data retained until this block executes. + immutablePartData = nil; + }); + + if (dataAccumulator == nil) { + // First part. + dataAccumulator = newDataPart; + } else { + // Append the additional part. + dataAccumulator = dispatch_data_create_concat(dataAccumulator, newDataPart); + } + } + *outDispatchData = dataAccumulator; + } +} + ++ (NSData *)dataWithHeaders:(NSDictionary *)headers { + // Generate the header data by coalescing the dictionary as lines of "key: value\r\n". + NSMutableString* headerString = [NSMutableString string]; + + // Sort the header keys so we have a deterministic order for unit testing. + SEL sortSel = @selector(caseInsensitiveCompare:); + NSArray *sortedKeys = [headers.allKeys sortedArrayUsingSelector:sortSel]; + + for (NSString *key in sortedKeys) { + NSString *value = [headers objectForKey:key]; + +#if DEBUG + // Look for troublesome characters in the header keys & values. + NSCharacterSet *badKeyChars = [NSCharacterSet characterSetWithCharactersInString:@":\r\n"]; + NSCharacterSet *badValueChars = [NSCharacterSet characterSetWithCharactersInString:@"\r\n"]; + + NSRange badRange = [key rangeOfCharacterFromSet:badKeyChars]; + NSAssert(badRange.location == NSNotFound, @"invalid key: %@", key); + + badRange = [value rangeOfCharacterFromSet:badValueChars]; + NSAssert(badRange.location == NSNotFound, @"invalid value: %@", value); +#endif + + [headerString appendFormat:@"%@: %@\r\n", key, value]; + } + // Headers end with an extra blank line. + [headerString appendString:@"\r\n"]; + + NSData *result = [headerString dataUsingEncoding:NSUTF8StringEncoding]; + return result; +} + +#pragma mark - Separating Parts + ++ (NSArray *)MIMEPartsWithBoundary:(NSString *)boundary + data:(NSData *)fullDocumentData { + // In MIME documents, the boundary is preceded by CRLF and two dashes, and followed + // at the end by two dashes. + NSData *boundaryData = [boundary dataUsingEncoding:NSUTF8StringEncoding]; + NSUInteger boundaryLength = boundaryData.length; + + NSMutableArray *foundBoundaryOffsets; + [self searchData:fullDocumentData + targetBytes:boundaryData.bytes + targetLength:boundaryLength + foundOffsets:&foundBoundaryOffsets]; + + // According to rfc1341, ignore anything before the first boundary, or after the last, though two + // dashes are expected to follow the last boundary. + if (foundBoundaryOffsets.count < 2) { + return nil; + } + + // Wrap the full document data with a dispatch_data_t for more efficient slicing + // and dicing. + dispatch_data_t dataWrapper; + if ([fullDocumentData conformsToProtocol:@protocol(OS_dispatch_data)]) { + dataWrapper = (dispatch_data_t)fullDocumentData; + } else { + // A no-op self invocation on fullDocumentData will keep it retained until the block is invoked. + dispatch_queue_t bgQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + dataWrapper = dispatch_data_create(fullDocumentData.bytes, + fullDocumentData.length, + bgQueue, ^{ [fullDocumentData self]; }); + } + NSMutableArray *parts; + NSInteger previousBoundaryOffset = -1; + NSInteger partCounter = -1; + NSInteger numberOfPartsWithHeaders = 0; + for (NSNumber *currentBoundaryOffset in foundBoundaryOffsets) { + ++partCounter; + if (previousBoundaryOffset == -1) { + // This is the first boundary. + previousBoundaryOffset = currentBoundaryOffset.integerValue; + continue; + } else { + // Create a part data subrange between the previous boundary and this one. + // + // The last four bytes before a boundary are CRLF--. + // The first two bytes following a boundary are either CRLF or, for the last boundary, --. + NSInteger previousPartDataStartOffset = + previousBoundaryOffset + (NSInteger)boundaryLength + 2; + NSInteger previousPartDataEndOffset = currentBoundaryOffset.integerValue - 4; + NSInteger previousPartDataLength = previousPartDataEndOffset - previousPartDataStartOffset; + + if (previousPartDataLength < 2) { + // The preceding part was too short to be useful. +#if DEBUG + NSLog(@"MIME part %zd has %zd bytes", partCounter - 1, previousPartDataLength); +#endif + } else { + if (!parts) parts = [NSMutableArray array]; + + dispatch_data_t partData = + dispatch_data_create_subrange(dataWrapper, + (size_t)previousPartDataStartOffset, (size_t)previousPartDataLength); + // Scan the part data for the separator between headers and body. After the CRLF, + // either the headers start immediately, or there's another CRLF and there are no headers. + // + // We need to map the part data to get the first two bytes. (Or we could cast it to + // NSData and get the bytes pointer of that.) If we're concerned that a single part + // data may be expensive to map, we could make a subrange here for just the first two bytes, + // and map that two-byte subrange. + const void *partDataBuffer; + size_t partDataBufferSize; + dispatch_data_t mappedPartData NS_VALID_UNTIL_END_OF_SCOPE = + dispatch_data_create_map(partData, &partDataBuffer, &partDataBufferSize); + dispatch_data_t bodyData; + NSDictionary *headers; + BOOL hasAnotherCRLF = (((char *)partDataBuffer)[0] == '\r' + && ((char *)partDataBuffer)[1] == '\n'); + mappedPartData = nil; + + if (hasAnotherCRLF) { + // There are no headers; skip the CRLF to get to the body, and leave headers nil. + bodyData = dispatch_data_create_subrange(partData, 2, (size_t)previousPartDataLength - 2); + } else { + // There are part headers. They are separated from body data by CRLFCRLF. + NSArray *crlfOffsets; + [self searchData:(NSData *)partData + targetBytes:"\r\n\r\n" + targetLength:4 + foundOffsets:&crlfOffsets]; + if (crlfOffsets.count == 0) { +#if DEBUG + // We could not distinguish body and headers. + NSLog(@"MIME part %zd lacks a header separator: %@", partCounter - 1, + [[NSString alloc] initWithData:(NSData *)partData encoding:NSUTF8StringEncoding]); +#endif + } else { + NSInteger headerSeparatorOffset = ((NSNumber *)crlfOffsets.firstObject).integerValue; + dispatch_data_t headerData = + dispatch_data_create_subrange(partData, 0, (size_t)headerSeparatorOffset); + headers = [self headersWithData:(NSData *)headerData]; + + bodyData = dispatch_data_create_subrange(partData, (size_t)headerSeparatorOffset + 4, + (size_t)(previousPartDataLength - (headerSeparatorOffset + 4))); + + numberOfPartsWithHeaders++; + } // crlfOffsets.count == 0 + } // hasAnotherCRLF + GTMMIMEDocumentPart *part = [GTMMIMEDocumentPart partWithHeaders:headers + body:(NSData *)bodyData]; + [parts addObject:part]; + } // previousPartDataLength < 2 + previousBoundaryOffset = currentBoundaryOffset.integerValue; + } + } +#if DEBUG + // In debug builds, warn if a reasonably long document lacks any CRLF characters. + if (numberOfPartsWithHeaders == 0) { + NSUInteger length = fullDocumentData.length; + if (length > 20) { // Reasonably long. + NSMutableArray *foundCRLFs; + [self searchData:fullDocumentData + targetBytes:"\r\n" + targetLength:2 + foundOffsets:&foundCRLFs]; + if (foundCRLFs.count == 0) { + // Parts were logged above (due to lacking header separators.) + NSLog(@"Warning: MIME document lacks any headers (may have wrong line endings)"); + } + } + } +#endif // DEBUG + return parts; +} + +// Efficiently search the supplied data for the target bytes. +// +// This uses enumerateByteRangesUsingBlock: to scan for bytes. It can find +// the target even if it spans multiple separate byte ranges. +// +// Returns an array of found byte offset values, as NSNumbers. ++ (void)searchData:(NSData *)data + targetBytes:(const void *)targetBytes + targetLength:(NSUInteger)targetLength + foundOffsets:(GTM_NSArrayOf(NSNumber *) **)outFoundOffsets { + NSMutableArray *foundOffsets = [NSMutableArray array]; + SearchDataForBytes(data, targetBytes, targetLength, foundOffsets, NULL); + *outFoundOffsets = foundOffsets; +} + + +// This version of searchData: also returns the block numbers (0-based) where the +// target was found, used for testing that the supplied dispatch_data buffer +// has not been flattened. ++ (void)searchData:(NSData *)data + targetBytes:(const void *)targetBytes + targetLength:(NSUInteger)targetLength + foundOffsets:(GTM_NSArrayOf(NSNumber *) **)outFoundOffsets + foundBlockNumbers:(GTM_NSArrayOf(NSNumber *) **)outFoundBlockNumbers { + NSMutableArray *foundOffsets = [NSMutableArray array]; + NSMutableArray *foundBlockNumbers = [NSMutableArray array]; + + SearchDataForBytes(data, targetBytes, targetLength, foundOffsets, foundBlockNumbers); + *outFoundOffsets = foundOffsets; + *outFoundBlockNumbers = foundBlockNumbers; +} + +static void SearchDataForBytes(NSData *data, const void *targetBytes, NSUInteger targetLength, + NSMutableArray *foundOffsets, NSMutableArray *foundBlockNumbers) { + __block NSUInteger priorPartialMatchAmount = 0; + __block NSInteger priorPartialMatchStartingBlockNumber = -1; + __block NSInteger blockNumber = -1; + + [data enumerateByteRangesUsingBlock:^(const void *bytes, + NSRange byteRange, + BOOL *stop) { + // Search for the first character in the current range. + const void *ptr = bytes; + NSInteger remainingInCurrentRange = (NSInteger)byteRange.length; + ++blockNumber; + + if (priorPartialMatchAmount > 0) { + NSUInteger amountRemainingToBeMatched = targetLength - priorPartialMatchAmount; + NSUInteger remainingFoundOffset; + NSUInteger amountMatched = FindBytes(targetBytes + priorPartialMatchAmount, + amountRemainingToBeMatched, + ptr, (NSUInteger)remainingInCurrentRange, &remainingFoundOffset); + if (amountMatched == 0 || remainingFoundOffset > 0) { + // No match of the rest of the prior partial match in this range. + } else if (amountMatched < amountRemainingToBeMatched) { + // Another partial match; we're done with this range. + priorPartialMatchAmount = priorPartialMatchAmount + amountMatched; + return; + } else { + // The offset is in an earlier range. + NSUInteger offset = byteRange.location - priorPartialMatchAmount; + [foundOffsets addObject:@(offset)]; + [foundBlockNumbers addObject:@(priorPartialMatchStartingBlockNumber)]; + priorPartialMatchStartingBlockNumber = -1; + } + priorPartialMatchAmount = 0; + } + + while (remainingInCurrentRange > 0) { + NSUInteger offsetFromPtr; + NSUInteger amountMatched = FindBytes(targetBytes, targetLength, ptr, + (NSUInteger)remainingInCurrentRange, &offsetFromPtr); + if (amountMatched == 0) { + // No match in this range. + return; + } + if (amountMatched < targetLength) { + // Found a partial target. If there's another range, we'll check for the rest. + priorPartialMatchAmount = amountMatched; + priorPartialMatchStartingBlockNumber = blockNumber; + return; + } + // Found the full target. + NSUInteger globalOffset = byteRange.location + (NSUInteger)(ptr - bytes) + offsetFromPtr; + + [foundOffsets addObject:@(globalOffset)]; + [foundBlockNumbers addObject:@(blockNumber)]; + + ptr += targetLength + offsetFromPtr; + remainingInCurrentRange -= (targetLength + offsetFromPtr); + } + }]; +} + +// Internal method only for testing; this calls through the static method. ++ (NSUInteger)findBytesWithNeedle:(const unsigned char *)needle + needleLength:(NSUInteger)needleLength + haystack:(const unsigned char *)haystack + haystackLength:(NSUInteger)haystackLength + foundOffset:(NSUInteger *)foundOffset { + return FindBytes(needle, needleLength, haystack, haystackLength, foundOffset); +} + +// Utility method to parse header bytes into an NSDictionary. ++ (NSDictionary *)headersWithData:(NSData *)data { + NSString *headersString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + if (!headersString) return nil; + + NSMutableDictionary *headers = [NSMutableDictionary dictionary]; + NSScanner *scanner = [NSScanner scannerWithString:headersString]; + // The scanner is skipping leading whitespace and newline characters by default. + NSCharacterSet *newlineCharacters = [NSCharacterSet newlineCharacterSet]; + NSString *key; + NSString *value; + while ([scanner scanUpToString:@":" intoString:&key] + && [scanner scanString:@":" intoString:NULL] + && [scanner scanUpToCharactersFromSet:newlineCharacters intoString:&value]) { + [headers setObject:value forKey:key]; + // Discard the trailing newline. + [scanner scanCharactersFromSet:newlineCharacters intoString:NULL]; + } + return headers; +} + +@end + +// Return how much of the needle was found in the haystack. +// +// If the result is less than needleLen, then the beginning of the needle +// was found at the end of the haystack. +static NSUInteger FindBytes(const unsigned char* needle, NSUInteger needleLen, + const unsigned char* haystack, NSUInteger haystackLen, + NSUInteger *foundOffset) { + const unsigned char *ptr = haystack; + NSInteger remain = (NSInteger)haystackLen; + // Assume memchr is an efficient way to find a match for the first + // byte of the needle, and memcmp is an efficient way to compare a + // range of bytes. + while (remain > 0 && (ptr = memchr(ptr, needle[0], (size_t)remain)) != 0) { + // The first character is present. + NSUInteger offset = (NSUInteger)(ptr - haystack); + remain = (NSInteger)(haystackLen - offset); + + NSUInteger amountToCompare = MIN((NSUInteger)remain, needleLen); + if (memcmp(ptr, needle, amountToCompare) == 0) { + if (foundOffset) *foundOffset = offset; + return amountToCompare; + } + ptr++; + remain--; + } + if (foundOffset) *foundOffset = 0; + return 0; +} diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMReadMonitorInputStream.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMReadMonitorInputStream.h new file mode 100644 index 000000000..4e306428a --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMReadMonitorInputStream.h @@ -0,0 +1,49 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#ifndef GTM_NONNULL + #if defined(__has_attribute) + #if __has_attribute(nonnull) + #define GTM_NONNULL(x) __attribute__((nonnull x)) + #else + #define GTM_NONNULL(x) + #endif + #else + #define GTM_NONNULL(x) + #endif +#endif + + +@interface GTMReadMonitorInputStream : NSInputStream + ++ (instancetype)inputStreamWithStream:(NSInputStream *)input GTM_NONNULL((1)); + +- (instancetype)initWithStream:(NSInputStream *)input GTM_NONNULL((1)); + +// The read monitor selector is called when bytes have been read. It should have this signature: +// +// - (void)inputStream:(GTMReadMonitorInputStream *)stream +// readIntoBuffer:(uint8_t *)buffer +// length:(int64_t)length; + +@property(atomic, weak) id readDelegate; +@property(atomic, assign) SEL readSelector; + +// Modes for invoking callbacks, when necessary. +@property(atomic, strong) NSArray *runLoopModes; + +@end diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMReadMonitorInputStream.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMReadMonitorInputStream.m new file mode 100644 index 000000000..53a01728b --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMReadMonitorInputStream.m @@ -0,0 +1,187 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMReadMonitorInputStream.h" + +@implementation GTMReadMonitorInputStream { + NSInputStream *_inputStream; // Encapsulated stream that does the work. + + NSThread *_thread; // Thread in which this object was created. + NSArray *_runLoopModes; // Modes for calling callbacks, when necessary. +} + + +@synthesize readDelegate = _readDelegate; +@synthesize readSelector = _readSelector; +@synthesize runLoopModes = _runLoopModes; + +// We'll forward all unhandled messages to the NSInputStream class or to the encapsulated input +// stream. This is needed for all messages sent to NSInputStream which aren't handled by our +// superclass; that includes various private run loop calls. ++ (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { + return [NSInputStream methodSignatureForSelector:selector]; +} + ++ (void)forwardInvocation:(NSInvocation*)invocation { + [invocation invokeWithTarget:[NSInputStream class]]; +} + +- (BOOL)respondsToSelector:(SEL)selector { + return [_inputStream respondsToSelector:selector]; +} + +- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector { + return [_inputStream methodSignatureForSelector:selector]; +} + +- (void)forwardInvocation:(NSInvocation*)invocation { + [invocation invokeWithTarget:_inputStream]; +} + +#pragma mark - + ++ (instancetype)inputStreamWithStream:(NSInputStream *)input { + return [[self alloc] initWithStream:input]; +} + +- (instancetype)initWithStream:(NSInputStream *)input { + self = [super init]; + if (self) { + _inputStream = input; + _thread = [NSThread currentThread]; + } + return self; +} + +- (instancetype)init { + [self doesNotRecognizeSelector:_cmd]; + return nil; +} + +#pragma mark - + +- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len { + // Read from the encapsulated stream. + NSInteger numRead = [_inputStream read:buffer maxLength:len]; + if (numRead > 0) { + if (_readDelegate && _readSelector) { + // Call the read selector with the buffer and number of bytes actually read into it. + BOOL isOnOriginalThread = [_thread isEqual:[NSThread currentThread]]; + if (isOnOriginalThread) { + // Invoke immediately. + NSData *data = [NSData dataWithBytesNoCopy:buffer + length:(NSUInteger)numRead + freeWhenDone:NO]; + [self invokeReadSelectorWithBuffer:data]; + } else { + // Copy the buffer into an NSData to be retained by the performSelector, + // and invoke on the proper thread. + SEL sel = @selector(invokeReadSelectorWithBuffer:); + NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numRead]; + if (_runLoopModes) { + [self performSelector:sel + onThread:_thread + withObject:data + waitUntilDone:NO + modes:_runLoopModes]; + } else { + [self performSelector:sel + onThread:_thread + withObject:data + waitUntilDone:NO]; + } + } + } + } + return numRead; +} + +- (void)invokeReadSelectorWithBuffer:(NSData *)data { + const void *buffer = data.bytes; + int64_t length = (int64_t)data.length; + + id argSelf = self; + id readDelegate = _readDelegate; + if (readDelegate) { + NSMethodSignature *signature = [readDelegate methodSignatureForSelector:_readSelector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; + [invocation setSelector:_readSelector]; + [invocation setTarget:readDelegate]; + [invocation setArgument:&argSelf atIndex:2]; + [invocation setArgument:&buffer atIndex:3]; + [invocation setArgument:&length atIndex:4]; + [invocation invoke]; + } +} + +- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len { + return [_inputStream getBuffer:buffer length:len]; +} + +- (BOOL)hasBytesAvailable { + return [_inputStream hasBytesAvailable]; +} + +#pragma mark Standard messages + +// Pass expected messages to our encapsulated stream. +// +// We want our encapsulated NSInputStream to handle the standard messages; +// we don't want the superclass to handle them. +- (void)open { + [_inputStream open]; +} + +- (void)close { + [_inputStream close]; +} + +- (id)delegate { + return [_inputStream delegate]; +} + +- (void)setDelegate:(id)delegate { + [_inputStream setDelegate:delegate]; +} + +- (id)propertyForKey:(NSString *)key { + return [_inputStream propertyForKey:key]; +} + +- (BOOL)setProperty:(id)property forKey:(NSString *)key { + return [_inputStream setProperty:property forKey:key]; +} + +- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { + [_inputStream scheduleInRunLoop:aRunLoop forMode:mode]; +} + +- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { + [_inputStream removeFromRunLoop:aRunLoop forMode:mode]; +} + +- (NSStreamStatus)streamStatus { + return [_inputStream streamStatus]; +} + +- (NSError *)streamError { + return [_inputStream streamError]; +} + +@end diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h new file mode 100644 index 000000000..a649cf0e0 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.h @@ -0,0 +1,1308 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// GTMSessionFetcher is a wrapper around NSURLSession for http operations. +// +// What does this offer on top of of NSURLSession? +// +// - Block-style callbacks for useful functionality like progress rather +// than delegate methods. +// - Out-of-process uploads and downloads using NSURLSession, including +// management of fetches after relaunch. +// - Integration with GTMAppAuth for invisible management and refresh of +// authorization tokens. +// - Pretty-printed http logging. +// - Cookies handling that does not interfere with or get interfered with +// by WebKit cookies or on Mac by Safari and other apps. +// - Credentials handling for the http operation. +// - Rate-limiting and cookie grouping when fetchers are created with +// GTMSessionFetcherService. +// +// If the bodyData or bodyFileURL property is set, then a POST request is assumed. +// +// Each fetcher is assumed to be for a one-shot fetch request; don't reuse the object +// for a second fetch. +// +// The fetcher will be self-retained as long as a connection is pending. +// +// To keep user activity private, URLs must have an https scheme (unless the property +// allowedInsecureSchemes is set to permit the scheme.) +// +// Callbacks will be released when the fetch completes or is stopped, so there is no need +// to use weak self references in the callback blocks. +// +// Sample usage: +// +// _fetcherService = [[GTMSessionFetcherService alloc] init]; +// +// GTMSessionFetcher *myFetcher = [_fetcherService fetcherWithURLString:myURLString]; +// myFetcher.retryEnabled = YES; +// myFetcher.comment = @"First profile image"; +// +// // Optionally specify a file URL or NSData for the request body to upload. +// myFetcher.bodyData = [postString dataUsingEncoding:NSUTF8StringEncoding]; +// +// [myFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { +// if (error != nil) { +// // Server status code or network error. +// // +// // If the domain is kGTMSessionFetcherStatusDomain then the error code +// // is a failure status from the server. +// } else { +// // Fetch succeeded. +// } +// }]; +// +// There is also a beginFetch call that takes a pointer and selector for the completion handler; +// a pointer and selector is a better style when the callback is a substantial, separate method. +// +// NOTE: Fetches may retrieve data from the server even though the server +// returned an error, so the criteria for success is a non-nil error. +// The completion handler is called when the server status is >= 300 with an NSError +// having domain kGTMSessionFetcherStatusDomain and code set to the server status. +// +// Status codes are at +// +// +// Background session support: +// +// Out-of-process uploads and downloads may be created by setting the fetcher's +// useBackgroundSession property. Data to be uploaded should be provided via +// the uploadFileURL property; the download destination should be specified with +// the destinationFileURL. NOTE: Background upload files should be in a location +// that will be valid even after the device is restarted, so the file should not +// be uploaded from a system temporary or cache directory. +// +// Background session transfers are slower, and should typically be used only +// for very large downloads or uploads (hundreds of megabytes). +// +// When background sessions are used in iOS apps, the application delegate must +// pass through the parameters from UIApplicationDelegate's +// application:handleEventsForBackgroundURLSession:completionHandler: to the +// fetcher class. +// +// When the application has been relaunched, it may also create a new fetcher +// instance to handle completion of the transfers. +// +// - (void)application:(UIApplication *)application +// handleEventsForBackgroundURLSession:(NSString *)identifier +// completionHandler:(void (^)())completionHandler { +// // Application was re-launched on completing an out-of-process download. +// +// // Pass the URLSession info related to this re-launch to the fetcher class. +// [GTMSessionFetcher application:application +// handleEventsForBackgroundURLSession:identifier +// completionHandler:completionHandler]; +// +// // Get a fetcher related to this re-launch and re-hook up a completionHandler to it. +// GTMSessionFetcher *fetcher = [GTMSessionFetcher fetcherWithSessionIdentifier:identifier]; +// NSURL *destinationFileURL = fetcher.destinationFileURL; +// fetcher.completionHandler = ^(NSData *data, NSError *error) { +// [self downloadCompletedToFile:destinationFileURL error:error]; +// }; +// } +// +// +// Threading and queue support: +// +// Networking always happens on a background thread; there is no advantage to +// changing thread or queue to create or start a fetcher. +// +// Callbacks are run on the main thread; alternatively, the app may set the +// fetcher's callbackQueue to a dispatch queue. +// +// Once the fetcher's beginFetch method has been called, the fetcher's methods and +// properties may be accessed from any thread. +// +// Downloading to disk: +// +// To have downloaded data saved directly to disk, specify a file URL for the +// destinationFileURL property. +// +// HTTP methods and headers: +// +// Alternative HTTP methods, like PUT, and custom headers can be specified by +// creating the fetcher with an appropriate NSMutableURLRequest. +// +// +// Caching: +// +// The fetcher avoids caching. That is best for API requests, but may hurt +// repeat fetches of static data. Apps may enable a persistent disk cache by +// customizing the config: +// +// fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher, +// NSURLSessionConfiguration *config) { +// config.URLCache = [NSURLCache sharedURLCache]; +// }; +// +// Or use the standard system config to share cookie storage with web views +// and to enable disk caching: +// +// fetcher.configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; +// +// +// Cookies: +// +// There are three supported mechanisms for remembering cookies between fetches. +// +// By default, a standalone GTMSessionFetcher uses a mutable array held +// statically to track cookies for all instantiated fetchers. This avoids +// cookies being set by servers for the application from interfering with +// Safari and WebKit cookie settings, and vice versa. +// The fetcher cookies are lost when the application quits. +// +// To rely instead on WebKit's global NSHTTPCookieStorage, set the fetcher's +// cookieStorage property: +// myFetcher.cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; +// +// To share cookies with other apps, use the method introduced in iOS 9/OS X 10.11: +// myFetcher.cookieStorage = +// [NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:kMyCompanyContainedID]; +// +// To ignore existing cookies and only have cookies related to the single fetch +// be applied, make a temporary cookie storage object: +// myFetcher.cookieStorage = [[GTMSessionCookieStorage alloc] init]; +// +// Note: cookies set while following redirects will be sent to the server, as +// the redirects are followed by the fetcher. +// +// To completely disable cookies, similar to setting cookieStorageMethod to +// kGTMHTTPFetcherCookieStorageMethodNone, adjust the session configuration +// appropriately in the fetcher or fetcher service: +// fetcher.configurationBlock = ^(GTMSessionFetcher *configFetcher, +// NSURLSessionConfiguration *config) { +// config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; +// config.HTTPShouldSetCookies = NO; +// }; +// +// If the fetcher is created from a GTMSessionFetcherService object +// then the cookie storage mechanism is set to use the cookie storage in the +// service object rather than the static storage. Disabling cookies in the +// session configuration set on a service object will disable cookies for all +// fetchers created from that GTMSessionFetcherService object, since the session +// configuration is propagated to the fetcher. +// +// +// Monitoring data transfers. +// +// The fetcher supports a variety of properties for progress monitoring +// progress with callback blocks. +// GTMSessionFetcherSendProgressBlock sendProgressBlock +// GTMSessionFetcherReceivedProgressBlock receivedProgressBlock +// GTMSessionFetcherDownloadProgressBlock downloadProgressBlock +// +// If supplied by the server, the anticipated total download size is available +// as [[myFetcher response] expectedContentLength] (and may be -1 for unknown +// download sizes.) +// +// +// Automatic retrying of fetches +// +// The fetcher can optionally create a timer and reattempt certain kinds of +// fetch failures (status codes 408, request timeout; 502, gateway failure; +// 503, service unavailable; 504, gateway timeout; networking errors +// NSURLErrorTimedOut and NSURLErrorNetworkConnectionLost.) The user may +// set a retry selector to customize the type of errors which will be retried. +// +// Retries are done in an exponential-backoff fashion (that is, after 1 second, +// 2, 4, 8, and so on.) +// +// Enabling automatic retries looks like this: +// myFetcher.retryEnabled = YES; +// +// With retries enabled, the completion callbacks are called only +// when no more retries will be attempted. Calling the fetcher's stopFetching +// method will terminate the retry timer, without the finished or failure +// selectors being invoked. +// +// Optionally, the client may set the maximum retry interval: +// myFetcher.maxRetryInterval = 60.0; // in seconds; default is 60 seconds +// // for downloads, 600 for uploads +// +// Servers should never send a 400 or 500 status for errors that are retryable +// by clients, as those values indicate permanent failures. In nearly all +// cases, the default standard retry behavior is correct for clients, and no +// custom client retry behavior is needed or appropriate. Servers that send +// non-retryable status codes and expect the client to retry the request are +// faulty. +// +// Still, the client may provide a block to determine if a status code or other +// error should be retried. The block returns YES to set the retry timer or NO +// to fail without additional fetch attempts. +// +// The retry method may return the |suggestedWillRetry| argument to get the +// default retry behavior. Server status codes are present in the +// error argument, and have the domain kGTMSessionFetcherStatusDomain. The +// user's method may look something like this: +// +// myFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *error, +// GTMSessionFetcherRetryResponse response) { +// // Perhaps examine error.domain and error.code, or fetcher.retryCount +// // +// // Respond with YES to start the retry timer, NO to proceed to the failure +// // callback, or suggestedWillRetry to get default behavior for the +// // current error domain and code values. +// response(suggestedWillRetry); +// }; + + +#import + +#if TARGET_OS_IPHONE +#import +#endif +#if TARGET_OS_WATCH +#import +#endif + +// By default it is stripped from non DEBUG builds. Developers can override +// this in their project settings. +#ifndef STRIP_GTM_FETCH_LOGGING + #if !DEBUG + #define STRIP_GTM_FETCH_LOGGING 1 + #else + #define STRIP_GTM_FETCH_LOGGING 0 + #endif +#endif + +// Logs in debug builds. +#ifndef GTMSESSION_LOG_DEBUG + #if DEBUG + #define GTMSESSION_LOG_DEBUG(...) NSLog(__VA_ARGS__) + #else + #define GTMSESSION_LOG_DEBUG(...) do { } while (0) + #endif +#endif + +// Asserts in debug builds (or logs in debug builds if GTMSESSION_ASSERT_AS_LOG +// or NS_BLOCK_ASSERTIONS are defined.) +#ifndef GTMSESSION_ASSERT_DEBUG + #if DEBUG && !defined(NS_BLOCK_ASSERTIONS) && !GTMSESSION_ASSERT_AS_LOG + #undef GTMSESSION_ASSERT_AS_LOG + #define GTMSESSION_ASSERT_AS_LOG 1 + #endif + + #if DEBUG && !GTMSESSION_ASSERT_AS_LOG + #define GTMSESSION_ASSERT_DEBUG(...) NSAssert(__VA_ARGS__) + #elif DEBUG + #define GTMSESSION_ASSERT_DEBUG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); } + #else + #define GTMSESSION_ASSERT_DEBUG(pred, ...) do { } while (0) + #endif +#endif + +// Asserts in debug builds, logs in release builds (or logs in debug builds if +// GTMSESSION_ASSERT_AS_LOG is defined.) +#ifndef GTMSESSION_ASSERT_DEBUG_OR_LOG + #if DEBUG && !GTMSESSION_ASSERT_AS_LOG + #define GTMSESSION_ASSERT_DEBUG_OR_LOG(...) NSAssert(__VA_ARGS__) + #else + #define GTMSESSION_ASSERT_DEBUG_OR_LOG(pred, ...) if (!(pred)) { NSLog(__VA_ARGS__); } + #endif +#endif + +// Macro useful for examining messages from NSURLSession during debugging. +#if 0 +#define GTM_LOG_SESSION_DELEGATE(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__) +#else +#define GTM_LOG_SESSION_DELEGATE(...) +#endif + +#ifndef GTM_NULLABLE + #if __has_feature(nullability) // Available starting in Xcode 6.3 + #define GTM_NULLABLE_TYPE __nullable + #define GTM_NONNULL_TYPE __nonnull + #define GTM_NULLABLE nullable + #define GTM_NONNULL_DECL nonnull // GTM_NONNULL is used by GTMDefines.h + #define GTM_NULL_RESETTABLE null_resettable + + #define GTM_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN + #define GTM_ASSUME_NONNULL_END NS_ASSUME_NONNULL_END + #else + #define GTM_NULLABLE_TYPE + #define GTM_NONNULL_TYPE + #define GTM_NULLABLE + #define GTM_NONNULL_DECL + #define GTM_NULL_RESETTABLE + #define GTM_ASSUME_NONNULL_BEGIN + #define GTM_ASSUME_NONNULL_END + #endif // __has_feature(nullability) +#endif // GTM_NULLABLE + +#if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0)) +#define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) __attribute__((deprecated("" _MSG))) +#else +#define GTMSESSION_DEPRECATE_ON_2016_SDKS(_MSG) +#endif + +#ifndef GTM_DECLARE_GENERICS + #if __has_feature(objc_generics) + #define GTM_DECLARE_GENERICS 1 + #else + #define GTM_DECLARE_GENERICS 0 + #endif +#endif + +#ifndef GTM_NSArrayOf + #if GTM_DECLARE_GENERICS + #define GTM_NSArrayOf(value) NSArray + #define GTM_NSDictionaryOf(key, value) NSDictionary + #else + #define GTM_NSArrayOf(value) NSArray + #define GTM_NSDictionaryOf(key, value) NSDictionary + #endif // __has_feature(objc_generics) +#endif // GTM_NSArrayOf + +// For iOS, the fetcher can declare itself a background task to allow fetches +// to finish when the app leaves the foreground. +// +// (This is unrelated to providing a background configuration, which allows +// out-of-process uploads and downloads.) +// +// To disallow use of background tasks during fetches, the target should define +// GTM_BACKGROUND_TASK_FETCHING to 0, or alternatively may set the +// skipBackgroundTask property to YES. +#if TARGET_OS_IPHONE && !TARGET_OS_WATCH && !defined(GTM_BACKGROUND_TASK_FETCHING) + #define GTM_BACKGROUND_TASK_FETCHING 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)) + #ifndef GTM_USE_SESSION_FETCHER + #define GTM_USE_SESSION_FETCHER 1 + #endif +#endif + +#if !defined(GTMBridgeFetcher) + // These bridge macros should be identical in GTMHTTPFetcher.h and GTMSessionFetcher.h + #if GTM_USE_SESSION_FETCHER + // Macros to new fetcher class. + #define GTMBridgeFetcher GTMSessionFetcher + #define GTMBridgeFetcherService GTMSessionFetcherService + #define GTMBridgeFetcherServiceProtocol GTMSessionFetcherServiceProtocol + #define GTMBridgeAssertValidSelector GTMSessionFetcherAssertValidSelector + #define GTMBridgeCookieStorage GTMSessionCookieStorage + #define GTMBridgeCleanedUserAgentString GTMFetcherCleanedUserAgentString + #define GTMBridgeSystemVersionString GTMFetcherSystemVersionString + #define GTMBridgeApplicationIdentifier GTMFetcherApplicationIdentifier + #define kGTMBridgeFetcherStatusDomain kGTMSessionFetcherStatusDomain + #define kGTMBridgeFetcherStatusBadRequest GTMSessionFetcherStatusBadRequest + #else + // Macros to old fetcher class. + #define GTMBridgeFetcher GTMHTTPFetcher + #define GTMBridgeFetcherService GTMHTTPFetcherService + #define GTMBridgeFetcherServiceProtocol GTMHTTPFetcherServiceProtocol + #define GTMBridgeAssertValidSelector GTMAssertSelectorNilOrImplementedWithArgs + #define GTMBridgeCookieStorage GTMCookieStorage + #define GTMBridgeCleanedUserAgentString GTMCleanedUserAgentString + #define GTMBridgeSystemVersionString GTMSystemVersionString + #define GTMBridgeApplicationIdentifier GTMApplicationIdentifier + #define kGTMBridgeFetcherStatusDomain kGTMHTTPFetcherStatusDomain + #define kGTMBridgeFetcherStatusBadRequest kGTMHTTPFetcherStatusBadRequest + #endif // GTM_USE_SESSION_FETCHER +#endif + +GTM_ASSUME_NONNULL_BEGIN + +// Notifications +// +// Fetch started and stopped, and fetch retry delay started and stopped. +extern NSString *const kGTMSessionFetcherStartedNotification; +extern NSString *const kGTMSessionFetcherStoppedNotification; +extern NSString *const kGTMSessionFetcherRetryDelayStartedNotification; +extern NSString *const kGTMSessionFetcherRetryDelayStoppedNotification; + +// Completion handler notification. This is intended for use by code capturing +// and replaying fetch requests and results for testing. For fetches where +// destinationFileURL or accumulateDataBlock is set for the fetcher, the data +// will be nil for successful fetches. +// +// This notification is posted on the main thread. +extern NSString *const kGTMSessionFetcherCompletionInvokedNotification; +extern NSString *const kGTMSessionFetcherCompletionDataKey; +extern NSString *const kGTMSessionFetcherCompletionErrorKey; + +// Constants for NSErrors created by the fetcher (excluding server status errors, +// and error objects originating in the OS.) +extern NSString *const kGTMSessionFetcherErrorDomain; + +// The fetcher turns server error status values (3XX, 4XX, 5XX) into NSErrors +// with domain kGTMSessionFetcherStatusDomain. +// +// Any server response body data accompanying the status error is added to the +// userInfo dictionary with key kGTMSessionFetcherStatusDataKey. +extern NSString *const kGTMSessionFetcherStatusDomain; +extern NSString *const kGTMSessionFetcherStatusDataKey; + +// When a fetch fails with an error, these keys are included in the error userInfo +// dictionary if retries were attempted. +extern NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey; +extern NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey; + +// Background session support requires access to NSUserDefaults. +// If [NSUserDefaults standardUserDefaults] doesn't yield the correct NSUserDefaults for your usage, +// ie for an App Extension, then implement this class/method to return the correct NSUserDefaults. +// https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW6 +@interface GTMSessionFetcherUserDefaultsFactory : NSObject + ++ (NSUserDefaults *)fetcherUserDefaults; + +@end + +#ifdef __cplusplus +} +#endif + +typedef NS_ENUM(NSInteger, GTMSessionFetcherError) { + GTMSessionFetcherErrorDownloadFailed = -1, + GTMSessionFetcherErrorUploadChunkUnavailable = -2, + GTMSessionFetcherErrorBackgroundExpiration = -3, + GTMSessionFetcherErrorBackgroundFetchFailed = -4, + GTMSessionFetcherErrorInsecureRequest = -5, + GTMSessionFetcherErrorTaskCreationFailed = -6, +}; + +typedef NS_ENUM(NSInteger, GTMSessionFetcherStatus) { + // Standard http status codes. + GTMSessionFetcherStatusNotModified = 304, + GTMSessionFetcherStatusBadRequest = 400, + GTMSessionFetcherStatusUnauthorized = 401, + GTMSessionFetcherStatusForbidden = 403, + GTMSessionFetcherStatusPreconditionFailed = 412 +}; + +#ifdef __cplusplus +extern "C" { +#endif + +@class GTMSessionCookieStorage; +@class GTMSessionFetcher; + +// The configuration block is for modifying the NSURLSessionConfiguration only. +// DO NOT change any fetcher properties in the configuration block. +typedef void (^GTMSessionFetcherConfigurationBlock)(GTMSessionFetcher *fetcher, + NSURLSessionConfiguration *configuration); +typedef void (^GTMSessionFetcherSystemCompletionHandler)(void); +typedef void (^GTMSessionFetcherCompletionHandler)(NSData * GTM_NULLABLE_TYPE data, + NSError * GTM_NULLABLE_TYPE error); +typedef void (^GTMSessionFetcherBodyStreamProviderResponse)(NSInputStream *bodyStream); +typedef void (^GTMSessionFetcherBodyStreamProvider)(GTMSessionFetcherBodyStreamProviderResponse response); +typedef void (^GTMSessionFetcherDidReceiveResponseDispositionBlock)(NSURLSessionResponseDisposition disposition); +typedef void (^GTMSessionFetcherDidReceiveResponseBlock)(NSURLResponse *response, + GTMSessionFetcherDidReceiveResponseDispositionBlock dispositionBlock); +typedef void (^GTMSessionFetcherChallengeDispositionBlock)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential); +typedef void (^GTMSessionFetcherChallengeBlock)(GTMSessionFetcher *fetcher, + NSURLAuthenticationChallenge *challenge, + GTMSessionFetcherChallengeDispositionBlock dispositionBlock); +typedef void (^GTMSessionFetcherWillRedirectResponse)(NSURLRequest * GTM_NULLABLE_TYPE redirectedRequest); +typedef void (^GTMSessionFetcherWillRedirectBlock)(NSHTTPURLResponse *redirectResponse, + NSURLRequest *redirectRequest, + GTMSessionFetcherWillRedirectResponse response); +typedef void (^GTMSessionFetcherAccumulateDataBlock)(NSData * GTM_NULLABLE_TYPE buffer); +typedef void (^GTMSessionFetcherSimulateByteTransferBlock)(NSData * GTM_NULLABLE_TYPE buffer, + int64_t bytesWritten, + int64_t totalBytesWritten, + int64_t totalBytesExpectedToWrite); +typedef void (^GTMSessionFetcherReceivedProgressBlock)(int64_t bytesWritten, + int64_t totalBytesWritten); +typedef void (^GTMSessionFetcherDownloadProgressBlock)(int64_t bytesWritten, + int64_t totalBytesWritten, + int64_t totalBytesExpectedToWrite); +typedef void (^GTMSessionFetcherSendProgressBlock)(int64_t bytesSent, + int64_t totalBytesSent, + int64_t totalBytesExpectedToSend); +typedef void (^GTMSessionFetcherWillCacheURLResponseResponse)(NSCachedURLResponse * GTM_NULLABLE_TYPE cachedResponse); +typedef void (^GTMSessionFetcherWillCacheURLResponseBlock)(NSCachedURLResponse *proposedResponse, + GTMSessionFetcherWillCacheURLResponseResponse responseBlock); +typedef void (^GTMSessionFetcherRetryResponse)(BOOL shouldRetry); +typedef void (^GTMSessionFetcherRetryBlock)(BOOL suggestedWillRetry, + NSError * GTM_NULLABLE_TYPE error, + GTMSessionFetcherRetryResponse response); + +typedef void (^GTMSessionFetcherTestResponse)(NSHTTPURLResponse * GTM_NULLABLE_TYPE response, + NSData * GTM_NULLABLE_TYPE data, + NSError * GTM_NULLABLE_TYPE error); +typedef void (^GTMSessionFetcherTestBlock)(GTMSessionFetcher *fetcherToTest, + GTMSessionFetcherTestResponse testResponse); + +void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...); + +// Utility functions for applications self-identifying to servers via a +// user-agent header + +// The "standard" user agent includes the application identifier, taken from the bundle, +// followed by a space and the system version string. Pass nil to use +mainBundle as the source +// of the bundle identifier. +// +// Applications may use this as a starting point for their own user agent strings, perhaps +// with additional sections appended. Use GTMFetcherCleanedUserAgentString() below to +// clean up any string being added to the user agent. +NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle); + +// Make a generic name and version for the current application, like +// com.example.MyApp/1.2.3 relying on the bundle identifier and the +// CFBundleShortVersionString or CFBundleVersion. +// +// The bundle ID may be overridden as the base identifier string by +// adding to the bundle's Info.plist a "GTMUserAgentID" key. +// +// If no bundle ID or override is available, the process name preceded +// by "proc_" is used. +NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle); + +// Make an identifier like "MacOSX/10.7.1" or "iPod_Touch/4.1 hw/iPod1_1" +NSString *GTMFetcherSystemVersionString(void); + +// Make a parseable user-agent identifier from the given string, replacing whitespace +// and commas with underscores, and removing other characters that may interfere +// with parsing of the full user-agent string. +// +// For example, @"[My App]" would become @"My_App" +NSString *GTMFetcherCleanedUserAgentString(NSString *str); + +// Grab the data from an input stream. Since streams cannot be assumed to be rewindable, +// this may be destructive; the caller can try to rewind the stream (by setting the +// NSStreamFileCurrentOffsetKey property) or can just use the NSData to make a new +// NSInputStream. This function is intended to facilitate testing rather than be used in +// production. +// +// This function operates synchronously on the current thread. Depending on how the +// input stream is implemented, it may be appropriate to dispatch to a different +// queue before calling this function. +// +// Failure is indicated by a returned data value of nil. +NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError); + +#ifdef __cplusplus +} // extern "C" +#endif + + +#if !GTM_USE_SESSION_FETCHER +@protocol GTMHTTPFetcherServiceProtocol; +#endif + +// This protocol allows abstract references to the fetcher service, primarily for +// fetchers (which may be compiled without the fetcher service class present.) +// +// Apps should not need to use this protocol. +@protocol GTMSessionFetcherServiceProtocol +// This protocol allows us to call into the service without requiring +// GTMSessionFetcherService sources in this project + +@property(atomic, strong) dispatch_queue_t callbackQueue; + +- (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher; +- (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher; +- (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher; +- (void)fetcherDidStop:(GTMSessionFetcher *)fetcher; + +- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request; +- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher; + +@property(atomic, assign) BOOL reuseSession; +- (GTM_NULLABLE NSURLSession *)session; +- (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation; +- (GTM_NULLABLE id)sessionDelegate; +- (GTM_NULLABLE NSDate *)stoppedAllFetchersDate; + +// Methods for compatibility with the old GTMHTTPFetcher. +@property(readonly, strong, GTM_NULLABLE) NSOperationQueue *delegateQueue; + +@end // @protocol GTMSessionFetcherServiceProtocol + +#ifndef GTM_FETCHER_AUTHORIZATION_PROTOCOL +#define GTM_FETCHER_AUTHORIZATION_PROTOCOL 1 +@protocol GTMFetcherAuthorizationProtocol +@required +// This protocol allows us to call the authorizer without requiring its sources +// in this project. +- (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request + delegate:(id)delegate + didFinishSelector:(SEL)sel; + +- (void)stopAuthorization; + +- (void)stopAuthorizationForRequest:(NSURLRequest *)request; + +- (BOOL)isAuthorizingRequest:(NSURLRequest *)request; + +- (BOOL)isAuthorizedRequest:(NSURLRequest *)request; + +@property(strong, readonly, GTM_NULLABLE) NSString *userEmail; + +@optional + +// Indicate if authorization may be attempted. Even if this succeeds, +// authorization may fail if the user's permissions have been revoked. +@property(readonly) BOOL canAuthorize; + +// For development only, allow authorization of non-SSL requests, allowing +// transmission of the bearer token unencrypted. +@property(assign) BOOL shouldAuthorizeAllRequests; + +- (void)authorizeRequest:(GTM_NULLABLE NSMutableURLRequest *)request + completionHandler:(void (^)(NSError * GTM_NULLABLE_TYPE error))handler; + +#if GTM_USE_SESSION_FETCHER +@property (weak, GTM_NULLABLE) id fetcherService; +#else +@property (weak, GTM_NULLABLE) id fetcherService; +#endif + +- (BOOL)primeForRefresh; + +@end +#endif // GTM_FETCHER_AUTHORIZATION_PROTOCOL + +#if TARGET_OS_IPHONE +// A protocol for an alternative target for messages from GTMSessionFetcher to UIApplication. +// Set the target using +[GTMSessionFetcher setSubstituteUIApplication:] +@protocol GTMUIApplicationProtocol +- (UIBackgroundTaskIdentifier)beginBackgroundTaskWithName:(nullable NSString *)taskName + expirationHandler:(void(^ __nullable)(void))handler; +- (void)endBackgroundTask:(UIBackgroundTaskIdentifier)identifier; +@end +#endif + +#pragma mark - + +// GTMSessionFetcher objects are used for async retrieval of an http get or post +// +// See additional comments at the beginning of this file +@interface GTMSessionFetcher : NSObject + +// Create a fetcher +// +// fetcherWithRequest will return an autoreleased fetcher, but if +// the connection is successfully created, the connection should retain the +// fetcher for the life of the connection as well. So the caller doesn't have +// to retain the fetcher explicitly unless they want to be able to cancel it. ++ (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request; + +// Convenience methods that make a request, like +fetcherWithRequest ++ (instancetype)fetcherWithURL:(NSURL *)requestURL; ++ (instancetype)fetcherWithURLString:(NSString *)requestURLString; + +// Methods for creating fetchers to continue previous fetches. ++ (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData; ++ (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier; + +// Returns an array of currently active fetchers for background sessions, +// both restarted and newly created ones. ++ (GTM_NSArrayOf(GTMSessionFetcher *) *)fetchersForBackgroundSessions; + +// Designated initializer. +// +// Applications should create fetchers with a "fetcherWith..." method on a fetcher +// service or a class method, not with this initializer. +// +// The configuration should typically be nil. Applications needing to customize +// the configuration may do so by setting the configurationBlock property. +- (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request + configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration; + +// The fetcher's request. This may not be set after beginFetch has been invoked. The request +// may change due to redirects. +@property(strong, GTM_NULLABLE) NSURLRequest *request; + +// Set a header field value on the request. Header field value changes will not +// affect a fetch after the fetch has begun. +- (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field; + +// The fetcher's request (deprecated.) +// +// Exposing a mutable object in the interface was convenient but a bad design decision due +// to thread-safety requirements. Clients should use the request property and +// setRequestValue:forHTTPHeaderField: instead. +@property(atomic, readonly, GTM_NULLABLE) NSMutableURLRequest *mutableRequest + GTMSESSION_DEPRECATE_ON_2016_SDKS("use 'request' or '-setRequestValue:forHTTPHeaderField:'"); + +// Data used for resuming a download task. +@property(atomic, readonly, GTM_NULLABLE) NSData *downloadResumeData; + +// The configuration; this must be set before the fetch begins. If no configuration is +// set or inherited from the fetcher service, then the fetcher uses an ephemeral config. +// +// NOTE: This property should typically be nil. Applications needing to customize +// the configuration should do so by setting the configurationBlock property. +// That allows the fetcher to pick an appropriate base configuration, with the +// application setting only the configuration properties it needs to customize. +@property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration; + +// A block the client may use to customize the configuration used to create the session. +// +// This is called synchronously, either on the thread that begins the fetch or, during a retry, +// on the main thread. The configuration block may be called repeatedly if multiple fetchers are +// created. +// +// The configuration block is for modifying the NSURLSessionConfiguration only. +// DO NOT change any fetcher properties in the configuration block. Fetcher properties +// may be set in the fetcher service prior to fetcher creation, or on the fetcher prior +// to invoking beginFetch. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock; + +// A session is created as needed by the fetcher. A fetcher service object +// may maintain sessions for multiple fetches to the same host. +@property(atomic, strong, GTM_NULLABLE) NSURLSession *session; + +// The task in flight. +@property(atomic, readonly, GTM_NULLABLE) NSURLSessionTask *sessionTask; + +// The background session identifier. +@property(atomic, readonly, GTM_NULLABLE) NSString *sessionIdentifier; + +// Indicates a fetcher created to finish a background session task. +@property(atomic, readonly) BOOL wasCreatedFromBackgroundSession; + +// Additional user-supplied data to encode into the session identifier. Since session identifier +// length limits are unspecified, this should be kept small. Key names beginning with an underscore +// are reserved for use by the fetcher. +@property(atomic, strong, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *sessionUserInfo; + +// The human-readable description to be assigned to the task. +@property(atomic, copy, GTM_NULLABLE) NSString *taskDescription; + +// The priority assigned to the task, if any. Use NSURLSessionTaskPriorityLow, +// NSURLSessionTaskPriorityDefault, or NSURLSessionTaskPriorityHigh. +@property(atomic, assign) float taskPriority; + +// The fetcher encodes information used to resume a session in the session identifier. +// This method, intended for internal use returns the encoded information. The sessionUserInfo +// dictionary is stored as identifier metadata. +- (GTM_NULLABLE GTM_NSDictionaryOf(NSString *, NSString *) *)sessionIdentifierMetadata; + +#if TARGET_OS_IPHONE +// The app should pass to this method the completion handler passed in the app delegate method +// application:handleEventsForBackgroundURLSession:completionHandler: ++ (void)application:(UIApplication *)application + handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler; +#endif + +// Indicate that a newly created session should be a background session. +// A new session identifier will be created by the fetcher. +// +// Warning: The only thing background sessions are for is rare download +// of huge, batched files of data. And even just for those, there's a lot +// of pain and hackery needed to get transfers to actually happen reliably +// with background sessions. +// +// Don't try to upload or download in many background sessions, since the system +// will impose an exponentially increasing time penalty to prevent the app from +// getting too much background execution time. +// +// References: +// +// "Moving to Fewer, Larger Transfers" +// https://forums.developer.apple.com/thread/14853 +// +// "NSURLSession’s Resume Rate Limiter" +// https://forums.developer.apple.com/thread/14854 +// +// "Background Session Task state persistence" +// https://forums.developer.apple.com/thread/11554 +// +@property(assign) BOOL useBackgroundSession; + +// Indicates if the fetcher was started using a background session. +@property(atomic, readonly, getter=isUsingBackgroundSession) BOOL usingBackgroundSession; + +// Indicates if uploads should use an upload task. This is always set for file or stream-provider +// bodies, but may be set explicitly for NSData bodies. +@property(atomic, assign) BOOL useUploadTask; + +// Indicates that the fetcher is using a session that may be shared with other fetchers. +@property(atomic, readonly) BOOL canShareSession; + +// By default, the fetcher allows only secure (https) schemes unless this +// property is set, or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. +// +// For example, during debugging when fetching from a development server that lacks SSL support, +// this may be set to @[ @"http" ], or when the fetcher is used to retrieve local files, +// this may be set to @[ @"file" ]. +// +// This should be left as nil for release builds to avoid creating the opportunity for +// leaking private user behavior and data. If a server is providing insecure URLs +// for fetching by the client app, report the problem as server security & privacy bug. +// +// For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when +// the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist. +@property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes; + +// By default, the fetcher prohibits localhost requests unless this property is set, +// or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. +// +// For localhost requests, the URL scheme is not checked when this property is set. +// +// For builds with the iOS 9/OS X 10.11 and later SDKs, this property is required only when +// the app specifies NSAppTransportSecurity/NSAllowsArbitraryLoads in the main bundle's Info.plist. +@property(atomic, assign) BOOL allowLocalhostRequest; + +// By default, the fetcher requires valid server certs. This may be bypassed +// temporarily for development against a test server with an invalid cert. +@property(atomic, assign) BOOL allowInvalidServerCertificates; + +// Cookie storage object for this fetcher. If nil, the fetcher will use a static cookie +// storage instance shared among fetchers. If this fetcher was created by a fetcher service +// object, it will be set to use the service object's cookie storage. See Cookies section above for +// the full discussion. +// +// Because as of Jan 2014 standalone instances of NSHTTPCookieStorage do not actually +// store any cookies (Radar 15735276) we use our own subclass, GTMSessionCookieStorage, +// to hold cookies in memory. +@property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage; + +// Setting the credential is optional; it is used if the connection receives +// an authentication challenge. +@property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential; + +// Setting the proxy credential is optional; it is used if the connection +// receives an authentication challenge from a proxy. +@property(atomic, strong, GTM_NULLABLE) NSURLCredential *proxyCredential; + +// If body data, body file URL, or body stream provider is not set, then a GET request +// method is assumed. +@property(atomic, strong, GTM_NULLABLE) NSData *bodyData; + +// File to use as the request body. This forces use of an upload task. +@property(atomic, strong, GTM_NULLABLE) NSURL *bodyFileURL; + +// Length of body to send, expected or actual. +@property(atomic, readonly) int64_t bodyLength; + +// The body stream provider may be called repeatedly to provide a body. +// Setting a body stream provider forces use of an upload task. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherBodyStreamProvider bodyStreamProvider; + +// Object to add authorization to the request, if needed. +// +// This may not be changed once beginFetch has been invoked. +@property(atomic, strong, GTM_NULLABLE) id authorizer; + +// The service object that created and monitors this fetcher, if any. +@property(atomic, strong) id service; + +// The host, if any, used to classify this fetcher in the fetcher service. +@property(atomic, copy, GTM_NULLABLE) NSString *serviceHost; + +// The priority, if any, used for starting fetchers in the fetcher service. +// +// Lower values are higher priority; the default is 0, and values may +// be negative or positive. This priority affects only the start order of +// fetchers that are being delayed by a fetcher service when the running fetchers +// exceeds the service's maxRunningFetchersPerHost. A priority of NSIntegerMin will +// exempt this fetcher from delay. +@property(atomic, assign) NSInteger servicePriority; + +// The delegate's optional didReceiveResponse block may be used to inspect or alter +// the session task response. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock; + +// The delegate's optional challenge block may be used to inspect or alter +// the session task challenge. +// +// If this block is not set, the fetcher's default behavior for the NSURLSessionTask +// didReceiveChallenge: delegate method is to use the fetcher's respondToChallenge: method +// which relies on the fetcher's credential and proxyCredential properties. +// +// Warning: This may be called repeatedly if the challenge fails. Check +// challenge.previousFailureCount to identify repeated invocations. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock; + +// The delegate's optional willRedirect block may be used to inspect or alter +// the redirection. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillRedirectBlock willRedirectBlock; + +// The optional send progress block reports body bytes uploaded. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherSendProgressBlock sendProgressBlock; + +// The optional accumulate block may be set by clients wishing to accumulate data +// themselves rather than let the fetcher append each buffer to an NSData. +// +// When this is called with nil data (such as on redirect) the client +// should empty its accumulation buffer. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherAccumulateDataBlock accumulateDataBlock; + +// The optional received progress block may be used to monitor data +// received from a data task. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherReceivedProgressBlock receivedProgressBlock; + +// The delegate's optional downloadProgress block may be used to monitor download +// progress in writing to disk. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherDownloadProgressBlock downloadProgressBlock; + +// The delegate's optional willCacheURLResponse block may be used to alter the cached +// NSURLResponse. The user may prevent caching by passing nil to the block's response. +// +// This is called on the callback queue. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock; + +// Enable retrying; see comments at the top of this file. Setting +// retryEnabled=YES resets the min and max retry intervals. +@property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled; + +// Retry block is optional for retries. +// +// If present, this block should call the response block with YES to cause a retry or NO to end the +// fetch. +// See comments at the top of this file. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock; + +// Retry intervals must be strictly less than maxRetryInterval, else +// they will be limited to maxRetryInterval and no further retries will +// be attempted. Setting maxRetryInterval to 0.0 will reset it to the +// default value, 60 seconds for downloads and 600 seconds for uploads. +@property(atomic, assign) NSTimeInterval maxRetryInterval; + +// Starting retry interval. Setting minRetryInterval to 0.0 will reset it +// to a random value between 1.0 and 2.0 seconds. Clients should normally not +// set this except for unit testing. +@property(atomic, assign) NSTimeInterval minRetryInterval; + +// Multiplier used to increase the interval between retries, typically 2.0. +// Clients should not need to set this. +@property(atomic, assign) double retryFactor; + +// Number of retries attempted. +@property(atomic, readonly) NSUInteger retryCount; + +// Interval delay to precede next retry. +@property(atomic, readonly) NSTimeInterval nextRetryInterval; + +#if GTM_BACKGROUND_TASK_FETCHING +// Skip use of a UIBackgroundTask, thus requiring fetches to complete when the app is in the +// foreground. +// +// Targets should define GTM_BACKGROUND_TASK_FETCHING to 0 to avoid use of a UIBackgroundTask +// on iOS to allow fetches to complete in the background. This property is available when +// it's not practical to set the preprocessor define. +@property(atomic, assign) BOOL skipBackgroundTask; +#endif // GTM_BACKGROUND_TASK_FETCHING + +// Begin fetching the request +// +// The delegate may optionally implement the callback or pass nil for the selector or handler. +// +// The delegate and all callback blocks are retained between the beginFetch call until after the +// finish callback, or until the fetch is stopped. +// +// An error is passed to the callback for server statuses 300 or +// higher, with the status stored as the error object's code. +// +// finishedSEL has a signature like: +// - (void)fetcher:(GTMSessionFetcher *)fetcher +// finishedWithData:(NSData *)data +// error:(NSError *)error; +// +// If the application has specified a destinationFileURL or an accumulateDataBlock +// for the fetcher, the data parameter passed to the callback will be nil. + +- (void)beginFetchWithDelegate:(GTM_NULLABLE id)delegate + didFinishSelector:(GTM_NULLABLE SEL)finishedSEL; + +- (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler; + +// Returns YES if this fetcher is in the process of fetching a URL. +@property(atomic, readonly, getter=isFetching) BOOL fetching; + +// Cancel the fetch of the request that's currently in progress. The completion handler +// will not be called. +- (void)stopFetching; + +// A block to be called when the fetch completes. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherCompletionHandler completionHandler; + +// A block to be called if download resume data becomes available. +@property(atomic, strong, GTM_NULLABLE) void (^resumeDataBlock)(NSData *); + +// Return the status code from the server response. +@property(atomic, readonly) NSInteger statusCode; + +// Return the http headers from the response. +@property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSString *) *responseHeaders; + +// The response, once it's been received. +@property(atomic, strong, readonly, GTM_NULLABLE) NSURLResponse *response; + +// Bytes downloaded so far. +@property(atomic, readonly) int64_t downloadedLength; + +// Buffer of currently-downloaded data, if available. +@property(atomic, readonly, strong, GTM_NULLABLE) NSData *downloadedData; + +// Local path to which the downloaded file will be moved. +// +// If a file already exists at the path, it will be overwritten. +// Will create the enclosing folders if they are not present. +@property(atomic, strong, GTM_NULLABLE) NSURL *destinationFileURL; + +// The time this fetcher originally began fetching. This is useful as a time +// barrier for ignoring irrelevant fetch notifications or callbacks. +@property(atomic, strong, readonly, GTM_NULLABLE) NSDate *initialBeginFetchDate; + +// userData is retained solely for the convenience of the client. +@property(atomic, strong, GTM_NULLABLE) id userData; + +// Stored property values are retained solely for the convenience of the client. +@property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties; + +- (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key; // Pass nil for obj to remove the property. +- (GTM_NULLABLE id)propertyForKey:(NSString *)key; + +- (void)addPropertiesFromDictionary:(GTM_NSDictionaryOf(NSString *, id) *)dict; + +// Comments are useful for logging, so are strongly recommended for each fetcher. +@property(atomic, copy, GTM_NULLABLE) NSString *comment; + +- (void)setCommentWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2); + +// Log of request and response, if logging is enabled +@property(atomic, copy, GTM_NULLABLE) NSString *log; + +// Callbacks are run on this queue. If none is supplied, the main queue is used. +@property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue; + +// The queue used internally by the session to invoke its delegate methods in the fetcher. +// +// Application callbacks are always called by the fetcher on the callbackQueue above, +// not on this queue. Apps should generally not change this queue. +// +// The default delegate queue is the main queue. +// +// This value is ignored after the session has been created, so this +// property should be set in the fetcher service rather in the fetcher as it applies +// to a shared session. +@property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue; + +// Spin the run loop or sleep the thread, discarding events, until the fetch has completed. +// +// This is only for use in testing or in tools without a user interface. +// +// Note: Synchronous fetches should never be used by shipping apps; they are +// sufficient reason for rejection from the app store. +// +// Returns NO if timed out. +- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds; + +// Test block is optional for testing. +// +// If present, this block will cause the fetcher to skip starting the session, and instead +// use the test block response values when calling the completion handler and delegate code. +// +// Test code can set this on the fetcher or on the fetcher service. For testing libraries +// that use a fetcher without exposing either the fetcher or the fetcher service, the global +// method setGlobalTestBlock: will set the block for all fetchers that do not have a test +// block set. +// +// The test code can pass nil for all response parameters to indicate that the fetch +// should proceed. +// +// Applications can exclude test block support by setting GTM_DISABLE_FETCHER_TEST_BLOCK. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock; + ++ (void)setGlobalTestBlock:(GTM_NULLABLE GTMSessionFetcherTestBlock)block; + +// When using the testBlock, |testBlockAccumulateDataChunkCount| is the desired number of chunks to +// divide the response data into if the client has streaming enabled. The data will be divided up to +// |testBlockAccumulateDataChunkCount| chunks; however, the exact amount may vary depending on the +// size of the response data (e.g. a 1-byte response can only be divided into one chunk). +@property(atomic, readwrite) NSUInteger testBlockAccumulateDataChunkCount; + +#if TARGET_OS_IPHONE +// For testing or to override UIApplication invocations, apps may specify an alternative +// target for messages to UIApplication. ++ (void)setSubstituteUIApplication:(nullable id)substituteUIApplication; ++ (nullable id)substituteUIApplication; +#endif // TARGET_OS_IPHONE + +// Exposed for testing. ++ (GTMSessionCookieStorage *)staticCookieStorage; ++ (BOOL)appAllowsInsecureRequests; + +#if STRIP_GTM_FETCH_LOGGING +// If logging is stripped, provide a stub for the main method +// for controlling logging. ++ (void)setLoggingEnabled:(BOOL)flag; ++ (BOOL)isLoggingEnabled; + +#else + +// These methods let an application log specific body text, such as the text description of a binary +// request or response. The application should set the fetcher to defer response body logging until +// the response has been received and the log response body has been set by the app. For example: +// +// fetcher.logRequestBody = [binaryObject stringDescription]; +// fetcher.deferResponseBodyLogging = YES; +// [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { +// if (error == nil) { +// fetcher.logResponseBody = [[[MyThing alloc] initWithData:data] stringDescription]; +// } +// fetcher.deferResponseBodyLogging = NO; +// }]; + +@property(atomic, copy, GTM_NULLABLE) NSString *logRequestBody; +@property(atomic, assign) BOOL deferResponseBodyLogging; +@property(atomic, copy, GTM_NULLABLE) NSString *logResponseBody; + +// Internal logging support. +@property(atomic, readonly) NSData *loggedStreamData; +@property(atomic, assign) BOOL hasLoggedError; +@property(atomic, strong, GTM_NULLABLE) NSURL *redirectedFromURL; +- (void)appendLoggedStreamData:(NSData *)dataToAdd; +- (void)clearLoggedStreamData; + +#endif // STRIP_GTM_FETCH_LOGGING + +@end + +@interface GTMSessionFetcher (BackwardsCompatibilityOnly) +// Clients using GTMSessionFetcher should set the cookie storage explicitly themselves. +// This method is just for compatibility with the old GTMHTTPFetcher class. +- (void)setCookieStorageMethod:(NSInteger)method; +@end + +// Until we can just instantiate NSHTTPCookieStorage for local use, we'll +// implement all the public methods ourselves. This stores cookies only in +// memory. Additional methods are provided for testing. +// +// iOS 9/OS X 10.11 added +[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:] +// which may also be used to create cookie storage. +@interface GTMSessionCookieStorage : NSHTTPCookieStorage + +// Add the array off cookies to the storage, replacing duplicates. +// Also removes expired cookies from the storage. +- (void)setCookies:(GTM_NULLABLE GTM_NSArrayOf(NSHTTPCookie *) *)cookies; + +- (void)removeAllCookies; + +@end + +// Macros to monitor synchronization blocks in debug builds. +// These report problems using GTMSessionCheckDebug. +// +// GTMSessionMonitorSynchronized Start monitoring a top-level-only +// @sync scope. +// GTMSessionMonitorRecursiveSynchronized Start monitoring a top-level or +// recursive @sync scope. +// GTMSessionCheckSynchronized Verify that the current execution +// is inside a @sync scope. +// GTMSessionCheckNotSynchronized Verify that the current execution +// is not inside a @sync scope. +// +// Example usage: +// +// - (void)myExternalMethod { +// @synchronized(self) { +// GTMSessionMonitorSynchronized(self) +// +// - (void)myInternalMethod { +// GTMSessionCheckSynchronized(self); +// +// - (void)callMyCallbacks { +// GTMSessionCheckNotSynchronized(self); +// +// GTMSessionCheckNotSynchronized is available for verifying the code isn't +// in a deadlockable @sync state when posting notifications and invoking +// callbacks. Don't use GTMSessionCheckNotSynchronized immediately before a +// @sync scope; the normal recursiveness check of GTMSessionMonitorSynchronized +// can catch those. + +#ifdef __OBJC__ +#if DEBUG + #define __GTMSessionMonitorSynchronizedVariableInner(varname, counter) \ + varname ## counter + #define __GTMSessionMonitorSynchronizedVariable(varname, counter) \ + __GTMSessionMonitorSynchronizedVariableInner(varname, counter) + + #define GTMSessionMonitorSynchronized(obj) \ + NS_VALID_UNTIL_END_OF_SCOPE id \ + __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \ + [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \ + allowRecursive:NO \ + functionName:__func__] + + #define GTMSessionMonitorRecursiveSynchronized(obj) \ + NS_VALID_UNTIL_END_OF_SCOPE id \ + __GTMSessionMonitorSynchronizedVariable(__monitor, __COUNTER__) = \ + [[GTMSessionSyncMonitorInternal alloc] initWithSynchronizationObject:obj \ + allowRecursive:YES \ + functionName:__func__] + + #define GTMSessionCheckSynchronized(obj) { \ + GTMSESSION_ASSERT_DEBUG( \ + [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ + @"GTMSessionCheckSynchronized(" #obj ") failed: not sync'd" \ + @" on " #obj " in %s. Call stack:\n%@", \ + __func__, [NSThread callStackSymbols]); \ + } + + #define GTMSessionCheckNotSynchronized(obj) { \ + GTMSESSION_ASSERT_DEBUG( \ + ![GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ + @"GTMSessionCheckNotSynchronized(" #obj ") failed: was sync'd" \ + @" on " #obj " in %s by %@. Call stack:\n%@", __func__, \ + [GTMSessionSyncMonitorInternal functionsHoldingSynchronizationOnObject:obj], \ + [NSThread callStackSymbols]); \ + } + +// GTMSessionSyncMonitorInternal is a private class that keeps track of the +// beginning and end of synchronized scopes. +// +// This class should not be used directly, but only via the +// GTMSessionMonitorSynchronized macro. +@interface GTMSessionSyncMonitorInternal : NSObject +- (instancetype)initWithSynchronizationObject:(id)object + allowRecursive:(BOOL)allowRecursive + functionName:(const char *)functionName; +// Return the names of the functions that hold sync on the object, or nil if none. ++ (NSArray *)functionsHoldingSynchronizationOnObject:(id)object; +@end + +#else + #define GTMSessionMonitorSynchronized(obj) do { } while (0) + #define GTMSessionMonitorRecursiveSynchronized(obj) do { } while (0) + #define GTMSessionCheckSynchronized(obj) do { } while (0) + #define GTMSessionCheckNotSynchronized(obj) do { } while (0) +#endif // !DEBUG +#endif // __OBJC__ + + +GTM_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m new file mode 100644 index 000000000..e3f52d873 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcher.m @@ -0,0 +1,4549 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMSessionFetcher.h" + +#import + +#ifndef STRIP_GTM_FETCH_LOGGING + #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined. +#endif + +GTM_ASSUME_NONNULL_BEGIN + +NSString *const kGTMSessionFetcherStartedNotification = @"kGTMSessionFetcherStartedNotification"; +NSString *const kGTMSessionFetcherStoppedNotification = @"kGTMSessionFetcherStoppedNotification"; +NSString *const kGTMSessionFetcherRetryDelayStartedNotification = @"kGTMSessionFetcherRetryDelayStartedNotification"; +NSString *const kGTMSessionFetcherRetryDelayStoppedNotification = @"kGTMSessionFetcherRetryDelayStoppedNotification"; + +NSString *const kGTMSessionFetcherCompletionInvokedNotification = @"kGTMSessionFetcherCompletionInvokedNotification"; +NSString *const kGTMSessionFetcherCompletionDataKey = @"data"; +NSString *const kGTMSessionFetcherCompletionErrorKey = @"error"; + +NSString *const kGTMSessionFetcherErrorDomain = @"com.google.GTMSessionFetcher"; +NSString *const kGTMSessionFetcherStatusDomain = @"com.google.HTTPStatus"; +NSString *const kGTMSessionFetcherStatusDataKey = @"data"; // data returned with a kGTMSessionFetcherStatusDomain error + +NSString *const kGTMSessionFetcherNumberOfRetriesDoneKey = @"kGTMSessionFetcherNumberOfRetriesDoneKey"; +NSString *const kGTMSessionFetcherElapsedIntervalWithRetriesKey = @"kGTMSessionFetcherElapsedIntervalWithRetriesKey"; + +static NSString *const kGTMSessionIdentifierPrefix = @"com.google.GTMSessionFetcher"; +static NSString *const kGTMSessionIdentifierDestinationFileURLMetadataKey = @"_destURL"; +static NSString *const kGTMSessionIdentifierBodyFileURLMetadataKey = @"_bodyURL"; + +// The default max retry interview is 10 minutes for uploads (POST/PUT/PATCH), +// 1 minute for downloads. +static const NSTimeInterval kUnsetMaxRetryInterval = -1.0; +static const NSTimeInterval kDefaultMaxDownloadRetryInterval = 60.0; +static const NSTimeInterval kDefaultMaxUploadRetryInterval = 60.0 * 10.; + +#ifdef GTMSESSION_PERSISTED_DESTINATION_KEY +// Projects using unique class names should also define a unique persisted destination key. +static NSString * const kGTMSessionFetcherPersistedDestinationKey = + GTMSESSION_PERSISTED_DESTINATION_KEY; +#else +static NSString * const kGTMSessionFetcherPersistedDestinationKey = + @"com.google.GTMSessionFetcher.downloads"; +#endif + +GTM_ASSUME_NONNULL_END + +// +// GTMSessionFetcher +// + +#if 0 +#define GTM_LOG_BACKGROUND_SESSION(...) GTMSESSION_LOG_DEBUG(__VA_ARGS__) +#else +#define GTM_LOG_BACKGROUND_SESSION(...) +#endif + +#ifndef GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY + #if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0)) + #define GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY 1 + #endif +#endif + +@interface GTMSessionFetcher () + +@property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadedData; +@property(atomic, strong, readwrite, GTM_NULLABLE) NSData *downloadResumeData; + +#if GTM_BACKGROUND_TASK_FETCHING +// Should always be accessed within an @synchranized(self). +@property(assign, nonatomic) UIBackgroundTaskIdentifier backgroundTaskIdentifier; +#endif + +@property(atomic, readwrite, getter=isUsingBackgroundSession) BOOL usingBackgroundSession; + +@end + +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMSessionFetcher (GTMSessionFetcherLoggingInternal) +- (void)logFetchWithError:(NSError *)error; +- (void)logNowWithError:(GTM_NULLABLE NSError *)error; +- (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream; +- (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: + (GTMSessionFetcherBodyStreamProvider)streamProvider; +@end +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +GTM_ASSUME_NONNULL_BEGIN + +static NSTimeInterval InitialMinRetryInterval(void) { + return 1.0 + ((double)(arc4random_uniform(0x0FFFF)) / (double) 0x0FFFF); +} + +static BOOL IsLocalhost(NSString * GTM_NULLABLE_TYPE host) { + // We check if there's host, and then make the comparisons. + if (host == nil) return NO; + return ([host caseInsensitiveCompare:@"localhost"] == NSOrderedSame + || [host isEqual:@"::1"] + || [host isEqual:@"127.0.0.1"]); +} + +static GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE gGlobalTestBlock; + +@implementation GTMSessionFetcher { + NSMutableURLRequest *_request; // after beginFetch, changed only in delegate callbacks + BOOL _useUploadTask; // immutable after beginFetch + NSURL *_bodyFileURL; // immutable after beginFetch + GTMSessionFetcherBodyStreamProvider _bodyStreamProvider; // immutable after beginFetch + NSURLSession *_session; + BOOL _shouldInvalidateSession; // immutable after beginFetch + NSURLSession *_sessionNeedingInvalidation; + NSURLSessionConfiguration *_configuration; + NSURLSessionTask *_sessionTask; + NSString *_taskDescription; + float _taskPriority; + NSURLResponse *_response; + NSString *_sessionIdentifier; + BOOL _wasCreatedFromBackgroundSession; + BOOL _didCreateSessionIdentifier; + NSString *_sessionIdentifierUUID; + BOOL _userRequestedBackgroundSession; + BOOL _usingBackgroundSession; + NSMutableData * GTM_NULLABLE_TYPE _downloadedData; + NSError *_downloadFinishedError; + NSData *_downloadResumeData; // immutable after construction + NSURL *_destinationFileURL; + int64_t _downloadedLength; + NSURLCredential *_credential; // username & password + NSURLCredential *_proxyCredential; // credential supplied to proxy servers + BOOL _isStopNotificationNeeded; // set when start notification has been sent + BOOL _isUsingTestBlock; // set when a test block was provided (remains set when the block is released) + id _userData; // retained, if set by caller + NSMutableDictionary *_properties; // more data retained for caller + dispatch_queue_t _callbackQueue; + dispatch_group_t _callbackGroup; // read-only after creation + NSOperationQueue *_delegateQueue; // immutable after beginFetch + + id _authorizer; // immutable after beginFetch + + // The service object that created and monitors this fetcher, if any. + id _service; // immutable; set by the fetcher service upon creation + NSString *_serviceHost; + NSInteger _servicePriority; // immutable after beginFetch + BOOL _hasStoppedFetching; // counterpart to _initialBeginFetchDate + BOOL _userStoppedFetching; + + BOOL _isRetryEnabled; // user wants auto-retry + NSTimer *_retryTimer; + NSUInteger _retryCount; + NSTimeInterval _maxRetryInterval; // default 60 (download) or 600 (upload) seconds + NSTimeInterval _minRetryInterval; // random between 1 and 2 seconds + NSTimeInterval _retryFactor; // default interval multiplier is 2 + NSTimeInterval _lastRetryInterval; + NSDate *_initialBeginFetchDate; // date that beginFetch was first invoked; immutable after initial beginFetch + NSDate *_initialRequestDate; // date of first request to the target server (ignoring auth) + BOOL _hasAttemptedAuthRefresh; // accessed only in shouldRetryNowForStatus: + + NSString *_comment; // comment for log + NSString *_log; +#if !STRIP_GTM_FETCH_LOGGING + NSMutableData *_loggedStreamData; + NSURL *_redirectedFromURL; + NSString *_logRequestBody; + NSString *_logResponseBody; + BOOL _hasLoggedError; + BOOL _deferResponseBodyLogging; +#endif +} + +#if !GTMSESSION_UNIT_TESTING ++ (void)load { + [self fetchersForBackgroundSessions]; +} +#endif + ++ (instancetype)fetcherWithRequest:(GTM_NULLABLE NSURLRequest *)request { + return [[self alloc] initWithRequest:request configuration:nil]; +} + ++ (instancetype)fetcherWithURL:(NSURL *)requestURL { + return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; +} + ++ (instancetype)fetcherWithURLString:(NSString *)requestURLString { + return [self fetcherWithURL:(NSURL *)[NSURL URLWithString:requestURLString]]; +} + ++ (instancetype)fetcherWithDownloadResumeData:(NSData *)resumeData { + GTMSessionFetcher *fetcher = [self fetcherWithRequest:nil]; + fetcher.comment = @"Resuming download"; + fetcher.downloadResumeData = resumeData; + return fetcher; +} + ++ (GTM_NULLABLE instancetype)fetcherWithSessionIdentifier:(NSString *)sessionIdentifier { + GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); + NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; + GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; + if (!fetcher && [sessionIdentifier hasPrefix:kGTMSessionIdentifierPrefix]) { + fetcher = [self fetcherWithRequest:nil]; + [fetcher setSessionIdentifier:sessionIdentifier]; + [sessionIdentifierToFetcherMap setObject:fetcher forKey:sessionIdentifier]; + fetcher->_wasCreatedFromBackgroundSession = YES; + [fetcher setCommentWithFormat:@"Resuming %@", + fetcher && fetcher->_sessionIdentifierUUID ? fetcher->_sessionIdentifierUUID : @"?"]; + } + return fetcher; +} + ++ (NSMapTable *)sessionIdentifierToFetcherMap { + // TODO: What if a service is involved in creating the fetcher? Currently, when re-creating + // fetchers, if a service was involved, it is not re-created. Should the service maintain a map? + static NSMapTable *gSessionIdentifierToFetcherMap = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gSessionIdentifierToFetcherMap = [NSMapTable strongToWeakObjectsMapTable]; + }); + return gSessionIdentifierToFetcherMap; +} + +#if !GTM_ALLOW_INSECURE_REQUESTS ++ (BOOL)appAllowsInsecureRequests { + // If the main bundle Info.plist key NSAppTransportSecurity is present, and it specifies + // NSAllowsArbitraryLoads, then we need to explicitly enforce secure schemes. +#if GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY + static BOOL allowsInsecureRequests; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *mainBundle = [NSBundle mainBundle]; + NSDictionary *appTransportSecurity = + [mainBundle objectForInfoDictionaryKey:@"NSAppTransportSecurity"]; + allowsInsecureRequests = + [[appTransportSecurity objectForKey:@"NSAllowsArbitraryLoads"] boolValue]; + }); + return allowsInsecureRequests; +#else + // For builds targeting iOS 8 or 10.10 and earlier, we want to require fetcher + // security checks. + return YES; +#endif // GTM_TARGET_SUPPORTS_APP_TRANSPORT_SECURITY +} +#else // GTM_ALLOW_INSECURE_REQUESTS ++ (BOOL)appAllowsInsecureRequests { + return YES; +} +#endif // !GTM_ALLOW_INSECURE_REQUESTS + + +- (instancetype)init { + return [self initWithRequest:nil configuration:nil]; +} + +- (instancetype)initWithRequest:(NSURLRequest *)request { + return [self initWithRequest:request configuration:nil]; +} + +- (instancetype)initWithRequest:(GTM_NULLABLE NSURLRequest *)request + configuration:(GTM_NULLABLE NSURLSessionConfiguration *)configuration { + self = [super init]; + if (self) { + if (![NSURLSession class]) { + Class oldFetcherClass = NSClassFromString(@"GTMHTTPFetcher"); + if (oldFetcherClass && request) { + self = [[oldFetcherClass alloc] initWithRequest:(NSURLRequest *)request]; + } else { + self = nil; + } + return self; + } +#if GTM_BACKGROUND_TASK_FETCHING + _backgroundTaskIdentifier = UIBackgroundTaskInvalid; +#endif + _request = [request mutableCopy]; + _configuration = configuration; + + NSData *bodyData = request.HTTPBody; + if (bodyData) { + _bodyLength = (int64_t)bodyData.length; + } else { + _bodyLength = NSURLSessionTransferSizeUnknown; + } + + _callbackQueue = dispatch_get_main_queue(); + _callbackGroup = dispatch_group_create(); + _delegateQueue = [NSOperationQueue mainQueue]; + + _minRetryInterval = InitialMinRetryInterval(); + _maxRetryInterval = kUnsetMaxRetryInterval; + + _taskPriority = -1.0f; // Valid values if set are 0.0...1.0. + + _testBlockAccumulateDataChunkCount = 1; + +#if !STRIP_GTM_FETCH_LOGGING + // Encourage developers to set the comment property or use + // setCommentWithFormat: by providing a default string. + _comment = @"(No fetcher comment set)"; +#endif + } + return self; +} + +- (id)copyWithZone:(NSZone *)zone { + // disallow use of fetchers in a copy property + [self doesNotRecognizeSelector:_cmd]; + return nil; +} + +- (NSString *)description { + NSString *requestStr = self.request.URL.description; + if (requestStr.length == 0) { + if (self.downloadResumeData.length > 0) { + requestStr = @""; + } else if (_wasCreatedFromBackgroundSession) { + requestStr = @""; + } else { + requestStr = @""; + } + } + return [NSString stringWithFormat:@"%@ %p (%@)", [self class], self, requestStr]; +} + +- (void)dealloc { + GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, + @"unbalanced fetcher notification for %@", _request.URL); + [self forgetSessionIdentifierForFetcherWithoutSyncCheck]; + + // Note: if a session task or a retry timer was pending, then this instance + // would be retained by those so it wouldn't be getting dealloc'd, + // hence we don't need to stopFetch here +} + +#pragma mark - + +// Begin fetching the URL (or begin a retry fetch). The delegate is retained +// for the duration of the fetch connection. + +- (void)beginFetchWithCompletionHandler:(GTM_NULLABLE GTMSessionFetcherCompletionHandler)handler { + GTMSessionCheckNotSynchronized(self); + + _completionHandler = [handler copy]; + + // The user may have called setDelegate: earlier if they want to use other + // delegate-style callbacks during the fetch; otherwise, the delegate is nil, + // which is fine. + [self beginFetchMayDelay:YES mayAuthorize:YES]; +} + +- (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(GTM_NULLABLE_TYPE id)target + didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector { + GTMSessionFetcherAssertValidSelector(target, finishedSelector, @encode(GTMSessionFetcher *), + @encode(NSData *), @encode(NSError *), 0); + GTMSessionFetcherCompletionHandler completionHandler = ^(NSData *data, NSError *error) { + if (target && finishedSelector) { + id selfArg = self; // Placate ARC. + NSMethodSignature *sig = [target methodSignatureForSelector:finishedSelector]; + NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; + [invocation setSelector:(SEL)finishedSelector]; + [invocation setTarget:target]; + [invocation setArgument:&selfArg atIndex:2]; + [invocation setArgument:&data atIndex:3]; + [invocation setArgument:&error atIndex:4]; + [invocation invoke]; + } + }; + return completionHandler; +} + +- (void)beginFetchWithDelegate:(GTM_NULLABLE_TYPE id)target + didFinishSelector:(GTM_NULLABLE_TYPE SEL)finishedSelector { + GTMSessionCheckNotSynchronized(self); + + GTMSessionFetcherCompletionHandler handler = [self completionHandlerWithTarget:target + didFinishSelector:finishedSelector]; + [self beginFetchWithCompletionHandler:handler]; +} + +- (void)beginFetchMayDelay:(BOOL)mayDelay + mayAuthorize:(BOOL)mayAuthorize { + // This is the internal entry point for re-starting fetches. + GTMSessionCheckNotSynchronized(self); + + NSMutableURLRequest *fetchRequest = _request; // The request property is now externally immutable. + NSURL *fetchRequestURL = fetchRequest.URL; + NSString *priorSessionIdentifier = self.sessionIdentifier; + + // A utility block for creating error objects when we fail to start the fetch. + NSError *(^beginFailureError)(NSInteger) = ^(NSInteger code){ + NSString *urlString = fetchRequestURL.absoluteString; + NSDictionary *userInfo = @{ + NSURLErrorFailingURLStringErrorKey : (urlString ? urlString : @"(missing URL)") + }; + return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:code + userInfo:userInfo]; + }; + + // Catch delegate queue maxConcurrentOperationCount values other than 1, particularly + // NSOperationQueueDefaultMaxConcurrentOperationCount (-1), to avoid the additional complexity + // of simultaneous or out-of-order delegate callbacks. + GTMSESSION_ASSERT_DEBUG(_delegateQueue.maxConcurrentOperationCount == 1, + @"delegate queue %@ should support one concurrent operation, not %zd", + _delegateQueue.name, _delegateQueue.maxConcurrentOperationCount); + + if (!_initialBeginFetchDate) { + // This ivar is set only here on the initial beginFetch so need not be synchronized. + _initialBeginFetchDate = [[NSDate alloc] init]; + } + + if (self.sessionTask != nil) { + // If cached fetcher returned through fetcherWithSessionIdentifier:, then it's + // already begun, but don't consider this a failure, since the user need not know this. + if (self.sessionIdentifier != nil) { + return; + } + GTMSESSION_ASSERT_DEBUG(NO, @"Fetch object %@ being reused; this should never happen", self); + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)]; + return; + } + + if (fetchRequestURL == nil && !_downloadResumeData && !priorSessionIdentifier) { + GTMSESSION_ASSERT_DEBUG(NO, @"Beginning a fetch requires a request with a URL"); + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorDownloadFailed)]; + return; + } + + // We'll respect the user's request for a background session (unless this is + // an upload fetcher, which does its initial request foreground.) + self.usingBackgroundSession = self.useBackgroundSession && [self canFetchWithBackgroundSession]; + + NSURL *bodyFileURL = self.bodyFileURL; + if (bodyFileURL) { + NSError *fileCheckError; + if (![bodyFileURL checkResourceIsReachableAndReturnError:&fileCheckError]) { + // This assert fires when the file being uploaded no longer exists once + // the fetcher is ready to start the upload. + GTMSESSION_ASSERT_DEBUG_OR_LOG(0, @"Body file is unreachable: %@\n %@", + bodyFileURL.path, fileCheckError); + [self failToBeginFetchWithError:fileCheckError]; + return; + } + } + + NSString *requestScheme = fetchRequestURL.scheme; + BOOL isDataRequest = [requestScheme isEqual:@"data"]; + if (isDataRequest) { + // NSURLSession does not support data URLs in background sessions. +#if DEBUG + if (priorSessionIdentifier || self.sessionIdentifier) { + GTMSESSION_LOG_DEBUG(@"Converting background to foreground session for %@", + fetchRequest); + } +#endif + [self setSessionIdentifierInternal:nil]; + self.useBackgroundSession = NO; + } + +#if GTM_ALLOW_INSECURE_REQUESTS + BOOL shouldCheckSecurity = NO; +#else + BOOL shouldCheckSecurity = (fetchRequestURL != nil + && !isDataRequest + && [[self class] appAllowsInsecureRequests]); +#endif + + if (shouldCheckSecurity) { + // Allow https only for requests, unless overridden by the client. + // + // Non-https requests may too easily be snooped, so we disallow them by default. + // + // file: and data: schemes are usually safe if they are hardcoded in the client or provided + // by a trusted source, but since it's fairly rare to need them, it's safest to make clients + // explicitly whitelist them. + BOOL isSecure = + requestScheme != nil && [requestScheme caseInsensitiveCompare:@"https"] == NSOrderedSame; + if (!isSecure) { + BOOL allowRequest = NO; + NSString *host = fetchRequestURL.host; + + // Check schemes first. A file scheme request may be allowed here, or as a localhost request. + for (NSString *allowedScheme in _allowedInsecureSchemes) { + if (requestScheme != nil && + [requestScheme caseInsensitiveCompare:allowedScheme] == NSOrderedSame) { + allowRequest = YES; + break; + } + } + if (!allowRequest) { + // Check for localhost requests. Security checks only occur for non-https requests, so + // this check won't happen for an https request to localhost. + BOOL isLocalhostRequest = (host.length == 0 && [fetchRequestURL isFileURL]) || IsLocalhost(host); + if (isLocalhostRequest) { + if (self.allowLocalhostRequest) { + allowRequest = YES; + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"Fetch request for localhost but fetcher" + @" allowLocalhostRequest is not set: %@", fetchRequestURL); + } + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"Insecure fetch request has a scheme (%@)" + @" not found in fetcher allowedInsecureSchemes (%@): %@", + requestScheme, _allowedInsecureSchemes ?: @" @[] ", fetchRequestURL); + } + } + + if (!allowRequest) { +#if !DEBUG + NSLog(@"Insecure fetch disallowed for %@", fetchRequestURL.description ?: @"nil request URL"); +#endif + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorInsecureRequest)]; + return; + } + } // !isSecure + } // (requestURL != nil) && !isDataRequest + + if (self.cookieStorage == nil) { + self.cookieStorage = [[self class] staticCookieStorage]; + } + + BOOL isRecreatingSession = (self.sessionIdentifier != nil) && (fetchRequest == nil); + + self.canShareSession = !isRecreatingSession && !self.usingBackgroundSession; + + if (!self.session && self.canShareSession) { + self.session = [_service sessionForFetcherCreation]; + // If _session is nil, then the service's session creation semaphore will block + // until this fetcher invokes fetcherDidCreateSession: below, so this *must* invoke + // that method, even if the session fails to be created. + } + + if (!self.session) { + // Create a session. + if (!_configuration) { + if (priorSessionIdentifier || self.usingBackgroundSession) { + NSString *sessionIdentifier = priorSessionIdentifier; + if (!sessionIdentifier) { + sessionIdentifier = [self createSessionIdentifierWithMetadata:nil]; + } + NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap]; + [sessionIdentifierToFetcherMap setObject:self forKey:self.sessionIdentifier]; + +#if (TARGET_OS_TV \ + || TARGET_OS_WATCH \ + || (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0)) + // iOS 8/10.10 builds require the new backgroundSessionConfiguration method name. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier]; +#elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0) + // Do a runtime check to avoid a deprecation warning about using + // +backgroundSessionConfiguration: on iOS 8. + if ([NSURLSessionConfiguration respondsToSelector:@selector(backgroundSessionConfigurationWithIdentifier:)]) { + // Running on iOS 8+/OS X 10.10+. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier]; + } else { + // Running on iOS 7/OS X 10.9. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; + } +#else + // Building with an SDK earlier than iOS 8/OS X 10.10. + _configuration = + [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; +#endif + self.usingBackgroundSession = YES; + self.canShareSession = NO; + } else { + _configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + } +#if !GTM_ALLOW_INSECURE_REQUESTS + _configuration.TLSMinimumSupportedProtocol = kTLSProtocol12; +#endif + } // !_configuration + _configuration.HTTPCookieStorage = self.cookieStorage; + + if (_configurationBlock) { + _configurationBlock(self, _configuration); + } + + id delegate = [_service sessionDelegate]; + if (!delegate || !self.canShareSession) { + delegate = self; + } + self.session = [NSURLSession sessionWithConfiguration:_configuration + delegate:delegate + delegateQueue:self.sessionDelegateQueue]; + GTMSESSION_ASSERT_DEBUG(self.session, @"Couldn't create session"); + + // Tell the service about the session created by this fetcher. This also signals the + // service's semaphore to allow other fetchers to request this session. + [_service fetcherDidCreateSession:self]; + + // If this assertion fires, the client probably tried to use a session identifier that was + // already used. The solution is to make the client use a unique identifier (or better yet let + // the session fetcher assign the identifier). + GTMSESSION_ASSERT_DEBUG(self.session.delegate == delegate, @"Couldn't assign delegate."); + + if (self.session) { + BOOL isUsingSharedDelegate = (delegate != self); + if (!isUsingSharedDelegate) { + _shouldInvalidateSession = YES; + } + } + } + + if (isRecreatingSession) { + _shouldInvalidateSession = YES; + + // Let's make sure there are tasks still running or if not that we get a callback from a + // completed one; otherwise, we assume the tasks failed. + // This is the observed behavior perhaps 25% of the time within the Simulator running 7.0.3 on + // exiting the app after starting an upload and relaunching the app if we manage to relaunch + // after the task has completed, but before the system relaunches us in the background. + [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, + NSArray *downloadTasks) { + if (dataTasks.count == 0 && uploadTasks.count == 0 && downloadTasks.count == 0) { + double const kDelayInSeconds = 1.0; // We should get progress indication or completion soon + dispatch_time_t checkForFeedbackDelay = + dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kDelayInSeconds * NSEC_PER_SEC)); + dispatch_after(checkForFeedbackDelay, dispatch_get_main_queue(), ^{ + if (!self.sessionTask && !fetchRequest) { + // If our task and/or request haven't been restored, then we assume task feedback lost. + [self removePersistedBackgroundSessionFromDefaults]; + NSError *sessionError = + [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:GTMSessionFetcherErrorBackgroundFetchFailed + userInfo:nil]; + [self failToBeginFetchWithError:sessionError]; + } + }); + } + }]; + return; + } + + self.downloadedData = nil; + self.downloadedLength = 0; + + if (_servicePriority == NSIntegerMin) { + mayDelay = NO; + } + if (mayDelay && _service) { + BOOL shouldFetchNow = [_service fetcherShouldBeginFetching:self]; + if (!shouldFetchNow) { + // The fetch is deferred, but will happen later. + // + // If this session is held by the fetcher service, clear the session now so that we don't + // assume it's still valid after the fetcher is restarted. + if (self.canShareSession) { + self.session = nil; + } + return; + } + } + + NSString *effectiveHTTPMethod = [fetchRequest valueForHTTPHeaderField:@"X-HTTP-Method-Override"]; + if (effectiveHTTPMethod == nil) { + effectiveHTTPMethod = fetchRequest.HTTPMethod; + } + BOOL isEffectiveHTTPGet = (effectiveHTTPMethod == nil + || [effectiveHTTPMethod isEqual:@"GET"]); + + BOOL needsUploadTask = (self.useUploadTask || self.bodyFileURL || self.bodyStreamProvider); + if (_bodyData || self.bodyStreamProvider || fetchRequest.HTTPBodyStream) { + if (isEffectiveHTTPGet) { + fetchRequest.HTTPMethod = @"POST"; + isEffectiveHTTPGet = NO; + } + + if (_bodyData) { + if (!needsUploadTask) { + fetchRequest.HTTPBody = _bodyData; + } +#if !STRIP_GTM_FETCH_LOGGING + } else if (fetchRequest.HTTPBodyStream) { + if ([self respondsToSelector:@selector(loggedInputStreamForInputStream:)]) { + fetchRequest.HTTPBodyStream = + [self performSelector:@selector(loggedInputStreamForInputStream:) + withObject:fetchRequest.HTTPBodyStream]; + } +#endif + } + } + + // We authorize after setting up the http method and body in the request + // because OAuth 1 may need to sign the request body + if (mayAuthorize && _authorizer && !isDataRequest) { + BOOL isAuthorized = [_authorizer isAuthorizedRequest:fetchRequest]; + if (!isAuthorized) { + // Authorization needed. + // + // If this session is held by the fetcher service, clear the session now so that we don't + // assume it's still valid after authorization completes. + if (self.canShareSession) { + self.session = nil; + } + + // Authorizing the request will recursively call this beginFetch:mayDelay: + // or failToBeginFetchWithError:. + [self authorizeRequest]; + return; + } + } + + // set the default upload or download retry interval, if necessary + if ([self isRetryEnabled] && self.maxRetryInterval <= 0) { + if (isEffectiveHTTPGet || [effectiveHTTPMethod isEqual:@"HEAD"]) { + [self setMaxRetryInterval:kDefaultMaxDownloadRetryInterval]; + } else { + [self setMaxRetryInterval:kDefaultMaxUploadRetryInterval]; + } + } + + // finally, start the connection + NSURLSessionTask *newSessionTask; + BOOL needsDataAccumulator = NO; + if (_downloadResumeData) { + newSessionTask = [_session downloadTaskWithResumeData:_downloadResumeData]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed downloadTaskWithResumeData for %@, resume data %tu bytes", + _session, _downloadResumeData.length); + } else if (_destinationFileURL && !isDataRequest) { + newSessionTask = [_session downloadTaskWithRequest:fetchRequest]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed downloadTaskWithRequest for %@, %@", + _session, fetchRequest); + } else if (needsUploadTask) { + if (bodyFileURL) { + newSessionTask = [_session uploadTaskWithRequest:fetchRequest + fromFile:bodyFileURL]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed uploadTaskWithRequest for %@, %@, file %@", + _session, fetchRequest, bodyFileURL.path); + } else if (self.bodyStreamProvider) { + newSessionTask = [_session uploadTaskWithStreamedRequest:fetchRequest]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed uploadTaskWithStreamedRequest for %@, %@", + _session, fetchRequest); + } else { + GTMSESSION_ASSERT_DEBUG_OR_LOG(_bodyData != nil, + @"Upload task needs body data, %@", fetchRequest); + newSessionTask = [_session uploadTaskWithRequest:fetchRequest + fromData:(NSData * GTM_NONNULL_TYPE)_bodyData]; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, + @"Failed uploadTaskWithRequest for %@, %@, body data %tu bytes", + _session, fetchRequest, _bodyData.length); + } + needsDataAccumulator = YES; + } else { + newSessionTask = [_session dataTaskWithRequest:fetchRequest]; + needsDataAccumulator = YES; + GTMSESSION_ASSERT_DEBUG_OR_LOG(newSessionTask, @"Failed dataTaskWithRequest for %@, %@", + _session, fetchRequest); + } + self.sessionTask = newSessionTask; + + if (!newSessionTask) { + // We shouldn't get here; if we're here, an earlier assertion should have fired to explain + // which session task creation failed. + [self failToBeginFetchWithError:beginFailureError(GTMSessionFetcherErrorTaskCreationFailed)]; + return; + } + + if (needsDataAccumulator && _accumulateDataBlock == nil) { + self.downloadedData = [NSMutableData data]; + } + if (_taskDescription) { + newSessionTask.taskDescription = _taskDescription; + } + if (_taskPriority >= 0) { +#if TARGET_OS_TV || TARGET_OS_WATCH + BOOL hasTaskPriority = YES; +#elif (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_8_0) + BOOL hasTaskPriority = YES; +#else + BOOL hasTaskPriority = [newSessionTask respondsToSelector:@selector(setPriority:)]; +#endif + if (hasTaskPriority) { + newSessionTask.priority = _taskPriority; + } + } + +#if GTM_DISABLE_FETCHER_TEST_BLOCK + GTMSESSION_ASSERT_DEBUG(_testBlock == nil && gGlobalTestBlock == nil, @"test blocks disabled"); + _testBlock = nil; +#else + if (!_testBlock) { + if (gGlobalTestBlock) { + // Note that the test block may pass nil for all of its response parameters, + // indicating that the fetch should actually proceed. This is useful when the + // global test block has been set, and the app is only testing a specific + // fetcher. The block simulation code will then resume the task. + _testBlock = gGlobalTestBlock; + } + } + _isUsingTestBlock = (_testBlock != nil); +#endif // GTM_DISABLE_FETCHER_TEST_BLOCK + +#if GTM_BACKGROUND_TASK_FETCHING + id app = [[self class] fetcherUIApplication]; + // Background tasks seem to interfere with out-of-process uploads and downloads. + if (app && !self.skipBackgroundTask && !self.useBackgroundSession) { + // Tell UIApplication that we want to continue even when the app is in the + // background. +#if DEBUG + NSString *bgTaskName = [NSString stringWithFormat:@"%@-%@", + [self class], fetchRequest.URL.host]; +#else + NSString *bgTaskName = @"GTMSessionFetcher"; +#endif + __block UIBackgroundTaskIdentifier bgTaskID = [app beginBackgroundTaskWithName:bgTaskName + expirationHandler:^{ + // Background task expiration callback - this block is always invoked by + // UIApplication on the main thread. + if (bgTaskID != UIBackgroundTaskInvalid) { + @synchronized(self) { + if (bgTaskID == self.backgroundTaskIdentifier) { + self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } + } + [app endBackgroundTask:bgTaskID]; + } + }]; + @synchronized(self) { + self.backgroundTaskIdentifier = bgTaskID; + } + } +#endif + + if (!_initialRequestDate) { + _initialRequestDate = [[NSDate alloc] init]; + } + + // We don't expect to reach here even on retry or auth until a stop notification has been sent + // for the previous task, but we should ensure that we don't unbalance that. + GTMSESSION_ASSERT_DEBUG(!_isStopNotificationNeeded, @"Start notification without a prior stop"); + [self sendStopNotificationIfNeeded]; + + [self addPersistedBackgroundSessionToDefaults]; + + [self setStopNotificationNeeded:YES]; + + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStartedNotification + userInfo:nil + requireAsync:NO]; + + // The service needs to know our task if it is serving as NSURLSession delegate. + [_service fetcherDidBeginFetching:self]; + + if (_testBlock) { +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + [self simulateFetchForTestBlock]; +#endif + } else { + // We resume the session task after posting the notification since the + // delegate callbacks may happen immediately if the fetch is started off + // the main thread or the session delegate queue is on a background thread, + // and we don't want to post a start notification after a premature finish + // of the session task. + [newSessionTask resume]; + } +} + +NSData * GTM_NULLABLE_TYPE GTMDataFromInputStream(NSInputStream *inputStream, NSError **outError) { + NSMutableData *data = [NSMutableData data]; + + [inputStream open]; + NSInteger numberOfBytesRead = 0; + while ([inputStream hasBytesAvailable]) { + uint8_t buffer[512]; + numberOfBytesRead = [inputStream read:buffer maxLength:sizeof(buffer)]; + if (numberOfBytesRead > 0) { + [data appendBytes:buffer length:(NSUInteger)numberOfBytesRead]; + } else { + break; + } + } + [inputStream close]; + NSError *streamError = inputStream.streamError; + + if (streamError) { + data = nil; + } + if (outError) { + *outError = streamError; + } + return data; +} + +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + +- (void)simulateFetchForTestBlock { + // This is invoked on the same thread as the beginFetch method was. + // + // Callbacks will all occur on the callback queue. + _testBlock(self, ^(NSURLResponse *response, NSData *responseData, NSError *error) { + // Callback from test block. + if (response == nil && responseData == nil && error == nil) { + // Assume the fetcher should execute rather than be tested. + _testBlock = nil; + _isUsingTestBlock = NO; + [_sessionTask resume]; + return; + } + + GTMSessionFetcherBodyStreamProvider bodyStreamProvider = self.bodyStreamProvider; + if (bodyStreamProvider) { + bodyStreamProvider(^(NSInputStream *bodyStream){ + // Read from the input stream into an NSData buffer. We'll drain the stream + // explicitly on a background queue. + [self invokeOnCallbackQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) + afterUserStopped:NO + block:^{ + NSError *streamError; + NSData *streamedData = GTMDataFromInputStream(bodyStream, &streamError); + + dispatch_async(dispatch_get_main_queue(), ^{ + // Continue callbacks on the main thread, since serial behavior + // is more reliable for tests. + [self simulateDataCallbacksForTestBlockWithBodyData:streamedData + response:response + responseData:responseData + error:(error ?: streamError)]; + }); + }]; + }); + } else { + // No input stream; use the supplied data or file URL. + NSURL *bodyFileURL = self.bodyFileURL; + if (bodyFileURL) { + NSError *readError; + _bodyData = [NSData dataWithContentsOfURL:bodyFileURL + options:NSDataReadingMappedIfSafe + error:&readError]; + error = readError; + } + + // No stream provider. + + // In real fetches, nothing happens until the run loop spins, so apps have leeway to + // set callbacks after they call beginFetch. We'll mirror that fetcher behavior by + // delaying callbacks here at least to the next spin of the run loop. That keeps + // immediate, synchronous setting of callback blocks after beginFetch working in tests. + dispatch_async(dispatch_get_main_queue(), ^{ + [self simulateDataCallbacksForTestBlockWithBodyData:_bodyData + response:response + responseData:responseData + error:error]; + }); + } + }); +} + +- (void)simulateByteTransferReportWithDataLength:(int64_t)totalDataLength + block:(GTMSessionFetcherSendProgressBlock)block { + // This utility method simulates transfer progress with up to three callbacks. + // It is used to call back to any of the progress blocks. + int64_t sendReportSize = totalDataLength / 3 + 1; + int64_t totalSent = 0; + while (totalSent < totalDataLength) { + int64_t bytesRemaining = totalDataLength - totalSent; + sendReportSize = MIN(sendReportSize, bytesRemaining); + totalSent += sendReportSize; + [self invokeOnCallbackQueueUnlessStopped:^{ + block(sendReportSize, totalSent, totalDataLength); + }]; + } +} + +- (void)simulateDataCallbacksForTestBlockWithBodyData:(NSData * GTM_NULLABLE_TYPE)bodyData + response:(NSURLResponse *)response + responseData:(NSData *)suppliedData + error:(NSError *)suppliedError { + __block NSData *responseData = suppliedData; + __block NSError *responseError = suppliedError; + + // This method does the test simulation of callbacks once the upload + // and download data are known. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Get copies of ivars we'll access in async invocations. This simulation assumes + // they won't change during fetcher execution. + NSURL *destinationFileURL = _destinationFileURL; + GTMSessionFetcherWillRedirectBlock willRedirectBlock = _willRedirectBlock; + GTMSessionFetcherDidReceiveResponseBlock didReceiveResponseBlock = _didReceiveResponseBlock; + GTMSessionFetcherSendProgressBlock sendProgressBlock = _sendProgressBlock; + GTMSessionFetcherDownloadProgressBlock downloadProgressBlock = _downloadProgressBlock; + GTMSessionFetcherAccumulateDataBlock accumulateDataBlock = _accumulateDataBlock; + GTMSessionFetcherReceivedProgressBlock receivedProgressBlock = _receivedProgressBlock; + GTMSessionFetcherWillCacheURLResponseBlock willCacheURLResponseBlock = + _willCacheURLResponseBlock; + + // Simulate receipt of redirection. + if (willRedirectBlock) { + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + willRedirectBlock((NSHTTPURLResponse *)response, _request, + ^(NSURLRequest *redirectRequest) { + // For simulation, we'll assume the app will just continue. + }); + }]; + } + + // If the fetcher has a challenge block, simulate a challenge. + // + // It might be nice to eventually let the user determine which testBlock + // fetches get challenged rather than always executing the supplied + // challenge block. + if (_challengeBlock) { + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + if (_challengeBlock) { + NSURL *requestURL = _request.URL; + NSString *host = requestURL.host; + NSURLProtectionSpace *pspace = + [[NSURLProtectionSpace alloc] initWithHost:host + port:requestURL.port.integerValue + protocol:requestURL.scheme + realm:nil + authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; + id unusedSender = + (id)[NSNull null]; + NSURLAuthenticationChallenge *challenge = + [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:pspace + proposedCredential:nil + previousFailureCount:0 + failureResponse:nil + error:nil + sender:unusedSender]; + _challengeBlock(self, challenge, ^(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential){ + // We could change the responseData and responseError based on the disposition, + // but it's easier for apps to just supply the expected data and error + // directly to the test block. So this simulation ignores the disposition. + }); + } + }]; + } + + // Simulate receipt of an initial response. + if (response && didReceiveResponseBlock) { + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + didReceiveResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) { + // For simulation, we'll assume the disposition is to continue. + }); + }]; + } + + // Simulate reporting send progress. + if (sendProgressBlock) { + [self simulateByteTransferReportWithDataLength:(int64_t)bodyData.length + block:^(int64_t bytesSent, + int64_t totalBytesSent, + int64_t totalBytesExpectedToSend) { + // This is invoked on the callback queue unless stopped. + sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend); + }]; + } + + if (destinationFileURL) { + // Simulate download to file progress. + if (downloadProgressBlock) { + [self simulateByteTransferReportWithDataLength:(int64_t)responseData.length + block:^(int64_t bytesDownloaded, + int64_t totalBytesDownloaded, + int64_t totalBytesExpectedToDownload) { + // This is invoked on the callback queue unless stopped. + downloadProgressBlock(bytesDownloaded, totalBytesDownloaded, + totalBytesExpectedToDownload); + }]; + } + + NSError *writeError; + [responseData writeToURL:destinationFileURL + options:NSDataWritingAtomic + error:&writeError]; + if (writeError) { + // Tell the test code that writing failed. + responseError = writeError; + } + } else { + // Simulate download to NSData progress. + if ((accumulateDataBlock || receivedProgressBlock) && responseData) { + [self simulateByteTransferWithData:responseData + block:^(NSData *data, + int64_t bytesReceived, + int64_t totalBytesReceived, + int64_t totalBytesExpectedToReceive) { + // This is invoked on the callback queue unless stopped. + if (accumulateDataBlock) { + accumulateDataBlock(data); + } + + if (receivedProgressBlock) { + receivedProgressBlock(bytesReceived, totalBytesReceived); + } + }]; + } + + if (!accumulateDataBlock) { + _downloadedData = [responseData mutableCopy]; + } + + if (willCacheURLResponseBlock) { + // Simulate letting the client inspect and alter the cached response. + NSData *cachedData = responseData ?: [[NSData alloc] init]; // Always have non-nil data. + NSCachedURLResponse *cachedResponse = + [[NSCachedURLResponse alloc] initWithResponse:response + data:cachedData]; + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:YES + block:^{ + willCacheURLResponseBlock(cachedResponse, ^(NSCachedURLResponse *responseToCache){ + // The app may provide an alternative response, or nil to defeat caching. + }); + }]; + } + } + _response = response; + } // @synchronized(self) + + NSOperationQueue *queue = self.sessionDelegateQueue; + [queue addOperationWithBlock:^{ + // Rather than invoke failToBeginFetchWithError: we want to simulate completion of + // a connection that started and ended, so we'll call down to finishWithError: + NSInteger status = responseError ? responseError.code : 200; + if (status >= 200 && status <= 399) { + [self finishWithError:nil shouldRetry:NO]; + } else { + [self shouldRetryNowForStatus:status + error:responseError + forceAssumeRetry:NO + response:^(BOOL shouldRetry) { + [self finishWithError:responseError shouldRetry:shouldRetry]; + }]; + } + }]; +} + +- (void)simulateByteTransferWithData:(NSData *)responseData + block:(GTMSessionFetcherSimulateByteTransferBlock)transferBlock { + // This utility method simulates transfering data to the client. It divides the data into at most + // "chunkCount" chunks and then passes each chunk along with a progress update to transferBlock. + // This function can be used with accumulateDataBlock or receivedProgressBlock. + + NSUInteger chunkCount = MAX(self.testBlockAccumulateDataChunkCount, (NSUInteger) 1); + NSUInteger totalDataLength = responseData.length; + NSUInteger sendDataSize = totalDataLength / chunkCount + 1; + NSUInteger totalSent = 0; + while (totalSent < totalDataLength) { + NSUInteger bytesRemaining = totalDataLength - totalSent; + sendDataSize = MIN(sendDataSize, bytesRemaining); + NSData *chunkData = [responseData subdataWithRange:NSMakeRange(totalSent, sendDataSize)]; + totalSent += sendDataSize; + [self invokeOnCallbackQueueUnlessStopped:^{ + transferBlock(chunkData, + (int64_t)sendDataSize, + (int64_t)totalSent, + (int64_t)totalDataLength); + }]; + } +} + +#endif // !GTM_DISABLE_FETCHER_TEST_BLOCK + +- (void)setSessionTask:(NSURLSessionTask *)sessionTask { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_sessionTask != sessionTask) { + _sessionTask = sessionTask; + if (_sessionTask) { + // Request could be nil on restoring this fetcher from a background session. + if (!_request) { + _request = [_sessionTask.originalRequest mutableCopy]; + } + } + } + } // @synchronized(self) +} + +- (NSURLSessionTask * GTM_NULLABLE_TYPE)sessionTask { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _sessionTask; + } // @synchronized(self) +} + ++ (NSUserDefaults *)fetcherUserDefaults { + static NSUserDefaults *gFetcherUserDefaults = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + Class fetcherUserDefaultsClass = NSClassFromString(@"GTMSessionFetcherUserDefaultsFactory"); + if (fetcherUserDefaultsClass) { + gFetcherUserDefaults = [fetcherUserDefaultsClass fetcherUserDefaults]; + } else { + gFetcherUserDefaults = [NSUserDefaults standardUserDefaults]; + } + }); + return gFetcherUserDefaults; +} + +- (void)addPersistedBackgroundSessionToDefaults { + NSString *sessionIdentifier = self.sessionIdentifier; + if (!sessionIdentifier) { + return; + } + NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions]; + if ([oldBackgroundSessions containsObject:_sessionIdentifier]) { + return; + } + NSMutableArray *newBackgroundSessions = + [NSMutableArray arrayWithArray:oldBackgroundSessions]; + [newBackgroundSessions addObject:sessionIdentifier]; + GTM_LOG_BACKGROUND_SESSION(@"Add to background sessions: %@", newBackgroundSessions); + + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + [userDefaults setObject:newBackgroundSessions + forKey:kGTMSessionFetcherPersistedDestinationKey]; + [userDefaults synchronize]; +} + +- (void)removePersistedBackgroundSessionFromDefaults { + NSString *sessionIdentifier = self.sessionIdentifier; + if (!sessionIdentifier) return; + + NSArray *oldBackgroundSessions = [[self class] activePersistedBackgroundSessions]; + if (!oldBackgroundSessions) { + return; + } + NSMutableArray *newBackgroundSessions = + [NSMutableArray arrayWithArray:oldBackgroundSessions]; + NSUInteger sessionIndex = [newBackgroundSessions indexOfObject:sessionIdentifier]; + if (sessionIndex == NSNotFound) { + return; + } + [newBackgroundSessions removeObjectAtIndex:sessionIndex]; + GTM_LOG_BACKGROUND_SESSION(@"Remove from background sessions: %@", newBackgroundSessions); + + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + if (newBackgroundSessions.count == 0) { + [userDefaults removeObjectForKey:kGTMSessionFetcherPersistedDestinationKey]; + } else { + [userDefaults setObject:newBackgroundSessions + forKey:kGTMSessionFetcherPersistedDestinationKey]; + } + [userDefaults synchronize]; +} + ++ (GTM_NULLABLE NSArray *)activePersistedBackgroundSessions { + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + NSArray *oldBackgroundSessions = + [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey]; + if (oldBackgroundSessions.count == 0) { + return nil; + } + NSMutableArray *activeBackgroundSessions = nil; + NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; + for (NSString *sessionIdentifier in oldBackgroundSessions) { + GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; + if (fetcher) { + if (!activeBackgroundSessions) { + activeBackgroundSessions = [[NSMutableArray alloc] init]; + } + [activeBackgroundSessions addObject:sessionIdentifier]; + } + } + return activeBackgroundSessions; +} + ++ (NSArray *)fetchersForBackgroundSessions { + NSUserDefaults *userDefaults = [[self class] fetcherUserDefaults]; + NSArray *backgroundSessions = + [userDefaults arrayForKey:kGTMSessionFetcherPersistedDestinationKey]; + NSMapTable *sessionIdentifierToFetcherMap = [self sessionIdentifierToFetcherMap]; + NSMutableArray *fetchers = [NSMutableArray array]; + for (NSString *sessionIdentifier in backgroundSessions) { + GTMSessionFetcher *fetcher = [sessionIdentifierToFetcherMap objectForKey:sessionIdentifier]; + if (!fetcher) { + fetcher = [self fetcherWithSessionIdentifier:sessionIdentifier]; + GTMSESSION_ASSERT_DEBUG(fetcher != nil, + @"Unexpected invalid session identifier: %@", sessionIdentifier); + [fetcher beginFetchWithCompletionHandler:nil]; + } + GTM_LOG_BACKGROUND_SESSION(@"%@ restoring session %@ by creating fetcher %@ %p", + [self class], sessionIdentifier, fetcher, fetcher); + if (fetcher != nil) { + [fetchers addObject:fetcher]; + } + } + return fetchers; +} + +#if TARGET_OS_IPHONE ++ (void)application:(UIApplication *)application + handleEventsForBackgroundURLSession:(NSString *)identifier + completionHandler:(GTMSessionFetcherSystemCompletionHandler)completionHandler { + GTMSessionFetcher *fetcher = [self fetcherWithSessionIdentifier:identifier]; + if (fetcher != nil) { + fetcher.systemCompletionHandler = completionHandler; + } else { + GTM_LOG_BACKGROUND_SESSION(@"%@ did not create background session identifier: %@", + [self class], identifier); + } +} +#endif + +- (NSString * GTM_NULLABLE_TYPE)sessionIdentifier { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _sessionIdentifier; + } // @synchronized(self) +} + +- (void)setSessionIdentifier:(NSString *)sessionIdentifier { + GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(!_session, @"Unable to set session identifier after session created"); + _sessionIdentifier = [sessionIdentifier copy]; + _usingBackgroundSession = YES; + _canShareSession = NO; + [self restoreDefaultStateForSessionIdentifierMetadata]; + } // @synchronized(self) +} + +- (void)setSessionIdentifierInternal:(GTM_NULLABLE NSString *)sessionIdentifier { + // This internal method only does a synchronized set of the session identifier. + // It does not have side effects on the background session, shared session, or + // session identifier metadata. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _sessionIdentifier = [sessionIdentifier copy]; + } // @synchronized(self) +} + +- (NSDictionary * GTM_NULLABLE_TYPE)sessionUserInfo { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_sessionUserInfo == nil) { + // We'll return the metadata dictionary with internal keys removed. This avoids the user + // re-using the userInfo dictionary later and accidentally including the internal keys. + NSMutableDictionary *metadata = [[self sessionIdentifierMetadataUnsynchronized] mutableCopy]; + NSSet *keysToRemove = [metadata keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) { + return [key hasPrefix:@"_"]; + }]; + [metadata removeObjectsForKeys:[keysToRemove allObjects]]; + if (metadata.count > 0) { + _sessionUserInfo = metadata; + } + } + return _sessionUserInfo; + } // @synchronized(self) +} + +- (void)setSessionUserInfo:(NSDictionary * GTM_NULLABLE_TYPE)dictionary { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(_sessionIdentifier == nil, @"Too late to assign userInfo"); + _sessionUserInfo = dictionary; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSDictionary *)sessionIdentifierDefaultMetadata { + GTMSessionCheckSynchronized(self); + + NSMutableDictionary *defaultUserInfo = [[NSMutableDictionary alloc] init]; + if (_destinationFileURL) { + defaultUserInfo[kGTMSessionIdentifierDestinationFileURLMetadataKey] = + [_destinationFileURL absoluteString]; + } + if (_bodyFileURL) { + defaultUserInfo[kGTMSessionIdentifierBodyFileURLMetadataKey] = [_bodyFileURL absoluteString]; + } + return (defaultUserInfo.count > 0) ? defaultUserInfo : nil; +} + +- (void)restoreDefaultStateForSessionIdentifierMetadata { + GTMSessionCheckSynchronized(self); + + NSDictionary *metadata = [self sessionIdentifierMetadataUnsynchronized]; + NSString *destinationFileURLString = metadata[kGTMSessionIdentifierDestinationFileURLMetadataKey]; + if (destinationFileURLString) { + _destinationFileURL = [NSURL URLWithString:destinationFileURLString]; + GTM_LOG_BACKGROUND_SESSION(@"Restoring destination file URL: %@", _destinationFileURL); + } + NSString *bodyFileURLString = metadata[kGTMSessionIdentifierBodyFileURLMetadataKey]; + if (bodyFileURLString) { + _bodyFileURL = [NSURL URLWithString:bodyFileURLString]; + GTM_LOG_BACKGROUND_SESSION(@"Restoring body file URL: %@", _bodyFileURL); + } +} + +- (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadata { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [self sessionIdentifierMetadataUnsynchronized]; + } +} + +- (NSDictionary * GTM_NULLABLE_TYPE)sessionIdentifierMetadataUnsynchronized { + GTMSessionCheckSynchronized(self); + + // Session Identifier format: "com.google.__ + if (!_sessionIdentifier) { + return nil; + } + NSScanner *metadataScanner = [NSScanner scannerWithString:_sessionIdentifier]; + [metadataScanner setCharactersToBeSkipped:nil]; + NSString *metadataString; + NSString *uuid; + if ([metadataScanner scanUpToString:@"_" intoString:NULL] && + [metadataScanner scanString:@"_" intoString:NULL] && + [metadataScanner scanUpToString:@"_" intoString:&uuid] && + [metadataScanner scanString:@"_" intoString:NULL] && + [metadataScanner scanUpToString:@"\n" intoString:&metadataString]) { + _sessionIdentifierUUID = uuid; + NSData *metadataData = [metadataString dataUsingEncoding:NSUTF8StringEncoding]; + NSError *error; + NSDictionary *metadataDict = + [NSJSONSerialization JSONObjectWithData:metadataData + options:0 + error:&error]; + GTM_LOG_BACKGROUND_SESSION(@"User Info from session identifier: %@ %@", + metadataDict, error ? error : @""); + return metadataDict; + } + return nil; +} + +- (NSString *)createSessionIdentifierWithMetadata:(NSDictionary * GTM_NULLABLE_TYPE)metadataToInclude { + NSString *result; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Session Identifier format: "com.google.__ + GTMSESSION_ASSERT_DEBUG(!_sessionIdentifier, @"Session identifier already created"); + _sessionIdentifierUUID = [[NSUUID UUID] UUIDString]; + _sessionIdentifier = + [NSString stringWithFormat:@"%@_%@", kGTMSessionIdentifierPrefix, _sessionIdentifierUUID]; + // Start with user-supplied keys so they cannot accidentally override the fetcher's keys. + NSMutableDictionary *metadataDict = + [NSMutableDictionary dictionaryWithDictionary:(NSDictionary * GTM_NONNULL_TYPE)_sessionUserInfo]; + + if (metadataToInclude) { + [metadataDict addEntriesFromDictionary:(NSDictionary *)metadataToInclude]; + } + NSDictionary *defaultMetadataDict = [self sessionIdentifierDefaultMetadata]; + if (defaultMetadataDict) { + [metadataDict addEntriesFromDictionary:defaultMetadataDict]; + } + if (metadataDict.count > 0) { + NSData *metadataData = [NSJSONSerialization dataWithJSONObject:metadataDict + options:0 + error:NULL]; + GTMSESSION_ASSERT_DEBUG(metadataData != nil, + @"Session identifier user info failed to convert to JSON"); + if (metadataData.length > 0) { + NSString *metadataString = [[NSString alloc] initWithData:metadataData + encoding:NSUTF8StringEncoding]; + _sessionIdentifier = + [_sessionIdentifier stringByAppendingFormat:@"_%@", metadataString]; + } + } + _didCreateSessionIdentifier = YES; + result = _sessionIdentifier; + } // @synchronized(self) + return result; +} + +- (void)failToBeginFetchWithError:(NSError *)error { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _hasStoppedFetching = YES; + } + + if (error == nil) { + error = [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:GTMSessionFetcherErrorDownloadFailed + userInfo:nil]; + } + + [self invokeFetchCallbacksOnCallbackQueueWithData:nil + error:error]; + [self releaseCallbacks]; + + [_service fetcherDidStop:self]; + + self.authorizer = nil; +} + ++ (GTMSessionCookieStorage *)staticCookieStorage { + static GTMSessionCookieStorage *gCookieStorage = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gCookieStorage = [[GTMSessionCookieStorage alloc] init]; + }); + return gCookieStorage; +} + +#if GTM_BACKGROUND_TASK_FETCHING + +- (void)endBackgroundTask { + // Whenever the connection stops or background execution expires, + // we need to tell UIApplication we're done. + UIBackgroundTaskIdentifier bgTaskID; + @synchronized(self) { + bgTaskID = self.backgroundTaskIdentifier; + if (bgTaskID != UIBackgroundTaskInvalid) { + self.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } + } + + if (bgTaskID != UIBackgroundTaskInvalid) { + id app = [[self class] fetcherUIApplication]; + [app endBackgroundTask:bgTaskID]; + } +} + +#endif // GTM_BACKGROUND_TASK_FETCHING + +- (void)authorizeRequest { + GTMSessionCheckNotSynchronized(self); + + id authorizer = self.authorizer; + SEL asyncAuthSel = @selector(authorizeRequest:delegate:didFinishSelector:); + if ([authorizer respondsToSelector:asyncAuthSel]) { + SEL callbackSel = @selector(authorizer:request:finishedWithError:); + NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; + [authorizer authorizeRequest:mutableRequest + delegate:self + didFinishSelector:callbackSel]; + } else { + GTMSESSION_ASSERT_DEBUG(authorizer == nil, @"invalid authorizer for fetch"); + + // No authorizing possible, and authorizing happens only after any delay; + // just begin fetching + [self beginFetchMayDelay:NO + mayAuthorize:NO]; + } +} + +- (void)authorizer:(id)auth + request:(NSMutableURLRequest *)authorizedRequest + finishedWithError:(NSError *)error { + GTMSessionCheckNotSynchronized(self); + + if (error != nil) { + // We can't fetch without authorization + [self failToBeginFetchWithError:error]; + } else { + @synchronized(self) { + _request = authorizedRequest; + } + [self beginFetchMayDelay:NO + mayAuthorize:NO]; + } +} + + +- (BOOL)canFetchWithBackgroundSession { + // Subclasses may override. + return YES; +} + +// Returns YES if the fetcher has been started and has not yet stopped. +// +// Fetching includes waiting for authorization or for retry, waiting to be allowed by the +// service object to start the request, and actually fetching the request. +- (BOOL)isFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [self isFetchingUnsynchronized]; + } +} + +- (BOOL)isFetchingUnsynchronized { + GTMSessionCheckSynchronized(self); + + BOOL hasBegun = (_initialBeginFetchDate != nil); + return hasBegun && !_hasStoppedFetching; +} + +- (NSURLResponse * GTM_NULLABLE_TYPE)response { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURLResponse *response = [self responseUnsynchronized]; + return response; + } // @synchronized(self) +} + +- (NSURLResponse * GTM_NULLABLE_TYPE)responseUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSURLResponse *response = _sessionTask.response; + if (!response) response = _response; + return response; +} + +- (NSInteger)statusCode { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSInteger statusCode = [self statusCodeUnsynchronized]; + return statusCode; + } // @synchronized(self) +} + +- (NSInteger)statusCodeUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSURLResponse *response = [self responseUnsynchronized]; + NSInteger statusCode; + + if ([response respondsToSelector:@selector(statusCode)]) { + statusCode = [(NSHTTPURLResponse *)response statusCode]; + } else { + // Default to zero, in hopes of hinting "Unknown" (we can't be + // sure that things are OK enough to use 200). + statusCode = 0; + } + return statusCode; +} + +- (NSDictionary * GTM_NULLABLE_TYPE)responseHeaders { + GTMSessionCheckNotSynchronized(self); + + NSURLResponse *response = self.response; + if ([response respondsToSelector:@selector(allHeaderFields)]) { + NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; + return headers; + } + return nil; +} + +- (NSDictionary * GTM_NULLABLE_TYPE)responseHeadersUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSURLResponse *response = [self responseUnsynchronized]; + if ([response respondsToSelector:@selector(allHeaderFields)]) { + NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; + return headers; + } + return nil; +} + +- (void)releaseCallbacks { + // Avoid releasing blocks in the sync section since objects dealloc'd by + // the blocks being released may call back into the fetcher or fetcher + // service. + dispatch_queue_t NS_VALID_UNTIL_END_OF_SCOPE holdCallbackQueue; + GTMSessionFetcherCompletionHandler NS_VALID_UNTIL_END_OF_SCOPE holdCompletionHandler; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + holdCallbackQueue = _callbackQueue; + holdCompletionHandler = _completionHandler; + + _callbackQueue = nil; + _completionHandler = nil; // Setter overridden in upload. Setter assumed to be used externally. + } + + // Set local callback pointers to nil here rather than let them release at the end of the scope + // to make any problems due to the blocks being released be a bit more obvious in a stack trace. + holdCallbackQueue = nil; + holdCompletionHandler = nil; + + self.configurationBlock = nil; + self.didReceiveResponseBlock = nil; + self.challengeBlock = nil; + self.willRedirectBlock = nil; + self.sendProgressBlock = nil; + self.receivedProgressBlock = nil; + self.downloadProgressBlock = nil; + self.accumulateDataBlock = nil; + self.willCacheURLResponseBlock = nil; + self.retryBlock = nil; + self.testBlock = nil; + self.resumeDataBlock = nil; +} + +- (void)forgetSessionIdentifierForFetcher { + GTMSessionCheckSynchronized(self); + [self forgetSessionIdentifierForFetcherWithoutSyncCheck]; +} + +- (void)forgetSessionIdentifierForFetcherWithoutSyncCheck { + // This should be called inside a @synchronized block (except during dealloc.) + if (_sessionIdentifier) { + NSMapTable *sessionIdentifierToFetcherMap = [[self class] sessionIdentifierToFetcherMap]; + [sessionIdentifierToFetcherMap removeObjectForKey:_sessionIdentifier]; + _sessionIdentifier = nil; + _didCreateSessionIdentifier = NO; + } +} + +// External stop method +- (void)stopFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Prevent enqueued callbacks from executing. + _userStoppedFetching = YES; + } // @synchronized(self) + [self stopFetchReleasingCallbacks:YES]; +} + +// Cancel the fetch of the URL that's currently in progress. +// +// If shouldReleaseCallbacks is NO then the fetch will be retried so the callbacks +// need to still be retained. +- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { + [self removePersistedBackgroundSessionFromDefaults]; + + id service; + NSMutableURLRequest *request; + + // If the task or the retry timer is all that's retaining the fetcher, + // we want to be sure this instance survives stopping at least long enough for + // the stack to unwind. + __autoreleasing GTMSessionFetcher *holdSelf = self; + + BOOL hasCanceledTask = NO; + + [holdSelf destroyRetryTimer]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _hasStoppedFetching = YES; + + service = _service; + request = _request; + + if (_sessionTask) { + // In case cancelling the task or session calls this recursively, we want + // to ensure that we'll only release the task and delegate once, + // so first set _sessionTask to nil + // + // This may be called in a callback from the task, so use autorelease to avoid + // releasing the task in its own callback. + __autoreleasing NSURLSessionTask *oldTask = _sessionTask; + if (!_isUsingTestBlock) { + _response = _sessionTask.response; + } + _sessionTask = nil; + + if ([oldTask state] != NSURLSessionTaskStateCompleted) { + // For download tasks, when the fetch is stopped, we may provide resume data that can + // be used to create a new session. + BOOL mayResume = (_resumeDataBlock + && [oldTask respondsToSelector:@selector(cancelByProducingResumeData:)]); + if (!mayResume) { + [oldTask cancel]; + // A side effect of stopping the task is that URLSession:task:didCompleteWithError: + // will be invoked asynchronously on the delegate queue. + } else { + void (^resumeBlock)(NSData *) = _resumeDataBlock; + _resumeDataBlock = nil; + + // Save callbackQueue since releaseCallbacks clears it. + dispatch_queue_t callbackQueue = _callbackQueue; + dispatch_group_enter(_callbackGroup); + [(NSURLSessionDownloadTask *)oldTask cancelByProducingResumeData:^(NSData *resumeData) { + [self invokeOnCallbackQueue:callbackQueue + afterUserStopped:YES + block:^{ + resumeBlock(resumeData); + dispatch_group_leave(_callbackGroup); + }]; + }]; + } + hasCanceledTask = YES; + } + } + + // If the task was canceled, wait until the URLSession:task:didCompleteWithError: to call + // finishTasksAndInvalidate, since calling it immediately tends to crash, see radar 18471901. + if (_session) { + BOOL shouldInvalidate = _shouldInvalidateSession; +#if TARGET_OS_IPHONE + // Don't invalidate if we've got a systemCompletionHandler, since + // URLSessionDidFinishEventsForBackgroundURLSession: won't be called if invalidated. + shouldInvalidate = shouldInvalidate && !self.systemCompletionHandler; +#endif + if (shouldInvalidate) { + __autoreleasing NSURLSession *oldSession = _session; + _session = nil; + + if (!hasCanceledTask) { + [oldSession finishTasksAndInvalidate]; + } else { + _sessionNeedingInvalidation = oldSession; + } + } + } + } // @synchronized(self) + + // send the stopped notification + [self sendStopNotificationIfNeeded]; + + [_authorizer stopAuthorizationForRequest:request]; + + if (shouldReleaseCallbacks) { + [self releaseCallbacks]; + + self.authorizer = nil; + } + + [service fetcherDidStop:self]; + +#if GTM_BACKGROUND_TASK_FETCHING + [self endBackgroundTask]; +#endif +} + +- (void)setStopNotificationNeeded:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _isStopNotificationNeeded = flag; + } // @synchronized(self) +} + +- (void)sendStopNotificationIfNeeded { + BOOL sendNow = NO; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_isStopNotificationNeeded) { + _isStopNotificationNeeded = NO; + sendNow = YES; + } + } // @synchronized(self) + + if (sendNow) { + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherStoppedNotification + userInfo:nil + requireAsync:NO]; + } +} + +- (void)retryFetch { + [self stopFetchReleasingCallbacks:NO]; + + GTMSessionFetcherCompletionHandler completionHandler; + + // A retry will need a configuration with a fresh session identifier. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_sessionIdentifier && _didCreateSessionIdentifier) { + [self forgetSessionIdentifierForFetcher]; + _configuration = nil; + } + + if (_canShareSession) { + // Force a grab of the current session from the fetcher service in case + // the service's old one has become invalid. + _session = nil; + } + + completionHandler = _completionHandler; + } // @synchronized(self) + + [self beginFetchWithCompletionHandler:completionHandler]; +} + +- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { + // Uncovered in upload fetcher testing, because the chunk fetcher is being waited on, and gets + // released by the upload code. The uploader just holds onto it with an ivar, and that gets + // nilled in the chunk fetcher callback. + // Used once in while loop just to avoid unused variable compiler warning. + __autoreleasing GTMSessionFetcher *holdSelf = self; + + NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; + + BOOL shouldSpinRunLoop = ([NSThread isMainThread] && + (!self.callbackQueue + || self.callbackQueue == dispatch_get_main_queue())); + BOOL expired = NO; + + // Loop until the callbacks have been called and released, and until + // the connection is no longer pending, until there are no callback dispatches + // in flight, or until the timeout has expired. + int64_t delta = (int64_t)(100 * NSEC_PER_MSEC); // 100 ms + while (1) { + BOOL isTaskInProgress = (holdSelf->_sessionTask + && [_sessionTask state] != NSURLSessionTaskStateCompleted); + BOOL needsToCallCompletion = (_completionHandler != nil); + BOOL isCallbackInProgress = (_callbackGroup + && dispatch_group_wait(_callbackGroup, dispatch_time(DISPATCH_TIME_NOW, delta))); + + if (!isTaskInProgress && !needsToCallCompletion && !isCallbackInProgress) break; + + expired = ([giveUpDate timeIntervalSinceNow] < 0); + if (expired) { + GTMSESSION_LOG_DEBUG(@"GTMSessionFetcher waitForCompletionWithTimeout:%0.1f expired -- " + @"%@%@%@", timeoutInSeconds, + isTaskInProgress ? @"taskInProgress " : @"", + needsToCallCompletion ? @"needsToCallCompletion " : @"", + isCallbackInProgress ? @"isCallbackInProgress" : @""); + break; + } + + // Run the current run loop 1/1000 of a second to give the networking + // code a chance to work + const NSTimeInterval kSpinInterval = 0.001; + if (shouldSpinRunLoop) { + NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval]; + [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; + } else { + [NSThread sleepForTimeInterval:kSpinInterval]; + } + } + return !expired; +} + ++ (void)setGlobalTestBlock:(GTMSessionFetcherTestBlock GTM_NULLABLE_TYPE)block { +#if GTM_DISABLE_FETCHER_TEST_BLOCK + GTMSESSION_ASSERT_DEBUG(block == nil, @"test blocks disabled"); +#endif + gGlobalTestBlock = [block copy]; +} + +#if TARGET_OS_IPHONE + +static GTM_NULLABLE_TYPE id gSubstituteUIApp; + ++ (void)setSubstituteUIApplication:(nullable id)app { + gSubstituteUIApp = app; +} + ++ (nullable id)substituteUIApplication { + return gSubstituteUIApp; +} + ++ (nullable id)fetcherUIApplication { + id app = gSubstituteUIApp; + if (app) return app; + + // iOS App extensions should not call [UIApplication sharedApplication], even + // if UIApplication responds to it. + + static Class applicationClass = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + BOOL isAppExtension = [[[NSBundle mainBundle] bundlePath] hasSuffix:@".appex"]; + if (!isAppExtension) { + Class cls = NSClassFromString(@"UIApplication"); + if (cls && [cls respondsToSelector:NSSelectorFromString(@"sharedApplication")]) { + applicationClass = cls; + } + } + }); + + if (applicationClass) { + app = (id)[applicationClass sharedApplication]; + } + return app; +} +#endif // TARGET_OS_IPHONE + +#pragma mark NSURLSession Delegate Methods + +// NSURLSession documentation indicates that redirectRequest can be passed to the handler +// but empirically redirectRequest lacks the HTTP body, so passing it will break POSTs. +// Instead, we construct a new request, a copy of the original, with overrides from the +// redirect. + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)redirectResponse + newRequest:(NSURLRequest *)redirectRequest + completionHandler:(void (^)(NSURLRequest * GTM_NULLABLE_TYPE))handler { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ willPerformHTTPRedirection:%@ newRequest:%@", + [self class], self, session, task, redirectResponse, redirectRequest); + + if ([self userStoppedFetching]) { + handler(nil); + return; + } + if (redirectRequest && redirectResponse) { + // Copy the original request, including the body. + NSURLRequest *originalRequest = self.request; + NSMutableURLRequest *newRequest = [originalRequest mutableCopy]; + + // Disallow scheme changes (say, from https to http). + NSURL *originalRequestURL = originalRequest.URL; + NSURL *redirectRequestURL = redirectRequest.URL; + + NSString *originalScheme = originalRequestURL.scheme; + NSString *redirectScheme = redirectRequestURL.scheme; + + if (originalScheme != nil + && [originalScheme caseInsensitiveCompare:@"http"] == NSOrderedSame + && redirectScheme != nil + && [redirectScheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { + // Allow the change from http to https. + } else { + // Disallow any other scheme changes. + redirectScheme = originalScheme; + } + // The new requests's URL overrides the original's URL. + NSURLComponents *components = [NSURLComponents componentsWithURL:redirectRequestURL + resolvingAgainstBaseURL:NO]; + components.scheme = redirectScheme; + NSURL *newURL = components.URL; + [newRequest setURL:newURL]; + + // Any headers in the redirect override headers in the original. + NSDictionary *redirectHeaders = redirectRequest.allHTTPHeaderFields; + for (NSString *key in redirectHeaders) { + NSString *value = [redirectHeaders objectForKey:key]; + [newRequest setValue:value forHTTPHeaderField:key]; + } + + redirectRequest = newRequest; + + // Log the response we just received + [self setResponse:redirectResponse]; + [self logNowWithError:nil]; + + GTMSessionFetcherWillRedirectBlock willRedirectBlock = self.willRedirectBlock; + if (willRedirectBlock) { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + willRedirectBlock(redirectResponse, redirectRequest, ^(NSURLRequest *clientRequest) { + + // Update the request for future logging. + [self updateMutableRequest:[clientRequest mutableCopy]]; + + handler(clientRequest); + }); + }]; + } // @synchronized(self) + return; + } + // Continues here if the client did not provide a redirect block. + + // Update the request for future logging. + [self updateMutableRequest:[redirectRequest mutableCopy]]; + } + handler(redirectRequest); +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))handler { + [self setSessionTask:dataTask]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveResponse:%@", + [self class], self, session, dataTask, response); + void (^accumulateAndFinish)(NSURLSessionResponseDisposition) = + ^(NSURLSessionResponseDisposition dispositionValue) { + // This method is called when the server has determined that it + // has enough information to create the NSURLResponse + // it can be called multiple times, for example in the case of a + // redirect, so each time we reset the data. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + BOOL hadPreviousData = _downloadedLength > 0; + + [_downloadedData setLength:0]; + _downloadedLength = 0; + + if (hadPreviousData && (dispositionValue != NSURLSessionResponseCancel)) { + // Tell the accumulate block to discard prior data. + GTMSessionFetcherAccumulateDataBlock accumulateBlock = _accumulateDataBlock; + if (accumulateBlock) { + [self invokeOnCallbackQueueUnlessStopped:^{ + accumulateBlock(nil); + }]; + } + } + } // @synchronized(self) + handler(dispositionValue); + }; + + GTMSessionFetcherDidReceiveResponseBlock receivedResponseBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + receivedResponseBlock = _didReceiveResponseBlock; + if (receivedResponseBlock) { + // We will ultimately need to call back to NSURLSession's handler with the disposition value + // for this delegate method even if the user has stopped the fetcher. + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + receivedResponseBlock(response, ^(NSURLSessionResponseDisposition desiredDisposition) { + accumulateAndFinish(desiredDisposition); + }); + }]; + } + } // @synchronized(self) + + if (receivedResponseBlock == nil) { + accumulateAndFinish(NSURLSessionResponseAllow); + } +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didBecomeDownloadTask:%@", + [self class], self, session, dataTask, downloadTask); + [self setSessionTask:downloadTask]; +} + + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential))handler { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didReceiveChallenge:%@", + [self class], self, session, task, challenge); + + GTMSessionFetcherChallengeBlock challengeBlock = self.challengeBlock; + if (challengeBlock) { + // The fetcher user has provided custom challenge handling. + // + // We will ultimately need to call back to NSURLSession's handler with the disposition value + // for this delegate method even if the user has stopped the fetcher. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + challengeBlock(self, challenge, handler); + }]; + } + } else { + // No challenge block was provided by the client. + [self respondToChallenge:challenge + completionHandler:handler]; + } +} + +- (void)respondToChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, + NSURLCredential * GTM_NULLABLE_TYPE credential))handler { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSInteger previousFailureCount = [challenge previousFailureCount]; + if (previousFailureCount <= 2) { + NSURLProtectionSpace *protectionSpace = [challenge protectionSpace]; + NSString *authenticationMethod = [protectionSpace authenticationMethod]; + if ([authenticationMethod isEqual:NSURLAuthenticationMethodServerTrust]) { + // SSL. + // + // Background sessions seem to require an explicit check of the server trust object + // rather than default handling. + SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; + if (serverTrust == NULL) { + // No server trust information is available. + handler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + } else { + // Server trust information is available. + void (^callback)(SecTrustRef, BOOL) = ^(SecTrustRef trustRef, BOOL allow){ + if (allow) { + NSURLCredential *trustCredential = [NSURLCredential credentialForTrust:trustRef]; + handler(NSURLSessionAuthChallengeUseCredential, trustCredential); + } else { + GTMSESSION_LOG_DEBUG(@"Cancelling authentication challenge for %@", _request.URL); + handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + } + }; + if (_allowInvalidServerCertificates) { + callback(serverTrust, YES); + } else { + [[self class] evaluateServerTrust:serverTrust + forRequest:_request + completionHandler:callback]; + } + } + return; + } + + NSURLCredential *credential = _credential; + + if ([[challenge protectionSpace] isProxy] && _proxyCredential != nil) { + credential = _proxyCredential; + } + + if (credential) { + handler(NSURLSessionAuthChallengeUseCredential, credential); + } else { + // The credential is still nil; tell the OS to use the default handling. This is needed + // for things that can come out of the keychain (proxies, client certificates, etc.). + // + // Note: Looking up a credential with NSURLCredentialStorage's + // defaultCredentialForProtectionSpace: is *not* the same invoking the handler with + // NSURLSessionAuthChallengePerformDefaultHandling. In the case of + // NSURLAuthenticationMethodClientCertificate, you can get nil back from + // NSURLCredentialStorage, while using this code path instead works. + handler(NSURLSessionAuthChallengePerformDefaultHandling, nil); + } + + } else { + // We've failed auth 3 times. The completion handler will be called with code + // NSURLErrorCancelled. + handler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil); + } + } // @synchronized(self) +} + +// Validate the certificate chain. +// +// This may become a public method if it appears to be useful to users. ++ (void)evaluateServerTrust:(SecTrustRef)serverTrust + forRequest:(NSURLRequest *)request + completionHandler:(void (^)(SecTrustRef trustRef, BOOL allow))handler { + // Retain the trust object to avoid a SecTrustEvaluate() crash on iOS 7. + CFRetain(serverTrust); + + // Evaluate the certificate chain. + // + // The delegate queue may be the main thread. Trust evaluation could cause some + // blocking network activity, so we must evaluate async, as documented at + // https://developer.apple.com/library/ios/technotes/tn2232/ + // + // We must also avoid multiple uses of the trust object, per docs: + // "It is not safe to call this function concurrently with any other function that uses + // the same trust management object, or to re-enter this function for the same trust + // management object." + // + // SecTrustEvaluateAsync both does sync execution of Evaluate and calls back on the + // queue passed to it, according to at sources in + // http://www.opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55050.9/lib/SecTrust.cpp + // It would require a global serial queue to ensure the evaluate happens only on a + // single thread at a time, so we'll stick with using SecTrustEvaluate on a background + // thread. + dispatch_queue_t evaluateBackgroundQueue = + dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); + dispatch_async(evaluateBackgroundQueue, ^{ + // It looks like the implementation of SecTrustEvaluate() on Mac grabs a global lock, + // so it may be redundant for us to also lock, but it's easy to synchronize here + // anyway. + SecTrustResultType trustEval = kSecTrustResultInvalid; + BOOL shouldAllow; + OSStatus trustError; + @synchronized([GTMSessionFetcher class]) { + GTMSessionMonitorSynchronized([GTMSessionFetcher class]); + + trustError = SecTrustEvaluate(serverTrust, &trustEval); + } + if (trustError != errSecSuccess) { + GTMSESSION_LOG_DEBUG(@"Error %d evaluating trust for %@", + (int)trustError, request); + shouldAllow = NO; + } else { + // Having a trust level "unspecified" by the user is the usual result, described at + // https://developer.apple.com/library/mac/qa/qa1360 + if (trustEval == kSecTrustResultUnspecified + || trustEval == kSecTrustResultProceed) { + shouldAllow = YES; + } else { + shouldAllow = NO; + GTMSESSION_LOG_DEBUG(@"Challenge SecTrustResultType %u for %@, properties: %@", + trustEval, request.URL.host, + CFBridgingRelease(SecTrustCopyProperties(serverTrust))); + } + } + handler(serverTrust, shouldAllow); + + CFRelease(serverTrust); + }); +} + +- (void)invokeOnCallbackQueueUnlessStopped:(void (^)(void))block { + [self invokeOnCallbackQueueAfterUserStopped:NO + block:block]; +} + +- (void)invokeOnCallbackQueueAfterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block { + GTMSessionCheckSynchronized(self); + + [self invokeOnCallbackUnsynchronizedQueueAfterUserStopped:afterStopped + block:block]; +} + +- (void)invokeOnCallbackUnsynchronizedQueueAfterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block { + // testBlock simulation code may not be synchronizing when this is invoked. + [self invokeOnCallbackQueue:_callbackQueue + afterUserStopped:afterStopped + block:block]; +} + +- (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue + afterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block { + if (callbackQueue) { + dispatch_group_async(_callbackGroup, callbackQueue, ^{ + if (!afterStopped) { + NSDate *serviceStoppedAllDate = [_service stoppedAllFetchersDate]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Avoid a race between stopFetching and the callback. + if (_userStoppedFetching) { + return; + } + + // Also avoid calling back if the service has stopped all fetchers + // since this one was created. The fetcher may have stopped before + // stopAllFetchers was invoked, so _userStoppedFetching wasn't set, + // but the app still won't expect the callback to fire after + // the service's stopAllFetchers was invoked. + if (serviceStoppedAllDate + && [_initialBeginFetchDate compare:serviceStoppedAllDate] != NSOrderedDescending) { + // stopAllFetchers was called after this fetcher began. + return; + } + } // @synchronized(self) + } + block(); + }); + } +} + +- (void)invokeFetchCallbacksOnCallbackQueueWithData:(GTM_NULLABLE NSData *)data + error:(GTM_NULLABLE NSError *)error { + // Callbacks will be released in the method stopFetchReleasingCallbacks: + GTMSessionFetcherCompletionHandler handler; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + handler = _completionHandler; + + if (handler) { + [self invokeOnCallbackQueueUnlessStopped:^{ + handler(data, error); + + // Post a notification, primarily to allow code to collect responses for + // testing. + // + // The observing code is not likely on the fetcher's callback + // queue, so this posts explicitly to the main queue. + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + if (data) { + userInfo[kGTMSessionFetcherCompletionDataKey] = data; + } + if (error) { + userInfo[kGTMSessionFetcherCompletionErrorKey] = error; + } + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherCompletionInvokedNotification + userInfo:userInfo + requireAsync:NO]; + }]; + } + } // @synchronized(self) +} + +- (void)postNotificationOnMainThreadWithName:(NSString *)noteName + userInfo:(GTM_NULLABLE NSDictionary *)userInfo + requireAsync:(BOOL)requireAsync { + dispatch_block_t postBlock = ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:noteName + object:self + userInfo:userInfo]; + }; + + if ([NSThread isMainThread] && !requireAsync) { + // Post synchronously for compatibility with older code using the fetcher. + + // Avoid calling out to other code from inside a sync block to avoid risk + // of a deadlock or of recursive sync. + GTMSessionCheckNotSynchronized(self); + + postBlock(); + } else { + dispatch_async(dispatch_get_main_queue(), postBlock); + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)uploadTask + needNewBodyStream:(void (^)(NSInputStream * GTM_NULLABLE_TYPE bodyStream))completionHandler { + [self setSessionTask:uploadTask]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ needNewBodyStream:", + [self class], self, session, uploadTask); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSessionFetcherBodyStreamProvider provider = _bodyStreamProvider; +#if !STRIP_GTM_FETCH_LOGGING + if ([self respondsToSelector:@selector(loggedStreamProviderForStreamProvider:)]) { + provider = [self performSelector:@selector(loggedStreamProviderForStreamProvider:) + withObject:provider]; + } +#endif + if (provider) { + [self invokeOnCallbackQueueUnlessStopped:^{ + provider(completionHandler); + }]; + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"NSURLSession expects a stream provider"); + + completionHandler(nil); + } + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didSendBodyData:%lld" + @" totalBytesSent:%lld totalBytesExpectedToSend:%lld", + [self class], self, session, task, bytesSent, totalBytesSent, + totalBytesExpectedToSend); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (!_sendProgressBlock) { + return; + } + // We won't hold on to send progress block; it's ok to not send it if the upload finishes. + [self invokeOnCallbackQueueUnlessStopped:^{ + GTMSessionFetcherSendProgressBlock progressBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + progressBlock = _sendProgressBlock; + } + if (progressBlock) { + progressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend); + } + }]; + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data { + [self setSessionTask:dataTask]; + NSUInteger bufferLength = data.length; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ didReceiveData:%p (%llu bytes)", + [self class], self, session, dataTask, data, + (unsigned long long)bufferLength); + if (bufferLength == 0) { + // Observed on completing an out-of-process upload. + return; + } + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSessionFetcherAccumulateDataBlock accumulateBlock = _accumulateDataBlock; + if (accumulateBlock) { + // Let the client accumulate the data. + _downloadedLength += bufferLength; + [self invokeOnCallbackQueueUnlessStopped:^{ + accumulateBlock(data); + }]; + } else if (!_userStoppedFetching) { + // Append to the mutable data buffer unless the fetch has been cancelled. + + // Resumed upload tasks may not yet have a data buffer. + if (_downloadedData == nil) { + // Using NSClassFromString for iOS 6 compatibility. + GTMSESSION_ASSERT_DEBUG( + ![dataTask isKindOfClass:NSClassFromString(@"NSURLSessionDownloadTask")], + @"Resumed download tasks should not receive data bytes"); + _downloadedData = [[NSMutableData alloc] init]; + } + + [_downloadedData appendData:data]; + _downloadedLength = (int64_t)_downloadedData.length; + + // We won't hold on to receivedProgressBlock here; it's ok to not send + // it if the transfer finishes. + if (_receivedProgressBlock) { + [self invokeOnCallbackQueueUnlessStopped:^{ + GTMSessionFetcherReceivedProgressBlock progressBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + progressBlock = _receivedProgressBlock; + } + if (progressBlock) { + progressBlock((int64_t)bufferLength, _downloadedLength); + } + }]; + } + } + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *cachedResponse))completionHandler { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ dataTask:%@ willCacheResponse:%@ %@", + [self class], self, session, dataTask, + proposedResponse, proposedResponse.response); + GTMSessionFetcherWillCacheURLResponseBlock callback; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + callback = _willCacheURLResponseBlock; + + if (callback) { + [self invokeOnCallbackQueueAfterUserStopped:YES + block:^{ + callback(proposedResponse, completionHandler); + }]; + } + } // @synchronized(self) + if (!callback) { + completionHandler(proposedResponse); + } +} + + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalBytesWritten +totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didWriteData:%lld" + @" bytesWritten:%lld totalBytesExpectedToWrite:%lld", + [self class], self, session, downloadTask, bytesWritten, + totalBytesWritten, totalBytesExpectedToWrite); + [self setSessionTask:downloadTask]; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if ((totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown) && + (totalBytesExpectedToWrite < totalBytesWritten)) { + // Have observed cases were bytesWritten == totalBytesExpectedToWrite, + // but totalBytesWritten > totalBytesExpectedToWrite, so setting to unkown in these cases. + totalBytesExpectedToWrite = NSURLSessionTransferSizeUnknown; + } + // We won't hold on to download progress block during the enqueue; + // it's ok to not send it if the upload finishes. + + [self invokeOnCallbackQueueUnlessStopped:^{ + GTMSessionFetcherDownloadProgressBlock progressBlock; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + progressBlock = _downloadProgressBlock; + } + if (progressBlock) { + progressBlock(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + } + }]; + } // @synchronized(self) +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didResumeAtOffset:%lld" + @" expectedTotalBytes:%lld", + [self class], self, session, downloadTask, fileOffset, + expectedTotalBytes); + [self setSessionTask:downloadTask]; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)downloadLocationURL { + // Download may have relaunched app, so update _sessionTask. + [self setSessionTask:downloadTask]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ downloadTask:%@ didFinishDownloadingToURL:%@", + [self class], self, session, downloadTask, downloadLocationURL); + NSNumber *fileSizeNum; + [downloadLocationURL getResourceValue:&fileSizeNum + forKey:NSURLFileSizeKey + error:NULL]; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURL *destinationURL = _destinationFileURL; + + _downloadedLength = fileSizeNum.longLongValue; + + // Overwrite any previous file at the destination URL. + NSFileManager *fileMgr = [NSFileManager defaultManager]; + NSError *removeError; + if (![fileMgr removeItemAtURL:destinationURL error:&removeError] + && removeError.code != NSFileNoSuchFileError) { + GTMSESSION_LOG_DEBUG(@"Could not remove previous file at %@ due to %@", + downloadLocationURL.path, removeError); + } + + NSInteger statusCode = [self statusCodeUnsynchronized]; + if (statusCode < 200 || statusCode > 399) { + // In OS X 10.11, the response body is written to a file even on a server + // status error. For convenience of the fetcher client, we'll skip saving the + // downloaded body to the destination URL so that clients do not need to know + // to delete the file following fetch errors. A downside of this is that + // the server may have included error details in the response body, and + // abandoning the downloaded file here means that the details from the + // body are not available to the fetcher client. + GTMSESSION_LOG_DEBUG(@"Abandoning download due to status %zd, file %@", + statusCode, downloadLocationURL.path); + } else { + NSError *moveError; + NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent]; + BOOL didMoveDownload = NO; + if ([fileMgr createDirectoryAtURL:destinationFolderURL + withIntermediateDirectories:YES + attributes:nil + error:&moveError]) { + didMoveDownload = [fileMgr moveItemAtURL:downloadLocationURL + toURL:destinationURL + error:&moveError]; + } + if (!didMoveDownload) { + _downloadFinishedError = moveError; + } + GTM_LOG_BACKGROUND_SESSION(@"%@ %p Moved download from \"%@\" to \"%@\" %@", + [self class], self, + downloadLocationURL.path, destinationURL.path, + error ? error : @""); + } + } // @synchronized(self) +} + +/* Sent as the last message related to a specific task. Error may be + * nil, which implies that no error occurred and this task is complete. + */ +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error { + [self setSessionTask:task]; + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ task:%@ didCompleteWithError:%@", + [self class], self, session, task, error); + + NSInteger status = self.statusCode; + BOOL forceAssumeRetry = NO; + BOOL succeeded = NO; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + // The task is never resumed when a testBlock is used. When the session is destroyed, + // we should ignore the callback, since the testBlock support code itself invokes + // shouldRetryNowForStatus: and finishWithError:shouldRetry: + if (_isUsingTestBlock) return; +#endif + + if (error == nil) { + error = _downloadFinishedError; + } + succeeded = (error == nil && status >= 0 && status < 300); + if (succeeded) { + // Succeeded. + _bodyLength = task.countOfBytesSent; + } + } // @synchronized(self) + + if (succeeded) { + [self finishWithError:nil shouldRetry:NO]; + return; + } + // For background redirects, no delegate method is called, so we cannot restore a stripped + // Authorization header, so if a 403 ("Forbidden") was generated due to a missing OAuth 2 header, + // set the current request's URL to the redirected URL, so we in effect restore the Authorization + // header. + if ((status == 403) && self.usingBackgroundSession) { + NSURL *redirectURL = self.response.URL; + NSURLRequest *request = self.request; + if (![request.URL isEqual:redirectURL]) { + NSString *authorizationHeader = [request.allHTTPHeaderFields objectForKey:@"Authorization"]; + if (authorizationHeader != nil) { + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + mutableRequest.URL = redirectURL; + [self updateMutableRequest:mutableRequest]; + // Avoid assuming the session is still valid. + self.session = nil; + forceAssumeRetry = YES; + } + } + } + + // If invalidating the session was deferred in stopFetchReleasingCallbacks: then do it now. + NSURLSession *oldSession = self.sessionNeedingInvalidation; + if (oldSession) { + [self setSessionNeedingInvalidation:NULL]; + [oldSession finishTasksAndInvalidate]; + } + + // Failed. + [self shouldRetryNowForStatus:status + error:error + forceAssumeRetry:forceAssumeRetry + response:^(BOOL shouldRetry) { + [self finishWithError:error shouldRetry:shouldRetry]; + }]; +} + +#if TARGET_OS_IPHONE +- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSessionDidFinishEventsForBackgroundURLSession:%@", + [self class], self, session); + [self removePersistedBackgroundSessionFromDefaults]; + + GTMSessionFetcherSystemCompletionHandler handler; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + handler = self.systemCompletionHandler; + self.systemCompletionHandler = nil; + } // @synchronized(self) + if (handler) { + GTM_LOG_BACKGROUND_SESSION(@"%@ %p Calling system completionHandler", [self class], self); + handler(); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURLSession *oldSession = _session; + _session = nil; + if (_shouldInvalidateSession) { + [oldSession finishTasksAndInvalidate]; + } + } // @synchronized(self) + } +} +#endif + +- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(GTM_NULLABLE NSError *)error { + // This may happen repeatedly for retries. On authentication callbacks, the retry + // may begin before the prior session sends the didBecomeInvalid delegate message. + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@", + [self class], self, session, error); + if (session == (NSURLSession *)self.session) { + GTM_LOG_SESSION_DELEGATE(@" Unexpected retained invalid session: %@", session); + self.session = nil; + } +} + +- (void)finishWithError:(GTM_NULLABLE NSError *)error shouldRetry:(BOOL)shouldRetry { + [self removePersistedBackgroundSessionFromDefaults]; + + BOOL shouldStopFetching = YES; + NSData *downloadedData = nil; +#if !STRIP_GTM_FETCH_LOGGING + BOOL shouldDeferLogging = NO; +#endif + BOOL shouldBeginRetryTimer = NO; + NSInteger status = [self statusCode]; + NSURL *destinationURL = self.destinationFileURL; + + BOOL fetchSucceeded = (error == nil && status >= 0 && status < 300); + +#if !STRIP_GTM_FETCH_LOGGING + if (!fetchSucceeded) { + if (!shouldDeferLogging && !self.hasLoggedError) { + [self logNowWithError:error]; + self.hasLoggedError = YES; + } + } +#endif // !STRIP_GTM_FETCH_LOGGING + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + +#if !STRIP_GTM_FETCH_LOGGING + shouldDeferLogging = _deferResponseBodyLogging; +#endif + if (fetchSucceeded) { + // Success + if ((_downloadedData.length > 0) && (destinationURL != nil)) { + // Overwrite any previous file at the destination URL. + NSFileManager *fileMgr = [NSFileManager defaultManager]; + [fileMgr removeItemAtURL:destinationURL + error:NULL]; + NSURL *destinationFolderURL = [destinationURL URLByDeletingLastPathComponent]; + BOOL didMoveDownload = NO; + if ([fileMgr createDirectoryAtURL:destinationFolderURL + withIntermediateDirectories:YES + attributes:nil + error:&error]) { + didMoveDownload = [_downloadedData writeToURL:destinationURL + options:NSDataWritingAtomic + error:&error]; + } + if (didMoveDownload) { + _downloadedData = nil; + } else { + _downloadFinishedError = error; + } + } + downloadedData = _downloadedData; + } else { + // Unsuccessful with error or status over 300. Retry or notify the delegate of failure + if (shouldRetry) { + // Retrying. + shouldBeginRetryTimer = YES; + shouldStopFetching = NO; + } else { + if (error == nil) { + // Create an error. + NSDictionary *userInfo = nil; + if (_downloadedData.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : _downloadedData }; + } + error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain + code:status + userInfo:userInfo]; + } else { + // If the error had resume data, and the client supplied a resume block, pass the + // data to the client. + void (^resumeBlock)(NSData *) = _resumeDataBlock; + _resumeDataBlock = nil; + if (resumeBlock) { + NSData *resumeData = [error.userInfo objectForKey:NSURLSessionDownloadTaskResumeData]; + if (resumeData) { + [self invokeOnCallbackQueueAfterUserStopped:YES block:^{ + resumeBlock(resumeData); + }]; + } + } + } + if (_downloadedData.length > 0) { + downloadedData = _downloadedData; + } + // If the error occurred after retries, report the number and duration of the + // retries. This provides a clue to a developer looking at the error description + // that the fetcher did retry before failing with this error. + if (_retryCount > 0) { + NSMutableDictionary *userInfoWithRetries = + [NSMutableDictionary dictionaryWithDictionary:(NSDictionary *)error.userInfo]; + NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow]; + [userInfoWithRetries setObject:@(timeSinceInitialRequest) + forKey:kGTMSessionFetcherElapsedIntervalWithRetriesKey]; + [userInfoWithRetries setObject:@(_retryCount) + forKey:kGTMSessionFetcherNumberOfRetriesDoneKey]; + error = [NSError errorWithDomain:(NSString *)error.domain + code:error.code + userInfo:userInfoWithRetries]; + } + } + } + } // @synchronized(self) + + if (shouldBeginRetryTimer) { + [self beginRetryTimer]; + } + + // We want to send the stop notification before calling the delegate's + // callback selector, since the callback selector may release all of + // the fetcher properties that the client is using to track the fetches. + // + // We'll also stop now so that, to any observers watching the notifications, + // it doesn't look like our wait for a retry (which may be long, + // 30 seconds or more) is part of the network activity. + [self sendStopNotificationIfNeeded]; + + if (shouldStopFetching) { + [self invokeFetchCallbacksOnCallbackQueueWithData:downloadedData + error:error]; + // The upload subclass doesn't want to release callbacks until upload chunks have completed. + BOOL shouldRelease = [self shouldReleaseCallbacksUponCompletion]; + [self stopFetchReleasingCallbacks:shouldRelease]; + } + +#if !STRIP_GTM_FETCH_LOGGING + // _hasLoggedError is only set by this method + if (!shouldDeferLogging && !_hasLoggedError) { + [self logNowWithError:error]; + } +#endif +} + +- (BOOL)shouldReleaseCallbacksUponCompletion { + // A subclass can override this to keep callbacks around after the + // connection has finished successfully + return YES; +} + +- (void)logNowWithError:(GTM_NULLABLE NSError *)error { + GTMSessionCheckNotSynchronized(self); + + // If the logging category is available, then log the current request, + // response, data, and error + if ([self respondsToSelector:@selector(logFetchWithError:)]) { + [self performSelector:@selector(logFetchWithError:) withObject:error]; + } +} + +#pragma mark Retries + +- (BOOL)isRetryError:(NSError *)error { + struct RetryRecord { + __unsafe_unretained NSString *const domain; + NSInteger code; + }; + + struct RetryRecord retries[] = { + { kGTMSessionFetcherStatusDomain, 408 }, // request timeout + { kGTMSessionFetcherStatusDomain, 502 }, // failure gatewaying to another server + { kGTMSessionFetcherStatusDomain, 503 }, // service unavailable + { kGTMSessionFetcherStatusDomain, 504 }, // request timeout + { NSURLErrorDomain, NSURLErrorTimedOut }, + { NSURLErrorDomain, NSURLErrorNetworkConnectionLost }, + { nil, 0 } + }; + + // NSError's isEqual always returns false for equal but distinct instances + // of NSError, so we have to compare the domain and code values explicitly + NSString *domain = error.domain; + NSInteger code = error.code; + for (int idx = 0; retries[idx].domain != nil; idx++) { + if (code == retries[idx].code && [domain isEqual:retries[idx].domain]) { + return YES; + } + } + return NO; +} + +// shouldRetryNowForStatus:error: responds with YES if the user has enabled retries +// and the status or error is one that is suitable for retrying. "Suitable" +// means either the isRetryError:'s list contains the status or error, or the +// user's retry block is present and returns YES when called, or the +// authorizer may be able to fix. +- (void)shouldRetryNowForStatus:(NSInteger)status + error:(NSError *)error + forceAssumeRetry:(BOOL)forceAssumeRetry + response:(GTMSessionFetcherRetryResponse)response { + // Determine if a refreshed authorizer may avoid an authorization error + BOOL willRetry = NO; + + // We assume _authorizer is immutable after beginFetch, and _hasAttemptedAuthRefresh is modified + // only in this method, and this method is invoked on the serial delegate queue. + // + // We want to avoid calling the authorizer from inside a sync block. + BOOL isFirstAuthError = (_authorizer != nil + && !_hasAttemptedAuthRefresh + && status == GTMSessionFetcherStatusUnauthorized); // 401 + + BOOL hasPrimed = NO; + if (isFirstAuthError) { + if ([_authorizer respondsToSelector:@selector(primeForRefresh)]) { + hasPrimed = [_authorizer primeForRefresh]; + } + } + + BOOL shouldRetryForAuthRefresh = NO; + if (hasPrimed) { + shouldRetryForAuthRefresh = YES; + _hasAttemptedAuthRefresh = YES; + [self updateRequestValue:nil forHTTPHeaderField:@"Authorization"]; + } + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + BOOL shouldDoRetry = [self isRetryEnabledUnsynchronized]; + if (shouldDoRetry && ![self hasRetryAfterInterval]) { + + // Determine if we're doing exponential backoff retries + shouldDoRetry = [self nextRetryIntervalUnsynchronized] < _maxRetryInterval; + + if (shouldDoRetry) { + // If an explicit max retry interval was set, we expect repeated backoffs to take + // up to roughly twice that for repeated fast failures. If the initial attempt is + // already more than 3 times the max retry interval, then failures have taken a long time + // (such as from network timeouts) so don't retry again to avoid the app becoming + // unexpectedly unresponsive. + if (_maxRetryInterval > 0) { + NSTimeInterval maxAllowedIntervalBeforeRetry = _maxRetryInterval * 3; + NSTimeInterval timeSinceInitialRequest = -[_initialRequestDate timeIntervalSinceNow]; + if (timeSinceInitialRequest > maxAllowedIntervalBeforeRetry) { + shouldDoRetry = NO; + } + } + } + } + BOOL canRetry = shouldRetryForAuthRefresh || forceAssumeRetry || shouldDoRetry; + if (canRetry) { + NSDictionary *userInfo = nil; + if (_downloadedData.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : _downloadedData }; + } + NSError *statusError = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain + code:status + userInfo:userInfo]; + if (error == nil) { + error = statusError; + } + willRetry = shouldRetryForAuthRefresh || + forceAssumeRetry || + [self isRetryError:error] || + ((error != statusError) && [self isRetryError:statusError]); + + // If the user has installed a retry callback, consult that. + GTMSessionFetcherRetryBlock retryBlock = _retryBlock; + if (retryBlock) { + [self invokeOnCallbackQueueUnlessStopped:^{ + retryBlock(willRetry, error, response); + }]; + return; + } + } + } // @synchronized(self) + response(willRetry); +} + +- (BOOL)hasRetryAfterInterval { + GTMSessionCheckSynchronized(self); + + NSDictionary *responseHeaders = [self responseHeadersUnsynchronized]; + NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"]; + return (retryAfterValue != nil); +} + +- (NSTimeInterval)retryAfterInterval { + GTMSessionCheckSynchronized(self); + + NSDictionary *responseHeaders = [self responseHeadersUnsynchronized]; + NSString *retryAfterValue = [responseHeaders valueForKey:@"Retry-After"]; + if (retryAfterValue == nil) { + return 0; + } + // Retry-After formatted as HTTP-date | delta-seconds + // Reference: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + NSDateFormatter *rfc1123DateFormatter = [[NSDateFormatter alloc] init]; + rfc1123DateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; + rfc1123DateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; + rfc1123DateFormatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss z"; + NSDate *retryAfterDate = [rfc1123DateFormatter dateFromString:retryAfterValue]; + NSTimeInterval retryAfterInterval = (retryAfterDate != nil) ? + retryAfterDate.timeIntervalSinceNow : retryAfterValue.intValue; + retryAfterInterval = MAX(0, retryAfterInterval); + return retryAfterInterval; +} + +- (void)beginRetryTimer { + if (![NSThread isMainThread]) { + // Defer creating and starting the timer until we're on the main thread to ensure it has + // a run loop. + dispatch_group_async(_callbackGroup, dispatch_get_main_queue(), ^{ + [self beginRetryTimer]; + }); + return; + } + + [self destroyRetryTimer]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSTimeInterval nextInterval = [self nextRetryIntervalUnsynchronized]; + NSTimeInterval maxInterval = _maxRetryInterval; + NSTimeInterval newInterval = MIN(nextInterval, (maxInterval > 0 ? maxInterval : DBL_MAX)); + NSTimeInterval newIntervalTolerance = (newInterval / 10) > 1.0 ?: 1.0; + + _lastRetryInterval = newInterval; + + _retryTimer = [NSTimer timerWithTimeInterval:newInterval + target:self + selector:@selector(retryTimerFired:) + userInfo:nil + repeats:NO]; + _retryTimer.tolerance = newIntervalTolerance; + [[NSRunLoop mainRunLoop] addTimer:_retryTimer + forMode:NSDefaultRunLoopMode]; + } // @synchronized(self) + + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStartedNotification + userInfo:nil + requireAsync:NO]; +} + +- (void)retryTimerFired:(NSTimer *)timer { + [self destroyRetryTimer]; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _retryCount++; + } // @synchronized(self) + + NSOperationQueue *queue = self.sessionDelegateQueue; + [queue addOperationWithBlock:^{ + [self retryFetch]; + }]; +} + +- (void)destroyRetryTimer { + BOOL shouldNotify = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_retryTimer) { + [_retryTimer invalidate]; + _retryTimer = nil; + shouldNotify = YES; + } + } + + if (shouldNotify) { + [self postNotificationOnMainThreadWithName:kGTMSessionFetcherRetryDelayStoppedNotification + userInfo:nil + requireAsync:NO]; + } +} + +- (NSUInteger)retryCount { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _retryCount; + } // @synchronized(self) +} + +- (NSTimeInterval)nextRetryInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSTimeInterval interval = [self nextRetryIntervalUnsynchronized]; + return interval; + } // @synchronized(self) +} + +- (NSTimeInterval)nextRetryIntervalUnsynchronized { + GTMSessionCheckSynchronized(self); + + NSInteger statusCode = [self statusCodeUnsynchronized]; + if ((statusCode == 503) && [self hasRetryAfterInterval]) { + NSTimeInterval secs = [self retryAfterInterval]; + return secs; + } + // The next wait interval is the factor (2.0) times the last interval, + // but never less than the minimum interval. + NSTimeInterval secs = _lastRetryInterval * _retryFactor; + if (_maxRetryInterval > 0) { + secs = MIN(secs, _maxRetryInterval); + } + secs = MAX(secs, _minRetryInterval); + + return secs; +} + +- (NSTimer *)retryTimer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _retryTimer; + } // @synchronized(self) +} + +- (BOOL)isRetryEnabled { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _isRetryEnabled; + } // @synchronized(self) +} + +- (BOOL)isRetryEnabledUnsynchronized { + GTMSessionCheckSynchronized(self); + + return _isRetryEnabled; +} + +- (void)setRetryEnabled:(BOOL)flag { + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (flag && !_isRetryEnabled) { + // We defer initializing these until the user calls setRetryEnabled + // to avoid using the random number generator if it's not needed. + // However, this means min and max intervals for this fetcher are reset + // as a side effect of calling setRetryEnabled. + // + // Make an initial retry interval random between 1.0 and 2.0 seconds + _minRetryInterval = InitialMinRetryInterval(); + _maxRetryInterval = kUnsetMaxRetryInterval; + _retryFactor = 2.0; + _lastRetryInterval = 0.0; + } + _isRetryEnabled = flag; + } // @synchronized(self) +}; + +- (NSTimeInterval)maxRetryInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _maxRetryInterval; + } // @synchronized(self) +} + +- (void)setMaxRetryInterval:(NSTimeInterval)secs { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (secs > 0) { + _maxRetryInterval = secs; + } else { + _maxRetryInterval = kUnsetMaxRetryInterval; + } + } // @synchronized(self) +} + +- (double)minRetryInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _minRetryInterval; + } // @synchronized(self) +} + +- (void)setMinRetryInterval:(NSTimeInterval)secs { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (secs > 0) { + _minRetryInterval = secs; + } else { + // Set min interval to a random value between 1.0 and 2.0 seconds + // so that if multiple clients start retrying at the same time, they'll + // repeat at different times and avoid overloading the server + _minRetryInterval = InitialMinRetryInterval(); + } + } // @synchronized(self) + +} + +#pragma mark iOS System Completion Handlers + +#if TARGET_OS_IPHONE +static NSMutableDictionary *gSystemCompletionHandlers = nil; + +- (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler { + return [[self class] systemCompletionHandlerForSessionIdentifier:_sessionIdentifier]; +} + +- (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler { + [[self class] setSystemCompletionHandler:systemCompletionHandler + forSessionIdentifier:_sessionIdentifier]; +} + ++ (void)setSystemCompletionHandler:(GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandler + forSessionIdentifier:(NSString *)sessionIdentifier { + if (!sessionIdentifier) { + NSLog(@"%s with nil identifier", __PRETTY_FUNCTION__); + return; + } + + @synchronized([GTMSessionFetcher class]) { + if (gSystemCompletionHandlers == nil && systemCompletionHandler != nil) { + gSystemCompletionHandlers = [[NSMutableDictionary alloc] init]; + } + // Use setValue: to remove the object if completionHandler is nil. + [gSystemCompletionHandlers setValue:systemCompletionHandler + forKey:sessionIdentifier]; + } +} + ++ (GTM_NULLABLE GTMSessionFetcherSystemCompletionHandler)systemCompletionHandlerForSessionIdentifier:(NSString *)sessionIdentifier { + if (!sessionIdentifier) { + return nil; + } + @synchronized([GTMSessionFetcher class]) { + return [gSystemCompletionHandlers objectForKey:sessionIdentifier]; + } +} +#endif // TARGET_OS_IPHONE + +#pragma mark Getters and Setters + +@synthesize downloadResumeData = _downloadResumeData, + configuration = _configuration, + configurationBlock = _configurationBlock, + sessionTask = _sessionTask, + wasCreatedFromBackgroundSession = _wasCreatedFromBackgroundSession, + sessionUserInfo = _sessionUserInfo, + taskDescription = _taskDescription, + taskPriority = _taskPriority, + usingBackgroundSession = _usingBackgroundSession, + canShareSession = _canShareSession, + completionHandler = _completionHandler, + credential = _credential, + proxyCredential = _proxyCredential, + bodyData = _bodyData, + bodyLength = _bodyLength, + service = _service, + serviceHost = _serviceHost, + accumulateDataBlock = _accumulateDataBlock, + receivedProgressBlock = _receivedProgressBlock, + downloadProgressBlock = _downloadProgressBlock, + resumeDataBlock = _resumeDataBlock, + didReceiveResponseBlock = _didReceiveResponseBlock, + challengeBlock = _challengeBlock, + willRedirectBlock = _willRedirectBlock, + sendProgressBlock = _sendProgressBlock, + willCacheURLResponseBlock = _willCacheURLResponseBlock, + retryBlock = _retryBlock, + retryFactor = _retryFactor, + allowedInsecureSchemes = _allowedInsecureSchemes, + allowLocalhostRequest = _allowLocalhostRequest, + allowInvalidServerCertificates = _allowInvalidServerCertificates, + cookieStorage = _cookieStorage, + callbackQueue = _callbackQueue, + initialBeginFetchDate = _initialBeginFetchDate, + testBlock = _testBlock, + testBlockAccumulateDataChunkCount = _testBlockAccumulateDataChunkCount, + comment = _comment, + log = _log; + +#if !STRIP_GTM_FETCH_LOGGING +@synthesize redirectedFromURL = _redirectedFromURL, + logRequestBody = _logRequestBody, + logResponseBody = _logResponseBody, + hasLoggedError = _hasLoggedError; +#endif + +#if GTM_BACKGROUND_TASK_FETCHING +@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier, + skipBackgroundTask = _skipBackgroundTask; +#endif + +- (GTM_NULLABLE NSURLRequest *)request { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_request copy]; + } // @synchronized(self) +} + +- (void)setRequest:(GTM_NULLABLE NSURLRequest *)request { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (![self isFetchingUnsynchronized]) { + _request = [request mutableCopy]; + } else { + GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked"); + } + } // @synchronized(self) +} + +- (GTM_NULLABLE NSMutableURLRequest *)mutableRequestForTesting { + // Allow tests only to modify the request, useful during retries. + return _request; +} + +- (GTM_NULLABLE NSMutableURLRequest *)mutableRequest { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_LOG_DEBUG(@"[GTMSessionFetcher mutableRequest] is deprecated; use -request or" + @" -setRequestValue:forHTTPHeaderField:"); + + return _request; + } // @synchronized(self) +} + +- (void)setMutableRequest:(GTM_NULLABLE NSMutableURLRequest *)request { + GTMSESSION_LOG_DEBUG(@"[GTMSessionFetcher setMutableRequest:] is deprecated; use -request or" + @" -setRequestValue:forHTTPHeaderField:"); + + GTMSESSION_ASSERT_DEBUG(![self isFetching], + @"mutableRequest should not change after beginFetch has been invoked"); + [self updateMutableRequest:request]; +} + +// Internal method for updating the request property such as on redirects. +- (void)updateMutableRequest:(GTM_NULLABLE NSMutableURLRequest *)request { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _request = request; + } // @synchronized(self) +} + +// Set a header field value on the request. Header field value changes will not +// affect a fetch after the fetch has begun. +- (void)setRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field { + if (![self isFetching]) { + [self updateRequestValue:value forHTTPHeaderField:field]; + } else { + GTMSESSION_ASSERT_DEBUG(0, @"request may not be set after beginFetch has been invoked"); + } +} + +// Internal method for updating request headers. +- (void)updateRequestValue:(GTM_NULLABLE NSString *)value forHTTPHeaderField:(NSString *)field { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [_request setValue:value forHTTPHeaderField:field]; + } // @synchronized(self) +} + +- (void)setResponse:(GTM_NULLABLE NSURLResponse *)response { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _response = response; + } // @synchronized(self) +} + +- (int64_t)bodyLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_bodyLength == NSURLSessionTransferSizeUnknown) { + if (_bodyData) { + _bodyLength = (int64_t)_bodyData.length; + } else if (_bodyFileURL) { + NSNumber *fileSizeNum = nil; + NSError *fileSizeError = nil; + if ([_bodyFileURL getResourceValue:&fileSizeNum + forKey:NSURLFileSizeKey + error:&fileSizeError]) { + _bodyLength = [fileSizeNum longLongValue]; + } + } + } + return _bodyLength; + } // @synchronized(self) +} + +- (BOOL)useUploadTask { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _useUploadTask; + } // @synchronized(self) +} + +- (void)setUseUploadTask:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (flag != _useUploadTask) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"useUploadTask should not change after beginFetch has been invoked"); + _useUploadTask = flag; + } + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURL *)bodyFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _bodyFileURL; + } // @synchronized(self) +} + +- (void)setBodyFileURL:(GTM_NULLABLE NSURL *)fileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // The comparison here is a trivial optimization and forgiveness for any client that + // repeatedly sets the property, so it just uses pointer comparison rather than isEqual:. + if (fileURL != _bodyFileURL) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"fileURL should not change after beginFetch has been invoked"); + + _bodyFileURL = fileURL; + } + } // @synchronized(self) +} + +- (GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)bodyStreamProvider { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _bodyStreamProvider; + } // @synchronized(self) +} + +- (void)setBodyStreamProvider:(GTM_NULLABLE GTMSessionFetcherBodyStreamProvider)block { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"stream provider should not change after beginFetch has been invoked"); + + _bodyStreamProvider = [block copy]; + } // @synchronized(self) +} + +- (GTM_NULLABLE id)authorizer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _authorizer; + } // @synchronized(self) +} + +- (void)setAuthorizer:(GTM_NULLABLE id)authorizer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (authorizer != _authorizer) { + if ([self isFetchingUnsynchronized]) { + GTMSESSION_ASSERT_DEBUG(0, @"authorizer should not change after beginFetch has been invoked"); + } else { + _authorizer = authorizer; + } + } + } // @synchronized(self) +} + +- (GTM_NULLABLE NSData *)downloadedData { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _downloadedData; + } // @synchronized(self) +} + +- (void)setDownloadedData:(GTM_NULLABLE NSData *)data { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _downloadedData = [data mutableCopy]; + } // @synchronized(self) +} + +- (int64_t)downloadedLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _downloadedLength; + } // @synchronized(self) +} + +- (void)setDownloadedLength:(int64_t)length { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _downloadedLength = length; + } // @synchronized(self) +} + +- (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _callbackQueue; + } // @synchronized(self) +} + +- (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _callbackQueue = queue ?: dispatch_get_main_queue(); + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _session; + } // @synchronized(self) +} + +- (NSInteger)servicePriority { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _servicePriority; + } // @synchronized(self) +} + +- (void)setServicePriority:(NSInteger)value { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (value != _servicePriority) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"servicePriority should not change after beginFetch has been invoked"); + + _servicePriority = value; + } + } // @synchronized(self) +} + + +- (void)setSession:(GTM_NULLABLE NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _session = session; + } // @synchronized(self) +} + +- (BOOL)canShareSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _canShareSession; + } // @synchronized(self) +} + +- (void)setCanShareSession:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _canShareSession = flag; + } // @synchronized(self) +} + +- (BOOL)useBackgroundSession { + // This reflects if the user requested a background session, not necessarily + // if one was created. That is tracked with _usingBackgroundSession. + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _userRequestedBackgroundSession; + } // @synchronized(self) +} + +- (void)setUseBackgroundSession:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (flag != _userRequestedBackgroundSession) { + GTMSESSION_ASSERT_DEBUG(![self isFetchingUnsynchronized], + @"useBackgroundSession should not change after beginFetch has been invoked"); + + _userRequestedBackgroundSession = flag; + } + } // @synchronized(self) +} + +- (BOOL)isUsingBackgroundSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _usingBackgroundSession; + } // @synchronized(self) +} + +- (void)setUsingBackgroundSession:(BOOL)flag { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _usingBackgroundSession = flag; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURLSession *)sessionNeedingInvalidation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _sessionNeedingInvalidation; + } // @synchronized(self) +} + +- (void)setSessionNeedingInvalidation:(GTM_NULLABLE NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _sessionNeedingInvalidation = session; + } // @synchronized(self) +} + +- (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateQueue; + } // @synchronized(self) +} + +- (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (queue != _delegateQueue) { + if ([self isFetchingUnsynchronized]) { + GTMSESSION_ASSERT_DEBUG(0, @"sessionDelegateQueue should not change after fetch begins"); + } else { + _delegateQueue = queue ?: [NSOperationQueue mainQueue]; + } + } + } // @synchronized(self) +} + +- (BOOL)userStoppedFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _userStoppedFetching; + } // @synchronized(self) +} + +- (GTM_NULLABLE id)userData { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _userData; + } // @synchronized(self) +} + +- (void)setUserData:(GTM_NULLABLE id)theObj { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _userData = theObj; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSURL *)destinationFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _destinationFileURL; + } // @synchronized(self) +} + +- (void)setDestinationFileURL:(GTM_NULLABLE NSURL *)destinationFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (((_destinationFileURL == nil) && (destinationFileURL == nil)) || + [_destinationFileURL isEqual:destinationFileURL]) { + return; + } + if (_sessionIdentifier) { + // This is something we don't expect to happen in production. + // However if it ever happen, leave a system log. + NSLog(@"%@: Destination File URL changed from (%@) to (%@) after session identifier has " + @"been created.", + [self class], _destinationFileURL, destinationFileURL); +#if DEBUG + // On both the simulator and devices, the path can change to the download file, but the name + // shouldn't change. Technically, this isn't supported in the fetcher, but the change of + // URL is expected to happen only across development runs through Xcode. + NSString *oldFilename = [_destinationFileURL lastPathComponent]; + NSString *newFilename = [destinationFileURL lastPathComponent]; + #pragma unused(oldFilename) + #pragma unused(newFilename) + GTMSESSION_ASSERT_DEBUG([oldFilename isEqualToString:newFilename], + @"Destination File URL cannot be changed after session identifier has been created"); +#endif + } + _destinationFileURL = destinationFileURL; + } // @synchronized(self) +} + +- (void)setProperties:(GTM_NULLABLE NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _properties = [dict mutableCopy]; + } // @synchronized(self) +} + +- (GTM_NULLABLE NSDictionary *)properties { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _properties; + } // @synchronized(self) +} + +- (void)setProperty:(GTM_NULLABLE id)obj forKey:(NSString *)key { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_properties == nil && obj != nil) { + _properties = [[NSMutableDictionary alloc] init]; + } + [_properties setValue:obj forKey:key]; + } // @synchronized(self) +} + +- (GTM_NULLABLE id)propertyForKey:(NSString *)key { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_properties objectForKey:key]; + } // @synchronized(self) +} + +- (void)addPropertiesFromDictionary:(NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_properties == nil && dict != nil) { + [self setProperties:[dict mutableCopy]]; + } else { + [_properties addEntriesFromDictionary:dict]; + } + } // @synchronized(self) +} + +- (void)setCommentWithFormat:(id)format, ... { +#if !STRIP_GTM_FETCH_LOGGING + NSString *result = format; + if (format) { + va_list argList; + va_start(argList, format); + + result = [[NSString alloc] initWithFormat:format + arguments:argList]; + va_end(argList); + } + [self setComment:result]; +#endif +} + +#if !STRIP_GTM_FETCH_LOGGING +- (NSData *)loggedStreamData { + return _loggedStreamData; +} + +- (void)appendLoggedStreamData:dataToAdd { + if (!_loggedStreamData) { + _loggedStreamData = [NSMutableData data]; + } + [_loggedStreamData appendData:dataToAdd]; +} + +- (void)clearLoggedStreamData { + _loggedStreamData = nil; +} + +- (void)setDeferResponseBodyLogging:(BOOL)deferResponseBodyLogging { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (deferResponseBodyLogging != _deferResponseBodyLogging) { + _deferResponseBodyLogging = deferResponseBodyLogging; + if (!deferResponseBodyLogging && !self.hasLoggedError) { + [_delegateQueue addOperationWithBlock:^{ + [self logNowWithError:nil]; + }]; + } + } + } // @synchronized(self) +} + +- (BOOL)deferResponseBodyLogging { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _deferResponseBodyLogging; + } // @synchronized(self) +} + +#else ++ (void)setLoggingEnabled:(BOOL)flag { +} + ++ (BOOL)isLoggingEnabled { + return NO; +} +#endif // STRIP_GTM_FETCH_LOGGING + +@end + +@implementation GTMSessionFetcher (BackwardsCompatibilityOnly) + +- (void)setCookieStorageMethod:(NSInteger)method { + // For backwards compatibility with the old fetcher, we'll support the old constants. + // + // Clients using the GTMSessionFetcher class should set the cookie storage explicitly + // themselves. + NSHTTPCookieStorage *storage = nil; + switch(method) { + case 0: // kGTMHTTPFetcherCookieStorageMethodStatic + // nil storage will use [[self class] staticCookieStorage] when the fetch begins. + break; + case 1: // kGTMHTTPFetcherCookieStorageMethodFetchHistory + // Do nothing; use whatever was set by the fetcher service. + return; + case 2: // kGTMHTTPFetcherCookieStorageMethodSystemDefault + storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; + break; + case 3: // kGTMHTTPFetcherCookieStorageMethodNone + // Create temporary storage for this fetcher only. + storage = [[GTMSessionCookieStorage alloc] init]; + break; + default: + GTMSESSION_ASSERT_DEBUG(0, @"Invalid cookie storage method: %d", (int)method); + } + self.cookieStorage = storage; +} + +@end + +@implementation GTMSessionCookieStorage { + NSMutableArray *_cookies; + NSHTTPCookieAcceptPolicy _policy; +} + +- (id)init { + self = [super init]; + if (self != nil) { + _cookies = [[NSMutableArray alloc] init]; + } + return self; +} + +- (GTM_NULLABLE NSArray *)cookies { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_cookies copy]; + } // @synchronized(self) +} + +- (void)setCookie:(NSHTTPCookie *)cookie { + if (!cookie) return; + if (_policy == NSHTTPCookieAcceptPolicyNever) return; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self internalSetCookie:cookie]; + } // @synchronized(self) +} + +// Note: this should only be called from inside a @synchronized(self) block. +- (void)internalSetCookie:(NSHTTPCookie *)newCookie { + GTMSessionCheckSynchronized(self); + + if (_policy == NSHTTPCookieAcceptPolicyNever) return; + + BOOL isValidCookie = (newCookie.name.length > 0 + && newCookie.domain.length > 0 + && newCookie.path.length > 0); + GTMSESSION_ASSERT_DEBUG(isValidCookie, @"invalid cookie: %@", newCookie); + + if (isValidCookie) { + // Remove the cookie if it's currently in the array. + NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie]; + if (oldCookie) { + [_cookies removeObjectIdenticalTo:oldCookie]; + } + + if (![[self class] hasCookieExpired:newCookie]) { + [_cookies addObject:newCookie]; + } + } +} + +// Add all cookies in the new cookie array to the storage, +// replacing stored cookies as appropriate. +// +// Side effect: removes expired cookies from the storage array. +- (void)setCookies:(GTM_NULLABLE NSArray *)newCookies { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self removeExpiredCookies]; + + for (NSHTTPCookie *newCookie in newCookies) { + [self internalSetCookie:newCookie]; + } + } // @synchronized(self) +} + +- (void)setCookies:(NSArray *)cookies forURL:(GTM_NULLABLE NSURL *)URL mainDocumentURL:(GTM_NULLABLE NSURL *)mainDocumentURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_policy == NSHTTPCookieAcceptPolicyNever) { + return; + } + + if (_policy == NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain) { + NSString *mainHost = mainDocumentURL.host; + NSString *associatedHost = URL.host; + if (!mainHost || ![associatedHost hasSuffix:mainHost]) { + return; + } + } + } // @synchronized(self) + [self setCookies:cookies]; +} + +- (void)deleteCookie:(NSHTTPCookie *)cookie { + if (!cookie) return; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSHTTPCookie *foundCookie = [self cookieMatchingCookie:cookie]; + if (foundCookie) { + [_cookies removeObjectIdenticalTo:foundCookie]; + } + } // @synchronized(self) +} + +// Retrieve all cookies appropriate for the given URL, considering +// domain, path, cookie name, expiration, security setting. +// Side effect: removed expired cookies from the storage array. +- (GTM_NULLABLE NSArray *)cookiesForURL:(NSURL *)theURL { + NSMutableArray *foundCookies = nil; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self removeExpiredCookies]; + + // We'll prepend "." to the desired domain, since we want the + // actual domain "nytimes.com" to still match the cookie domain + // ".nytimes.com" when we check it below with hasSuffix. + NSString *host = theURL.host.lowercaseString; + NSString *path = theURL.path; + NSString *scheme = [theURL scheme]; + + NSString *requestingDomain = nil; + BOOL isLocalhostRetrieval = NO; + + if (IsLocalhost(host)) { + isLocalhostRetrieval = YES; + } else { + if (host.length > 0) { + requestingDomain = [@"." stringByAppendingString:host]; + } + } + + for (NSHTTPCookie *storedCookie in _cookies) { + NSString *cookieDomain = storedCookie.domain.lowercaseString; + NSString *cookiePath = storedCookie.path; + BOOL cookieIsSecure = [storedCookie isSecure]; + + BOOL isDomainOK; + + if (isLocalhostRetrieval) { + // Prior to 10.5.6, the domain stored into NSHTTPCookies for localhost + // is "localhost.local" + isDomainOK = (IsLocalhost(cookieDomain) + || [cookieDomain isEqual:@"localhost.local"]); + } else { + // Ensure we're matching exact domain names. We prepended a dot to the + // requesting domain, so we can also prepend one here if needed before + // checking if the request contains the cookie domain. + if (![cookieDomain hasPrefix:@"."]) { + cookieDomain = [@"." stringByAppendingString:cookieDomain]; + } + isDomainOK = [requestingDomain hasSuffix:cookieDomain]; + } + + BOOL isPathOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath]; + BOOL isSecureOK = (!cookieIsSecure + || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame); + + if (isDomainOK && isPathOK && isSecureOK) { + if (foundCookies == nil) { + foundCookies = [NSMutableArray array]; + } + [foundCookies addObject:storedCookie]; + } + } + } // @synchronized(self) + return foundCookies; +} + +// Override methods from the NSHTTPCookieStorage (NSURLSessionTaskAdditions) category. +- (void)storeCookies:(NSArray *)cookies forTask:(NSURLSessionTask *)task { + NSURLRequest *currentRequest = task.currentRequest; + [self setCookies:cookies forURL:currentRequest.URL mainDocumentURL:nil]; +} + +- (void)getCookiesForTask:(NSURLSessionTask *)task + completionHandler:(void (^)(GTM_NSArrayOf(NSHTTPCookie *) *))completionHandler { + if (completionHandler) { + NSURLRequest *currentRequest = task.currentRequest; + NSURL *currentRequestURL = currentRequest.URL; + NSArray *cookies = [self cookiesForURL:currentRequestURL]; + completionHandler(cookies); + } +} + +// Return a cookie from the array with the same name, domain, and path as the +// given cookie, or else return nil if none found. +// +// Both the cookie being tested and all cookies in the storage array should +// be valid (non-nil name, domains, paths). +// +// Note: this should only be called from inside a @synchronized(self) block +- (GTM_NULLABLE NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie { + GTMSessionCheckSynchronized(self); + + NSString *name = cookie.name; + NSString *domain = cookie.domain; + NSString *path = cookie.path; + + GTMSESSION_ASSERT_DEBUG(name && domain && path, + @"Invalid stored cookie (name:%@ domain:%@ path:%@)", name, domain, path); + + for (NSHTTPCookie *storedCookie in _cookies) { + if ([storedCookie.name isEqual:name] + && [storedCookie.domain isEqual:domain] + && [storedCookie.path isEqual:path]) { + return storedCookie; + } + } + return nil; +} + +// Internal routine to remove any expired cookies from the array, excluding +// cookies with nil expirations. +// +// Note: this should only be called from inside a @synchronized(self) block +- (void)removeExpiredCookies { + GTMSessionCheckSynchronized(self); + + // Count backwards since we're deleting items from the array + for (NSInteger idx = (NSInteger)_cookies.count - 1; idx >= 0; idx--) { + NSHTTPCookie *storedCookie = [_cookies objectAtIndex:(NSUInteger)idx]; + if ([[self class] hasCookieExpired:storedCookie]) { + [_cookies removeObjectAtIndex:(NSUInteger)idx]; + } + } +} + ++ (BOOL)hasCookieExpired:(NSHTTPCookie *)cookie { + NSDate *expiresDate = [cookie expiresDate]; + if (expiresDate == nil) { + // Cookies seem to have a Expires property even when the expiresDate method returns nil. + id expiresVal = [[cookie properties] objectForKey:NSHTTPCookieExpires]; + if ([expiresVal isKindOfClass:[NSDate class]]) { + expiresDate = expiresVal; + } + } + BOOL hasExpired = (expiresDate != nil && [expiresDate timeIntervalSinceNow] < 0); + return hasExpired; +} + +- (void)removeAllCookies { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [_cookies removeAllObjects]; + } // @synchronized(self) +} + +- (NSHTTPCookieAcceptPolicy)cookieAcceptPolicy { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _policy; + } // @synchronized(self) +} + +- (void)setCookieAcceptPolicy:(NSHTTPCookieAcceptPolicy)cookieAcceptPolicy { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _policy = cookieAcceptPolicy; + } // @synchronized(self) +} + +@end + +void GTMSessionFetcherAssertValidSelector(id GTM_NULLABLE_TYPE obj, SEL GTM_NULLABLE_TYPE sel, ...) { + // Verify that the object's selector is implemented with the proper + // number and type of arguments +#if DEBUG + va_list argList; + va_start(argList, sel); + + if (obj && sel) { + // Check that the selector is implemented + if (![obj respondsToSelector:sel]) { + NSLog(@"\"%@\" selector \"%@\" is unimplemented or misnamed", + NSStringFromClass([(id)obj class]), + NSStringFromSelector((SEL)sel)); + NSCAssert(0, @"callback selector unimplemented or misnamed"); + } else { + const char *expectedArgType; + unsigned int argCount = 2; // skip self and _cmd + NSMethodSignature *sig = [obj methodSignatureForSelector:sel]; + + // Check that each expected argument is present and of the correct type + while ((expectedArgType = va_arg(argList, const char*)) != 0) { + + if ([sig numberOfArguments] > argCount) { + const char *foundArgType = [sig getArgumentTypeAtIndex:argCount]; + + if (0 != strncmp(foundArgType, expectedArgType, strlen(expectedArgType))) { + NSLog(@"\"%@\" selector \"%@\" argument %d should be type %s", + NSStringFromClass([(id)obj class]), + NSStringFromSelector((SEL)sel), (argCount - 2), expectedArgType); + NSCAssert(0, @"callback selector argument type mistake"); + } + } + argCount++; + } + + // Check that the proper number of arguments are present in the selector + if (argCount != [sig numberOfArguments]) { + NSLog(@"\"%@\" selector \"%@\" should have %d arguments", + NSStringFromClass([(id)obj class]), + NSStringFromSelector((SEL)sel), (argCount - 2)); + NSCAssert(0, @"callback selector arguments incorrect"); + } + } + } + + va_end(argList); +#endif +} + +NSString *GTMFetcherCleanedUserAgentString(NSString *str) { + // Reference http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html + // and http://www-archive.mozilla.org/build/user-agent-strings.html + + if (str == nil) return @""; + + NSMutableString *result = [NSMutableString stringWithString:str]; + + // Replace spaces and commas with underscores + [result replaceOccurrencesOfString:@" " + withString:@"_" + options:0 + range:NSMakeRange(0, result.length)]; + [result replaceOccurrencesOfString:@"," + withString:@"_" + options:0 + range:NSMakeRange(0, result.length)]; + + // Delete http token separators and remaining whitespace + static NSCharacterSet *charsToDelete = nil; + if (charsToDelete == nil) { + // Make a set of unwanted characters + NSString *const kSeparators = @"()<>@;:\\\"/[]?={}"; + + NSMutableCharacterSet *mutableChars = + [[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy]; + [mutableChars addCharactersInString:kSeparators]; + charsToDelete = [mutableChars copy]; // hang on to an immutable copy + } + + while (1) { + NSRange separatorRange = [result rangeOfCharacterFromSet:charsToDelete]; + if (separatorRange.location == NSNotFound) break; + + [result deleteCharactersInRange:separatorRange]; + }; + + return result; +} + +NSString *GTMFetcherSystemVersionString(void) { + static NSString *sSavedSystemString; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + // The Xcode 8 SDKs finally cleaned up this mess by providing TARGET_OS_OSX + // and TARGET_OS_IOS, but to build with older SDKs, those don't exist and + // instead one has to rely on TARGET_OS_MAC (which is true for iOS, watchOS, + // and tvOS) and TARGET_OS_IPHONE (which is true for iOS, watchOS, tvOS). So + // one has to order these carefully so you pick off the specific things + // first. + // If the code can ever assume Xcode 8 or higher (even when building for + // older OSes), then + // TARGET_OS_MAC -> TARGET_OS_OSX + // TARGET_OS_IPHONE -> TARGET_OS_IOS + // TARGET_IPHONE_SIMULATOR -> TARGET_OS_SIMULATOR +#if TARGET_OS_WATCH + // watchOS - WKInterfaceDevice + + WKInterfaceDevice *currentDevice = [WKInterfaceDevice currentDevice]; + + NSString *rawModel = [currentDevice model]; + NSString *model = GTMFetcherCleanedUserAgentString(rawModel); + + NSString *systemVersion = [currentDevice systemVersion]; + +#if TARGET_OS_SIMULATOR + NSString *hardwareModel = @"sim"; +#else + NSString *hardwareModel; + struct utsname unameRecord; + if (uname(&unameRecord) == 0) { + NSString *machineName = @(unameRecord.machine); + hardwareModel = GTMFetcherCleanedUserAgentString(machineName); + } + if (hardwareModel.length == 0) { + hardwareModel = @"unk"; + } +#endif + + sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", + model, systemVersion, hardwareModel]; + // Example: Apple_Watch/3.0 hw/Watch1_2 +#elif TARGET_OS_TV || TARGET_OS_IPHONE + // iOS and tvOS have UIDevice, use that. + UIDevice *currentDevice = [UIDevice currentDevice]; + + NSString *rawModel = [currentDevice model]; + NSString *model = GTMFetcherCleanedUserAgentString(rawModel); + + NSString *systemVersion = [currentDevice systemVersion]; + +#if TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR + NSString *hardwareModel = @"sim"; +#else + NSString *hardwareModel; + struct utsname unameRecord; + if (uname(&unameRecord) == 0) { + NSString *machineName = @(unameRecord.machine); + hardwareModel = GTMFetcherCleanedUserAgentString(machineName); + } + if (hardwareModel.length == 0) { + hardwareModel = @"unk"; + } +#endif + + sSavedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", + model, systemVersion, hardwareModel]; + // Example: iPod_Touch/2.2 hw/iPod1_1 + // Example: Apple_TV/9.2 hw/AppleTV5,3 +#elif TARGET_OS_MAC + // Mac build + NSProcessInfo *procInfo = [NSProcessInfo processInfo]; +#if !defined(MAC_OS_X_VERSION_10_10) + BOOL hasOperatingSystemVersion = NO; +#elif MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10 + BOOL hasOperatingSystemVersion = + [procInfo respondsToSelector:@selector(operatingSystemVersion)]; +#else + BOOL hasOperatingSystemVersion = YES; +#endif + NSString *versString; + if (hasOperatingSystemVersion) { +#if defined(MAC_OS_X_VERSION_10_10) + // A reference to NSOperatingSystemVersion requires the 10.10 SDK. + NSOperatingSystemVersion version = procInfo.operatingSystemVersion; + versString = [NSString stringWithFormat:@"%zd.%zd.%zd", + version.majorVersion, version.minorVersion, version.patchVersion]; +#else +#pragma unused(procInfo) +#endif + } else { + // With Gestalt inexplicably deprecated in 10.8, we're reduced to reading + // the system plist file. + NSString *const kPath = @"/System/Library/CoreServices/SystemVersion.plist"; + NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:kPath]; + versString = [plist objectForKey:@"ProductVersion"]; + if (versString.length == 0) { + versString = @"10.?.?"; + } + } + + sSavedSystemString = [[NSString alloc] initWithFormat:@"MacOSX/%@", versString]; +#elif defined(_SYS_UTSNAME_H) + // Foundation-only build + struct utsname unameRecord; + uname(&unameRecord); + + sSavedSystemString = [NSString stringWithFormat:@"%s/%s", + unameRecord.sysname, unameRecord.release]; // "Darwin/8.11.1" +#else +#error No branch taken for a default user agent +#endif + }); + return sSavedSystemString; +} + +NSString *GTMFetcherStandardUserAgentString(NSBundle * GTM_NULLABLE_TYPE bundle) { + NSString *result = [NSString stringWithFormat:@"%@ %@", + GTMFetcherApplicationIdentifier(bundle), + GTMFetcherSystemVersionString()]; + return result; +} + +NSString *GTMFetcherApplicationIdentifier(NSBundle * GTM_NULLABLE_TYPE bundle) { + @synchronized([GTMSessionFetcher class]) { + static NSMutableDictionary *sAppIDMap = nil; + + // If there's a bundle ID, use that; otherwise, use the process name + if (bundle == nil) { + bundle = [NSBundle mainBundle]; + } + NSString *bundleID = [bundle bundleIdentifier]; + if (bundleID == nil) { + bundleID = @""; + } + + NSString *identifier = [sAppIDMap objectForKey:bundleID]; + if (identifier) return identifier; + + // Apps may add a string to the info.plist to uniquely identify different builds. + identifier = [bundle objectForInfoDictionaryKey:@"GTMUserAgentID"]; + if (identifier.length == 0) { + if (bundleID.length > 0) { + identifier = bundleID; + } else { + // Fall back on the procname, prefixed by "proc" to flag that it's + // autogenerated and perhaps unreliable + NSString *procName = [[NSProcessInfo processInfo] processName]; + identifier = [NSString stringWithFormat:@"proc_%@", procName]; + } + } + + // Clean up whitespace and special characters + identifier = GTMFetcherCleanedUserAgentString(identifier); + + // If there's a version number, append that + NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + if (version.length == 0) { + version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; + } + + // Clean up whitespace and special characters + version = GTMFetcherCleanedUserAgentString(version); + + // Glue the two together (cleanup done above or else cleanup would strip the + // slash) + if (version.length > 0) { + identifier = [identifier stringByAppendingFormat:@"/%@", version]; + } + + if (sAppIDMap == nil) { + sAppIDMap = [[NSMutableDictionary alloc] init]; + } + [sAppIDMap setObject:identifier forKey:bundleID]; + return identifier; + } +} + +#if DEBUG +@implementation GTMSessionSyncMonitorInternal { + NSValue *_objectKey; // The synchronize target object. + const char *_functionName; // The function containing the monitored sync block. +} + +- (instancetype)initWithSynchronizationObject:(id)object + allowRecursive:(BOOL)allowRecursive + functionName:(const char *)functionName { + self = [super init]; + if (self) { + Class threadKey = [GTMSessionSyncMonitorInternal class]; + _objectKey = [NSValue valueWithNonretainedObject:object]; + _functionName = functionName; + + NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; + NSMutableDictionary *counters = threadDict[threadKey]; + if (counters == nil) { + counters = [NSMutableDictionary dictionary]; + threadDict[(id)threadKey] = counters; + } + NSCountedSet *functionNamesCounter = counters[_objectKey]; + NSUInteger numberOfSyncingFunctions = functionNamesCounter.count; + + if (!allowRecursive) { + BOOL isTopLevelSyncScope = (numberOfSyncingFunctions == 0); + NSArray *stack = [NSThread callStackSymbols]; + GTMSESSION_ASSERT_DEBUG(isTopLevelSyncScope, + @"*** Recursive sync on %@ at %s; previous sync at %@\n%@", + [object class], functionName, functionNamesCounter.allObjects, + [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]); + } + + if (!functionNamesCounter) { + functionNamesCounter = [NSCountedSet set]; + counters[_objectKey] = functionNamesCounter; + } + [functionNamesCounter addObject:@(functionName)]; + } + return self; +} + +- (void)dealloc { + Class threadKey = [GTMSessionSyncMonitorInternal class]; + + NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; + NSMutableDictionary *counters = threadDict[threadKey]; + NSCountedSet *functionNamesCounter = counters[_objectKey]; + NSString *functionNameStr = @(_functionName); + NSUInteger numberOfSyncsByThisFunction = [functionNamesCounter countForObject:functionNameStr]; + NSArray *stack = [NSThread callStackSymbols]; + GTMSESSION_ASSERT_DEBUG(numberOfSyncsByThisFunction > 0, @"Sync not found on %@ at %s\n%@", + [_objectKey.nonretainedObjectValue class], _functionName, + [stack subarrayWithRange:NSMakeRange(1, stack.count - 1)]); + [functionNamesCounter removeObject:functionNameStr]; + if (functionNamesCounter.count == 0) { + [counters removeObjectForKey:_objectKey]; + } +} + ++ (NSArray *)functionsHoldingSynchronizationOnObject:(id)object { + Class threadKey = [GTMSessionSyncMonitorInternal class]; + NSValue *localObjectKey = [NSValue valueWithNonretainedObject:object]; + + NSMutableDictionary *threadDict = [NSThread currentThread].threadDictionary; + NSMutableDictionary *counters = threadDict[threadKey]; + NSCountedSet *functionNamesCounter = counters[localObjectKey]; + return functionNamesCounter.count > 0 ? functionNamesCounter.allObjects : nil; +} +@end +#endif // DEBUG +GTM_ASSUME_NONNULL_END diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogging.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h similarity index 65% rename from Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogging.h rename to Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h index 93ca24c19..bc0a65c0a 100644 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogging.h +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.h @@ -1,10 +1,10 @@ -/* Copyright (c) 2010 Google Inc. +/* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,13 +13,13 @@ * limitations under the License. */ -#import "GTMHTTPFetcher.h" +#import "GTMSessionFetcher.h" // GTM HTTP Logging // -// All traffic using GTMHTTPFetcher can be easily logged. Call +// All traffic using GTMSessionFetcher can be easily logged. Call // -// [GTMHTTPFetcher setLoggingEnabled:YES]; +// [GTMSessionFetcher setLoggingEnabled:YES]; // // to begin generating log files. // @@ -52,7 +52,7 @@ #if !STRIP_GTM_FETCH_LOGGING -@interface GTMHTTPFetcher (GTMHTTPFetcherLogging) +@interface GTMSessionFetcher (GTMSessionFetcherLogging) // Note: the default logs directory is ~/Desktop/GTMHTTPDebugLogs; it will be // created as needed. If a custom directory is set, the directory should @@ -61,43 +61,47 @@ + (NSString *)loggingDirectory; // client apps can turn logging on and off -+ (void)setLoggingEnabled:(BOOL)flag; ++ (void)setLoggingEnabled:(BOOL)isLoggingEnabled; + (BOOL)isLoggingEnabled; // client apps can turn off logging to a file if they want to only check // the fetcher's log property -+ (void)setLoggingToFileEnabled:(BOOL)flag; ++ (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled; + (BOOL)isLoggingToFileEnabled; // client apps can optionally specify process name and date string used in // log file names -+ (void)setLoggingProcessName:(NSString *)str; ++ (void)setLoggingProcessName:(NSString *)processName; + (NSString *)loggingProcessName; -+ (void)setLoggingDateStamp:(NSString *)str; ++ (void)setLoggingDateStamp:(NSString *)dateStamp; + (NSString *)loggingDateStamp; +// client apps can specify the directory for the log for this specific run, +// typically to match the directory used by another fetcher class, like: +// +// [GTMSessionFetcher setLogDirectoryForCurrentRun:[GTMHTTPFetcher logDirectoryForCurrentRun]]; +// +// Setting this overrides the logging directory, process name, and date stamp when writing +// the log file. ++ (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun; ++ (NSString *)logDirectoryForCurrentRun; + +// Prunes old log directories that have not been modified since the provided date. +// This will not delete the current run's log directory. ++ (void)deleteLogDirectoriesOlderThanDate:(NSDate *)date; + // internal; called by fetcher - (void)logFetchWithError:(NSError *)error; -- (BOOL)logCapturePostStream; +- (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream; +- (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: + (GTMSessionFetcherBodyStreamProvider)streamProvider; // internal; accessors useful for viewing logs + (NSString *)processNameLogPrefix; + (NSString *)symlinkNameSuffix; + (NSString *)htmlFileName; -// Applications may provide alternative body strings to be displayed in the -// log, such as for binary requests or responses. If deferring is turned -// on, the response log will not be sent until deferring is turned off, -// allowing the application to write the response body after the response -// data has been parsed. -- (void)setLogRequestBody:(NSString *)bodyString; -- (NSString *)logRequestBody; -- (void)setLogResponseBody:(NSString *)bodyString; -- (NSString *)logResponseBody; -- (void)setShouldDeferResponseBodyLogging:(BOOL)flag; -- (BOOL)shouldDeferResponseBodyLogging; - @end #endif // !STRIP_GTM_FETCH_LOGGING diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m new file mode 100644 index 000000000..02b46b608 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherLogging.m @@ -0,0 +1,976 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#include +#include + +#import "GTMSessionFetcherLogging.h" + +#ifndef STRIP_GTM_FETCH_LOGGING + #error GTMSessionFetcher headers should have defaulted this if it wasn't already defined. +#endif + +#if !STRIP_GTM_FETCH_LOGGING + +// Sensitive credential strings are replaced in logs with _snip_ +// +// Apps that must see the contents of sensitive tokens can set this to 1 +#ifndef SKIP_GTM_FETCH_LOGGING_SNIPPING +#define SKIP_GTM_FETCH_LOGGING_SNIPPING 0 +#endif + +// If GTMReadMonitorInputStream is available, it can be used for +// capturing uploaded streams of data +// +// We locally declare methods of GTMReadMonitorInputStream so we +// do not need to import the header, as some projects may not have it available +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMReadMonitorInputStream : NSInputStream + ++ (instancetype)inputStreamWithStream:(NSInputStream *)input; + +@property (assign) id readDelegate; +@property (assign) SEL readSelector; + +@end +#else +@class GTMReadMonitorInputStream; +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +@interface GTMSessionFetcher (GTMHTTPFetcherLoggingUtilities) + ++ (NSString *)headersStringForDictionary:(NSDictionary *)dict; ++ (NSString *)snipSubstringOfString:(NSString *)originalStr + betweenStartString:(NSString *)startStr + endString:(NSString *)endStr; +- (void)inputStream:(GTMReadMonitorInputStream *)stream + readIntoBuffer:(void *)buffer + length:(int64_t)length; + +@end + +@implementation GTMSessionFetcher (GTMSessionFetcherLogging) + +// fetchers come and fetchers go, but statics are forever +static BOOL gIsLoggingEnabled = NO; +static BOOL gIsLoggingToFile = YES; +static NSString *gLoggingDirectoryPath = nil; +static NSString *gLogDirectoryForCurrentRun = nil; +static NSString *gLoggingDateStamp = nil; +static NSString *gLoggingProcessName = nil; + ++ (void)setLoggingDirectory:(NSString *)path { + gLoggingDirectoryPath = [path copy]; +} + ++ (NSString *)loggingDirectory { + if (!gLoggingDirectoryPath) { + NSArray *paths = nil; +#if TARGET_IPHONE_SIMULATOR + // default to a directory called GTMHTTPDebugLogs into a sandbox-safe + // directory that a developer can find easily, the application home + paths = @[ NSHomeDirectory() ]; +#elif TARGET_OS_IPHONE + // Neither ~/Desktop nor ~/Home is writable on an actual iOS, watchOS, or tvOS device. + // Put it in ~/Documents. + paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); +#else + // default to a directory called GTMHTTPDebugLogs in the desktop folder + paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES); +#endif + + NSString *desktopPath = paths.firstObject; + if (desktopPath) { + NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs"; + NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName]; + + NSFileManager *fileMgr = [NSFileManager defaultManager]; + BOOL isDir; + BOOL doesFolderExist = [fileMgr fileExistsAtPath:logsFolderPath isDirectory:&isDir]; + if (!doesFolderExist) { + // make the directory + doesFolderExist = [fileMgr createDirectoryAtPath:logsFolderPath + withIntermediateDirectories:YES + attributes:nil + error:NULL]; + } + if (doesFolderExist) { + // it's there; store it in the global + gLoggingDirectoryPath = [logsFolderPath copy]; + } + } + } + return gLoggingDirectoryPath; +} + ++ (void)setLogDirectoryForCurrentRun:(NSString *)logDirectoryForCurrentRun { + // Set the path for this run's logs. + gLogDirectoryForCurrentRun = [logDirectoryForCurrentRun copy]; +} + ++ (NSString *)logDirectoryForCurrentRun { + // make a directory for this run's logs, like SyncProto_logs_10-16_01-56-58PM + if (gLogDirectoryForCurrentRun) return gLogDirectoryForCurrentRun; + + NSString *parentDir = [self loggingDirectory]; + NSString *logNamePrefix = [self processNameLogPrefix]; + NSString *dateStamp = [self loggingDateStamp]; + NSString *dirName = [NSString stringWithFormat:@"%@%@", logNamePrefix, dateStamp]; + NSString *logDirectory = [parentDir stringByAppendingPathComponent:dirName]; + + if (gIsLoggingToFile) { + NSFileManager *fileMgr = [NSFileManager defaultManager]; + // Be sure that the first time this app runs, it's not writing to a preexisting folder + static BOOL gShouldReuseFolder = NO; + if (!gShouldReuseFolder) { + gShouldReuseFolder = YES; + NSString *origLogDir = logDirectory; + for (int ctr = 2; ctr < 20; ++ctr) { + if (![fileMgr fileExistsAtPath:logDirectory]) break; + + // append a digit + logDirectory = [origLogDir stringByAppendingFormat:@"_%d", ctr]; + } + } + if (![fileMgr createDirectoryAtPath:logDirectory + withIntermediateDirectories:YES + attributes:nil + error:NULL]) return nil; + } + gLogDirectoryForCurrentRun = logDirectory; + + return gLogDirectoryForCurrentRun; +} + ++ (void)setLoggingEnabled:(BOOL)isLoggingEnabled { + gIsLoggingEnabled = isLoggingEnabled; +} + ++ (BOOL)isLoggingEnabled { + return gIsLoggingEnabled; +} + ++ (void)setLoggingToFileEnabled:(BOOL)isLoggingToFileEnabled { + gIsLoggingToFile = isLoggingToFileEnabled; +} + ++ (BOOL)isLoggingToFileEnabled { + return gIsLoggingToFile; +} + ++ (void)setLoggingProcessName:(NSString *)processName { + gLoggingProcessName = [processName copy]; +} + ++ (NSString *)loggingProcessName { + // get the process name (once per run) replacing spaces with underscores + if (!gLoggingProcessName) { + NSString *procName = [[NSProcessInfo processInfo] processName]; + gLoggingProcessName = [procName stringByReplacingOccurrencesOfString:@" " withString:@"_"]; + } + return gLoggingProcessName; +} + ++ (void)setLoggingDateStamp:(NSString *)dateStamp { + gLoggingDateStamp = [dateStamp copy]; +} + ++ (NSString *)loggingDateStamp { + // We'll pick one date stamp per run, so a run that starts at a later second + // will get a unique results html file + if (!gLoggingDateStamp) { + // produce a string like 08-21_01-41-23PM + + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setFormatterBehavior:NSDateFormatterBehavior10_4]; + [formatter setDateFormat:@"M-dd_hh-mm-ssa"]; + + gLoggingDateStamp = [formatter stringFromDate:[NSDate date]]; + } + return gLoggingDateStamp; +} + ++ (NSString *)processNameLogPrefix { + static NSString *gPrefix = nil; + if (!gPrefix) { + NSString *processName = [self loggingProcessName]; + gPrefix = [[NSString alloc] initWithFormat:@"%@_log_", processName]; + } + return gPrefix; +} + ++ (NSString *)symlinkNameSuffix { + return @"_log_newest.html"; +} + ++ (NSString *)htmlFileName { + return @"aperçu_http_log.html"; +} + ++ (void)deleteLogDirectoriesOlderThanDate:(NSDate *)cutoffDate { + NSFileManager *fileMgr = [NSFileManager defaultManager]; + NSURL *parentDir = [NSURL fileURLWithPath:[[self class] loggingDirectory]]; + NSURL *logDirectoryForCurrentRun = + [NSURL fileURLWithPath:[[self class] logDirectoryForCurrentRun]]; + NSError *error; + NSArray *contents = [fileMgr contentsOfDirectoryAtURL:parentDir + includingPropertiesForKeys:@[ NSURLContentModificationDateKey ] + options:0 + error:&error]; + for (NSURL *itemURL in contents) { + if ([itemURL isEqual:logDirectoryForCurrentRun]) continue; + + NSDate *modDate; + if ([itemURL getResourceValue:&modDate + forKey:NSURLContentModificationDateKey + error:&error]) { + if ([modDate compare:cutoffDate] == NSOrderedAscending) { + if (![fileMgr removeItemAtURL:itemURL error:&error]) { + NSLog(@"deleteLogDirectoriesOlderThanDate failed to delete %@: %@", + itemURL.path, error); + } + } + } else { + NSLog(@"deleteLogDirectoriesOlderThanDate failed to get mod date of %@: %@", + itemURL.path, error); + } + } +} + +// formattedStringFromData returns a prettyprinted string for XML or JSON input, +// and a plain string for other input data +- (NSString *)formattedStringFromData:(NSData *)inputData + contentType:(NSString *)contentType + JSON:(NSDictionary **)outJSON { + if (!inputData) return nil; + + // if the content type is JSON and we have the parsing class available, use that + if ([contentType hasPrefix:@"application/json"] && inputData.length > 5) { + // convert from JSON string to NSObjects and back to a formatted string + NSMutableDictionary *obj = [NSJSONSerialization JSONObjectWithData:inputData + options:NSJSONReadingMutableContainers + error:NULL]; + if (obj) { + if (outJSON) *outJSON = obj; + if ([obj isKindOfClass:[NSMutableDictionary class]]) { + // for security and privacy, omit OAuth 2 response access and refresh tokens + if ([obj valueForKey:@"refresh_token"] != nil) { + [obj setObject:@"_snip_" forKey:@"refresh_token"]; + } + if ([obj valueForKey:@"access_token"] != nil) { + [obj setObject:@"_snip_" forKey:@"access_token"]; + } + } + NSData *data = [NSJSONSerialization dataWithJSONObject:obj + options:NSJSONWritingPrettyPrinted + error:NULL]; + if (data) { + NSString *jsonStr = [[NSString alloc] initWithData:data + encoding:NSUTF8StringEncoding]; + return jsonStr; + } + } + } + +#if !TARGET_OS_IPHONE && !GTM_SKIP_LOG_XMLFORMAT + // verify that this data starts with the bytes indicating XML + + NSString *const kXMLLintPath = @"/usr/bin/xmllint"; + static BOOL gHasCheckedAvailability = NO; + static BOOL gIsXMLLintAvailable = NO; + + if (!gHasCheckedAvailability) { + gIsXMLLintAvailable = [[NSFileManager defaultManager] fileExistsAtPath:kXMLLintPath]; + gHasCheckedAvailability = YES; + } + if (gIsXMLLintAvailable + && inputData.length > 5 + && strncmp(inputData.bytes, " 0) { + // success + inputData = formattedData; + } + } +#else + // we can't call external tasks on the iPhone; leave the XML unformatted +#endif + + NSString *dataStr = [[NSString alloc] initWithData:inputData + encoding:NSUTF8StringEncoding]; + return dataStr; +} + +// stringFromStreamData creates a string given the supplied data +// +// If NSString can create a UTF-8 string from the data, then that is returned. +// +// Otherwise, this routine tries to find a MIME boundary at the beginning of the data block, and +// uses that to break up the data into parts. Each part will be used to try to make a UTF-8 string. +// For parts that fail, a replacement string showing the part header and <> is supplied +// in place of the binary data. + +- (NSString *)stringFromStreamData:(NSData *)data + contentType:(NSString *)contentType { + + if (!data) return nil; + + // optimistically, see if the whole data block is UTF-8 + NSString *streamDataStr = [self formattedStringFromData:data + contentType:contentType + JSON:NULL]; + if (streamDataStr) return streamDataStr; + + // Munge a buffer by replacing non-ASCII bytes with underscores, and turn that munged buffer an + // NSString. That gives us a string we can use with NSScanner. + NSMutableData *mutableData = [NSMutableData dataWithData:data]; + unsigned char *bytes = (unsigned char *)mutableData.mutableBytes; + + for (unsigned int idx = 0; idx < mutableData.length; ++idx) { + if (bytes[idx] > 0x7F || bytes[idx] == 0) { + bytes[idx] = '_'; + } + } + + NSString *mungedStr = [[NSString alloc] initWithData:mutableData + encoding:NSUTF8StringEncoding]; + if (mungedStr) { + + // scan for the boundary string + NSString *boundary = nil; + NSScanner *scanner = [NSScanner scannerWithString:mungedStr]; + + if ([scanner scanUpToString:@"\r\n" intoString:&boundary] + && [boundary hasPrefix:@"--"]) { + + // we found a boundary string; use it to divide the string into parts + NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary]; + + // look at each munged part in the original string, and try to convert those into UTF-8 + NSMutableArray *origParts = [NSMutableArray array]; + NSUInteger offset = 0; + for (NSString *mungedPart in mungedParts) { + NSUInteger partSize = mungedPart.length; + NSData *origPartData = [data subdataWithRange:NSMakeRange(offset, partSize)]; + NSString *origPartStr = [[NSString alloc] initWithData:origPartData + encoding:NSUTF8StringEncoding]; + if (origPartStr) { + // we could make this original part into UTF-8; use the string + [origParts addObject:origPartStr]; + } else { + // this part can't be made into UTF-8; scan the header, if we can + NSString *header = nil; + NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart]; + if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) { + // we couldn't find a header + header = @""; + } + // make a part string with the header and <> + NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%lu bytes>>\r", + header, (long)(partSize - header.length)]; + [origParts addObject:binStr]; + } + offset += partSize + boundary.length; + } + // rejoin the original parts + streamDataStr = [origParts componentsJoinedByString:boundary]; + } + } + if (!streamDataStr) { + // give up; just make a string showing the uploaded bytes + streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", (unsigned int)data.length]; + } + return streamDataStr; +} + +// logFetchWithError is called following a successful or failed fetch attempt +// +// This method does all the work for appending to and creating log files + +- (void)logFetchWithError:(NSError *)error { + if (![[self class] isLoggingEnabled]) return; + NSString *logDirectory = [[self class] logDirectoryForCurrentRun]; + if (!logDirectory) return; + NSString *processName = [[self class] loggingProcessName]; + + // TODO: add Javascript to display response data formatted in hex + + // each response's NSData goes into its own xml or txt file, though all responses for this run of + // the app share a main html file. This counter tracks all fetch responses for this app run. + // + // we'll use a local variable since this routine may be reentered while waiting for XML formatting + // to be completed by an external task + static int gResponseCounter = 0; + int responseCounter = ++gResponseCounter; + + NSURLResponse *response = [self response]; + NSDictionary *responseHeaders = [self responseHeaders]; + NSString *responseDataStr = nil; + NSDictionary *responseJSON = nil; + + // if there's response data, decide what kind of file to put it in based on the first bytes of the + // file or on the mime type supplied by the server + NSString *responseMIMEType = [response MIMEType]; + BOOL isResponseImage = NO; + + // file name for an image data file + NSString *responseDataFileName = nil; + + int64_t responseDataLength = self.downloadedLength; + if (responseDataLength > 0) { + NSData *downloadedData = self.downloadedData; + if (downloadedData == nil + && responseDataLength > 0 + && responseDataLength < 20000 + && self.destinationFileURL) { + // There's a download file that's not too big, so get the data to display from the downloaded + // file. + NSURL *destinationURL = self.destinationFileURL; + downloadedData = [NSData dataWithContentsOfURL:destinationURL]; + } + NSString *responseType = [responseHeaders valueForKey:@"Content-Type"]; + responseDataStr = [self formattedStringFromData:downloadedData + contentType:responseType + JSON:&responseJSON]; + NSString *responseDataExtn = nil; + NSData *dataToWrite = nil; + if (responseDataStr) { + // we were able to make a UTF-8 string from the response data + if ([responseMIMEType isEqual:@"application/atom+xml"] + || [responseMIMEType hasSuffix:@"/xml"]) { + responseDataExtn = @"xml"; + dataToWrite = [responseDataStr dataUsingEncoding:NSUTF8StringEncoding]; + } + } else if ([responseMIMEType isEqual:@"image/jpeg"]) { + responseDataExtn = @"jpg"; + dataToWrite = downloadedData; + isResponseImage = YES; + } else if ([responseMIMEType isEqual:@"image/gif"]) { + responseDataExtn = @"gif"; + dataToWrite = downloadedData; + isResponseImage = YES; + } else if ([responseMIMEType isEqual:@"image/png"]) { + responseDataExtn = @"png"; + dataToWrite = downloadedData; + isResponseImage = YES; + } else { + // add more non-text types here + } + // if we have an extension, save the raw data in a file with that extension + if (responseDataExtn && dataToWrite) { + // generate a response file base name like + NSString *responseBaseName = [NSString stringWithFormat:@"fetch_%d_response", responseCounter]; + responseDataFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn]; + NSString *responseDataFilePath = [logDirectory stringByAppendingPathComponent:responseDataFileName]; + + NSError *downloadedError = nil; + if (gIsLoggingToFile && ![dataToWrite writeToFile:responseDataFilePath + options:0 + error:&downloadedError]) { + NSLog(@"%@ logging write error:%@ (%@)", [self class], downloadedError, responseDataFileName); + } + } + } + // we'll have one main html file per run of the app + NSString *htmlName = [[self class] htmlFileName]; + NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName]; + + // if the html file exists (from logging previous fetches) we don't need + // to re-write the header or the scripts + NSFileManager *fileMgr = [NSFileManager defaultManager]; + BOOL didFileExist = [fileMgr fileExistsAtPath:htmlPath]; + + NSMutableString* outputHTML = [NSMutableString string]; + + // we need a header to say we'll have UTF-8 text + if (!didFileExist) { + [outputHTML appendFormat:@"%@ HTTP fetch log %@", + processName, [[self class] loggingDateStamp]]; + } + // now write the visible html elements + NSString *copyableFileName = [NSString stringWithFormat:@"fetch_%d.txt", responseCounter]; + + NSDate *now = [NSDate date]; + // write the date & time, the comment, and the link to the plain-text (copyable) log + [outputHTML appendFormat:@"%@      ", now]; + + NSString *comment = [self comment]; + if (comment.length > 0) { + [outputHTML appendFormat:@"%@      ", comment]; + } + [outputHTML appendFormat:@"request/response log
", copyableFileName]; + NSTimeInterval elapsed = -self.initialBeginFetchDate.timeIntervalSinceNow; + [outputHTML appendFormat:@"elapsed: %5.3fsec
", elapsed]; + + // write the request URL + NSURLRequest *request = self.request; + NSString *requestMethod = request.HTTPMethod; + NSURL *requestURL = request.URL; + + // Save the request URL for next time in case this redirects. + NSString *redirectedFromURLString = [self.redirectedFromURL absoluteString]; + self.redirectedFromURL = [requestURL copy]; + if (redirectedFromURLString) { + [outputHTML appendFormat:@"redirected from %@
", + redirectedFromURLString]; + } + [outputHTML appendFormat:@"request: %@ %@
\n", requestMethod, requestURL]; + + // write the request headers + NSDictionary *requestHeaders = request.allHTTPHeaderFields; + NSUInteger numberOfRequestHeaders = requestHeaders.count; + if (numberOfRequestHeaders > 0) { + // Indicate if the request is authorized; warn if the request is authorized but non-SSL + NSString *auth = [requestHeaders objectForKey:@"Authorization"]; + NSString *headerDetails = @""; + if (auth) { + BOOL isInsecure = [[requestURL scheme] isEqual:@"http"]; + if (isInsecure) { + // 26A0 = ⚠ + headerDetails = + @"   authorized, non-SSL "; + } else { + headerDetails = @"   authorized"; + } + } + NSString *cookiesHdr = [requestHeaders objectForKey:@"Cookie"]; + if (cookiesHdr) { + headerDetails = [headerDetails stringByAppendingString:@"   cookies"]; + } + NSString *matchHdr = [requestHeaders objectForKey:@"If-Match"]; + if (matchHdr) { + headerDetails = [headerDetails stringByAppendingString:@"   if-match"]; + } + matchHdr = [requestHeaders objectForKey:@"If-None-Match"]; + if (matchHdr) { + headerDetails = [headerDetails stringByAppendingString:@"   if-none-match"]; + } + [outputHTML appendFormat:@"   headers: %d %@
", + (int)numberOfRequestHeaders, headerDetails]; + } else { + [outputHTML appendFormat:@"   headers: none
"]; + } + // write the request post data + NSData *bodyData = nil; + NSData *loggedStreamData = self.loggedStreamData; + if (loggedStreamData) { + bodyData = loggedStreamData; + } else { + bodyData = self.bodyData; + if (bodyData == nil) { + bodyData = self.request.HTTPBody; + } + } + uint64_t bodyDataLength = bodyData.length; + + if (bodyData.length == 0) { + // If the data is in a body upload file URL, read that in if it's not huge. + NSURL *bodyFileURL = self.bodyFileURL; + if (bodyFileURL) { + NSNumber *fileSizeNum = nil; + NSError *fileSizeError = nil; + if ([bodyFileURL getResourceValue:&fileSizeNum + forKey:NSURLFileSizeKey + error:&fileSizeError]) { + bodyDataLength = [fileSizeNum unsignedLongLongValue]; + if (bodyDataLength > 0 && bodyDataLength < 50000) { + bodyData = [NSData dataWithContentsOfURL:bodyFileURL + options:NSDataReadingUncached + error:&fileSizeError]; + } + } + } + } + NSString *bodyDataStr = nil; + NSString *postType = [requestHeaders valueForKey:@"Content-Type"]; + + if (bodyDataLength > 0) { + [outputHTML appendFormat:@"   data: %llu bytes, %@
\n", + bodyDataLength, postType ? postType : @"(no type)"]; + NSString *logRequestBody = self.logRequestBody; + if (logRequestBody) { + bodyDataStr = [logRequestBody copy]; + self.logRequestBody = nil; + } else { + bodyDataStr = [self stringFromStreamData:bodyData + contentType:postType]; + if (bodyDataStr) { + // remove OAuth 2 client secret and refresh token + bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr + betweenStartString:@"client_secret=" + endString:@"&"]; + bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr + betweenStartString:@"refresh_token=" + endString:@"&"]; + // remove ClientLogin password + bodyDataStr = [[self class] snipSubstringOfString:bodyDataStr + betweenStartString:@"&Passwd=" + endString:@"&"]; + } + } + } else { + // no post data + } + // write the response status, MIME type, URL + NSInteger status = [self statusCode]; + if (response) { + NSString *statusString = @""; + if (status != 0) { + if (status == 200 || status == 201) { + statusString = [NSString stringWithFormat:@"%ld", (long)status]; + + // report any JSON-RPC error + if ([responseJSON isKindOfClass:[NSDictionary class]]) { + NSDictionary *jsonError = [responseJSON objectForKey:@"error"]; + if ([jsonError isKindOfClass:[NSDictionary class]]) { + NSString *jsonCode = [[jsonError valueForKey:@"code"] description]; + NSString *jsonMessage = [jsonError valueForKey:@"message"]; + if (jsonCode || jsonMessage) { + // 2691 = ⚑ + NSString *const jsonErrFmt = + @"   JSON error: %@ %@  ⚑"; + statusString = [statusString stringByAppendingFormat:jsonErrFmt, + jsonCode ? jsonCode : @"", + jsonMessage ? jsonMessage : @""]; + } + } + } + } else { + // purple for anything other than 200 or 201 + NSString *flag = status >= 400 ? @" ⚑" : @""; // 2691 = ⚑ + NSString *explanation = [NSHTTPURLResponse localizedStringForStatusCode:status]; + NSString *const statusFormat = @"%ld %@ %@"; + statusString = [NSString stringWithFormat:statusFormat, (long)status, explanation, flag]; + } + } + // show the response URL only if it's different from the request URL + NSString *responseURLStr = @""; + NSURL *responseURL = response.URL; + + if (responseURL && ![responseURL isEqual:request.URL]) { + NSString *const responseURLFormat = + @"response URL: %@
\n"; + responseURLStr = [NSString stringWithFormat:responseURLFormat, [responseURL absoluteString]]; + } + [outputHTML appendFormat:@"response:  status %@
\n%@", + statusString, responseURLStr]; + // Write the response headers + NSUInteger numberOfResponseHeaders = responseHeaders.count; + if (numberOfResponseHeaders > 0) { + // Indicate if the server is setting cookies + NSString *cookiesSet = [responseHeaders valueForKey:@"Set-Cookie"]; + NSString *cookiesStr = + cookiesSet ? @"  sets cookies" : @""; + // Indicate if the server is redirecting + NSString *location = [responseHeaders valueForKey:@"Location"]; + BOOL isRedirect = status >= 300 && status <= 399 && location != nil; + NSString *redirectsStr = + isRedirect ? @"  redirects" : @""; + [outputHTML appendFormat:@"   headers: %d %@ %@
\n", + (int)numberOfResponseHeaders, cookiesStr, redirectsStr]; + } else { + [outputHTML appendString:@"   headers: none
\n"]; + } + } + // error + if (error) { + [outputHTML appendFormat:@"Error: %@
\n", error.description]; + } + // Write the response data + if (responseDataFileName) { + if (isResponseImage) { + // Make a small inline image that links to the full image file + [outputHTML appendFormat:@"   data: %lld bytes, %@
", + responseDataLength, responseMIMEType]; + NSString *const fmt = + @"image\n"; + [outputHTML appendFormat:fmt, responseDataFileName, responseDataFileName]; + } else { + // The response data was XML; link to the xml file + NSString *const fmt = + @"   data: %lld bytes, %@   %@\n"; + [outputHTML appendFormat:fmt, responseDataLength, responseMIMEType, + responseDataFileName, [responseDataFileName pathExtension]]; + } + } else { + // The response data was not an image; just show the length and MIME type + [outputHTML appendFormat:@"   data: %lld bytes, %@\n", + responseDataLength, responseMIMEType ? responseMIMEType : @"(no response type)"]; + } + // Make a single string of the request and response, suitable for copying + // to the clipboard and pasting into a bug report + NSMutableString *copyable = [NSMutableString string]; + if (comment) { + [copyable appendFormat:@"%@\n\n", comment]; + } + [copyable appendFormat:@"%@ elapsed: %5.3fsec\n", now, elapsed]; + if (redirectedFromURLString) { + [copyable appendFormat:@"Redirected from %@\n", redirectedFromURLString]; + } + [copyable appendFormat:@"Request: %@ %@\n", requestMethod, requestURL]; + if (requestHeaders.count > 0) { + [copyable appendFormat:@"Request headers:\n%@\n", + [[self class] headersStringForDictionary:requestHeaders]]; + } + if (bodyDataLength > 0) { + [copyable appendFormat:@"Request body: (%llu bytes)\n", bodyDataLength]; + if (bodyDataStr) { + [copyable appendFormat:@"%@\n", bodyDataStr]; + } + [copyable appendString:@"\n"]; + } + if (response) { + [copyable appendFormat:@"Response: status %d\n", (int) status]; + [copyable appendFormat:@"Response headers:\n%@\n", + [[self class] headersStringForDictionary:responseHeaders]]; + [copyable appendFormat:@"Response body: (%lld bytes)\n", responseDataLength]; + if (responseDataLength > 0) { + NSString *logResponseBody = self.logResponseBody; + if (logResponseBody) { + // The user has provided the response body text. + responseDataStr = [logResponseBody copy]; + self.logResponseBody = nil; + } + if (responseDataStr != nil) { + [copyable appendFormat:@"%@\n", responseDataStr]; + } else { + // Even though it's redundant, we'll put in text to indicate that all the bytes are binary. + if (self.destinationFileURL) { + [copyable appendFormat:@"<<%lld bytes>> to file %@\n", + responseDataLength, self.destinationFileURL.path]; + } else { + [copyable appendFormat:@"<<%lld bytes>>\n", responseDataLength]; + } + } + } + } + if (error) { + [copyable appendFormat:@"Error: %@\n", error]; + } + // Save to log property before adding the separator + self.log = copyable; + + [copyable appendString:@"-----------------------------------------------------------\n"]; + + // Write the copyable version to another file (linked to at the top of the html file, above) + // + // Ideally, something to just copy this to the clipboard like + // Copy here." + // would work everywhere, but it only works in Safari as of 8/2010 + if (gIsLoggingToFile) { + NSString *parentDir = [[self class] loggingDirectory]; + NSString *copyablePath = [logDirectory stringByAppendingPathComponent:copyableFileName]; + NSError *copyableError = nil; + if (![copyable writeToFile:copyablePath + atomically:NO + encoding:NSUTF8StringEncoding + error:©ableError]) { + // Error writing to file + NSLog(@"%@ logging write error:%@ (%@)", [self class], copyableError, copyablePath); + } + [outputHTML appendString:@"

"]; + + // Append the HTML to the main output file + const char* htmlBytes = outputHTML.UTF8String; + NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath + append:YES]; + [stream open]; + [stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)]; + [stream close]; + + // Make a symlink to the latest html + NSString *const symlinkNameSuffix = [[self class] symlinkNameSuffix]; + NSString *symlinkName = [processName stringByAppendingString:symlinkNameSuffix]; + NSString *symlinkPath = [parentDir stringByAppendingPathComponent:symlinkName]; + + [fileMgr removeItemAtPath:symlinkPath error:NULL]; + [fileMgr createSymbolicLinkAtPath:symlinkPath + withDestinationPath:htmlPath + error:NULL]; +#if TARGET_OS_IPHONE + static BOOL gReportedLoggingPath = NO; + if (!gReportedLoggingPath) { + gReportedLoggingPath = YES; + NSLog(@"GTMSessionFetcher logging to \"%@\"", parentDir); + } +#endif + } +} + +- (NSInputStream *)loggedInputStreamForInputStream:(NSInputStream *)inputStream { + if (!inputStream) return nil; + if (![GTMSessionFetcher isLoggingEnabled]) return inputStream; + + [self clearLoggedStreamData]; // Clear any previous data. + Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); + if (!monitorClass) { + NSString const *str = @"<>"; + NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding]; + [self appendLoggedStreamData:stringData]; + return inputStream; + } + inputStream = [monitorClass inputStreamWithStream:inputStream]; + + GTMReadMonitorInputStream *readMonitorInputStream = (GTMReadMonitorInputStream *)inputStream; + [readMonitorInputStream setReadDelegate:self]; + SEL readSel = @selector(inputStream:readIntoBuffer:length:); + [readMonitorInputStream setReadSelector:readSel]; + + return inputStream; +} + +- (GTMSessionFetcherBodyStreamProvider)loggedStreamProviderForStreamProvider: + (GTMSessionFetcherBodyStreamProvider)streamProvider { + if (!streamProvider) return nil; + if (![GTMSessionFetcher isLoggingEnabled]) return streamProvider; + + [self clearLoggedStreamData]; // Clear any previous data. + Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); + if (!monitorClass) { + NSString const *str = @"<>"; + NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding]; + [self appendLoggedStreamData:stringData]; + return streamProvider; + } + GTMSessionFetcherBodyStreamProvider loggedStreamProvider = + ^(GTMSessionFetcherBodyStreamProviderResponse response) { + streamProvider(^(NSInputStream *bodyStream) { + bodyStream = [self loggedInputStreamForInputStream:bodyStream]; + response(bodyStream); + }); + }; + return loggedStreamProvider; +} + +@end + +@implementation GTMSessionFetcher (GTMSessionFetcherLoggingUtilities) + +- (void)inputStream:(GTMReadMonitorInputStream *)stream + readIntoBuffer:(void *)buffer + length:(int64_t)length { + // append the captured data + NSData *data = [NSData dataWithBytesNoCopy:buffer + length:(NSUInteger)length + freeWhenDone:NO]; + [self appendLoggedStreamData:data]; +} + +#pragma mark Fomatting Utilities + ++ (NSString *)snipSubstringOfString:(NSString *)originalStr + betweenStartString:(NSString *)startStr + endString:(NSString *)endStr { +#if SKIP_GTM_FETCH_LOGGING_SNIPPING + return originalStr; +#else + if (!originalStr) return nil; + + // Find the start string, and replace everything between it + // and the end string (or the end of the original string) with "_snip_" + NSRange startRange = [originalStr rangeOfString:startStr]; + if (startRange.location == NSNotFound) return originalStr; + + // We found the start string + NSUInteger originalLength = originalStr.length; + NSUInteger startOfTarget = NSMaxRange(startRange); + NSRange targetAndRest = NSMakeRange(startOfTarget, originalLength - startOfTarget); + NSRange endRange = [originalStr rangeOfString:endStr + options:0 + range:targetAndRest]; + NSRange replaceRange; + if (endRange.location == NSNotFound) { + // Found no end marker so replace to end of string + replaceRange = targetAndRest; + } else { + // Replace up to the endStr + replaceRange = NSMakeRange(startOfTarget, endRange.location - startOfTarget); + } + NSString *result = [originalStr stringByReplacingCharactersInRange:replaceRange + withString:@"_snip_"]; + return result; +#endif // SKIP_GTM_FETCH_LOGGING_SNIPPING +} + ++ (NSString *)headersStringForDictionary:(NSDictionary *)dict { + // Format the dictionary in http header style, like + // Accept: application/json + // Cache-Control: no-cache + // Content-Type: application/json; charset=utf-8 + // + // Pad the key names, but not beyond 16 chars, since long custom header + // keys just create too much whitespace + NSArray *keys = [dict.allKeys sortedArrayUsingSelector:@selector(compare:)]; + + NSMutableString *str = [NSMutableString string]; + for (NSString *key in keys) { + NSString *value = [dict valueForKey:key]; + if ([key isEqual:@"Authorization"]) { + // Remove OAuth 1 token + value = [[self class] snipSubstringOfString:value + betweenStartString:@"oauth_token=\"" + endString:@"\""]; + + // Remove OAuth 2 bearer token (draft 16, and older form) + value = [[self class] snipSubstringOfString:value + betweenStartString:@"Bearer " + endString:@"\n"]; + value = [[self class] snipSubstringOfString:value + betweenStartString:@"OAuth " + endString:@"\n"]; + + // Remove Google ClientLogin + value = [[self class] snipSubstringOfString:value + betweenStartString:@"GoogleLogin auth=" + endString:@"\n"]; + } + [str appendFormat:@" %@: %@\n", key, value]; + } + return str; +} + +@end + +#endif // !STRIP_GTM_FETCH_LOGGING diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h new file mode 100644 index 000000000..a696ac7e4 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.h @@ -0,0 +1,190 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// For best performance and convenient usage, fetchers should be generated by a common +// GTMSessionFetcherService instance, like +// +// _fetcherService = [[GTMSessionFetcherService alloc] init]; +// GTMSessionFetcher* myFirstFetcher = [_fetcherService fetcherWithRequest:request1]; +// GTMSessionFetcher* mySecondFetcher = [_fetcherService fetcherWithRequest:request2]; + +#import "GTMSessionFetcher.h" + +GTM_ASSUME_NONNULL_BEGIN + +// Notifications. + +// This notification indicates a reusable session has become invalid. It is intended mainly for the +// service's unit tests. +// +// The notification object is the fetcher service. +// The invalid session is provided via the userInfo kGTMSessionFetcherServiceSessionKey key. +extern NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification; +extern NSString *const kGTMSessionFetcherServiceSessionKey; + +@interface GTMSessionFetcherService : NSObject + +// Queues of delayed and running fetchers. Each dictionary contains arrays +// of GTMSessionFetcher *fetchers, keyed by NSString *host +@property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSArray *) *delayedFetchersByHost; +@property(atomic, strong, readonly, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, NSArray *) *runningFetchersByHost; + +// A max value of 0 means no fetchers should be delayed. +// The default limit is 10 simultaneous fetchers targeting each host. +// This does not apply to fetchers whose useBackgroundSession property is YES. Since services are +// not resurrected on an app relaunch, delayed fetchers would effectively be abandoned. +@property(atomic, assign) NSUInteger maxRunningFetchersPerHost; + +// Properties to be applied to each fetcher; see GTMSessionFetcher.h for descriptions +@property(atomic, strong, GTM_NULLABLE) NSURLSessionConfiguration *configuration; +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherConfigurationBlock configurationBlock; +@property(atomic, strong, GTM_NULLABLE) NSHTTPCookieStorage *cookieStorage; +@property(atomic, strong, GTM_NULL_RESETTABLE) dispatch_queue_t callbackQueue; +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherChallengeBlock challengeBlock; +@property(atomic, strong, GTM_NULLABLE) NSURLCredential *credential; +@property(atomic, strong) NSURLCredential *proxyCredential; +@property(atomic, copy, GTM_NULLABLE) GTM_NSArrayOf(NSString *) *allowedInsecureSchemes; +@property(atomic, assign) BOOL allowLocalhostRequest; +@property(atomic, assign) BOOL allowInvalidServerCertificates; +@property(atomic, assign, getter=isRetryEnabled) BOOL retryEnabled; +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherRetryBlock retryBlock; +@property(atomic, assign) NSTimeInterval maxRetryInterval; +@property(atomic, assign) NSTimeInterval minRetryInterval; +@property(atomic, copy, GTM_NULLABLE) GTM_NSDictionaryOf(NSString *, id) *properties; + +#if GTM_BACKGROUND_TASK_FETCHING +@property(atomic, assign) BOOL skipBackgroundTask; +#endif + +// A default useragent of GTMFetcherStandardUserAgentString(nil) will be given to each fetcher +// created by this service unless the request already has a user-agent header set. +// This default will be added starting with builds with the SDKs for OS X 10.11 and iOS 9. +// +// To use the configuration's default user agent, set this property to nil. +@property(atomic, copy, GTM_NULLABLE) NSString *userAgent; + +// The authorizer to attach to the created fetchers. If a specific fetcher should +// not authorize its requests, the fetcher's authorizer property may be set to nil +// before the fetch begins. +@property(atomic, strong, GTM_NULLABLE) id authorizer; + +// Delegate queue used by the session when calling back to the fetcher. The default +// is the main queue. Changing this does not affect the queue used to call back to the +// application; that is specified by the callbackQueue property above. +@property(atomic, strong, GTM_NULL_RESETTABLE) NSOperationQueue *sessionDelegateQueue; + +// When enabled, indicates the same session should be used by subsequent fetchers. +// +// This is enabled by default. +@property(atomic, assign) BOOL reuseSession; + +// Sets the delay until an unused session is invalidated. +// The default interval is 60 seconds. +// +// If the interval is set to 0, then any reused session is not invalidated except by +// explicitly invoking -resetSession. Be aware that setting the interval to 0 thus +// causes the session's delegate to be retained until the session is explicitly reset. +@property(atomic, assign) NSTimeInterval unusedSessionTimeout; + +// If shouldReuseSession is enabled, this will force creation of a new session when future +// fetchers begin. +- (void)resetSession; + +// Create a fetcher +// +// These methods will return a fetcher. If successfully created, the connection +// will hold a strong reference to it for the life of the connection as well. +// So the caller doesn't have to hold onto the fetcher explicitly unless they +// want to be able to monitor or cancel it. +- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request; +- (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL; +- (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString; + +// Common method for fetcher creation. +// +// -fetcherWithRequest:fetcherClass: may be overridden to customize creation of +// fetchers. This is the ONLY method in the GTMSessionFetcher library intended to +// be overridden. +- (id)fetcherWithRequest:(NSURLRequest *)request + fetcherClass:(Class)fetcherClass; + +- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher; + +- (NSUInteger)numberOfFetchers; // running + delayed fetchers +- (NSUInteger)numberOfRunningFetchers; +- (NSUInteger)numberOfDelayedFetchers; + +// Return a list of all running or delayed fetchers. This includes fetchers created +// by the service which have been started and have not yet stopped. +// +// Returns an array of fetcher objects, or nil if none. +- (GTM_NULLABLE GTM_NSArrayOf(GTMSessionFetcher *) *)issuedFetchers; + +// Search for running or delayed fetchers with the specified URL. +// +// Returns an array of fetcher objects found, or nil if none found. +- (GTM_NULLABLE GTM_NSArrayOf(GTMSessionFetcher *) *)issuedFetchersWithRequestURL:(NSURL *)requestURL; + +- (void)stopAllFetchers; + +// Methods for use by the fetcher class only. +- (GTM_NULLABLE NSURLSession *)session; +- (GTM_NULLABLE NSURLSession *)sessionForFetcherCreation; +- (GTM_NULLABLE id)sessionDelegate; +- (GTM_NULLABLE NSDate *)stoppedAllFetchersDate; + +// The testBlock can inspect its fetcher parameter's request property to +// determine which fetcher is being faked. +@property(atomic, copy, GTM_NULLABLE) GTMSessionFetcherTestBlock testBlock; + +@end + +@interface GTMSessionFetcherService (TestingSupport) + +// Convenience method to create a fetcher service for testing. +// +// Fetchers generated by this mock fetcher service will not perform any +// network operation, but will invoke callbacks and provide the supplied data +// or error to the completion handler. +// +// You can make more customized mocks by setting the test block property of the service +// or fetcher; the test block can inspect the fetcher's request or other properties. +// +// See the description of the testBlock property below. ++ (instancetype)mockFetcherServiceWithFakedData:(GTM_NULLABLE NSData *)fakedDataOrNil + fakedError:(GTM_NULLABLE NSError *)fakedErrorOrNil; + +// Spin the run loop and discard events (or, if not on the main thread, just sleep the thread) +// until all running and delayed fetchers have completed. +// +// This is only for use in testing or in tools without a user interface. +// +// Synchronous fetches should never be done by shipping apps; they are +// sufficient reason for rejection from the app store. +// +// Returns NO if timed out. +- (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds; + +@end + +@interface GTMSessionFetcherService (BackwardsCompatibilityOnly) + +// Clients using GTMSessionFetcher should set the cookie storage explicitly themselves. +// This method is just for compatibility with the old fetcher. +@property(atomic, assign) NSInteger cookieStorageMethod; + +@end + +GTM_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m new file mode 100644 index 000000000..fc6e6d964 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionFetcherService.m @@ -0,0 +1,1352 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMSessionFetcherService.h" + +NSString *const kGTMSessionFetcherServiceSessionBecameInvalidNotification + = @"kGTMSessionFetcherServiceSessionBecameInvalidNotification"; +NSString *const kGTMSessionFetcherServiceSessionKey + = @"kGTMSessionFetcherServiceSessionKey"; + +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMSessionFetcher (ServiceMethods) +- (BOOL)beginFetchMayDelay:(BOOL)mayDelay + mayAuthorize:(BOOL)mayAuthorize; +@end +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +@interface GTMSessionFetcherService () + +@property(atomic, strong, readwrite) NSDictionary *delayedFetchersByHost; +@property(atomic, strong, readwrite) NSDictionary *runningFetchersByHost; + +@end + +// Since NSURLSession doesn't support a separate delegate per task (!), instances of this +// class serve as a session delegate trampoline. +// +// This class maps a session's tasks to fetchers, and resends delegate messages to the task's +// fetcher. +@interface GTMSessionFetcherSessionDelegateDispatcher : NSObject + +// The session for the tasks in this dispatcher's task-to-fetcher map. +@property(atomic) NSURLSession *session; + +// The timer interval for invalidating a session that has no active tasks. +@property(atomic) NSTimeInterval discardInterval; + +// The current discard timer. +@property(atomic, readonly) NSTimer *discardTimer; + + +- (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService + sessionDiscardInterval:(NSTimeInterval)discardInterval; + +- (void)setFetcher:(GTMSessionFetcher *)fetcher + forTask:(NSURLSessionTask *)task; +- (void)removeFetcher:(GTMSessionFetcher *)fetcher; + +// Before using a session, tells the delegate dispatcher to stop the discard timer. +- (void)startSessionUsage; + +// When abandoning a delegate dispatcher, we want to avoid the session retaining +// the delegate after tasks complete. +- (void)abandon; + +@end + + +@implementation GTMSessionFetcherService { + NSMutableDictionary *_delayedFetchersByHost; + NSMutableDictionary *_runningFetchersByHost; + NSUInteger _maxRunningFetchersPerHost; + + // When this ivar is nil, the service will not reuse sessions. + GTMSessionFetcherSessionDelegateDispatcher *_delegateDispatcher; + + // Fetchers will wait on this if another fetcher is creating the shared NSURLSession. + dispatch_semaphore_t _sessionCreationSemaphore; + + dispatch_queue_t _callbackQueue; + NSOperationQueue *_delegateQueue; + NSHTTPCookieStorage *_cookieStorage; + NSString *_userAgent; + NSTimeInterval _timeout; + + NSURLCredential *_credential; // Username & password. + NSURLCredential *_proxyCredential; // Credential supplied to proxy servers. + + NSInteger _cookieStorageMethod; + + id _authorizer; + + // For waitForCompletionOfAllFetchersWithTimeout: we need to wait on stopped fetchers since + // they've not yet finished invoking their queued callbacks. This array is nil except when + // waiting on fetchers. + NSMutableArray *_stoppedFetchersToWaitFor; + + // For fetchers that enqueued their callbacks before stopAllFetchers was called on the service, + // set a barrier so the callbacks know to bail out. + NSDate *_stoppedAllFetchersDate; +} + +@synthesize maxRunningFetchersPerHost = _maxRunningFetchersPerHost, + configuration = _configuration, + configurationBlock = _configurationBlock, + cookieStorage = _cookieStorage, + userAgent = _userAgent, + challengeBlock = _challengeBlock, + credential = _credential, + proxyCredential = _proxyCredential, + allowedInsecureSchemes = _allowedInsecureSchemes, + allowLocalhostRequest = _allowLocalhostRequest, + allowInvalidServerCertificates = _allowInvalidServerCertificates, + retryEnabled = _retryEnabled, + retryBlock = _retryBlock, + maxRetryInterval = _maxRetryInterval, + minRetryInterval = _minRetryInterval, + properties = _properties, + unusedSessionTimeout = _unusedSessionTimeout, + testBlock = _testBlock; + +#if GTM_BACKGROUND_TASK_FETCHING +@synthesize skipBackgroundTask = _skipBackgroundTask; +#endif + +- (instancetype)init { + self = [super init]; + if (self) { + _delayedFetchersByHost = [[NSMutableDictionary alloc] init]; + _runningFetchersByHost = [[NSMutableDictionary alloc] init]; + _maxRunningFetchersPerHost = 10; + _cookieStorageMethod = -1; + _unusedSessionTimeout = 60.0; + _delegateDispatcher = + [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self + sessionDiscardInterval:_unusedSessionTimeout]; + _callbackQueue = dispatch_get_main_queue(); + + _delegateQueue = [[NSOperationQueue alloc] init]; + _delegateQueue.maxConcurrentOperationCount = 1; + _delegateQueue.name = @"com.google.GTMSessionFetcher.NSURLSessionDelegateQueue"; + + _sessionCreationSemaphore = dispatch_semaphore_create(1); + + // Starting with the SDKs for OS X 10.11/iOS 9, the service has a default useragent. + // Apps can remove this and get the default system "CFNetwork" useragent by setting the + // fetcher service's userAgent property to nil. +#if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_11) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_11) \ + || (TARGET_OS_IPHONE && defined(__IPHONE_9_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_9_0) + _userAgent = GTMFetcherStandardUserAgentString(nil); +#endif + } + return self; +} + +- (void)dealloc { + [self detachAuthorizer]; + [_delegateDispatcher abandon]; +} + +#pragma mark Generate a new fetcher + +// Clients may override this method. Clients should not override any other library methods. +- (id)fetcherWithRequest:(NSURLRequest *)request + fetcherClass:(Class)fetcherClass { + GTMSessionFetcher *fetcher = [[fetcherClass alloc] initWithRequest:request + configuration:self.configuration]; + fetcher.callbackQueue = self.callbackQueue; + fetcher.sessionDelegateQueue = self.sessionDelegateQueue; + fetcher.challengeBlock = self.challengeBlock; + fetcher.credential = self.credential; + fetcher.proxyCredential = self.proxyCredential; + fetcher.authorizer = self.authorizer; + fetcher.cookieStorage = self.cookieStorage; + fetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; + fetcher.allowLocalhostRequest = self.allowLocalhostRequest; + fetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates; + fetcher.configurationBlock = self.configurationBlock; + fetcher.retryEnabled = self.retryEnabled; + fetcher.retryBlock = self.retryBlock; + fetcher.maxRetryInterval = self.maxRetryInterval; + fetcher.minRetryInterval = self.minRetryInterval; + fetcher.properties = self.properties; + fetcher.service = self; + if (self.cookieStorageMethod >= 0) { + [fetcher setCookieStorageMethod:self.cookieStorageMethod]; + } + +#if GTM_BACKGROUND_TASK_FETCHING + fetcher.skipBackgroundTask = self.skipBackgroundTask; +#endif + + NSString *userAgent = self.userAgent; + if (userAgent.length > 0 + && [request valueForHTTPHeaderField:@"User-Agent"] == nil) { + [fetcher setRequestValue:userAgent + forHTTPHeaderField:@"User-Agent"]; + } + fetcher.testBlock = self.testBlock; + + return fetcher; +} + +- (GTMSessionFetcher *)fetcherWithRequest:(NSURLRequest *)request { + return [self fetcherWithRequest:request + fetcherClass:[GTMSessionFetcher class]]; +} + +- (GTMSessionFetcher *)fetcherWithURL:(NSURL *)requestURL { + return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; +} + +- (GTMSessionFetcher *)fetcherWithURLString:(NSString *)requestURLString { + NSURL *url = [NSURL URLWithString:requestURLString]; + return [self fetcherWithURL:url]; +} + +// Returns a session for the fetcher's host, or nil. +- (NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSURLSession *session = _delegateDispatcher.session; + return session; + } +} + +// Returns a session for the fetcher's host, or nil. For shared sessions, this +// waits on a semaphore, blocking other fetchers while the caller creates the +// session if needed. +- (NSURLSession *)sessionForFetcherCreation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + if (!_delegateDispatcher) { + // This fetcher is creating a non-shared session, so skip the semaphore usage. + return nil; + } + } + + // Wait if another fetcher is currently creating a session; avoid waiting + // inside the @synchronized block, as that can deadlock. + dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Before getting the NSURLSession for task creation, it is + // important to invalidate and nil out the session discard timer; otherwise + // the session can be invalidated between when it is returned to the + // fetcher, and when the fetcher attempts to create its NSURLSessionTask. + [_delegateDispatcher startSessionUsage]; + + NSURLSession *session = _delegateDispatcher.session; + if (session) { + // The calling fetcher will receive a preexisting session, so + // we can allow other fetchers to create a session. + dispatch_semaphore_signal(_sessionCreationSemaphore); + } else { + // No existing session was obtained, so the calling fetcher will create the session; + // it *must* invoke fetcherDidCreateSession: to signal the dispatcher's semaphore after + // the session has been created (or fails to be created) to avoid a hang. + } + return session; + } +} + +- (id)sessionDelegate { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateDispatcher; + } +} + +#pragma mark Queue Management + +- (void)addRunningFetcher:(GTMSessionFetcher *)fetcher + forHost:(NSString *)host { + // Add to the array of running fetchers for this host, creating the array if needed. + NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; + if (runningForHost == nil) { + runningForHost = [NSMutableArray arrayWithObject:fetcher]; + [_runningFetchersByHost setObject:runningForHost forKey:host]; + } else { + [runningForHost addObject:fetcher]; + } +} + +- (void)addDelayedFetcher:(GTMSessionFetcher *)fetcher + forHost:(NSString *)host { + // Add to the array of delayed fetchers for this host, creating the array if needed. + NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; + if (delayedForHost == nil) { + delayedForHost = [NSMutableArray arrayWithObject:fetcher]; + [_delayedFetchersByHost setObject:delayedForHost forKey:host]; + } else { + [delayedForHost addObject:fetcher]; + } +} + +- (BOOL)isDelayingFetcher:(GTMSessionFetcher *)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSString *host = fetcher.request.URL.host; + if (host == nil) { + return NO; + } + NSArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; + NSUInteger idx = [delayedForHost indexOfObjectIdenticalTo:fetcher]; + BOOL isDelayed = (delayedForHost != nil) && (idx != NSNotFound); + return isDelayed; + } +} + +- (BOOL)fetcherShouldBeginFetching:(GTMSessionFetcher *)fetcher { + // Entry point from the fetcher + NSURL *requestURL = fetcher.request.URL; + NSString *host = requestURL.host; + + // Addresses "file:///path" case where localhost is the implicit host. + if (host.length == 0 && [requestURL isFileURL]) { + host = @"localhost"; + } + + if (host.length == 0) { + // Data URIs legitimately have no host, reject other hostless URLs. + GTMSESSION_ASSERT_DEBUG([[requestURL scheme] isEqual:@"data"], @"%@ lacks host", fetcher); + return YES; + } + + BOOL shouldBeginResult; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; + if (runningForHost != nil + && [runningForHost indexOfObjectIdenticalTo:fetcher] != NSNotFound) { + GTMSESSION_ASSERT_DEBUG(NO, @"%@ was already running", fetcher); + return YES; + } + + BOOL shouldRunNow = (fetcher.usingBackgroundSession + || _maxRunningFetchersPerHost == 0 + || _maxRunningFetchersPerHost > + [[self class] numberOfNonBackgroundSessionFetchers:runningForHost]); + if (shouldRunNow) { + [self addRunningFetcher:fetcher forHost:host]; + shouldBeginResult = YES; + } else { + [self addDelayedFetcher:fetcher forHost:host]; + shouldBeginResult = NO; + } + } // @synchronized(self) + + // We'll save the host that serves as the key for this fetcher's array + // to avoid any chance of the underlying request changing, stranding + // the fetcher in the wrong array + fetcher.serviceHost = host; + + return shouldBeginResult; +} + +- (void)startFetcher:(GTMSessionFetcher *)fetcher { + [fetcher beginFetchMayDelay:NO + mayAuthorize:YES]; +} + +// Internal utility. Returns a fetcher's delegate if it's a dispatcher, or nil if the fetcher +// is its own delegate and has no dispatcher. +- (GTMSessionFetcherSessionDelegateDispatcher *)delegateDispatcherForFetcher:(GTMSessionFetcher *)fetcher { + GTMSessionCheckNotSynchronized(self); + + NSURLSession *fetcherSession = fetcher.session; + if (fetcherSession) { + id fetcherDelegate = fetcherSession.delegate; + BOOL hasDispatcher = (fetcherDelegate != nil && fetcherDelegate != fetcher); + if (hasDispatcher) { + GTMSESSION_ASSERT_DEBUG([fetcherDelegate isKindOfClass:[GTMSessionFetcherSessionDelegateDispatcher class]], + @"Fetcher delegate class: %@", [fetcherDelegate class]); + return (GTMSessionFetcherSessionDelegateDispatcher *)fetcherDelegate; + } + } + return nil; +} + +- (void)fetcherDidCreateSession:(GTMSessionFetcher *)fetcher { + if (fetcher.canShareSession) { + NSURLSession *fetcherSession = fetcher.session; + GTMSESSION_ASSERT_DEBUG(fetcherSession != nil, @"Fetcher missing its session: %@", fetcher); + + GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = + [self delegateDispatcherForFetcher:fetcher]; + if (delegateDispatcher) { + GTMSESSION_ASSERT_DEBUG(delegateDispatcher.session == nil, + @"Fetcher made an extra session: %@", fetcher); + + // Save this fetcher's session. + delegateDispatcher.session = fetcherSession; + + // Allow other fetchers to request this session now. + dispatch_semaphore_signal(_sessionCreationSemaphore); + } + } +} + +- (void)fetcherDidBeginFetching:(GTMSessionFetcher *)fetcher { + // If this fetcher has a separate delegate with a shared session, then + // this fetcher should be added to the delegate's map of tasks to fetchers. + GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = + [self delegateDispatcherForFetcher:fetcher]; + if (delegateDispatcher) { + GTMSESSION_ASSERT_DEBUG(fetcher.canShareSession, + @"Inappropriate shared session: %@", fetcher); + + // There should already be a session, from this or a previous fetcher. + // + // Sanity check that the fetcher's session is the delegate's shared session. + NSURLSession *sharedSession = delegateDispatcher.session; + NSURLSession *fetcherSession = fetcher.session; + GTMSESSION_ASSERT_DEBUG(sharedSession != nil, @"Missing delegate session: %@", fetcher); + GTMSESSION_ASSERT_DEBUG(fetcherSession == sharedSession, + @"Inconsistent session: %@ %@ (shared: %@)", + fetcher, fetcherSession, sharedSession); + + if (sharedSession != nil && fetcherSession == sharedSession) { + NSURLSessionTask *task = fetcher.sessionTask; + GTMSESSION_ASSERT_DEBUG(task != nil, @"Missing session task: %@", fetcher); + + if (task) { + [delegateDispatcher setFetcher:fetcher + forTask:task]; + } + } + } +} + +- (void)stopFetcher:(GTMSessionFetcher *)fetcher { + [fetcher stopFetching]; +} + +- (void)fetcherDidStop:(GTMSessionFetcher *)fetcher { + // Entry point from the fetcher + NSString *host = fetcher.serviceHost; + if (!host) { + // fetcher has been stopped previously + return; + } + + // This removeFetcher: invocation is a fallback; typically, fetchers are removed from the task + // map when the task completes. + GTMSessionFetcherSessionDelegateDispatcher *delegateDispatcher = + [self delegateDispatcherForFetcher:fetcher]; + [delegateDispatcher removeFetcher:fetcher]; + + NSMutableArray *fetchersToStart; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // If a test is waiting for all fetchers to stop, it needs to wait for this one + // to invoke its callbacks on the callback queue. + [_stoppedFetchersToWaitFor addObject:fetcher]; + + NSMutableArray *runningForHost = [_runningFetchersByHost objectForKey:host]; + [runningForHost removeObject:fetcher]; + + NSMutableArray *delayedForHost = [_delayedFetchersByHost objectForKey:host]; + [delayedForHost removeObject:fetcher]; + + while (delayedForHost.count > 0 + && [[self class] numberOfNonBackgroundSessionFetchers:runningForHost] + < _maxRunningFetchersPerHost) { + // Start another delayed fetcher running, scanning for the minimum + // priority value, defaulting to FIFO for equal priorities + GTMSessionFetcher *nextFetcher = nil; + for (GTMSessionFetcher *delayedFetcher in delayedForHost) { + if (nextFetcher == nil + || delayedFetcher.servicePriority < nextFetcher.servicePriority) { + nextFetcher = delayedFetcher; + } + } + + if (nextFetcher) { + [self addRunningFetcher:nextFetcher forHost:host]; + runningForHost = [_runningFetchersByHost objectForKey:host]; + + [delayedForHost removeObjectIdenticalTo:nextFetcher]; + + if (!fetchersToStart) { + fetchersToStart = [NSMutableArray array]; + } + [fetchersToStart addObject:nextFetcher]; + } + } + + if (runningForHost.count == 0) { + // None left; remove the empty array + [_runningFetchersByHost removeObjectForKey:host]; + } + + if (delayedForHost.count == 0) { + [_delayedFetchersByHost removeObjectForKey:host]; + } + } // @synchronized(self) + + // Start fetchers outside of the synchronized block to avoid a deadlock. + for (GTMSessionFetcher *nextFetcher in fetchersToStart) { + [self startFetcher:nextFetcher]; + } + + // The fetcher is no longer in the running or the delayed array, + // so remove its host and thread properties + fetcher.serviceHost = nil; +} + +- (NSUInteger)numberOfFetchers { + NSUInteger running = [self numberOfRunningFetchers]; + NSUInteger delayed = [self numberOfDelayedFetchers]; + return running + delayed; +} + +- (NSUInteger)numberOfRunningFetchers { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSUInteger sum = 0; + for (NSString *host in _runningFetchersByHost) { + NSArray *fetchers = [_runningFetchersByHost objectForKey:host]; + sum += fetchers.count; + } + return sum; + } +} + +- (NSUInteger)numberOfDelayedFetchers { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSUInteger sum = 0; + for (NSString *host in _delayedFetchersByHost) { + NSArray *fetchers = [_delayedFetchersByHost objectForKey:host]; + sum += fetchers.count; + } + return sum; + } +} + +- (NSArray *)issuedFetchers { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSMutableArray *allFetchers = [NSMutableArray array]; + void (^accumulateFetchers)(id, id, BOOL *) = ^(NSString *host, + NSArray *fetchersForHost, + BOOL *stop) { + [allFetchers addObjectsFromArray:fetchersForHost]; + }; + [_runningFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers]; + [_delayedFetchersByHost enumerateKeysAndObjectsUsingBlock:accumulateFetchers]; + + GTMSESSION_ASSERT_DEBUG(allFetchers.count == [NSSet setWithArray:allFetchers].count, + @"Fetcher appears multiple times\n running: %@\n delayed: %@", + _runningFetchersByHost, _delayedFetchersByHost); + + return allFetchers.count > 0 ? allFetchers : nil; + } +} + +- (NSArray *)issuedFetchersWithRequestURL:(NSURL *)requestURL { + NSString *host = requestURL.host; + if (host.length == 0) return nil; + + NSURL *targetURL = [requestURL absoluteURL]; + + NSArray *allFetchers = [self issuedFetchers]; + NSIndexSet *indexes = [allFetchers indexesOfObjectsPassingTest:^BOOL(GTMSessionFetcher *fetcher, + NSUInteger idx, + BOOL *stop) { + NSURL *fetcherURL = [fetcher.request.URL absoluteURL]; + return [fetcherURL isEqual:targetURL]; + }]; + + NSArray *result = nil; + if (indexes.count > 0) { + result = [allFetchers objectsAtIndexes:indexes]; + } + return result; +} + +- (void)stopAllFetchers { + NSArray *delayedFetchersByHost; + NSArray *runningFetchersByHost; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Set the time barrier so fetchers know not to call back even if + // the stop calls below occur after the fetchers naturally + // stopped and so were removed from _runningFetchersByHost, + // but while the callbacks were already enqueued before stopAllFetchers + // was invoked. + _stoppedAllFetchersDate = [[NSDate alloc] init]; + + // Remove fetchers from the delayed list to avoid fetcherDidStop: from + // starting more fetchers running as a side effect of stopping one + delayedFetchersByHost = _delayedFetchersByHost.allValues; + [_delayedFetchersByHost removeAllObjects]; + + runningFetchersByHost = _runningFetchersByHost.allValues; + [_runningFetchersByHost removeAllObjects]; + } + + for (NSArray *delayedForHost in delayedFetchersByHost) { + for (GTMSessionFetcher *fetcher in delayedForHost) { + [self stopFetcher:fetcher]; + } + } + + for (NSArray *runningForHost in runningFetchersByHost) { + for (GTMSessionFetcher *fetcher in runningForHost) { + [self stopFetcher:fetcher]; + } + } +} + +- (NSDate *)stoppedAllFetchersDate { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _stoppedAllFetchersDate; + } +} + +#pragma mark Accessors + +- (BOOL)reuseSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateDispatcher != nil; + } +} + +- (void)setReuseSession:(BOOL)shouldReuse { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + BOOL wasReusing = (_delegateDispatcher != nil); + if (shouldReuse != wasReusing) { + [self abandonDispatcher]; + if (shouldReuse) { + _delegateDispatcher = + [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self + sessionDiscardInterval:_unusedSessionTimeout]; + } else { + _delegateDispatcher = nil; + } + } + } +} + +- (void)resetSession { + GTMSessionCheckNotSynchronized(self); + dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + [self resetSessionInternal]; + } + + dispatch_semaphore_signal(_sessionCreationSemaphore); +} + +- (void)resetSessionInternal { + GTMSessionCheckSynchronized(self); + + // The old dispatchers may be retained as delegates of any ongoing sessions by those sessions. + if (_delegateDispatcher) { + [self abandonDispatcher]; + _delegateDispatcher = + [[GTMSessionFetcherSessionDelegateDispatcher alloc] initWithParentService:self + sessionDiscardInterval:_unusedSessionTimeout]; + } +} + +- (void)resetSessionForDispatcherDiscardTimer:(NSTimer *)timer { + GTMSessionCheckNotSynchronized(self); + + dispatch_semaphore_wait(_sessionCreationSemaphore, DISPATCH_TIME_FOREVER); + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_delegateDispatcher.discardTimer == timer) { + // If the delegate dispatcher's current discardTimer is the same object as the timer + // that fired, no fetcher has recently attempted to start using the session by calling + // startSessionUsage, which invalidates and nils out the timer. + [self resetSessionInternal]; + } else { + // A fetcher has invalidated the timer between its triggering and now, potentially + // meaning a fetcher has requested access to the NSURLSession, and may be in the process + // of starting a new task. The dispatcher should not be abandoned, as this can lead + // to a race condition between calling -finishTasksAndInvalidate on the NSURLSession + // and the fetcher attempting to create a new task. + } + } + + dispatch_semaphore_signal(_sessionCreationSemaphore); +} + +- (NSTimeInterval)unusedSessionTimeout { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _unusedSessionTimeout; + } +} + +- (void)setUnusedSessionTimeout:(NSTimeInterval)timeout { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _unusedSessionTimeout = timeout; + _delegateDispatcher.discardInterval = timeout; + } +} + +// This method should be called inside of @synchronized(self) +- (void)abandonDispatcher { + GTMSessionCheckSynchronized(self); + [_delegateDispatcher abandon]; +} + +- (NSDictionary *)runningFetchersByHost { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_runningFetchersByHost copy]; + } +} + +- (void)setRunningFetchersByHost:(NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _runningFetchersByHost = [dict mutableCopy]; + } +} + +- (NSDictionary *)delayedFetchersByHost { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_delayedFetchersByHost copy]; + } +} + +- (void)setDelayedFetchersByHost:(NSDictionary *)dict { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delayedFetchersByHost = [dict mutableCopy]; + } +} + +- (id)authorizer { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _authorizer; + } +} + +- (void)setAuthorizer:(id)obj { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (obj != _authorizer) { + [self detachAuthorizer]; + } + + _authorizer = obj; + } + + // Use the fetcher service for the authorization fetches if the auth + // object supports fetcher services + if ([obj respondsToSelector:@selector(setFetcherService:)]) { +#if GTM_USE_SESSION_FETCHER + [obj setFetcherService:self]; +#else + [obj setFetcherService:(id)self]; +#endif + } +} + +// This should be called inside a @synchronized(self) block except during dealloc. +- (void)detachAuthorizer { + // This method is called by the fetcher service's dealloc and setAuthorizer: + // methods; do not override. + // + // The fetcher service retains the authorizer, and the authorizer has a + // weak pointer to the fetcher service (a non-zeroing pointer for + // compatibility with iOS 4 and Mac OS X 10.5/10.6.) + // + // When this fetcher service no longer uses the authorizer, we want to remove + // the authorizer's dependence on the fetcher service. Authorizers can still + // function without a fetcher service. + if ([_authorizer respondsToSelector:@selector(fetcherService)]) { + id authFetcherService = [_authorizer fetcherService]; + if (authFetcherService == self) { + [_authorizer setFetcherService:nil]; + } + } +} + +- (dispatch_queue_t GTM_NONNULL_TYPE)callbackQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _callbackQueue; + } // @synchronized(self) +} + +- (void)setCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _callbackQueue = queue ?: dispatch_get_main_queue(); + } // @synchronized(self) +} + +- (NSOperationQueue * GTM_NONNULL_TYPE)sessionDelegateQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateQueue; + } // @synchronized(self) +} + +- (void)setSessionDelegateQueue:(NSOperationQueue * GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateQueue = queue ?: [NSOperationQueue mainQueue]; + } // @synchronized(self) +} + +- (NSOperationQueue *)delegateQueue { + // Provided for compatibility with the old fetcher service. The gtm-oauth2 code respects + // any custom delegate queue for calling the app. + return nil; +} + ++ (NSUInteger)numberOfNonBackgroundSessionFetchers:(NSArray *)fetchers { + NSUInteger sum = 0; + for (GTMSessionFetcher *fetcher in fetchers) { + if (!fetcher.usingBackgroundSession) { + ++sum; + } + } + return sum; +} + +@end + +@implementation GTMSessionFetcherService (TestingSupport) + ++ (instancetype)mockFetcherServiceWithFakedData:(NSData *)fakedDataOrNil + fakedError:(NSError *)fakedErrorOrNil { +#if !GTM_DISABLE_FETCHER_TEST_BLOCK + NSURL *url = [NSURL URLWithString:@"http://example.invalid"]; + NSHTTPURLResponse *fakedResponse = + [[NSHTTPURLResponse alloc] initWithURL:url + statusCode:(fakedErrorOrNil ? 500 : 200) + HTTPVersion:@"HTTP/1.1" + headerFields:nil]; + GTMSessionFetcherService *service = [[self alloc] init]; + service.allowedInsecureSchemes = @[ @"http" ]; + service.testBlock = ^(GTMSessionFetcher *fetcherToTest, + GTMSessionFetcherTestResponse testResponse) { + testResponse(fakedResponse, fakedDataOrNil, fakedErrorOrNil); + }; + return service; +#else + GTMSESSION_ASSERT_DEBUG(0, @"Test blocks disabled"); + return nil; +#endif // GTM_DISABLE_FETCHER_TEST_BLOCK +} + +#pragma mark Synchronous Wait for Unit Testing + +- (BOOL)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds { + NSDate *giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; + _stoppedFetchersToWaitFor = [NSMutableArray array]; + + BOOL shouldSpinRunLoop = [NSThread isMainThread]; + const NSTimeInterval kSpinInterval = 0.001; + BOOL didTimeOut = NO; + while (([self numberOfFetchers] > 0 || _stoppedFetchersToWaitFor.count > 0)) { + didTimeOut = [giveUpDate timeIntervalSinceNow] < 0; + if (didTimeOut) break; + + GTMSessionFetcher *stoppedFetcher = _stoppedFetchersToWaitFor.firstObject; + if (stoppedFetcher) { + [_stoppedFetchersToWaitFor removeObject:stoppedFetcher]; + [stoppedFetcher waitForCompletionWithTimeout:10.0 * kSpinInterval]; + } + + if (shouldSpinRunLoop) { + NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:kSpinInterval]; + [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; + } else { + [NSThread sleepForTimeInterval:kSpinInterval]; + } + } + _stoppedFetchersToWaitFor = nil; + + return !didTimeOut; +} + +@end + +@implementation GTMSessionFetcherService (BackwardsCompatibilityOnly) + +- (NSInteger)cookieStorageMethod { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _cookieStorageMethod; + } +} + +- (void)setCookieStorageMethod:(NSInteger)cookieStorageMethod { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _cookieStorageMethod = cookieStorageMethod; + } +} + +@end + +@implementation GTMSessionFetcherSessionDelegateDispatcher { + __weak GTMSessionFetcherService *_parentService; + NSURLSession *_session; + + // The task map maps NSURLSessionTasks to GTMSessionFetchers + NSMutableDictionary *_taskToFetcherMap; + // The discard timer will invalidate sessions after the session's last task completes. + NSTimer *_discardTimer; + NSTimeInterval _discardInterval; +} + +@synthesize discardInterval = _discardInterval, + session = _session; + +- (instancetype)init { + [self doesNotRecognizeSelector:_cmd]; + return nil; +} + +- (instancetype)initWithParentService:(GTMSessionFetcherService *)parentService + sessionDiscardInterval:(NSTimeInterval)discardInterval { + self = [super init]; + if (self) { + _discardInterval = discardInterval; + _parentService = parentService; + } + return self; +} + +- (NSString *)description { + return [NSString stringWithFormat:@"%@ %p %@ %@", + [self class], self, + _session ?: @"", + _taskToFetcherMap.count > 0 ? _taskToFetcherMap : @""]; +} + +- (NSTimer *)discardTimer { + GTMSessionCheckNotSynchronized(self); + @synchronized(self) { + return _discardTimer; + } +} + +// This method should be called inside of a @synchronized(self) block. +- (void)startDiscardTimer { + GTMSessionCheckSynchronized(self); + [_discardTimer invalidate]; + _discardTimer = nil; + if (_discardInterval > 0) { + _discardTimer = [NSTimer timerWithTimeInterval:_discardInterval + target:self + selector:@selector(discardTimerFired:) + userInfo:nil + repeats:NO]; + [_discardTimer setTolerance:(_discardInterval / 10)]; + [[NSRunLoop mainRunLoop] addTimer:_discardTimer forMode:NSRunLoopCommonModes]; + } +} + +// This method should be called inside of a @synchronized(self) block. +- (void)destroyDiscardTimer { + GTMSessionCheckSynchronized(self); + [_discardTimer invalidate]; + _discardTimer = nil; +} + +- (void)discardTimerFired:(NSTimer *)timer { + GTMSessionFetcherService *service; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + NSUInteger numberOfTasks = _taskToFetcherMap.count; + if (numberOfTasks == 0) { + service = _parentService; + } + } + + // Inform the service that the discard timer has fired, and should check whether the + // service can abandon us. -resetSession cannot be called directly, as there is a + // race condition that must be guarded against with the NSURLSession being returned + // from sessionForFetcherCreation outside other locks. The service can take steps + // to prevent resetting the session if that has occurred. + // + // The service must be called from outside the @synchronized block. + [service resetSessionForDispatcherDiscardTimer:timer]; +} + +- (void)abandon { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self destroySessionAndTimer]; + } +} + +- (void)startSessionUsage { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [self destroyDiscardTimer]; + } +} + +// This method should be called inside of a @synchronized(self) block. +- (void)destroySessionAndTimer { + GTMSessionCheckSynchronized(self); + [self destroyDiscardTimer]; + + // Break any retain cycle from the session holding the delegate. + [_session finishTasksAndInvalidate]; + + // Immediately clear the session so no new task may be issued with it. + // + // The _taskToFetcherMap needs to stay valid until the outstanding tasks finish. + _session = nil; +} + +- (void)setFetcher:(GTMSessionFetcher *)fetcher forTask:(NSURLSessionTask *)task { + GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"missing fetcher"); + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_taskToFetcherMap == nil) { + _taskToFetcherMap = [[NSMutableDictionary alloc] init]; + } + + if (fetcher) { + [_taskToFetcherMap setObject:fetcher forKey:task]; + [self destroyDiscardTimer]; + } + } +} + +- (void)removeFetcher:(GTMSessionFetcher *)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + // Typically, a fetcher should be removed when its task invokes + // URLSession:task:didCompleteWithError:. + // + // When fetching with a testBlock, though, the task completed delegate + // method may not be invoked, requiring cleanup here. + NSArray *tasks = [_taskToFetcherMap allKeysForObject:fetcher]; + GTMSESSION_ASSERT_DEBUG(tasks.count <= 1, @"fetcher task not unmapped: %@", tasks); + [_taskToFetcherMap removeObjectsForKeys:tasks]; + + if (_taskToFetcherMap.count == 0) { + [self startDiscardTimer]; + } + } +} + +// This helper method provides synchronized access to the task map for the delegate +// methods below. +- (id)fetcherForTask:(NSURLSessionTask *)task { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return [_taskToFetcherMap objectForKey:task]; + } +} + +- (void)removeTaskFromMap:(NSURLSessionTask *)task { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + [_taskToFetcherMap removeObjectForKey:task]; + } +} + +- (void)setSession:(NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _session = session; + } +} + +- (NSURLSession *)session { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _session; + } +} + +- (NSTimeInterval)discardInterval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _discardInterval; + } +} + +- (void)setDiscardInterval:(NSTimeInterval)interval { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _discardInterval = interval; + } +} + +// NSURLSessionDelegate protocol methods. + +// - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session; +// +// TODO(seh): How do we route this to an appropriate fetcher? + + +- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error { + GTM_LOG_SESSION_DELEGATE(@"%@ %p URLSession:%@ didBecomeInvalidWithError:%@", + [self class], self, session, error); + NSDictionary *localTaskToFetcherMap; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _session = nil; + + localTaskToFetcherMap = [_taskToFetcherMap copy]; + } + + // Any "suspended" tasks may not have received callbacks from NSURLSession when the session + // completes; we'll call them now. + [localTaskToFetcherMap enumerateKeysAndObjectsUsingBlock:^(NSURLSessionTask *task, + GTMSessionFetcher *fetcher, + BOOL *stop) { + if (fetcher.session == session) { + // Our delegate method URLSession:task:didCompleteWithError: will rely on + // _taskToFetcherMap so that should still contain this fetcher. + NSError *canceledError = [NSError errorWithDomain:NSURLErrorDomain + code:NSURLErrorCancelled + userInfo:nil]; + [self URLSession:session task:task didCompleteWithError:canceledError]; + } else { + GTMSESSION_ASSERT_DEBUG(0, @"Unexpected session in fetcher: %@ has %@ (expected %@)", + fetcher, fetcher.session, session); + } + }]; + + // Our tests rely on this notification to know the session discard timer fired. + NSDictionary *userInfo = @{ kGTMSessionFetcherServiceSessionKey : session }; + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc postNotificationName:kGTMSessionFetcherServiceSessionBecameInvalidNotification + object:_parentService + userInfo:userInfo]; +} + + +#pragma mark - NSURLSessionTaskDelegate + +// NSURLSessionTaskDelegate protocol methods. +// +// We won't test here if the fetcher responds to these since we only want this +// class to implement the same delegate methods the fetcher does (so NSURLSession's +// tests for respondsToSelector: will have the same result whether the session +// delegate is the fetcher or this dispatcher.) + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task +willPerformHTTPRedirection:response + newRequest:request + completionHandler:completionHandler]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge + completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))handler { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task + didReceiveChallenge:challenge + completionHandler:handler]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + needNewBodyStream:(void (^)(NSInputStream *bodyStream))handler { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task + needNewBodyStream:handler]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent +totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { + id fetcher = [self fetcherForTask:task]; + [fetcher URLSession:session + task:task + didSendBodyData:bytesSent + totalBytesSent:totalBytesSent +totalBytesExpectedToSend:totalBytesExpectedToSend]; +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +didCompleteWithError:(NSError *)error { + id fetcher = [self fetcherForTask:task]; + + // This is the usual way tasks are removed from the task map. + [self removeTaskFromMap:task]; + + [fetcher URLSession:session + task:task + didCompleteWithError:error]; +} + +// NSURLSessionDataDelegate protocol methods. + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didReceiveResponse:(NSURLResponse *)response + completionHandler:(void (^)(NSURLSessionResponseDisposition))handler { + id fetcher = [self fetcherForTask:dataTask]; + [fetcher URLSession:session + dataTask:dataTask + didReceiveResponse:response + completionHandler:handler]; +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask +didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask { + id fetcher = [self fetcherForTask:dataTask]; + GTMSESSION_ASSERT_DEBUG(fetcher != nil, @"Missing fetcher for %@", dataTask); + [self removeTaskFromMap:dataTask]; + if (fetcher) { + GTMSESSION_ASSERT_DEBUG([fetcher isKindOfClass:[GTMSessionFetcher class]], + @"Expecting GTMSessionFetcher"); + [self setFetcher:(GTMSessionFetcher *)fetcher forTask:downloadTask]; + } + + [fetcher URLSession:session + dataTask:dataTask +didBecomeDownloadTask:downloadTask]; +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + didReceiveData:(NSData *)data { + id fetcher = [self fetcherForTask:dataTask]; + [fetcher URLSession:session + dataTask:dataTask + didReceiveData:data]; +} + +- (void)URLSession:(NSURLSession *)session + dataTask:(NSURLSessionDataTask *)dataTask + willCacheResponse:(NSCachedURLResponse *)proposedResponse + completionHandler:(void (^)(NSCachedURLResponse *))handler { + id fetcher = [self fetcherForTask:dataTask]; + [fetcher URLSession:session + dataTask:dataTask + willCacheResponse:proposedResponse + completionHandler:handler]; +} + +// NSURLSessionDownloadDelegate protocol methods. + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask +didFinishDownloadingToURL:(NSURL *)location { + id fetcher = [self fetcherForTask:downloadTask]; + [fetcher URLSession:session + downloadTask:downloadTask +didFinishDownloadingToURL:location]; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didWriteData:(int64_t)bytesWritten + totalBytesWritten:(int64_t)totalWritten +totalBytesExpectedToWrite:(int64_t)totalExpected { + id fetcher = [self fetcherForTask:downloadTask]; + [fetcher URLSession:session + downloadTask:downloadTask + didWriteData:bytesWritten + totalBytesWritten:totalWritten +totalBytesExpectedToWrite:totalExpected]; +} + +- (void)URLSession:(NSURLSession *)session + downloadTask:(NSURLSessionDownloadTask *)downloadTask + didResumeAtOffset:(int64_t)fileOffset +expectedTotalBytes:(int64_t)expectedTotalBytes { + id fetcher = [self fetcherForTask:downloadTask]; + [fetcher URLSession:session + downloadTask:downloadTask + didResumeAtOffset:fileOffset + expectedTotalBytes:expectedTotalBytes]; +} + +@end diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h new file mode 100644 index 000000000..51372f2fd --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.h @@ -0,0 +1,128 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// GTMSessionUploadFetcher implements Google's resumable upload protocol. + +// +// This subclass of GTMSessionFetcher simulates the series of fetches +// needed for chunked upload as a single fetch operation. +// +// Protocol document: TBD +// +// To the client, the only fetcher that exists is this class; the subsidiary +// fetchers needed for uploading chunks are not visible (though the most recent +// chunk fetcher may be accessed via the -activeFetcher or -chunkFetcher methods, and +// -responseHeaders and -statusCode reflect results from the most recent chunk +// fetcher.) +// +// Chunk fetchers are discarded as soon as they have completed. +// + +// Note: Unlike the fetcher superclass, the methods of GTMSessionUploadFetcher should +// only be used from the main thread until further work is done to make this subclass +// thread-safe. + +#import "GTMSessionFetcher.h" +#import "GTMSessionFetcherService.h" + +GTM_ASSUME_NONNULL_BEGIN + +// Unless an application knows it needs a smaller chunk size, it should use the standard +// chunk size, which sends the entire file as a single chunk to minimize upload overhead. +extern int64_t const kGTMSessionUploadFetcherStandardChunkSize; + +// When uploading requires data buffer allocations (such as uploading from an NSData or +// an NSFileHandle) this is the maximum buffer size that will be created by the fetcher. +extern int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize; + +// Notification that the upload location URL was provided by the server. +extern NSString *const kGTMSessionFetcherUploadLocationObtainedNotification; + +// Block to provide data during uploads. +// +// Response data may be allocated with dataWithBytesNoCopy:length:freeWhenDone: for efficiency, +// and released after the response block returns. +// +// Pass nil as the data (and optionally an NSError) for a failure. +typedef void (^GTMSessionUploadFetcherDataProviderResponse)(NSData * GTM_NULLABLE_TYPE data, + NSError * GTM_NULLABLE_TYPE error); +typedef void (^GTMSessionUploadFetcherDataProvider)(int64_t offset, int64_t length, + GTMSessionUploadFetcherDataProviderResponse response); + +@interface GTMSessionUploadFetcher : GTMSessionFetcher + +// Create an upload fetcher specifying either the request or the resume location URL, +// then set an upload data source using one of these: +// +// setUploadFileURL: +// setUploadDataLength:provider: +// setUploadFileHandle: +// setUploadData: + ++ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil; + ++ (instancetype)uploadFetcherWithLocation:(NSURL * GTM_NULLABLE_TYPE)uploadLocationURL + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTM_NULLABLE GTMSessionFetcherService *)fetcherServiceOrNil; + +- (void)setUploadDataLength:(int64_t)fullLength + provider:(GTM_NULLABLE GTMSessionUploadFetcherDataProvider)block; + ++ (NSArray *)uploadFetchersForBackgroundSessions; ++ (GTM_NULLABLE instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier; + +- (void)pauseFetching; +- (void)resumeFetching; +- (BOOL)isPaused; + +@property(atomic, strong, GTM_NULLABLE) NSURL *uploadLocationURL; +@property(atomic, strong, GTM_NULLABLE) NSData *uploadData; +@property(atomic, strong, GTM_NULLABLE) NSURL *uploadFileURL; +@property(atomic, strong, GTM_NULLABLE) NSFileHandle *uploadFileHandle; +@property(atomic, copy, readonly, GTM_NULLABLE) GTMSessionUploadFetcherDataProvider uploadDataProvider; +@property(atomic, copy) NSString *uploadMIMEType; +@property(atomic, assign) int64_t chunkSize; +@property(atomic, readonly, assign) int64_t currentOffset; + +// The fetcher for the current data chunk, if any +@property(atomic, strong, GTM_NULLABLE) GTMSessionFetcher *chunkFetcher; + +// The active fetcher is the current chunk fetcher, or the upload fetcher itself +// if no chunk fetcher has yet been created. +@property(atomic, readonly) GTMSessionFetcher *activeFetcher; + +// The last request made by an active fetcher. Useful for testing. +@property(atomic, readonly, GTM_NULLABLE) NSURLRequest *lastChunkRequest; + +// The status code from the most recently-completed fetch. +@property(atomic, assign) NSInteger statusCode; + +// Exposed for testing only. +@property(atomic, readonly, GTM_NULLABLE) dispatch_queue_t delegateCallbackQueue; +@property(atomic, readonly, GTM_NULLABLE) GTMSessionFetcherCompletionHandler delegateCompletionHandler; + +@end + +@interface GTMSessionFetcher (GTMSessionUploadFetcherMethods) + +@property(readonly, GTM_NULLABLE) GTMSessionUploadFetcher *parentUploadFetcher; + +@end + +GTM_ASSUME_NONNULL_END diff --git a/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m new file mode 100644 index 000000000..a5ae0dcd6 --- /dev/null +++ b/Paco-iOS/Pods/GTMSessionFetcher/Source/GTMSessionUploadFetcher.m @@ -0,0 +1,1804 @@ +/* Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#if !defined(__has_feature) || !__has_feature(objc_arc) +#error "This file requires ARC support." +#endif + +#import "GTMSessionUploadFetcher.h" + +static NSString *const kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey = @"_upChunk"; +static NSString *const kGTMSessionIdentifierUploadFileURLMetadataKey = @"_upFileURL"; +static NSString *const kGTMSessionIdentifierUploadFileLengthMetadataKey = @"_upFileLen"; +static NSString *const kGTMSessionIdentifierUploadLocationURLMetadataKey = @"_upLocURL"; +static NSString *const kGTMSessionIdentifierUploadMIMETypeMetadataKey = @"_uploadMIME"; +static NSString *const kGTMSessionIdentifierUploadChunkSizeMetadataKey = @"_upChSize"; +static NSString *const kGTMSessionIdentifierUploadCurrentOffsetMetadataKey = @"_upOffset"; + +static NSString *const kGTMSessionHeaderXGoogUploadChunkGranularity = @"X-Goog-Upload-Chunk-Granularity"; +static NSString *const kGTMSessionHeaderXGoogUploadCommand = @"X-Goog-Upload-Command"; +static NSString *const kGTMSessionHeaderXGoogUploadContentLength = @"X-Goog-Upload-Content-Length"; +static NSString *const kGTMSessionHeaderXGoogUploadContentType = @"X-Goog-Upload-Content-Type"; +static NSString *const kGTMSessionHeaderXGoogUploadOffset = @"X-Goog-Upload-Offset"; +static NSString *const kGTMSessionHeaderXGoogUploadProtocol = @"X-Goog-Upload-Protocol"; +static NSString *const kGTMSessionHeaderXGoogUploadSizeReceived = @"X-Goog-Upload-Size-Received"; +static NSString *const kGTMSessionHeaderXGoogUploadStatus = @"X-Goog-Upload-Status"; +static NSString *const kGTMSessionHeaderXGoogUploadURL = @"X-Goog-Upload-URL"; + +// Property of chunk fetchers identifying the parent upload fetcher. Non-retained NSValue. +static NSString *const kGTMSessionUploadFetcherChunkParentKey = @"_uploadFetcherChunkParent"; + +int64_t const kGTMSessionUploadFetcherStandardChunkSize = (int64_t)LLONG_MAX; + +#if TARGET_OS_IPHONE +int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 10 * 1024 * 1024; // 10 MB for iOS, watchOS, tvOS +#else +int64_t const kGTMSessionUploadFetcherMaximumDemandBufferSize = 100 * 1024 * 1024; // 100 MB for macOS +#endif + +typedef NS_ENUM(NSUInteger, GTMSessionUploadFetcherStatus) { + kStatusUnknown, + kStatusActive, + kStatusFinal, + kStatusCancelled, +}; + +NSString *const kGTMSessionFetcherUploadLocationObtainedNotification = + @"kGTMSessionFetcherUploadLocationObtainedNotification"; + +#if !GTMSESSION_BUILD_COMBINED_SOURCES +@interface GTMSessionFetcher (ProtectedMethods) + +// Access to non-public method on the parent fetcher class. +- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks; +- (void)createSessionIdentifierWithMetadata:(NSDictionary *)metadata; +- (GTMSessionFetcherCompletionHandler)completionHandlerWithTarget:(id)target + didFinishSelector:(SEL)finishedSelector; +- (void)invokeOnCallbackQueue:(dispatch_queue_t)callbackQueue + afterUserStopped:(BOOL)afterStopped + block:(void (^)(void))block; +- (NSTimer *)retryTimer; + +@property(readwrite, strong) NSData *downloadedData; +- (void)releaseCallbacks; + +- (NSInteger)statusCodeUnsynchronized; + +@end +#endif // !GTMSESSION_BUILD_COMBINED_SOURCES + +@interface GTMSessionUploadFetcher () + +// Changing readonly to readwrite. +@property(atomic, strong, readwrite) NSURLRequest *lastChunkRequest; +@property(atomic, readwrite, assign) int64_t currentOffset; + +// Internal properties. +@property(strong, atomic, GTM_NULLABLE) GTMSessionFetcher *fetcherInFlight; // Synchronized on self. + +@property(assign, atomic, getter=isSubdataGenerating) BOOL subdataGenerating; +@property(assign, atomic) BOOL shouldInitiateOffsetQuery; +@property(assign, atomic) int64_t uploadGranularity; + +@end + +@implementation GTMSessionUploadFetcher { + GTMSessionFetcher *_chunkFetcher; + + // We'll call through to the delegate's completion handler. + GTMSessionFetcherCompletionHandler _delegateCompletionHandler; + dispatch_queue_t _delegateCallbackQueue; + + // The initial fetch's body length and bytes actually sent are + // needed for calculating progress during subsequent chunk uploads + int64_t _initialBodyLength; + int64_t _initialBodySent; + + // The upload server address for the chunks of this upload session. + NSURL *_uploadLocationURL; + + // _uploadData, _uploadDataProvider, or _uploadFileHandle may be set, but only one. + NSData *_uploadData; + NSFileHandle *_uploadFileHandle; + GTMSessionUploadFetcherDataProvider _uploadDataProvider; + NSURL *_uploadFileURL; + int64_t _uploadFileLength; + NSString *_uploadMIMEType; + int64_t _chunkSize; + int64_t _uploadGranularity; + BOOL _isPaused; + BOOL _isRestartedUpload; + BOOL _shouldInitiateOffsetQuery; + + // Tied to useBackgroundSession property, since this property is applicable to chunk fetchers. + BOOL _useBackgroundSessionOnChunkFetchers; + + // We keep the latest offset into the upload data just for progress reporting. + int64_t _currentOffset; + + NSDictionary *_recentChunkReponseHeaders; + NSInteger _recentChunkStatusCode; + + // For waiting, we need to know the fetcher in flight, if any, and if subdata generation + // is in progress. + GTMSessionFetcher *_fetcherInFlight; + BOOL _isSubdataGenerating; +} + ++ (void)load { + [self uploadFetchersForBackgroundSessions]; +} + ++ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTMSessionFetcherService *)fetcherService { + GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:request + fetcherService:fetcherService]; + [fetcher setLocationURL:nil + uploadMIMEType:uploadMIMEType + chunkSize:chunkSize]; + return fetcher; +} + ++ (instancetype)uploadFetcherWithLocation:(NSURL * GTM_NULLABLE_TYPE)uploadLocationURL + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize + fetcherService:(GTMSessionFetcherService *)fetcherService { + GTMSessionUploadFetcher *fetcher = [self uploadFetcherWithRequest:nil + fetcherService:fetcherService]; + [fetcher setLocationURL:uploadLocationURL + uploadMIMEType:uploadMIMEType + chunkSize:chunkSize]; + return fetcher; +} + ++ (instancetype)uploadFetcherForSessionIdentifierMetadata:(NSDictionary *)metadata { + GTMSESSION_ASSERT_DEBUG( + [metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue], + @"Session identifier metadata is not for an upload fetcher: %@", metadata); + + NSNumber *uploadFileLengthNum = metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey]; + GTMSESSION_ASSERT_DEBUG(uploadFileLengthNum != nil, + @"Session metadata missing an UploadFileSize"); + if (uploadFileLengthNum == nil) return nil; + + int64_t uploadFileLength = [uploadFileLengthNum longLongValue]; + GTMSESSION_ASSERT_DEBUG(uploadFileLength >= 0, @"Session metadata UploadFileSize is unknown"); + + NSString *uploadFileURLString = metadata[kGTMSessionIdentifierUploadFileURLMetadataKey]; + GTMSESSION_ASSERT_DEBUG(uploadFileURLString, @"Session metadata missing an UploadFileURL"); + if (uploadFileURLString == nil) return nil; + + NSURL *uploadFileURL = [NSURL URLWithString:uploadFileURLString]; + // There used to be a call here to NSURL checkResourceIsReachableAndReturnError: to check for the + // existence of the file (also tried NSFileManager fileExistsAtPath:). We've determined + // empirically that the check can fail at startup even when the upload file does in fact exist. + // For now, we'll go ahead and restore the background upload fetcher. If the file doesn't exist, + // it will fail later. + + NSString *uploadLocationURLString = metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey]; + NSURL *uploadLocationURL = + uploadLocationURLString ? [NSURL URLWithString:uploadLocationURLString] : nil; + + NSString *uploadMIMEType = + metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey]; + int64_t uploadChunkSize = + [metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] longLongValue]; + if (uploadChunkSize <= 0) { + uploadChunkSize = kGTMSessionUploadFetcherStandardChunkSize; + } + int64_t currentOffset = + [metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] longLongValue]; + GTMSESSION_ASSERT_DEBUG(currentOffset <= uploadFileLength, + @"CurrentOffset (%lld) exceeds UploadFileSize (%lld)", + currentOffset, uploadFileLength); + if (currentOffset > uploadFileLength) return nil; + + GTMSessionUploadFetcher *uploadFetcher = [self uploadFetcherWithLocation:uploadLocationURL + uploadMIMEType:uploadMIMEType + chunkSize:uploadChunkSize + fetcherService:nil]; + // Set the upload file length before setting the upload file URL tries to determine the length. + [uploadFetcher setUploadFileLength:uploadFileLength]; + + uploadFetcher.uploadFileURL = uploadFileURL; + uploadFetcher.sessionUserInfo = metadata; + uploadFetcher.useBackgroundSession = YES; + uploadFetcher.currentOffset = currentOffset; + uploadFetcher.allowedInsecureSchemes = @[ @"http" ]; // Allowed on restored upload fetcher. + return uploadFetcher; +} + ++ (instancetype)uploadFetcherWithRequest:(NSURLRequest *)request + fetcherService:(GTMSessionFetcherService *)fetcherService { + // Internal utility method for instantiating fetchers + GTMSessionUploadFetcher *fetcher; + if ([fetcherService isKindOfClass:[GTMSessionFetcherService class]]) { + fetcher = [fetcherService fetcherWithRequest:request + fetcherClass:self]; + } else { + fetcher = [self fetcherWithRequest:request]; + } + fetcher.useBackgroundSession = YES; + return fetcher; +} + ++ (NSPointerArray *)uploadFetcherPointerArrayForBackgroundSessions { + static NSPointerArray *gUploadFetcherPointerArrayForBackgroundSessions = nil; + + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + gUploadFetcherPointerArrayForBackgroundSessions = [NSPointerArray weakObjectsPointerArray]; + }); + return gUploadFetcherPointerArrayForBackgroundSessions; +} + ++ (instancetype)uploadFetcherForSessionIdentifier:(NSString *)sessionIdentifier { + GTMSESSION_ASSERT_DEBUG(sessionIdentifier != nil, @"Invalid session identifier"); + NSArray *uploadFetchersForBackgroundSessions = [self uploadFetchersForBackgroundSessions]; + for (GTMSessionUploadFetcher *uploadFetcher in uploadFetchersForBackgroundSessions) { + if ([uploadFetcher.chunkFetcher.sessionIdentifier isEqual:sessionIdentifier]) { + return uploadFetcher; + } + } + return nil; +} + ++ (NSArray *)uploadFetchersForBackgroundSessions { + // Collect the background session upload fetchers that are still in memory. + NSPointerArray *uploadFetcherPointerArray = [self uploadFetcherPointerArrayForBackgroundSessions]; + [uploadFetcherPointerArray compact]; + NSMutableSet *restoredSessionIdentifiers = [[NSMutableSet alloc] init]; + NSMutableArray *uploadFetchers = [[NSMutableArray alloc] init]; + for (GTMSessionUploadFetcher *uploadFetcher in uploadFetcherPointerArray) { + NSString *sessionIdentifier = uploadFetcher.chunkFetcher.sessionIdentifier; + if (sessionIdentifier) { + [restoredSessionIdentifiers addObject:sessionIdentifier]; + [uploadFetchers addObject:uploadFetcher]; + } + } + + // The system may have other ongoing background upload sessions. Restore upload fetchers for those + // too. + NSArray *fetchers = [GTMSessionFetcher fetchersForBackgroundSessions]; + for (GTMSessionFetcher *fetcher in fetchers) { + NSString *sessionIdentifier = fetcher.sessionIdentifier; + if (!sessionIdentifier || [restoredSessionIdentifiers containsObject:sessionIdentifier]) { + continue; + } + NSDictionary *sessionIdentifierMetadata = [fetcher sessionIdentifierMetadata]; + if (sessionIdentifierMetadata == nil) { + continue; + } + if (![sessionIdentifierMetadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] boolValue]) { + continue; + } + GTMSessionUploadFetcher *uploadFetcher = + [self uploadFetcherForSessionIdentifierMetadata:sessionIdentifierMetadata]; + if (uploadFetcher == nil) { + // Something went wrong with this upload fetcher, so kill the restored chunk fetcher. + [fetcher stopFetching]; + continue; + } + [uploadFetchers addObject:uploadFetcher]; + uploadFetcher->_chunkFetcher = fetcher; + uploadFetcher->_fetcherInFlight = fetcher; + [uploadFetcher attachSendProgressBlockToChunkFetcher:fetcher]; + fetcher.completionHandler = + [fetcher completionHandlerWithTarget:uploadFetcher + didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; + + GTMSESSION_LOG_DEBUG(@"%@ restoring upload fetcher %@ for chunk fetcher %@", + [self class], uploadFetcher, fetcher); + } + return uploadFetchers; +} + +- (void)setUploadData:(NSData *)data { + BOOL changed = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadData != data) { + _uploadData = data; + changed = YES; + } + } + if (changed) { + [self setupRequestHeaders]; + } +} + +- (NSData *)uploadData { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadData; + } +} + +- (void)setUploadFileHandle:(NSFileHandle *)fh { + BOOL changed = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadFileHandle != fh) { + _uploadFileHandle = fh; + changed = YES; + } + } + if (changed) { + [self setupRequestHeaders]; + } +} + +- (NSFileHandle *)uploadFileHandle { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadFileHandle; + } +} + +- (void)setUploadFileURL:(NSURL *)uploadURL { + BOOL changed = NO; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadFileURL != uploadURL) { + _uploadFileURL = uploadURL; + changed = YES; + } + } + if (changed) { + [self setupRequestHeaders]; + } +} + +- (NSURL *)uploadFileURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadFileURL; + } +} + +- (void)setUploadFileLength:(int64_t)fullLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadFileLength = fullLength; + } +} + +- (void)setUploadDataLength:(int64_t)fullLength + provider:(GTMSessionUploadFetcherDataProvider)block { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadDataProvider = [block copy]; + _uploadFileLength = fullLength; + } + [self setupRequestHeaders]; +} + +- (GTMSessionUploadFetcherDataProvider)uploadDataProvider { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadDataProvider; + } +} + + +- (void)setUploadMIMEType:(NSString *)uploadMIMEType { + GTMSESSION_ASSERT_DEBUG(0, @"TODO: disallow setUploadMIMEType by making declaration readonly"); + // (and uploadMIMEType, chunksize, currentOffset) + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadMIMEType = uploadMIMEType; + } +} + +- (NSString *)uploadMIMEType { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadMIMEType; + } +} + +- (void)setChunkSize:(int64_t)chunkSize { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _chunkSize = chunkSize; + } +} + +- (int64_t)chunkSize { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _chunkSize; + } +} + +- (void)setupRequestHeaders { + GTMSessionCheckNotSynchronized(self); + +#if DEBUG + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + int hasData = (_uploadData != nil) ? 1 : 0; + int hasFileHandle = (_uploadFileHandle != nil) ? 1 : 0; + int hasFileURL = (_uploadFileURL != nil) ? 1 : 0; + int hasUploadDataProvider = (_uploadDataProvider != nil) ? 1 : 0; + int numberOfSources = hasData + hasFileHandle + hasFileURL + hasUploadDataProvider; + #pragma unused(numberOfSources) + GTMSESSION_ASSERT_DEBUG(numberOfSources == 1, + @"Need just one upload source (%d)", numberOfSources); + } // @synchronized(self) +#endif + + // Add our custom headers to the initial request indicating the data + // type and total size to be delivered later in the chunk requests. + NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; + + GTMSESSION_ASSERT_DEBUG((mutableRequest == nil) != (_uploadLocationURL == nil), + @"Request and location are mutually exclusive"); + if (!mutableRequest) return; + + NSNumber *lengthNum = @([self fullUploadLength]); + [mutableRequest setValue:@"resumable" + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadProtocol]; + [mutableRequest setValue:@"start" + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + [mutableRequest setValue:_uploadMIMEType + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentType]; + [mutableRequest setValue:lengthNum.stringValue + forHTTPHeaderField:kGTMSessionHeaderXGoogUploadContentLength]; + + NSString *method = mutableRequest.HTTPMethod; + if (method == nil || [method caseInsensitiveCompare:@"GET"] == NSOrderedSame) { + [mutableRequest setHTTPMethod:@"POST"]; + } + + // Ensure the user agent header identifies this to the upload server as a + // GTMSessionUploadFetcher client. The /1 can be incremented in the unlikely circumstance + // we need to make a bug fix in the client that the server can recognize. + NSString *const kUserAgentStub = @"(GTMSUF/1)"; + NSString *userAgent = [mutableRequest valueForHTTPHeaderField:@"User-Agent"]; + if (userAgent == nil + || [userAgent rangeOfString:kUserAgentStub].location == NSNotFound) { + if (userAgent.length == 0) { + userAgent = GTMFetcherStandardUserAgentString(nil); + } + userAgent = [userAgent stringByAppendingFormat:@" %@", kUserAgentStub]; + [mutableRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + [self setRequest:mutableRequest]; +} + +- (void)setLocationURL:(NSURL * GTM_NULLABLE_TYPE)location + uploadMIMEType:(NSString *)uploadMIMEType + chunkSize:(int64_t)chunkSize { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + GTMSESSION_ASSERT_DEBUG(chunkSize > 0, @"chunk size is zero"); + + // When resuming an upload, set the known upload target URL. + _uploadLocationURL = location; + + _uploadMIMEType = uploadMIMEType; + _chunkSize = chunkSize; + + // Indicate that we've not yet determined the file handle's length + _uploadFileLength = -1; + + // Indicate that we've not yet determined the upload fetcher status + _recentChunkStatusCode = -1; + + // If this is restarting an upload begun by another fetcher, + // the location is specified but the request is nil + _isRestartedUpload = (location != nil); + } // @synchronized(self) +} + +- (int64_t)fullUploadLength { + int64_t result; + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_uploadData) { + result = (int64_t)_uploadData.length; + } else { + if (_uploadFileLength == -1) { + if (_uploadFileHandle) { + // First time through, seek to end to determine file length + _uploadFileLength = (int64_t)[_uploadFileHandle seekToEndOfFile]; + } else if (_uploadDataProvider) { + // _uploadFileLength is set when the _uploadDataProvider is set. + GTMSESSION_ASSERT_DEBUG(_uploadFileLength >= 0, @"No uploadDataProvider length set"); + } else { + NSNumber *filesizeNum; + NSError *valueError; + if ([_uploadFileURL getResourceValue:&filesizeNum + forKey:NSURLFileSizeKey + error:&valueError]) { + _uploadFileLength = filesizeNum.longLongValue; + } else { + GTMSESSION_ASSERT_DEBUG(NO, @"Cannot get file size: %@\n %@", + valueError, _uploadFileURL.path); + _uploadFileLength = 0; + } + } + } + result = _uploadFileLength; + } + } // @synchronized(self) + return result; +} + +// Make a subdata of the upload data. +- (void)generateChunkSubdataWithOffset:(int64_t)offset + length:(int64_t)length + response:(GTMSessionUploadFetcherDataProviderResponse)response { + GTMSessionUploadFetcherDataProvider uploadDataProvider = self.uploadDataProvider; + if (uploadDataProvider) { + uploadDataProvider(offset, length, response); + return; + } + + NSData *uploadData = self.uploadData; + if (uploadData) { + // NSData provided. + NSData *resultData; + if (offset == 0 && length == (int64_t)uploadData.length) { + resultData = uploadData; + } else { + int64_t dataLength = (int64_t)uploadData.length; + // Ensure our range is valid. b/18007814 + if (offset + length > dataLength) { + NSString *errorMessage = [NSString stringWithFormat: + @"Range invalid for upload data. offset: %lld\tlength: %lld\tdataLength: %lld", + offset, length, dataLength]; + GTMSESSION_ASSERT_DEBUG(NO, @"%@", errorMessage); + response(nil, [self uploadChunkUnavailableErrorWithDescription:errorMessage]); + return; + } + NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length); + resultData = [uploadData subdataWithRange:range]; + } + response(resultData, nil); + return; + } + NSURL *uploadFileURL = self.uploadFileURL; + if (uploadFileURL) { + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self generateChunkSubdataFromFileURL:uploadFileURL + offset:offset + length:length + response:response]; + }); + return; + } + GTMSESSION_ASSERT_DEBUG(_uploadFileHandle, @"Unexpectedly missing upload data package"); + NSFileHandle *uploadFileHandle = self.uploadFileHandle; + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + [self generateChunkSubdataFromFileHandle:uploadFileHandle + offset:offset + length:length + response:response]; + }); +} + +- (void)generateChunkSubdataFromFileHandle:(NSFileHandle *)fileHandle + offset:(int64_t)offset + length:(int64_t)length + response:(GTMSessionUploadFetcherDataProviderResponse)response { + NSData *resultData; + NSError *error; + @try { + [fileHandle seekToFileOffset:(unsigned long long)offset]; + resultData = [fileHandle readDataOfLength:(NSUInteger)length]; + } + @catch (NSException *exception) { + GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileHandle failed to read, %@", exception); + error = [self uploadChunkUnavailableErrorWithDescription:exception.description]; + } + // The response always re-dispatches to the main thread, so we skip doing that here. + response(resultData, error); +} + +- (void)generateChunkSubdataFromFileURL:(NSURL *)fileURL + offset:(int64_t)offset + length:(int64_t)length + response:(GTMSessionUploadFetcherDataProviderResponse)response { + GTMSessionCheckNotSynchronized(self); + + NSData *resultData; + NSError *error; + int64_t fullUploadLength = [self fullUploadLength]; + NSData *mappedData = + [NSData dataWithContentsOfURL:fileURL + options:NSDataReadingMappedAlways + NSDataReadingUncached + error:&error]; + if (!mappedData) { + // We could not create an NSData by memory-mapping the file. +#if TARGET_IPHONE_SIMULATOR + // NSTemporaryDirectory() can differ in the simulator between app restarts, + // yet the contents for the new path remains unchanged, so try the latest temp path. + if ([error.domain isEqual:NSCocoaErrorDomain] && (error.code == NSFileReadNoSuchFileError)) { + NSString *filename = [fileURL lastPathComponent]; + NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:filename]; + NSURL *newFileURL = [NSURL fileURLWithPath:filePath]; + if (![newFileURL isEqual:fileURL]) { + [self generateChunkSubdataFromFileURL:newFileURL + offset:offset + length:length + response:response]; + return; + } + } +#endif + + // If the file is just too large to create an NSData for, or if for some other reason we can't + // map it, create an NSFileHandle instead to read a subset into an NSData. +#if DEBUG + NSNumber *fileSizeNum; + BOOL hasFileSize = [fileURL getResourceValue:&fileSizeNum forKey:NSURLFileSizeKey error:NULL]; + GTMSESSION_LOG_DEBUG(@"Note: uploadFileURL is falling back to creating upload chunks by reading" + @" an NSFileHandle since uploadFileURL failed to map the upload file," + @" file size %@, %@", + hasFileSize ? fileSizeNum : @"unknown", error); +#endif + + NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingFromURL:fileURL + error:&error]; + if (fileHandle != nil) { + [self generateChunkSubdataFromFileHandle:fileHandle + offset:offset + length:length + response:response]; + return; + } + GTMSESSION_ASSERT_DEBUG(NO, @"uploadFileURL failed to read, %@", error); + // Fall through with the error. + } else { + // Successfully created an NSData by memory-mapping the file. + if (offset > 0 || length < fullUploadLength) { + NSRange range = NSMakeRange((NSUInteger)offset, (NSUInteger)length); + resultData = [mappedData subdataWithRange:range]; + } else { + resultData = mappedData; + } + } + // The response always re-dispatches to the main thread, so we skip re-dispatching here. + response(resultData, error); +} + +- (NSError *)uploadChunkUnavailableErrorWithDescription:(NSString *)description { + // The description in the userInfo is intended as a clue to programmers, not + // for client code to examine or rely on. + NSDictionary *userInfo = @{ @"description" : description }; + return [NSError errorWithDomain:kGTMSessionFetcherErrorDomain + code:GTMSessionFetcherErrorUploadChunkUnavailable + userInfo:userInfo]; +} + +- (NSError *)prematureFailureErrorWithUserInfo:(NSDictionary *)userInfo { + // An error for if we get an unexpected status from the upload server or + // otherwise cannot continue. This is an issue beyond the upload protocol; + // there's no way the client can do anything useful except give up. + NSError *error = [NSError errorWithDomain:kGTMSessionFetcherStatusDomain + code:501 // Not implemented + userInfo:userInfo]; + return error; +} + ++ (GTMSessionUploadFetcherStatus)uploadStatusFromResponseHeaders:(NSDictionary *)responseHeaders { + NSString *statusString = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus]; + if ([statusString isEqual:@"active"]) { + return kStatusActive; + } + if ([statusString isEqual:@"final"]) { + return kStatusFinal; + } + if ([statusString isEqual:@"cancelled"]) { + return kStatusCancelled; + } + return kStatusUnknown; +} + +#pragma mark Method overrides affecting the initial fetch only + +- (void)setCompletionHandler:(GTMSessionFetcherCompletionHandler)handler { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateCompletionHandler = handler; + } +} + +- (void)setDelegateCallbackQueue:(dispatch_queue_t GTM_NULLABLE_TYPE)queue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateCallbackQueue = queue; + } +} + +- (dispatch_queue_t GTM_NULLABLE_TYPE)delegateCallbackQueue { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _delegateCallbackQueue; + } +} + +- (BOOL)isRestartedUpload { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _isRestartedUpload; + } +} + +- (GTMSessionFetcher * GTM_NULLABLE_TYPE)chunkFetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _chunkFetcher; + } +} + +- (void)setChunkFetcher:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _chunkFetcher = fetcher; + } +} + +- (void)setFetcherInFlight:(GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _fetcherInFlight = fetcher; + } +} + +- (GTMSessionFetcher * GTM_NULLABLE_TYPE)fetcherInFlight { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _fetcherInFlight; + } +} + +- (void)beginFetchWithCompletionHandler:(GTMSessionFetcherCompletionHandler)handler { + GTMSessionCheckNotSynchronized(self); + + [self setInitialBodyLength:[self bodyLength]]; + + // We'll hold onto the superclass's callback queue so we can invoke the handler + // even after the superclass has released the queue and its callback handler, as + // happens during auth failure. + [self setDelegateCallbackQueue:self.callbackQueue]; + self.completionHandler = handler; + + if ([self isRestartedUpload]) { + // When restarting an upload, we know the destination location for chunk fetches, + // but we need to query to find the initial offset. + if (![self isPaused]) { + [self sendQueryForUploadOffsetWithFetcherProperties:self.properties]; + } + return; + } + // We don't want to call into the client's completion block immediately + // after the finish of the initial connection (the delegate is called only + // when uploading finishes), so we substitute our own completion block to be + // called when the initial connection finishes + GTMSESSION_ASSERT_DEBUG(self.fetcherInFlight == nil, @"unexpected fetcher in flight: %@", + self.fetcherInFlight); + + self.fetcherInFlight = self; + [super beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + self.fetcherInFlight = nil; + // callback + + BOOL hasTestBlock = (self.testBlock != nil); + if (![self isRestartedUpload] && !hasTestBlock) { + if (error == nil) { + [self beginChunkFetches]; + } else { + if ([self retryTimer] == nil) { + [self invokeFinalCallbackWithData:nil + error:error + shouldInvalidateLocation:YES]; + } + } + } else { + // If there was no initial request, then this fetch is resuming some + // other uploadFetcher's initial request, and the superclass's connection + // is never used, so at this point we call the user's actual completion + // block. + if (!hasTestBlock) { + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:YES]; + } else { + // There was a test block, so we won't do chunk fetches, but we simulate obtaining + // the data to be uploaded from the upload data provider block or the file handle, + // and then call back. + [self generateChunkSubdataWithOffset:0 + length:[self fullUploadLength] + response:^(NSData *generateData, NSError *generateError) { + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:YES]; + }]; + } + } + }]; +} + +- (void)beginChunkFetches { + GTMSessionCheckNotSynchronized(self); + +#if DEBUG + // The initial response of the resumable upload protocol should have an + // empty body + // + // This assert typically happens because the upload create/edit link URL was + // not supplied with the request, and the server is thus expecting a non- + // resumable request/response. + if (self.downloadedData.length > 0) { + NSData *downloadedData = self.downloadedData; + NSString *str = [[NSString alloc] initWithData:downloadedData + encoding:NSUTF8StringEncoding]; + #pragma unused(str) + GTMSESSION_ASSERT_DEBUG(NO, @"unexpected response data (uploading to the wrong URL?)\n%@", str); + } +#endif + + // We need to get the upload URL from the location header to continue. + NSDictionary *responseHeaders = [self responseHeaders]; + + [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders]; + + GTMSessionUploadFetcherStatus uploadStatus = + [[self class] uploadStatusFromResponseHeaders:responseHeaders]; + GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown, + @"beginChunkFetches has unexpected upload status for headers %@", responseHeaders); + + BOOL isPrematureStop = (uploadStatus == kStatusFinal) || (uploadStatus == kStatusCancelled); + + NSString *uploadLocationURLStr = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadURL]; + BOOL hasUploadLocation = (uploadLocationURLStr.length > 0); + + if (isPrematureStop || !hasUploadLocation) { + GTMSESSION_ASSERT_DEBUG(NO, @"Premature failure: upload-status:\"%@\" location:%@", + [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], uploadLocationURLStr); + // We cannot continue since we do not know the location to use + // as our upload destination. + NSDictionary *userInfo = nil; + NSData *downloadedData = self.downloadedData; + if (downloadedData.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : downloadedData }; + } + NSError *failureError = [self prematureFailureErrorWithUserInfo:userInfo]; + [self invokeFinalCallbackWithData:nil + error:failureError + shouldInvalidateLocation:YES]; + return; + } + + self.uploadLocationURL = [NSURL URLWithString:uploadLocationURLStr]; + + NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; + [nc postNotificationName:kGTMSessionFetcherUploadLocationObtainedNotification + object:self]; + + // we've now sent all of the initial post body data, so we need to include + // its size in future progress indicator callbacks + [self setInitialBodySent:[self initialBodyLength]]; + + // just in case the user paused us during the initial fetch... + if (![self isPaused]) { + [self uploadNextChunkWithOffset:0]; + } +} + +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task + didSendBodyData:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent + totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend { + // Overrides the superclass. + [self invokeDelegateWithDidSendBytes:bytesSent + totalBytesSent:totalBytesSent + totalBytesExpectedToSend:totalBytesExpectedToSend + [self fullUploadLength]]; +} + +- (BOOL)shouldReleaseCallbacksUponCompletion { + // Overrides the superclass. + + // We don't want the superclass to release the delegate and callback + // blocks once the initial fetch has finished + // + // This is invoked for only successful completion of the connection; + // an error always will invoke and release the callbacks + return NO; +} + +- (void)invokeFinalCallbackWithData:(NSData *)data + error:(NSError *)error + shouldInvalidateLocation:(BOOL)shouldInvalidateLocation { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (shouldInvalidateLocation) { + _uploadLocationURL = nil; + } + + dispatch_queue_t queue = _delegateCallbackQueue; + GTMSessionFetcherCompletionHandler handler = _delegateCompletionHandler; + if (queue && handler) { + [self invokeOnCallbackQueue:queue + afterUserStopped:NO + block:^{ + handler(data, error); + }]; + } + } // @synchronized(self) + + [self releaseUploadAndBaseCallbacks]; +} + +- (void)releaseUploadAndBaseCallbacks { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _delegateCallbackQueue = nil; + _delegateCompletionHandler = nil; + _uploadDataProvider = nil; + } + + // Release the base class's callbacks, too, if needed. + [self releaseCallbacks]; +} + +- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { + GTMSessionCheckNotSynchronized(self); + + // Clear _fetcherInFlight when stopped. Moved from stopFetching, since that's a public method, + // where this method does the work. Fixes issue clearing value when retryBlock included. + GTMSessionFetcher *fetcherInFlight = self.fetcherInFlight; + if (fetcherInFlight == self) { + self.fetcherInFlight = nil; + } + + [super stopFetchReleasingCallbacks:shouldReleaseCallbacks]; + + if (shouldReleaseCallbacks) { + [self releaseUploadAndBaseCallbacks]; + } +} + +#pragma mark Chunk fetching methods + +- (void)uploadNextChunkWithOffset:(int64_t)offset { + // use the properties in each chunk fetcher + NSDictionary *props = [self properties]; + + [self uploadNextChunkWithOffset:offset + fetcherProperties:props]; +} + +- (void)sendQueryForUploadOffsetWithFetcherProperties:(NSDictionary *)props { + GTMSessionFetcher *queryFetcher = [self uploadFetcherWithProperties:props + isQueryFetch:YES]; + queryFetcher.bodyData = [NSData data]; + + NSString *originalComment = self.comment; + [queryFetcher setCommentWithFormat:@"%@ (query offset)", + originalComment ? originalComment : @"upload"]; + + [queryFetcher setRequestValue:@"query" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + + self.fetcherInFlight = queryFetcher; + [queryFetcher beginFetchWithDelegate:self + didFinishSelector:@selector(queryFetcher:finishedWithData:error:)]; +} + +- (void)queryFetcher:(GTMSessionFetcher *)queryFetcher + finishedWithData:(NSData *)data + error:(NSError *)error { + self.fetcherInFlight = nil; + + NSDictionary *responseHeaders = [queryFetcher responseHeaders]; + NSString *sizeReceivedHeader; + + GTMSessionUploadFetcherStatus uploadStatus = + [[self class] uploadStatusFromResponseHeaders:responseHeaders]; + GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown || error != nil, + @"query fetcher completion has unexpected upload status for headers %@", responseHeaders); + + if (error == nil) { + sizeReceivedHeader = [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadSizeReceived]; + + if (uploadStatus == kStatusCancelled || + (uploadStatus == kStatusActive && sizeReceivedHeader == nil)) { + NSDictionary *userInfo = nil; + if (data.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : data }; + } + error = [self prematureFailureErrorWithUserInfo:userInfo]; + } + } + + if (error == nil) { + int64_t offset = [sizeReceivedHeader longLongValue]; + int64_t fullUploadLength = [self fullUploadLength]; + if (offset >= fullUploadLength || uploadStatus == kStatusFinal) { + // Handle we're done + [self chunkFetcher:queryFetcher finishedWithData:data error:nil]; + } else { + [self retrieveUploadChunkGranularityFromResponseHeaders:responseHeaders]; + [self uploadNextChunkWithOffset:offset]; + } + } else { + // Handle query error + [self chunkFetcher:queryFetcher finishedWithData:data error:error]; + } +} + +- (void)sendCancelUploadWithFetcherProperties:(NSDictionary *)props { + GTMSessionFetcher *cancelFetcher = [self uploadFetcherWithProperties:props + isQueryFetch:YES]; + cancelFetcher.bodyData = [NSData data]; + + NSString *originalComment = self.comment; + [cancelFetcher setCommentWithFormat:@"%@ (cancel)", + originalComment ? originalComment : @"upload"]; + + [cancelFetcher setRequestValue:@"cancel" forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + + self.fetcherInFlight = cancelFetcher; + [cancelFetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { + self.fetcherInFlight = nil; + if (error) { + GTMSESSION_LOG_DEBUG(@"cancelFetcher %@", error); + } + }]; +} + +- (void)uploadNextChunkWithOffset:(int64_t)offset + fetcherProperties:(NSDictionary *)props { + GTMSessionCheckNotSynchronized(self); + + // Example chunk headers: + // X-Goog-Upload-Command: upload, finalize + // X-Goog-Upload-Offset: 0 + // Content-Length: 2000000 + // Content-Type: image/jpeg + // + // {bytes 0-1999999} + + // The chunk upload URL requires no authentication header. + GTMSessionFetcher *chunkFetcher = [self uploadFetcherWithProperties:props + isQueryFetch:NO]; + [self attachSendProgressBlockToChunkFetcher:chunkFetcher]; + + BOOL isUploadingFileURL = (self.uploadFileURL != nil); + + // Upload another chunk, meeting server-required granularity. + int64_t chunkSize = self.chunkSize; + + int64_t fullUploadLength = [self fullUploadLength]; + + BOOL isUploadingFullFile = (offset == 0 && chunkSize >= fullUploadLength); + if (!isUploadingFileURL || !isUploadingFullFile) { + // We're not uploading the entire file and given the file URL. Since we'll be + // allocating a subdata block for a chunk, we need to bound it to something that + // won't blow the process's memory. + if (chunkSize > kGTMSessionUploadFetcherMaximumDemandBufferSize) { + chunkSize = kGTMSessionUploadFetcherMaximumDemandBufferSize; + } + } + + int64_t granularity = self.uploadGranularity; + if (granularity > 0) { + if (chunkSize < granularity) { + chunkSize = granularity; + } else { + chunkSize = chunkSize - (chunkSize % granularity); + } + } + + GTMSESSION_ASSERT_DEBUG(offset < fullUploadLength || fullUploadLength == 0, + @"offset %lld exceeds data length %lld", offset, fullUploadLength); + + if (granularity > 0) { + offset = offset - (offset % granularity); + } + + // If the chunk size is bigger than the remaining data, or else + // it's close enough in size to the remaining data that we'd rather + // avoid having a whole extra http fetch for the leftover bit, then make + // this chunk size exactly match the remaining data size + NSString *command; + int64_t thisChunkSize = chunkSize; + + BOOL isChunkTooBig = (thisChunkSize >= (fullUploadLength - offset)); + BOOL isChunkAlmostBigEnough = (fullUploadLength - offset - 2500 < thisChunkSize); + BOOL isFinalChunk = isChunkTooBig || isChunkAlmostBigEnough; + if (isFinalChunk) { + thisChunkSize = fullUploadLength - offset; + if (thisChunkSize > 0) { + command = @"upload, finalize"; + } else { + command = @"finalize"; + } + } else { + command = @"upload"; + } + NSString *lengthStr = @(thisChunkSize).stringValue; + NSString *offsetStr = @(offset).stringValue; + + [chunkFetcher setRequestValue:command forHTTPHeaderField:kGTMSessionHeaderXGoogUploadCommand]; + [chunkFetcher setRequestValue:lengthStr forHTTPHeaderField:@"Content-Length"]; + [chunkFetcher setRequestValue:offsetStr forHTTPHeaderField:kGTMSessionHeaderXGoogUploadOffset]; + + // Append the range of bytes in this chunk to the fetcher comment. + NSString *baseComment = self.comment; + [chunkFetcher setCommentWithFormat:@"%@ (%lld-%lld)", + baseComment ? baseComment : @"upload", offset, MAX(0, offset + thisChunkSize - 1)]; + + // The chunk size may have changed, so determine again if we're uploading the full file. + isUploadingFullFile = (offset == 0 && thisChunkSize >= fullUploadLength); + if (isUploadingFullFile && isUploadingFileURL) { + // The data is the full upload file URL. + chunkFetcher.bodyFileURL = self.uploadFileURL; + [self beginChunkFetcher:chunkFetcher + offset:offset]; + } else { + // Make an NSData for the subset for this upload chunk. + self.subdataGenerating = YES; + [self generateChunkSubdataWithOffset:offset + length:thisChunkSize + response:^(NSData *chunkData, NSError *chunkError) { + // The subdata methods may leave us on a background thread. + dispatch_async(dispatch_get_main_queue(), ^{ + self.subdataGenerating = NO; + if (chunkData == nil) { + NSError *responseError = chunkError; + if (!responseError) { + responseError = [self uploadChunkUnavailableErrorWithDescription:@"chunkData is nil"]; + } + [self invokeFinalCallbackWithData:nil + error:responseError + shouldInvalidateLocation:YES]; + return; + } + + BOOL didWriteFile = NO; + if (isUploadingFileURL) { + // Make a temporary file with the data subset. + NSString *tempName = + [NSString stringWithFormat:@"GTMUpload_temp_%@", [[NSUUID UUID] UUIDString]]; + NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempName]; + NSError *writeError; + didWriteFile = [chunkData writeToFile:tempPath + options:NSDataWritingAtomic + error:&writeError]; + if (didWriteFile) { + chunkFetcher.bodyFileURL = [NSURL fileURLWithPath:tempPath]; + } else { + GTMSESSION_LOG_DEBUG(@"writeToFile failed: %@\n%@", writeError, tempPath); + } + } + if (!didWriteFile) { + chunkFetcher.bodyData = [chunkData copy]; + } + [self beginChunkFetcher:chunkFetcher + offset:offset]; + }); + }]; + } +} + +- (void)beginChunkFetcher:(GTMSessionFetcher *)chunkFetcher + offset:(int64_t)offset { + + // Track the current offset for progress reporting + self.currentOffset = offset; + + // Hang on to the fetcher in case we need to cancel it. We set these before beginning the + // chunk fetch so the observers notified of chunk fetches can inspect the upload fetcher to + // match to the chunk. + self.chunkFetcher = chunkFetcher; + self.fetcherInFlight = chunkFetcher; + + // Update the last chunk request, including any request headers. + self.lastChunkRequest = chunkFetcher.request; + + [chunkFetcher beginFetchWithDelegate:self + didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; +} + +- (void)attachSendProgressBlockToChunkFetcher:(GTMSessionFetcher *)chunkFetcher { + chunkFetcher.sendProgressBlock = ^(int64_t bytesSent, int64_t totalBytesSent, + int64_t totalBytesExpectedToSend) { + // The total bytes expected include the initial body and the full chunked + // data, independent of how big this fetcher's chunk is. + int64_t initialBodySent = [self bodyLength]; // TODO(grobbins) use [self initialBodySent] + int64_t totalSent = initialBodySent + self.currentOffset + totalBytesSent; + int64_t totalExpected = initialBodySent + [self fullUploadLength]; + + [self invokeDelegateWithDidSendBytes:bytesSent + totalBytesSent:totalSent + totalBytesExpectedToSend:totalExpected]; + }; +} + +- (NSDictionary *)uploadSessionIdentifierMetadata { + NSMutableDictionary *metadata = [NSMutableDictionary dictionary]; + metadata[kGTMSessionIdentifierIsUploadChunkFetcherMetadataKey] = @YES; + GTMSESSION_ASSERT_DEBUG(self.uploadFileURL, + @"Invalid upload fetcher to create session identifier for metadata"); + metadata[kGTMSessionIdentifierUploadFileURLMetadataKey] = [self.uploadFileURL absoluteString]; + metadata[kGTMSessionIdentifierUploadFileLengthMetadataKey] = @([self fullUploadLength]); + + if (self.uploadLocationURL) { + metadata[kGTMSessionIdentifierUploadLocationURLMetadataKey] = + [self.uploadLocationURL absoluteString]; + } + if (self.uploadMIMEType) { + metadata[kGTMSessionIdentifierUploadMIMETypeMetadataKey] = self.uploadMIMEType; + } + metadata[kGTMSessionIdentifierUploadChunkSizeMetadataKey] = @(self.chunkSize); + metadata[kGTMSessionIdentifierUploadCurrentOffsetMetadataKey] = @(self.currentOffset); + return metadata; +} + +- (GTMSessionFetcher *)uploadFetcherWithProperties:(NSDictionary *)properties + isQueryFetch:(BOOL)isQueryFetch { + GTMSessionCheckNotSynchronized(self); + + // Common code to make a request for a query command or for a chunk upload. + NSURL *uploadLocationURL = self.uploadLocationURL; + NSMutableURLRequest *chunkRequest = [NSMutableURLRequest requestWithURL:uploadLocationURL]; + [chunkRequest setHTTPMethod:@"PUT"]; + + // copy the user-agent from the original connection + NSURLRequest *origRequest = self.request; + NSString *userAgent = [origRequest valueForHTTPHeaderField:@"User-Agent"]; + if (userAgent.length > 0) { + [chunkRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; + } + // To avoid timeouts when debugging, copy the timeout of the initial fetcher. + NSTimeInterval origTimeout = [origRequest timeoutInterval]; + [chunkRequest setTimeoutInterval:origTimeout]; + + // + // Make a new chunk fetcher. + // + GTMSessionFetcher *chunkFetcher = [GTMSessionFetcher fetcherWithRequest:chunkRequest]; + chunkFetcher.callbackQueue = self.callbackQueue; + chunkFetcher.sessionUserInfo = self.sessionUserInfo; + chunkFetcher.configurationBlock = self.configurationBlock; + chunkFetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; + chunkFetcher.allowLocalhostRequest = self.allowLocalhostRequest; + chunkFetcher.allowInvalidServerCertificates = self.allowInvalidServerCertificates; + chunkFetcher.useUploadTask = !isQueryFetch; + + if (self.uploadFileURL && !isQueryFetch && self.useBackgroundSession) { + [chunkFetcher createSessionIdentifierWithMetadata:[self uploadSessionIdentifierMetadata]]; + } + + // Give the chunk fetcher the same properties as the previous chunk fetcher + chunkFetcher.properties = [properties mutableCopy]; + [chunkFetcher setProperty:[NSValue valueWithNonretainedObject:self] + forKey:kGTMSessionUploadFetcherChunkParentKey]; + + // copy other fetcher settings to the new fetcher + chunkFetcher.retryEnabled = self.retryEnabled; + chunkFetcher.maxRetryInterval = self.maxRetryInterval; + + if ([self isRetryEnabled]) { + // We interpose our own retry method both so we can change the request to ask the server to + // tell us where to resume the chunk. + chunkFetcher.retryBlock = ^(BOOL suggestedWillRetry, NSError *chunkError, + GTMSessionFetcherRetryResponse response){ + void (^finish)(BOOL) = ^(BOOL shouldRetry){ + // We'll retry by sending an offset query. + if (shouldRetry) { + self.shouldInitiateOffsetQuery = !isQueryFetch; + + // We don't know what our actual offset is anymore, but the server will tell us. + self.currentOffset = 0; + } + // We don't actually want to retry this specific fetcher. + response(NO); + }; + + GTMSessionFetcherRetryBlock retryBlock = self.retryBlock; + if (retryBlock) { + // Ask the client, then call the finish block above. + retryBlock(suggestedWillRetry, chunkError, finish); + } else { + finish(suggestedWillRetry); + } + }; + } + + return chunkFetcher; +} + +- (void)chunkFetcher:(GTMSessionFetcher *)chunkFetcher + finishedWithData:(NSData *)data + error:(NSError *)error { + BOOL hasDestroyedOldChunkFetcher = NO; + self.fetcherInFlight = nil; + + NSDictionary *responseHeaders = [chunkFetcher responseHeaders]; + GTMSessionUploadFetcherStatus uploadStatus = + [[self class] uploadStatusFromResponseHeaders:responseHeaders]; + GTMSESSION_ASSERT_DEBUG(uploadStatus != kStatusUnknown + || error != nil + || self.wasCreatedFromBackgroundSession, + @"chunk fetcher completion has kStatusUnknown upload status for headers %@ fetcher %@", + responseHeaders, self); + BOOL isUploadStatusStopped = (uploadStatus == kStatusFinal || uploadStatus == kStatusCancelled); + + // Check if the fetcher was actually querying. If it failed, do not retry, + // as it would enter an infinite retry loop. + NSString *uploadCommand = + chunkFetcher.request.allHTTPHeaderFields[kGTMSessionHeaderXGoogUploadCommand]; + BOOL isQueryFetch = [uploadCommand isEqual:@"query"]; + + int64_t previousContentLength = + [[chunkFetcher.request valueForHTTPHeaderField:@"Content-Length"] longLongValue]; + // The Content-Length header may not be present if the chunk fetcher was recreated from + // a background session. + BOOL hasKnownChunkSize = (previousContentLength > 0); + BOOL needsQuery = (!hasKnownChunkSize && !isUploadStatusStopped); + + if (error || (needsQuery && !isQueryFetch)) { + NSInteger status = error.code; + + // Status 4xx indicates a bad offset in the Google upload protocol. However, do not retry status + // 404 per spec, nor if the upload size appears to have been zero (since the server will just + // keep asking us to retry.) + if (self.shouldInitiateOffsetQuery || + (needsQuery && !isQueryFetch) || + ([error.domain isEqual:kGTMSessionFetcherStatusDomain] && + status >= 400 && status <= 499 && + status != 404 && + uploadStatus == kStatusActive && + previousContentLength > 0)) { + self.shouldInitiateOffsetQuery = NO; + [self destroyChunkFetcher]; + hasDestroyedOldChunkFetcher = YES; + [self sendQueryForUploadOffsetWithFetcherProperties:chunkFetcher.properties]; + } else { + // Some unexpected status has occurred; handle it as we would a regular + // object fetcher failure. + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:NO]; + } + } else { + // The chunk has uploaded successfully. + int64_t newOffset = self.currentOffset + previousContentLength; +#if DEBUG + // Verify that if we think all of the uploading data has been sent, the server responded with + // the "final" upload status. + BOOL hasUploadAllData = (newOffset == [self fullUploadLength]); + BOOL isFinalStatus = (uploadStatus == kStatusFinal); + #pragma unused(hasUploadAllData,isFinalStatus) + GTMSESSION_ASSERT_DEBUG(hasUploadAllData == isFinalStatus || !hasKnownChunkSize, + @"uploadStatus:%@ newOffset:%zd (%lld + %zd) fullUploadLength:%lld" + @" chunkFetcher:%@ requestHeaders:%@ responseHeaders:%@", + [responseHeaders objectForKey:kGTMSessionHeaderXGoogUploadStatus], + newOffset, self.currentOffset, previousContentLength, + [self fullUploadLength], + chunkFetcher, chunkFetcher.request.allHTTPHeaderFields, + responseHeaders); +#endif + if (isUploadStatusStopped) { + // This was the last chunk. + if (error == nil && uploadStatus == kStatusCancelled) { + // Report cancelled status as an error. + NSDictionary *userInfo = nil; + if (data.length > 0) { + userInfo = @{ kGTMSessionFetcherStatusDataKey : data }; + } + data = nil; + error = [self prematureFailureErrorWithUserInfo:userInfo]; + } else { + // The upload is in final status. + // + // Take the chunk fetcher's data as the superclass data. + self.downloadedData = data; + self.statusCode = chunkFetcher.statusCode; + } + + // we're done + [self invokeFinalCallbackWithData:data + error:error + shouldInvalidateLocation:YES]; + } else { + // Start the next chunk. + self.currentOffset = newOffset; + + // We want to destroy this chunk fetcher before creating the next one, but + // we want to pass on its properties + NSDictionary *props = [chunkFetcher properties]; + + // We no longer need to be able to cancel this chunkFetcher. Destroy it + // before we create a new chunk fetcher. + [self destroyChunkFetcher]; + hasDestroyedOldChunkFetcher = YES; + + [self uploadNextChunkWithOffset:newOffset + fetcherProperties:props]; + } + } + if (!hasDestroyedOldChunkFetcher) { + [self destroyChunkFetcher]; + } +} + +- (void)destroyChunkFetcher { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_fetcherInFlight == _chunkFetcher) { + _fetcherInFlight = nil; + } + + [_chunkFetcher stopFetching]; + + NSURL *chunkFileURL = _chunkFetcher.bodyFileURL; + BOOL wasTemporaryUploadFile = ![chunkFileURL isEqual:_uploadFileURL]; + if (wasTemporaryUploadFile) { + NSError *error; + [[NSFileManager defaultManager] removeItemAtURL:chunkFileURL + error:&error]; + if (error) { + GTMSESSION_LOG_DEBUG(@"removingItemAtURL failed: %@\n%@", error, chunkFileURL); + } + } + + _recentChunkReponseHeaders = _chunkFetcher.responseHeaders; + + // To avoid retain cycles, remove all properties except the parent identifier. + _chunkFetcher.properties = + @{ kGTMSessionUploadFetcherChunkParentKey : [NSValue valueWithNonretainedObject:self] }; + + _chunkFetcher.retryBlock = nil; + _chunkFetcher.sendProgressBlock = nil; + _chunkFetcher = nil; + } // @synchronized(self) +} + +// This method calculates the proper values to pass to the client's send progress block. +// +// The actual total bytes sent include the initial body sent, plus the +// offset into the batched data prior to the current chunk fetcher + +- (void)invokeDelegateWithDidSendBytes:(int64_t)bytesSent + totalBytesSent:(int64_t)totalBytesSent + totalBytesExpectedToSend:(int64_t)totalBytesExpected { + GTMSessionCheckNotSynchronized(self); + + // Ensure the chunk fetcher survives the callback in case the user pauses the upload process. + __block GTMSessionFetcher *holdFetcher = self.chunkFetcher; + + [self invokeOnCallbackQueue:self.delegateCallbackQueue + afterUserStopped:NO + block:^{ + GTMSessionFetcherSendProgressBlock sendProgressBlock = self.sendProgressBlock; + if (sendProgressBlock) { + sendProgressBlock(bytesSent, totalBytesSent, totalBytesExpected); + } + holdFetcher = nil; + }]; +} + +- (void)retrieveUploadChunkGranularityFromResponseHeaders:(NSDictionary *)responseHeaders { + GTMSessionCheckNotSynchronized(self); + + // Standard granularity for Google uploads is 256K. + NSString *chunkGranularityHeader = + [responseHeaders objectForKey:@"X-Goog-Upload-Chunk-Granularity"]; + self.uploadGranularity = chunkGranularityHeader.longLongValue; +} + +#pragma mark - + +- (BOOL)isPaused { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _isPaused; + } // @synchronized(self) +} + +- (void)pauseFetching { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _isPaused = YES; + } // @synchronized(self) + + // Pausing just means stopping the current chunk from uploading; + // when we resume, we will send a query request to the server to + // figure out what bytes to resume sending. + // + // We won't try to cancel the initial data upload, but rather will check + // for being paused in beginChunkFetches. + [self destroyChunkFetcher]; +} + +- (void)resumeFetching { + BOOL wasPaused; + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + wasPaused = _isPaused; + _isPaused = NO; + } // @synchronized(self) + + if (wasPaused) { + [self sendQueryForUploadOffsetWithFetcherProperties:self.properties]; + } +} + +- (void)stopFetching { + // Overrides the superclass + [self destroyChunkFetcher]; + + // If we think the server is waiting for more data, then tell it there won't be more. + if (self.uploadLocationURL) { + [self sendCancelUploadWithFetcherProperties:[self properties]]; + self.uploadLocationURL = nil; + } + + [super stopFetching]; +} + +#pragma mark - + +// Public properties. +@synthesize currentOffset = _currentOffset, + delegateCompletionHandler = _delegateCompletionHandler, + chunkFetcher = _chunkFetcher, + lastChunkRequest = _lastChunkRequest, + subdataGenerating = _subdataGenerating, + shouldInitiateOffsetQuery = _shouldInitiateOffsetQuery, + uploadGranularity = _uploadGranularity; + +// Internal properties. +@dynamic fetcherInFlight; +@dynamic activeFetcher; +@dynamic statusCode; +@dynamic delegateCallbackQueue; + ++ (void)removePointer:(void *)pointer fromPointerArray:(NSPointerArray *)pointerArray { + for (NSUInteger index = 0, count = pointerArray.count; index < count; ++index) { + void *pointerAtIndex = [pointerArray pointerAtIndex:index]; + if (pointerAtIndex == pointer) { + [pointerArray removePointerAtIndex:index]; + return; + } + } +} + +- (BOOL)useBackgroundSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _useBackgroundSessionOnChunkFetchers; + } // @synchronized(self +} + +- (void)setUseBackgroundSession:(BOOL)useBackgroundSession { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_useBackgroundSessionOnChunkFetchers != useBackgroundSession) { + _useBackgroundSessionOnChunkFetchers = useBackgroundSession; + NSPointerArray *uploadFetcherPointerArrayForBackgroundSessions = + [[self class] uploadFetcherPointerArrayForBackgroundSessions]; + if (_useBackgroundSessionOnChunkFetchers) { + [uploadFetcherPointerArrayForBackgroundSessions addPointer:(__bridge void *)self]; + } else { + [[self class] removePointer:(__bridge void *)self + fromPointerArray:uploadFetcherPointerArrayForBackgroundSessions]; + } + } + } // @synchronized(self +} + +- (BOOL)canFetchWithBackgroundSession { + // The initial upload fetcher is always a foreground session; the + // useBackgroundSession property will apply only to chunk fetchers, + // not to queries. + return NO; +} + +- (NSDictionary *)responseHeaders { + GTMSessionCheckNotSynchronized(self); + // Overrides the superclass + + // If asked for the fetcher's response, use the most recent chunk fetcher's response, + // since the original request's response lacks useful information like the actual + // Content-Type. + NSDictionary *dict = self.chunkFetcher.responseHeaders; + if (dict) { + return dict; + } + + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + if (_recentChunkReponseHeaders) { + return _recentChunkReponseHeaders; + } + } // @synchronized(self + + // No chunk fetcher yet completed, so return whatever we have from the initial fetch. + return [super responseHeaders]; +} + +- (NSInteger)statusCodeUnsynchronized { + GTMSessionCheckSynchronized(self); + + if (_recentChunkStatusCode != -1) { + // Overrides the superclass to indicate status appropriate to the initial + // or latest chunk fetch + return _recentChunkStatusCode; + } else { + return [super statusCodeUnsynchronized]; + } +} + + +- (void)setStatusCode:(NSInteger)val { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _recentChunkStatusCode = val; + } +} + +- (int64_t)initialBodyLength { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _initialBodyLength; + } +} + +- (void)setInitialBodyLength:(int64_t)length { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _initialBodyLength = length; + } +} + +- (int64_t)initialBodySent { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _initialBodySent; + } +} + +- (void)setInitialBodySent:(int64_t)length { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _initialBodySent = length; + } +} + +- (NSURL *)uploadLocationURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + return _uploadLocationURL; + } +} + +- (void)setUploadLocationURL:(NSURL *)locationURL { + @synchronized(self) { + GTMSessionMonitorSynchronized(self); + + _uploadLocationURL = locationURL; + } +} + +- (GTMSessionFetcher *)activeFetcher { + GTMSessionFetcher *result = self.fetcherInFlight; + if (result) return result; + + return self; +} + +- (BOOL)isFetching { + // If there is an active chunk fetcher, then the upload fetcher is considered + // to still be fetching. + if (self.fetcherInFlight != nil) return YES; + + return [super isFetching]; +} + +- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { + NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; + + while (self.fetcherInFlight || self.subdataGenerating) { + if ([timeoutDate timeIntervalSinceNow] < 0) return NO; + + if (self.subdataGenerating) { + // Allow time for subdata generation. + NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001]; + [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; + } else { + // Wait for any chunk or query fetchers that still have pending callbacks or + // notifications. + BOOL timedOut; + + if (self.fetcherInFlight == self) { + timedOut = ![super waitForCompletionWithTimeout:timeoutInSeconds]; + } else { + timedOut = ![self.fetcherInFlight waitForCompletionWithTimeout:timeoutInSeconds]; + } + if (timedOut) return NO; + } + } + return YES; +} + +@end + +@implementation GTMSessionFetcher (GTMSessionUploadFetcherMethods) + +- (GTMSessionUploadFetcher *)parentUploadFetcher { + NSValue *property = [self propertyForKey:kGTMSessionUploadFetcherChunkParentKey]; + if (!property) return nil; + + GTMSessionUploadFetcher *uploadFetcher = property.nonretainedObjectValue; + + GTMSESSION_ASSERT_DEBUG([uploadFetcher isKindOfClass:[GTMSessionUploadFetcher class]], + @"Unexpected parent upload fetcher class: %@", [uploadFetcher class]); + return uploadFetcher; +} + +@end diff --git a/Paco-iOS/Pods/Manifest.lock b/Paco-iOS/Pods/Manifest.lock new file mode 100644 index 000000000..d8a5d07a9 --- /dev/null +++ b/Paco-iOS/Pods/Manifest.lock @@ -0,0 +1,24 @@ +PODS: + - AppAuth (0.7.1) + - GTMAppAuth (0.5.0): + - AppAuth (~> 0.7.0) + - GTMSessionFetcher (~> 1.1) + - GTMSessionFetcher (1.1.9): + - GTMSessionFetcher/Full (= 1.1.9) + - GTMSessionFetcher/Core (1.1.9) + - GTMSessionFetcher/Full (1.1.9): + - GTMSessionFetcher/Core (= 1.1.9) + +DEPENDENCIES: + - AppAuth + - GTMAppAuth + - GTMSessionFetcher + +SPEC CHECKSUMS: + AppAuth: c56d352b0d50bb34dbb302d7ba50b20aa6b6ae89 + GTMAppAuth: 4b7bdc1fefdf6a49f3d9fc1aa6123f0c7e9b6660 + GTMSessionFetcher: 5c046c76a1f859bc9c187e918f18e4fc7bb57b5e + +PODFILE CHECKSUM: c665a47779f733e33fedc48ca8e7aafbb602f3d3 + +COCOAPODS: 1.2.1 diff --git a/Paco-iOS/Pods/Pods.xcodeproj/project.pbxproj b/Paco-iOS/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 000000000..6426f39b7 --- /dev/null +++ b/Paco-iOS/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1206 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 04FE4B8DF889CDC972F9DDB10B4309F2 /* OIDServiceDiscovery.h in Headers */ = {isa = PBXBuildFile; fileRef = 375C7DDCFF8094416317A1F78C0C945C /* OIDServiceDiscovery.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0897A26B3804CF0309918D2AF586634C /* OIDAuthorizationService.h in Headers */ = {isa = PBXBuildFile; fileRef = 63455CFDF6D04D12FDFFAEE532CC9F6E /* OIDAuthorizationService.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0D1B02523FAD4FEA08532986C2CC4D9E /* OIDTokenUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 68A279939DD415BC8CF3F46B06514C55 /* OIDTokenUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 0D4ADE285EF78D3A06163A71A6445013 /* OIDAuthorizationService.m in Sources */ = {isa = PBXBuildFile; fileRef = 89DEED8030ED39FD47A4E20B2C847F86 /* OIDAuthorizationService.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 13A8FA59BBD37888DAF84309AF8E38E9 /* OIDScopeUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = 0B9774BCDA3BBCE6B205C4AA5A96A41F /* OIDScopeUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 13F08C9FFA156E469A237C814BA78B9A /* GTMSessionFetcher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 5150A5E46D228CD1521517156771C294 /* GTMSessionFetcher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 14263EAA67C8A8CA4A2B48B7100B637E /* Pods-Paco-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D1FCC6F5352506E792EECF9C5628D0E3 /* Pods-Paco-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1547A2BE902B31084257BA060D3574CA /* GTMAppAuth-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = D53412410D74B04597223B92323B1440 /* GTMAppAuth-dummy.m */; }; + 19862760A53F3A6CA4E9067DA0139873 /* Pods-Paco-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = C2D2AF3C3C1CDF9D3B20A77590688B72 /* Pods-Paco-dummy.m */; }; + 1A29B9533EBED91F61FACEE36967AFED /* GTMAppAuthFetcherAuthorization.m in Sources */ = {isa = PBXBuildFile; fileRef = 3CB2CF71592703FABB023BA59DCB2597 /* GTMAppAuthFetcherAuthorization.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1AD85EA85FBBF6FAEB77DD550510C129 /* OIDAuthorizationRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = CAD16928502F4F55913677A189704C45 /* OIDAuthorizationRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1BA66882265D3E2F6DEAB16CEED26995 /* OIDAuthState.m in Sources */ = {isa = PBXBuildFile; fileRef = 3E66263F7F6CD4ACC9A470FF6F78017B /* OIDAuthState.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1D2434AB7550BCA92BA72756EB19EA98 /* GTMKeychain_iOS.m in Sources */ = {isa = PBXBuildFile; fileRef = C14505F278CD4F7A6A3FCB739A8ECB3E /* GTMKeychain_iOS.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 1DBDE74E7234F7F13CB7B03DBDB6943C /* OIDAuthorizationResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 0FD1CA6F54346736C2C1FCFE917A95BB /* OIDAuthorizationResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1E18489D34047F312C152B31425F582F /* OIDAuthorizationService+IOS.h in Headers */ = {isa = PBXBuildFile; fileRef = DFB005A72D69B6B7EABDABB1E88655F8 /* OIDAuthorizationService+IOS.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 226F07E34ED202CDD7C7F44C39A6C3F9 /* GTMAppAuthFetcherAuthorization+Keychain.h in Headers */ = {isa = PBXBuildFile; fileRef = D26D99FDCB4D9801024FACF74F21FE7B /* GTMAppAuthFetcherAuthorization+Keychain.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 255EBA8DEE85FE7DED245F4A102C1E62 /* GTMReadMonitorInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = FA1D03E0948398398A3A16B820B1DA64 /* GTMReadMonitorInputStream.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2660617C2C498739B46226290949E95C /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7913DC9B69DD1D3964FBA164783509BA /* Foundation.framework */; }; + 2B63606B0F2C3304BA96032CF8146D7C /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3230C62D1ACEA3C291D2A940D4BCB1FA /* Security.framework */; }; + 2E43631F412FBF781740B299FD1ADD59 /* OIDServiceDiscovery.m in Sources */ = {isa = PBXBuildFile; fileRef = 6E4E44554DBDB983ACF4650955C9FCC6 /* OIDServiceDiscovery.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3123B6E28D40FD4096EE2C5198B7D5E6 /* OIDFieldMapping.h in Headers */ = {isa = PBXBuildFile; fileRef = 63F9A90BC50DA5A31590E8B310C742F6 /* OIDFieldMapping.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 342F900F20D11C76722E8AF404C4472C /* GTMSessionUploadFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 5304ABCF7CC87CA09372FBAEE1217767 /* GTMSessionUploadFetcher.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3BC4EC25BB6F740A9838D434E61F8D19 /* GTMOAuth2KeychainCompatibility.h in Headers */ = {isa = PBXBuildFile; fileRef = 56D50B6AE74F5BEBED5D65D58EBCE861 /* GTMOAuth2KeychainCompatibility.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3C05DF646F6067AE76ED2B2707392109 /* OIDResponseTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = C9C46140D880D6988E43D8E0D4BBFD73 /* OIDResponseTypes.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3DE044FE8D403D23E7B5F122E7A8D39D /* OIDAuthorizationResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = CE0B9513B9FAB8667288E046C769D14D /* OIDAuthorizationResponse.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 3DF76B9F9186685EC9CAA507869229AA /* AppAuth.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D7E8CD2295D27D85E86452FEFDF8C29 /* AppAuth.framework */; }; + 3EC50952B6EF2E750AE2D40DD9CED6B4 /* OIDError.h in Headers */ = {isa = PBXBuildFile; fileRef = 033828E9F739061ABB0CD148F8DD1464 /* OIDError.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3F4E8D45F39FE16C1C1B186F62C590A9 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3230C62D1ACEA3C291D2A940D4BCB1FA /* Security.framework */; }; + 42024D4D8FF7CE2F399C987DB77A6B69 /* GTMSessionUploadFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 272FEEABF1FEDCC62FC45B7834FB7657 /* GTMSessionUploadFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 426B9B1010FD474F3413B7B2AD4A0709 /* OIDDefines.h in Headers */ = {isa = PBXBuildFile; fileRef = 2F8B9AB9204B82825009951CE3999341 /* OIDDefines.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 445174A094F252E5237E9A4E4D0672A4 /* OIDTokenRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = 64F2583E4879DDF971B154C556ACC18D /* OIDTokenRequest.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 453D96A62E3FBB4BE3E12F23A3EB2A09 /* GTMAppAuth.h in Headers */ = {isa = PBXBuildFile; fileRef = 52600E8E58A7AF664609726A67C8346C /* GTMAppAuth.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 458793DCB8A819F91488A99ABDEE8EB0 /* SafariServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BE75BFBB21B41BAE5645EEC8A13A7352 /* SafariServices.framework */; }; + 489DA103EBDA06A4E5F26F1A7D23315E /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2B4AA34F81886ED5DEA8F972E0E75F10 /* SystemConfiguration.framework */; }; + 4FA537437D014D26081F0A200E42E8D7 /* GTMSessionFetcherService.m in Sources */ = {isa = PBXBuildFile; fileRef = 6A81018DA512037BBDAFE34FCC9ABAC8 /* GTMSessionFetcherService.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 547E49212790E32BF7785C73E946475D /* GTMMIMEDocument.m in Sources */ = {isa = PBXBuildFile; fileRef = 49A516AF90D0109B7E9E61A5EDE08A62 /* GTMMIMEDocument.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 550A0254DC3B4C648FB1A9D8121CB728 /* OIDURLQueryComponent.h in Headers */ = {isa = PBXBuildFile; fileRef = 202F5DC2942FCBFA2D6D433E9F21C96C /* OIDURLQueryComponent.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6B42CE645116C6EF7729C037835427FC /* GTMSessionFetcherService.h in Headers */ = {isa = PBXBuildFile; fileRef = 6946FC57D765C7E3C752733FFF4BE7E7 /* GTMSessionFetcherService.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 6D8B8CFB7E83A8CA0B809FDBEB4A47C2 /* OIDError.m in Sources */ = {isa = PBXBuildFile; fileRef = F92C3416A5D56E3F173392F0F15D4F28 /* OIDError.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 73A31127AD73F6377798FE097D131CA9 /* GTMSessionFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = CB91E17F6A4CB1C04A11A18CBF150299 /* GTMSessionFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 748248840E5671419F2DC48D0771B385 /* GTMReadMonitorInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = AB21958B56BDE59D9716A5A40371064D /* GTMReadMonitorInputStream.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 7896642E95A419F50D4CB35328226EAE /* GTMSessionFetcherLogging.h in Headers */ = {isa = PBXBuildFile; fileRef = D69843FF00BEDAB2732040BD839B5BF5 /* GTMSessionFetcherLogging.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 79D65A3B66B05DE9E521580E8D80E219 /* GTMAppAuth-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E0350B74ADC0F8BD1DB3D4BBB6B6CA84 /* GTMAppAuth-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 7A75848963423CABE76715841215F587 /* OIDScopes.m in Sources */ = {isa = PBXBuildFile; fileRef = 42EB5A9C39D3D84B6F1B6FCCBA2E9D40 /* OIDScopes.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 831BCE3FB4505EADD68B4710897F2EBD /* GTMGatherInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = E6A55F3CADD407F51B351E9EEF0F2B82 /* GTMGatherInputStream.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 855F3C5D3D9DD7B1DC76C2F23BB15C7F /* OIDAuthorizationUICoordinatorIOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 66460CC526EA7E68C0B70107D5CAB52A /* OIDAuthorizationUICoordinatorIOS.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8A49B374D458711BCFAFC14CBEF468B9 /* OIDGrantTypes.h in Headers */ = {isa = PBXBuildFile; fileRef = E14392158D250569564E07CD4AB2EC0D /* OIDGrantTypes.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8C065922E821A04F5646393CECA0480F /* GTMSessionFetcher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 58BA9E6DD44A9AFCC1AB320BA7F8883D /* GTMSessionFetcher-dummy.m */; }; + 8C1D6E61F8BC5C4DF16764609C831D39 /* AppAuth.h in Headers */ = {isa = PBXBuildFile; fileRef = 97792B2D7AB722B03A55FB03221E7073 /* AppAuth.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8DAE14D02A9CDCA2A37FB8663616D52E /* OIDTokenResponse.h in Headers */ = {isa = PBXBuildFile; fileRef = 5DE246AAED9D6D8CBB31055CFBFD85EC /* OIDTokenResponse.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8DF27A4C9B970CD0A1383C04516DBF3C /* OIDAuthStateErrorDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = 0E9535007AD24552B7E98AEDEFF133E6 /* OIDAuthStateErrorDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 95FF8657E90CC8AB09546A3F28191513 /* GTMSessionFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = D194073227644378587F98E07E22D0FE /* GTMSessionFetcherLogging.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 97019F23C62401D00CB9092967FE6BA1 /* OIDServiceConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = 1B705CE4C794EE0BEA96A0477F37CF59 /* OIDServiceConfiguration.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 981D75064EE46576327BC6AB5EED0B50 /* OIDGrantTypes.m in Sources */ = {isa = PBXBuildFile; fileRef = B8CA0A1990BF67E574CEE2DB4D9F2D23 /* OIDGrantTypes.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + 988551E340F39E9DDF2F0D0A37697025 /* OIDAuthState+IOS.h in Headers */ = {isa = PBXBuildFile; fileRef = 73ED76485105C934414FC518238A5BBA /* OIDAuthState+IOS.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9B284B633436E76EE5B54F22C585DE09 /* GTMGatherInputStream.h in Headers */ = {isa = PBXBuildFile; fileRef = 900EFC7D2DA62CD97F4ACD702402511F /* GTMGatherInputStream.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 9D3116436BD43AD6F1377E42D25376C4 /* GTMAppAuthFetcherAuthorization+Keychain.m in Sources */ = {isa = PBXBuildFile; fileRef = DD444C88012D2F6FAE84D9550BB0EF4B /* GTMAppAuthFetcherAuthorization+Keychain.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A4D092754C00EFE99B711BC5A7BFA1E4 /* OIDAuthorizationRequest.m in Sources */ = {isa = PBXBuildFile; fileRef = C73B72198FEEF813588DEEC1FC1E8C61 /* OIDAuthorizationRequest.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A5D95128D92A21426818F15534A55F87 /* OIDScopes.h in Headers */ = {isa = PBXBuildFile; fileRef = 9687DA15623AB55FA6F6ABC8EA39462C /* OIDScopes.h */; settings = {ATTRIBUTES = (Public, ); }; }; + A85F9D92F3A2E727F577B226FD0F1C67 /* OIDAuthState+IOS.m in Sources */ = {isa = PBXBuildFile; fileRef = F604877DB3E7B3F56DC4288126E3FA8D /* OIDAuthState+IOS.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + A9895734D64C7E6DC6FD0F3A9FAD585E /* GTMOAuth2KeychainCompatibility.m in Sources */ = {isa = PBXBuildFile; fileRef = 587036783B41E4F706BE8F843BE0F01E /* GTMOAuth2KeychainCompatibility.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + AB3698270F8A3150361547937E6FAAB6 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7913DC9B69DD1D3964FBA164783509BA /* Foundation.framework */; }; + ADFBD87F7A0E559CDC45046C19E2BFFA /* OIDScopeUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E374F62E549B83FCB006E3218FDC26B /* OIDScopeUtilities.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + B71DB8CCBF93A0737DA9E5F2FCE256A4 /* OIDAuthorizationUICoordinatorIOS.m in Sources */ = {isa = PBXBuildFile; fileRef = 0814A830E538EA1DFEB08764DBFCBA9F /* OIDAuthorizationUICoordinatorIOS.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + BBF4EDA4ED288153AE21D05F16F9EF53 /* GTMAppAuthFetcherAuthorization.h in Headers */ = {isa = PBXBuildFile; fileRef = E07241835B7905672CDA3658CEB28709 /* GTMAppAuthFetcherAuthorization.h */; settings = {ATTRIBUTES = (Public, ); }; }; + BC7D1DA312042623733A0944227C1F48 /* SafariServices.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = BE75BFBB21B41BAE5645EEC8A13A7352 /* SafariServices.framework */; }; + C1EDD4B78D81BD3E32E4F75AD3731C80 /* OIDAuthState.h in Headers */ = {isa = PBXBuildFile; fileRef = 26B3C8EC9CC2B4F921871C8F9990D6CF /* OIDAuthState.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C66DF94893571FFFC3D18360A57029F0 /* OIDAuthorizationUICoordinator.h in Headers */ = {isa = PBXBuildFile; fileRef = FCC3F2C54FE772C769F267129A73176B /* OIDAuthorizationUICoordinator.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C747B9FFA800FC0593BBB37CB06BE6C1 /* GTMKeychain.h in Headers */ = {isa = PBXBuildFile; fileRef = D2754DFE752318982123E2DB433BDE72 /* GTMKeychain.h */; settings = {ATTRIBUTES = (Public, ); }; }; + C74FBC64C6F6693F1F27E1A37B63A5DA /* OIDErrorUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 053CCFF1E6CEBC2A729259D3C49DDA9D /* OIDErrorUtilities.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + CC01F710ADECFF21C80CD635CCAC0D4B /* OIDServiceConfiguration.h in Headers */ = {isa = PBXBuildFile; fileRef = DDFDCB828A435969C1BD570646121286 /* OIDServiceConfiguration.h */; settings = {ATTRIBUTES = (Public, ); }; }; + CCFB094368B5345A86D7D44850313D2C /* OIDErrorUtilities.h in Headers */ = {isa = PBXBuildFile; fileRef = F268693D17447A20315FD47D1F4083B3 /* OIDErrorUtilities.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D70DD8B1042EA6582C7E84B4578AEFEB /* OIDTokenUtilities.m in Sources */ = {isa = PBXBuildFile; fileRef = 5CB2BA724C5B3B353D0A664A12CFAADD /* OIDTokenUtilities.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D85F0BB3FF73D05B3FAA19CBFF350F05 /* OIDAuthStateChangeDelegate.h in Headers */ = {isa = PBXBuildFile; fileRef = B266D572236D795F81E72F163C8A6659 /* OIDAuthStateChangeDelegate.h */; settings = {ATTRIBUTES = (Public, ); }; }; + D8C453620219B0AC299BA9FA765E6003 /* OIDFieldMapping.m in Sources */ = {isa = PBXBuildFile; fileRef = 6143AF90655C1B173206C25159611901 /* OIDFieldMapping.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + D8EF474E1E5A1F8AF6C0191245B91A1B /* OIDURLQueryComponent.m in Sources */ = {isa = PBXBuildFile; fileRef = 6CCA4AA35A5C7C84F2855AE386D458C9 /* OIDURLQueryComponent.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + DA3D6056B026A60BC084830BEA82D0AF /* GTMSessionFetcher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0300BA24DF53F632FFE8858D06256AAC /* GTMSessionFetcher.framework */; }; + DC25CE95F2F1A02BC9FAF78590C15E72 /* OIDTokenRequest.h in Headers */ = {isa = PBXBuildFile; fileRef = AA2C4E5885B991C2A7FFC07DE78DE904 /* OIDTokenRequest.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DC7DD5E5E320B449E658957BE75F147F /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7913DC9B69DD1D3964FBA164783509BA /* Foundation.framework */; }; + E41651F835F25741B73DC31E1FD93C69 /* AppAuth-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 149FA635DFA5F502B7E5EEEDAD232B7D /* AppAuth-dummy.m */; }; + E4BD9365CB59C3786D727EED1508316E /* OIDResponseTypes.m in Sources */ = {isa = PBXBuildFile; fileRef = C40BB6E400A26455BF192D3DE9CD349C /* OIDResponseTypes.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + E91F9A4BA5D8957F697D099FFB2F3424 /* OIDTokenResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = 94400C1670EFAB4DD7C5A06C34E0BDE9 /* OIDTokenResponse.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + EC422826EE444A7E5343F97366AB2244 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7913DC9B69DD1D3964FBA164783509BA /* Foundation.framework */; }; + EF539B12034051C27D021FE541A31600 /* GTMSessionFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 6E8F664CC131087A42E85EC286F50FF6 /* GTMSessionFetcher.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F07647738909A3B29A44E33E63FC9F16 /* OIDAuthorizationService+IOS.m in Sources */ = {isa = PBXBuildFile; fileRef = 283251715BAE8BD44435BE7B4CF851BC /* OIDAuthorizationService+IOS.m */; settings = {COMPILER_FLAGS = "-w -Xanalyzer -analyzer-disable-all-checks"; }; }; + F84E02BC0092D6F89AE53914666769E1 /* AppAuth-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 11B00A3C40A1E3CAC28CF7173A83A284 /* AppAuth-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + FF028FF4F8EB620939BE52B7EBABA355 /* GTMMIMEDocument.h in Headers */ = {isa = PBXBuildFile; fileRef = 77488C3AE29F66A2DD169A7A0B8E9132 /* GTMMIMEDocument.h */; settings = {ATTRIBUTES = (Public, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 5C1E171E52B0C3159400DB12221A5D44 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 53F6FDC13F620DEF25DC511D8B05C851; + remoteInfo = AppAuth; + }; + 647DCA78031140F7F7D91B499B7A52EF /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = C665EB3E404B4D22FC56B866BD32E74F; + remoteInfo = GTMSessionFetcher; + }; + A2D198D08D70F04175CFE2BE9ACD28CB /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 998731B0C21D3DB32F5A1AECC0AC2721; + remoteInfo = GTMAppAuth; + }; + AD38F83A38C4B937C5F5C1A73FCFBCF3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = 53F6FDC13F620DEF25DC511D8B05C851; + remoteInfo = AppAuth; + }; + D9EFFA527DFFA69CC49EE421456D8D8E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = D41D8CD98F00B204E9800998ECF8427E /* Project object */; + proxyType = 1; + remoteGlobalIDString = C665EB3E404B4D22FC56B866BD32E74F; + remoteInfo = GTMSessionFetcher; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 0120206A8FF53C886C50D90170895BCE /* Pods-Paco-resources.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Paco-resources.sh"; sourceTree = ""; }; + 0300BA24DF53F632FFE8858D06256AAC /* GTMSessionFetcher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GTMSessionFetcher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 033828E9F739061ABB0CD148F8DD1464 /* OIDError.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDError.h; path = Source/OIDError.h; sourceTree = ""; }; + 053CCFF1E6CEBC2A729259D3C49DDA9D /* OIDErrorUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDErrorUtilities.m; path = Source/OIDErrorUtilities.m; sourceTree = ""; }; + 076A0E88DBC3FAAA62F74D546C98A69A /* GTMSessionFetcher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = GTMSessionFetcher.modulemap; sourceTree = ""; }; + 0814A830E538EA1DFEB08764DBFCBA9F /* OIDAuthorizationUICoordinatorIOS.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDAuthorizationUICoordinatorIOS.m; path = Source/iOS/OIDAuthorizationUICoordinatorIOS.m; sourceTree = ""; }; + 0B9774BCDA3BBCE6B205C4AA5A96A41F /* OIDScopeUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDScopeUtilities.h; path = Source/OIDScopeUtilities.h; sourceTree = ""; }; + 0E9535007AD24552B7E98AEDEFF133E6 /* OIDAuthStateErrorDelegate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthStateErrorDelegate.h; path = Source/OIDAuthStateErrorDelegate.h; sourceTree = ""; }; + 0FD1CA6F54346736C2C1FCFE917A95BB /* OIDAuthorizationResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthorizationResponse.h; path = Source/OIDAuthorizationResponse.h; sourceTree = ""; }; + 11B00A3C40A1E3CAC28CF7173A83A284 /* AppAuth-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AppAuth-umbrella.h"; sourceTree = ""; }; + 13EF6E71296C7218D7E1BE66CE06A48A /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 141AD2DDDB8351799E53BB553944F383 /* AppAuth.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = AppAuth.xcconfig; sourceTree = ""; }; + 149A77A4DBC464E76D1BEDD412391260 /* Pods-Paco-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Paco-acknowledgements.plist"; sourceTree = ""; }; + 149FA635DFA5F502B7E5EEEDAD232B7D /* AppAuth-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "AppAuth-dummy.m"; sourceTree = ""; }; + 19F85B128AFFE15CA245DF15B79B091E /* Pods-Paco.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Paco.release.xcconfig"; sourceTree = ""; }; + 1B705CE4C794EE0BEA96A0477F37CF59 /* OIDServiceConfiguration.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDServiceConfiguration.m; path = Source/OIDServiceConfiguration.m; sourceTree = ""; }; + 1CA011FF44771AE399909E798657E01D /* GTMAppAuth.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GTMAppAuth.xcconfig; sourceTree = ""; }; + 202F5DC2942FCBFA2D6D433E9F21C96C /* OIDURLQueryComponent.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDURLQueryComponent.h; path = Source/OIDURLQueryComponent.h; sourceTree = ""; }; + 269664272B64A2BCBD6ECBD99AF74AC4 /* AppAuth.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = AppAuth.modulemap; sourceTree = ""; }; + 26B3C8EC9CC2B4F921871C8F9990D6CF /* OIDAuthState.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthState.h; path = Source/OIDAuthState.h; sourceTree = ""; }; + 272FEEABF1FEDCC62FC45B7834FB7657 /* GTMSessionUploadFetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionUploadFetcher.h; path = Source/GTMSessionUploadFetcher.h; sourceTree = ""; }; + 283251715BAE8BD44435BE7B4CF851BC /* OIDAuthorizationService+IOS.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "OIDAuthorizationService+IOS.m"; path = "Source/iOS/OIDAuthorizationService+IOS.m"; sourceTree = ""; }; + 2B4AA34F81886ED5DEA8F972E0E75F10 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/SystemConfiguration.framework; sourceTree = DEVELOPER_DIR; }; + 2D7E8CD2295D27D85E86452FEFDF8C29 /* AppAuth.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = AppAuth.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 2E374F62E549B83FCB006E3218FDC26B /* OIDScopeUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDScopeUtilities.m; path = Source/OIDScopeUtilities.m; sourceTree = ""; }; + 2F8B9AB9204B82825009951CE3999341 /* OIDDefines.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDDefines.h; path = Source/OIDDefines.h; sourceTree = ""; }; + 3230C62D1ACEA3C291D2A940D4BCB1FA /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Security.framework; sourceTree = DEVELOPER_DIR; }; + 375C7DDCFF8094416317A1F78C0C945C /* OIDServiceDiscovery.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDServiceDiscovery.h; path = Source/OIDServiceDiscovery.h; sourceTree = ""; }; + 3CB2CF71592703FABB023BA59DCB2597 /* GTMAppAuthFetcherAuthorization.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMAppAuthFetcherAuthorization.m; path = Source/GTMAppAuthFetcherAuthorization.m; sourceTree = ""; }; + 3E66263F7F6CD4ACC9A470FF6F78017B /* OIDAuthState.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDAuthState.m; path = Source/OIDAuthState.m; sourceTree = ""; }; + 3ED390BB7B6E7AB1E9C3BBA283009B2B /* GTMSessionFetcher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GTMSessionFetcher.framework; path = GTMSessionFetcher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 42EB5A9C39D3D84B6F1B6FCCBA2E9D40 /* OIDScopes.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDScopes.m; path = Source/OIDScopes.m; sourceTree = ""; }; + 485019302B864BC20566A5F7BAB51B22 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 49A516AF90D0109B7E9E61A5EDE08A62 /* GTMMIMEDocument.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMMIMEDocument.m; path = Source/GTMMIMEDocument.m; sourceTree = ""; }; + 4AC8EB1132110E0C7EF942132C746860 /* Pods-Paco-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Paco-acknowledgements.markdown"; sourceTree = ""; }; + 50A985A40E6F1913AE9748EF943518AF /* AppAuth-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "AppAuth-prefix.pch"; sourceTree = ""; }; + 5150A5E46D228CD1521517156771C294 /* GTMSessionFetcher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMSessionFetcher-umbrella.h"; sourceTree = ""; }; + 52600E8E58A7AF664609726A67C8346C /* GTMAppAuth.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMAppAuth.h; path = Source/GTMAppAuth.h; sourceTree = ""; }; + 5304ABCF7CC87CA09372FBAEE1217767 /* GTMSessionUploadFetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionUploadFetcher.m; path = Source/GTMSessionUploadFetcher.m; sourceTree = ""; }; + 56D50B6AE74F5BEBED5D65D58EBCE861 /* GTMOAuth2KeychainCompatibility.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMOAuth2KeychainCompatibility.h; path = Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.h; sourceTree = ""; }; + 587036783B41E4F706BE8F843BE0F01E /* GTMOAuth2KeychainCompatibility.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMOAuth2KeychainCompatibility.m; path = Source/GTMOAuth2KeychainCompatibility/GTMOAuth2KeychainCompatibility.m; sourceTree = ""; }; + 58BA9E6DD44A9AFCC1AB320BA7F8883D /* GTMSessionFetcher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GTMSessionFetcher-dummy.m"; sourceTree = ""; }; + 5CB2BA724C5B3B353D0A664A12CFAADD /* OIDTokenUtilities.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDTokenUtilities.m; path = Source/OIDTokenUtilities.m; sourceTree = ""; }; + 5DE246AAED9D6D8CBB31055CFBFD85EC /* OIDTokenResponse.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDTokenResponse.h; path = Source/OIDTokenResponse.h; sourceTree = ""; }; + 6143AF90655C1B173206C25159611901 /* OIDFieldMapping.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDFieldMapping.m; path = Source/OIDFieldMapping.m; sourceTree = ""; }; + 63455CFDF6D04D12FDFFAEE532CC9F6E /* OIDAuthorizationService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthorizationService.h; path = Source/OIDAuthorizationService.h; sourceTree = ""; }; + 63F9A90BC50DA5A31590E8B310C742F6 /* OIDFieldMapping.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDFieldMapping.h; path = Source/OIDFieldMapping.h; sourceTree = ""; }; + 64F2583E4879DDF971B154C556ACC18D /* OIDTokenRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDTokenRequest.m; path = Source/OIDTokenRequest.m; sourceTree = ""; }; + 66460CC526EA7E68C0B70107D5CAB52A /* OIDAuthorizationUICoordinatorIOS.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthorizationUICoordinatorIOS.h; path = Source/iOS/OIDAuthorizationUICoordinatorIOS.h; sourceTree = ""; }; + 68A279939DD415BC8CF3F46B06514C55 /* OIDTokenUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDTokenUtilities.h; path = Source/OIDTokenUtilities.h; sourceTree = ""; }; + 6946FC57D765C7E3C752733FFF4BE7E7 /* GTMSessionFetcherService.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcherService.h; path = Source/GTMSessionFetcherService.h; sourceTree = ""; }; + 6A446BD3F07C1E721D3002146B260DB6 /* Pods-Paco.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Paco.debug.xcconfig"; sourceTree = ""; }; + 6A81018DA512037BBDAFE34FCC9ABAC8 /* GTMSessionFetcherService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcherService.m; path = Source/GTMSessionFetcherService.m; sourceTree = ""; }; + 6CCA4AA35A5C7C84F2855AE386D458C9 /* OIDURLQueryComponent.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDURLQueryComponent.m; path = Source/OIDURLQueryComponent.m; sourceTree = ""; }; + 6E4E44554DBDB983ACF4650955C9FCC6 /* OIDServiceDiscovery.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDServiceDiscovery.m; path = Source/OIDServiceDiscovery.m; sourceTree = ""; }; + 6E8F664CC131087A42E85EC286F50FF6 /* GTMSessionFetcher.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcher.m; path = Source/GTMSessionFetcher.m; sourceTree = ""; }; + 7339935E270AC81C7E3530A07439629F /* AppAuth.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = AppAuth.framework; path = AppAuth.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 73ED76485105C934414FC518238A5BBA /* OIDAuthState+IOS.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "OIDAuthState+IOS.h"; path = "Source/iOS/OIDAuthState+IOS.h"; sourceTree = ""; }; + 77488C3AE29F66A2DD169A7A0B8E9132 /* GTMMIMEDocument.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMMIMEDocument.h; path = Source/GTMMIMEDocument.h; sourceTree = ""; }; + 7913DC9B69DD1D3964FBA164783509BA /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 89618343D0C231973F4A5C6F4A28BB97 /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 89DEED8030ED39FD47A4E20B2C847F86 /* OIDAuthorizationService.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDAuthorizationService.m; path = Source/OIDAuthorizationService.m; sourceTree = ""; }; + 900EFC7D2DA62CD97F4ACD702402511F /* GTMGatherInputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMGatherInputStream.h; path = Source/GTMGatherInputStream.h; sourceTree = ""; }; + 91F6ECB2DBEDACB96ECFB893C93C529A /* GTMSessionFetcher.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = GTMSessionFetcher.xcconfig; sourceTree = ""; }; + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 94400C1670EFAB4DD7C5A06C34E0BDE9 /* OIDTokenResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDTokenResponse.m; path = Source/OIDTokenResponse.m; sourceTree = ""; }; + 9687DA15623AB55FA6F6ABC8EA39462C /* OIDScopes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDScopes.h; path = Source/OIDScopes.h; sourceTree = ""; }; + 97792B2D7AB722B03A55FB03221E7073 /* AppAuth.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = AppAuth.h; path = Source/AppAuth.h; sourceTree = ""; }; + 9B29E431B8F86498A840C1820E9D1B14 /* Pods_Paco.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_Paco.framework; path = "Pods-Paco.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; + A41F1AC66D55F42B54354AC887B28908 /* GTMAppAuth.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = GTMAppAuth.framework; path = GTMAppAuth.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AA2C4E5885B991C2A7FFC07DE78DE904 /* OIDTokenRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDTokenRequest.h; path = Source/OIDTokenRequest.h; sourceTree = ""; }; + AB21958B56BDE59D9716A5A40371064D /* GTMReadMonitorInputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMReadMonitorInputStream.m; path = Source/GTMReadMonitorInputStream.m; sourceTree = ""; }; + B266D572236D795F81E72F163C8A6659 /* OIDAuthStateChangeDelegate.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthStateChangeDelegate.h; path = Source/OIDAuthStateChangeDelegate.h; sourceTree = ""; }; + B8CA0A1990BF67E574CEE2DB4D9F2D23 /* OIDGrantTypes.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDGrantTypes.m; path = Source/OIDGrantTypes.m; sourceTree = ""; }; + BD37E7A2EB0FBBFDD34A61D0A8119677 /* GTMAppAuth-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMAppAuth-prefix.pch"; sourceTree = ""; }; + BE75BFBB21B41BAE5645EEC8A13A7352 /* SafariServices.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SafariServices.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/System/Library/Frameworks/SafariServices.framework; sourceTree = DEVELOPER_DIR; }; + BFA011652B437DCB315BF3C3E12897DE /* GTMSessionFetcher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMSessionFetcher-prefix.pch"; sourceTree = ""; }; + C14505F278CD4F7A6A3FCB739A8ECB3E /* GTMKeychain_iOS.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMKeychain_iOS.m; path = Source/iOS/GTMKeychain_iOS.m; sourceTree = ""; }; + C2D2AF3C3C1CDF9D3B20A77590688B72 /* Pods-Paco-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Paco-dummy.m"; sourceTree = ""; }; + C40BB6E400A26455BF192D3DE9CD349C /* OIDResponseTypes.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDResponseTypes.m; path = Source/OIDResponseTypes.m; sourceTree = ""; }; + C73B72198FEEF813588DEEC1FC1E8C61 /* OIDAuthorizationRequest.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDAuthorizationRequest.m; path = Source/OIDAuthorizationRequest.m; sourceTree = ""; }; + C9C46140D880D6988E43D8E0D4BBFD73 /* OIDResponseTypes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDResponseTypes.h; path = Source/OIDResponseTypes.h; sourceTree = ""; }; + CAD16928502F4F55913677A189704C45 /* OIDAuthorizationRequest.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthorizationRequest.h; path = Source/OIDAuthorizationRequest.h; sourceTree = ""; }; + CB91E17F6A4CB1C04A11A18CBF150299 /* GTMSessionFetcher.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcher.h; path = Source/GTMSessionFetcher.h; sourceTree = ""; }; + CBF00FDDFFD45BD1DA018FAD51FA1CFC /* Pods-Paco-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Paco-frameworks.sh"; sourceTree = ""; }; + CE0B9513B9FAB8667288E046C769D14D /* OIDAuthorizationResponse.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDAuthorizationResponse.m; path = Source/OIDAuthorizationResponse.m; sourceTree = ""; }; + CE2BF8D24AFF9CC8974205CF8036904A /* GTMAppAuth.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = GTMAppAuth.modulemap; sourceTree = ""; }; + D194073227644378587F98E07E22D0FE /* GTMSessionFetcherLogging.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMSessionFetcherLogging.m; path = Source/GTMSessionFetcherLogging.m; sourceTree = ""; }; + D1FCC6F5352506E792EECF9C5628D0E3 /* Pods-Paco-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Paco-umbrella.h"; sourceTree = ""; }; + D26D99FDCB4D9801024FACF74F21FE7B /* GTMAppAuthFetcherAuthorization+Keychain.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "GTMAppAuthFetcherAuthorization+Keychain.h"; path = "Source/GTMAppAuthFetcherAuthorization+Keychain.h"; sourceTree = ""; }; + D2754DFE752318982123E2DB433BDE72 /* GTMKeychain.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMKeychain.h; path = Source/GTMKeychain.h; sourceTree = ""; }; + D53412410D74B04597223B92323B1440 /* GTMAppAuth-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "GTMAppAuth-dummy.m"; sourceTree = ""; }; + D69843FF00BEDAB2732040BD839B5BF5 /* GTMSessionFetcherLogging.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMSessionFetcherLogging.h; path = Source/GTMSessionFetcherLogging.h; sourceTree = ""; }; + DD444C88012D2F6FAE84D9550BB0EF4B /* GTMAppAuthFetcherAuthorization+Keychain.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "GTMAppAuthFetcherAuthorization+Keychain.m"; path = "Source/GTMAppAuthFetcherAuthorization+Keychain.m"; sourceTree = ""; }; + DDFDCB828A435969C1BD570646121286 /* OIDServiceConfiguration.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDServiceConfiguration.h; path = Source/OIDServiceConfiguration.h; sourceTree = ""; }; + DFB005A72D69B6B7EABDABB1E88655F8 /* OIDAuthorizationService+IOS.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = "OIDAuthorizationService+IOS.h"; path = "Source/iOS/OIDAuthorizationService+IOS.h"; sourceTree = ""; }; + E0350B74ADC0F8BD1DB3D4BBB6B6CA84 /* GTMAppAuth-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "GTMAppAuth-umbrella.h"; sourceTree = ""; }; + E07241835B7905672CDA3658CEB28709 /* GTMAppAuthFetcherAuthorization.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMAppAuthFetcherAuthorization.h; path = Source/GTMAppAuthFetcherAuthorization.h; sourceTree = ""; }; + E14392158D250569564E07CD4AB2EC0D /* OIDGrantTypes.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDGrantTypes.h; path = Source/OIDGrantTypes.h; sourceTree = ""; }; + E5CA89CB5032AB69A562DA933BF5CFCE /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E6A55F3CADD407F51B351E9EEF0F2B82 /* GTMGatherInputStream.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = GTMGatherInputStream.m; path = Source/GTMGatherInputStream.m; sourceTree = ""; }; + F03DB0868A6F2928F5B004811B716C22 /* Pods-Paco.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; path = "Pods-Paco.modulemap"; sourceTree = ""; }; + F268693D17447A20315FD47D1F4083B3 /* OIDErrorUtilities.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDErrorUtilities.h; path = Source/OIDErrorUtilities.h; sourceTree = ""; }; + F604877DB3E7B3F56DC4288126E3FA8D /* OIDAuthState+IOS.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = "OIDAuthState+IOS.m"; path = "Source/iOS/OIDAuthState+IOS.m"; sourceTree = ""; }; + F92C3416A5D56E3F173392F0F15D4F28 /* OIDError.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = OIDError.m; path = Source/OIDError.m; sourceTree = ""; }; + FA1D03E0948398398A3A16B820B1DA64 /* GTMReadMonitorInputStream.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = GTMReadMonitorInputStream.h; path = Source/GTMReadMonitorInputStream.h; sourceTree = ""; }; + FCC3F2C54FE772C769F267129A73176B /* OIDAuthorizationUICoordinator.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = OIDAuthorizationUICoordinator.h; path = Source/OIDAuthorizationUICoordinator.h; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 036EDA244A5C125BC0AB43768BFA8F35 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2660617C2C498739B46226290949E95C /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 39CFA73041FCEE6EC27B030755DCAAC3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + EC422826EE444A7E5343F97366AB2244 /* Foundation.framework in Frameworks */, + 3F4E8D45F39FE16C1C1B186F62C590A9 /* Security.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9DF15C87226E44BF5463E100252D6101 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 3DF76B9F9186685EC9CAA507869229AA /* AppAuth.framework in Frameworks */, + DC7DD5E5E320B449E658957BE75F147F /* Foundation.framework in Frameworks */, + DA3D6056B026A60BC084830BEA82D0AF /* GTMSessionFetcher.framework in Frameworks */, + BC7D1DA312042623733A0944227C1F48 /* SafariServices.framework in Frameworks */, + 2B63606B0F2C3304BA96032CF8146D7C /* Security.framework in Frameworks */, + 489DA103EBDA06A4E5F26F1A7D23315E /* SystemConfiguration.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A5B184DEAE747D9FC762B59357862417 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + AB3698270F8A3150361547937E6FAAB6 /* Foundation.framework in Frameworks */, + 458793DCB8A819F91488A99ABDEE8EB0 /* SafariServices.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0B306B82CAA0C4C9A1E83AEDA2CDBA5D /* Products */ = { + isa = PBXGroup; + children = ( + 7339935E270AC81C7E3530A07439629F /* AppAuth.framework */, + A41F1AC66D55F42B54354AC887B28908 /* GTMAppAuth.framework */, + 3ED390BB7B6E7AB1E9C3BBA283009B2B /* GTMSessionFetcher.framework */, + 9B29E431B8F86498A840C1820E9D1B14 /* Pods_Paco.framework */, + ); + name = Products; + sourceTree = ""; + }; + 23AD62A5F1E89C605FEB506FD5632A05 /* iOS */ = { + isa = PBXGroup; + children = ( + 7913DC9B69DD1D3964FBA164783509BA /* Foundation.framework */, + BE75BFBB21B41BAE5645EEC8A13A7352 /* SafariServices.framework */, + 3230C62D1ACEA3C291D2A940D4BCB1FA /* Security.framework */, + 2B4AA34F81886ED5DEA8F972E0E75F10 /* SystemConfiguration.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 3114B152F89D59258D7C9990E20DC8FE /* GTMAppAuth */ = { + isa = PBXGroup; + children = ( + 52600E8E58A7AF664609726A67C8346C /* GTMAppAuth.h */, + E07241835B7905672CDA3658CEB28709 /* GTMAppAuthFetcherAuthorization.h */, + 3CB2CF71592703FABB023BA59DCB2597 /* GTMAppAuthFetcherAuthorization.m */, + D26D99FDCB4D9801024FACF74F21FE7B /* GTMAppAuthFetcherAuthorization+Keychain.h */, + DD444C88012D2F6FAE84D9550BB0EF4B /* GTMAppAuthFetcherAuthorization+Keychain.m */, + D2754DFE752318982123E2DB433BDE72 /* GTMKeychain.h */, + C14505F278CD4F7A6A3FCB739A8ECB3E /* GTMKeychain_iOS.m */, + 56D50B6AE74F5BEBED5D65D58EBCE861 /* GTMOAuth2KeychainCompatibility.h */, + 587036783B41E4F706BE8F843BE0F01E /* GTMOAuth2KeychainCompatibility.m */, + 4DE19E20380B8173427BCBC3A6258724 /* Support Files */, + ); + name = GTMAppAuth; + path = GTMAppAuth; + sourceTree = ""; + }; + 4DE19E20380B8173427BCBC3A6258724 /* Support Files */ = { + isa = PBXGroup; + children = ( + CE2BF8D24AFF9CC8974205CF8036904A /* GTMAppAuth.modulemap */, + 1CA011FF44771AE399909E798657E01D /* GTMAppAuth.xcconfig */, + D53412410D74B04597223B92323B1440 /* GTMAppAuth-dummy.m */, + BD37E7A2EB0FBBFDD34A61D0A8119677 /* GTMAppAuth-prefix.pch */, + E0350B74ADC0F8BD1DB3D4BBB6B6CA84 /* GTMAppAuth-umbrella.h */, + E5CA89CB5032AB69A562DA933BF5CFCE /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/GTMAppAuth"; + sourceTree = ""; + }; + 57EE6E224C471BA5C5FDB62E0FA51985 /* Support Files */ = { + isa = PBXGroup; + children = ( + 076A0E88DBC3FAAA62F74D546C98A69A /* GTMSessionFetcher.modulemap */, + 91F6ECB2DBEDACB96ECFB893C93C529A /* GTMSessionFetcher.xcconfig */, + 58BA9E6DD44A9AFCC1AB320BA7F8883D /* GTMSessionFetcher-dummy.m */, + BFA011652B437DCB315BF3C3E12897DE /* GTMSessionFetcher-prefix.pch */, + 5150A5E46D228CD1521517156771C294 /* GTMSessionFetcher-umbrella.h */, + 13EF6E71296C7218D7E1BE66CE06A48A /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/GTMSessionFetcher"; + sourceTree = ""; + }; + 5DAE5F786CA22495FF11AB3784CE5E97 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 2D7E8CD2295D27D85E86452FEFDF8C29 /* AppAuth.framework */, + 0300BA24DF53F632FFE8858D06256AAC /* GTMSessionFetcher.framework */, + 23AD62A5F1E89C605FEB506FD5632A05 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 611472FEDC48798D334369F9225B29C7 /* Core */ = { + isa = PBXGroup; + children = ( + CB91E17F6A4CB1C04A11A18CBF150299 /* GTMSessionFetcher.h */, + 6E8F664CC131087A42E85EC286F50FF6 /* GTMSessionFetcher.m */, + D69843FF00BEDAB2732040BD839B5BF5 /* GTMSessionFetcherLogging.h */, + D194073227644378587F98E07E22D0FE /* GTMSessionFetcherLogging.m */, + 6946FC57D765C7E3C752733FFF4BE7E7 /* GTMSessionFetcherService.h */, + 6A81018DA512037BBDAFE34FCC9ABAC8 /* GTMSessionFetcherService.m */, + 272FEEABF1FEDCC62FC45B7834FB7657 /* GTMSessionUploadFetcher.h */, + 5304ABCF7CC87CA09372FBAEE1217767 /* GTMSessionUploadFetcher.m */, + ); + name = Core; + sourceTree = ""; + }; + 782A9462A9A937348C6A6968D37BFA9D /* Support Files */ = { + isa = PBXGroup; + children = ( + 269664272B64A2BCBD6ECBD99AF74AC4 /* AppAuth.modulemap */, + 141AD2DDDB8351799E53BB553944F383 /* AppAuth.xcconfig */, + 149FA635DFA5F502B7E5EEEDAD232B7D /* AppAuth-dummy.m */, + 50A985A40E6F1913AE9748EF943518AF /* AppAuth-prefix.pch */, + 11B00A3C40A1E3CAC28CF7173A83A284 /* AppAuth-umbrella.h */, + 485019302B864BC20566A5F7BAB51B22 /* Info.plist */, + ); + name = "Support Files"; + path = "../Target Support Files/AppAuth"; + sourceTree = ""; + }; + 7A4C73E435EEA5EC22B3F000D820592F /* Pods-Paco */ = { + isa = PBXGroup; + children = ( + 89618343D0C231973F4A5C6F4A28BB97 /* Info.plist */, + F03DB0868A6F2928F5B004811B716C22 /* Pods-Paco.modulemap */, + 4AC8EB1132110E0C7EF942132C746860 /* Pods-Paco-acknowledgements.markdown */, + 149A77A4DBC464E76D1BEDD412391260 /* Pods-Paco-acknowledgements.plist */, + C2D2AF3C3C1CDF9D3B20A77590688B72 /* Pods-Paco-dummy.m */, + CBF00FDDFFD45BD1DA018FAD51FA1CFC /* Pods-Paco-frameworks.sh */, + 0120206A8FF53C886C50D90170895BCE /* Pods-Paco-resources.sh */, + D1FCC6F5352506E792EECF9C5628D0E3 /* Pods-Paco-umbrella.h */, + 6A446BD3F07C1E721D3002146B260DB6 /* Pods-Paco.debug.xcconfig */, + 19F85B128AFFE15CA245DF15B79B091E /* Pods-Paco.release.xcconfig */, + ); + name = "Pods-Paco"; + path = "Target Support Files/Pods-Paco"; + sourceTree = ""; + }; + 7DB346D0F39D3F0E887471402A8071AB = { + isa = PBXGroup; + children = ( + 93A4A3777CF96A4AAC1D13BA6DCCEA73 /* Podfile */, + 5DAE5F786CA22495FF11AB3784CE5E97 /* Frameworks */, + CA41948F98F4FC269D8F4ADC5323B690 /* Pods */, + 0B306B82CAA0C4C9A1E83AEDA2CDBA5D /* Products */, + BA9ECE4F5EFBA43F9003D3730B5EFCDB /* Targets Support Files */, + ); + sourceTree = ""; + }; + 9450EC1BF1AC142753FEEE807DE5F46E /* GTMSessionFetcher */ = { + isa = PBXGroup; + children = ( + 611472FEDC48798D334369F9225B29C7 /* Core */, + CE609F1D0F0E9D1EB19F7726DF8EE6C1 /* Full */, + 57EE6E224C471BA5C5FDB62E0FA51985 /* Support Files */, + ); + name = GTMSessionFetcher; + path = GTMSessionFetcher; + sourceTree = ""; + }; + A8EF8624149D3249B4399D63FD5361BA /* AppAuth */ = { + isa = PBXGroup; + children = ( + 97792B2D7AB722B03A55FB03221E7073 /* AppAuth.h */, + CAD16928502F4F55913677A189704C45 /* OIDAuthorizationRequest.h */, + C73B72198FEEF813588DEEC1FC1E8C61 /* OIDAuthorizationRequest.m */, + 0FD1CA6F54346736C2C1FCFE917A95BB /* OIDAuthorizationResponse.h */, + CE0B9513B9FAB8667288E046C769D14D /* OIDAuthorizationResponse.m */, + 63455CFDF6D04D12FDFFAEE532CC9F6E /* OIDAuthorizationService.h */, + 89DEED8030ED39FD47A4E20B2C847F86 /* OIDAuthorizationService.m */, + DFB005A72D69B6B7EABDABB1E88655F8 /* OIDAuthorizationService+IOS.h */, + 283251715BAE8BD44435BE7B4CF851BC /* OIDAuthorizationService+IOS.m */, + FCC3F2C54FE772C769F267129A73176B /* OIDAuthorizationUICoordinator.h */, + 66460CC526EA7E68C0B70107D5CAB52A /* OIDAuthorizationUICoordinatorIOS.h */, + 0814A830E538EA1DFEB08764DBFCBA9F /* OIDAuthorizationUICoordinatorIOS.m */, + 26B3C8EC9CC2B4F921871C8F9990D6CF /* OIDAuthState.h */, + 3E66263F7F6CD4ACC9A470FF6F78017B /* OIDAuthState.m */, + 73ED76485105C934414FC518238A5BBA /* OIDAuthState+IOS.h */, + F604877DB3E7B3F56DC4288126E3FA8D /* OIDAuthState+IOS.m */, + B266D572236D795F81E72F163C8A6659 /* OIDAuthStateChangeDelegate.h */, + 0E9535007AD24552B7E98AEDEFF133E6 /* OIDAuthStateErrorDelegate.h */, + 2F8B9AB9204B82825009951CE3999341 /* OIDDefines.h */, + 033828E9F739061ABB0CD148F8DD1464 /* OIDError.h */, + F92C3416A5D56E3F173392F0F15D4F28 /* OIDError.m */, + F268693D17447A20315FD47D1F4083B3 /* OIDErrorUtilities.h */, + 053CCFF1E6CEBC2A729259D3C49DDA9D /* OIDErrorUtilities.m */, + 63F9A90BC50DA5A31590E8B310C742F6 /* OIDFieldMapping.h */, + 6143AF90655C1B173206C25159611901 /* OIDFieldMapping.m */, + E14392158D250569564E07CD4AB2EC0D /* OIDGrantTypes.h */, + B8CA0A1990BF67E574CEE2DB4D9F2D23 /* OIDGrantTypes.m */, + C9C46140D880D6988E43D8E0D4BBFD73 /* OIDResponseTypes.h */, + C40BB6E400A26455BF192D3DE9CD349C /* OIDResponseTypes.m */, + 9687DA15623AB55FA6F6ABC8EA39462C /* OIDScopes.h */, + 42EB5A9C39D3D84B6F1B6FCCBA2E9D40 /* OIDScopes.m */, + 0B9774BCDA3BBCE6B205C4AA5A96A41F /* OIDScopeUtilities.h */, + 2E374F62E549B83FCB006E3218FDC26B /* OIDScopeUtilities.m */, + DDFDCB828A435969C1BD570646121286 /* OIDServiceConfiguration.h */, + 1B705CE4C794EE0BEA96A0477F37CF59 /* OIDServiceConfiguration.m */, + 375C7DDCFF8094416317A1F78C0C945C /* OIDServiceDiscovery.h */, + 6E4E44554DBDB983ACF4650955C9FCC6 /* OIDServiceDiscovery.m */, + AA2C4E5885B991C2A7FFC07DE78DE904 /* OIDTokenRequest.h */, + 64F2583E4879DDF971B154C556ACC18D /* OIDTokenRequest.m */, + 5DE246AAED9D6D8CBB31055CFBFD85EC /* OIDTokenResponse.h */, + 94400C1670EFAB4DD7C5A06C34E0BDE9 /* OIDTokenResponse.m */, + 68A279939DD415BC8CF3F46B06514C55 /* OIDTokenUtilities.h */, + 5CB2BA724C5B3B353D0A664A12CFAADD /* OIDTokenUtilities.m */, + 202F5DC2942FCBFA2D6D433E9F21C96C /* OIDURLQueryComponent.h */, + 6CCA4AA35A5C7C84F2855AE386D458C9 /* OIDURLQueryComponent.m */, + 782A9462A9A937348C6A6968D37BFA9D /* Support Files */, + ); + name = AppAuth; + path = AppAuth; + sourceTree = ""; + }; + BA9ECE4F5EFBA43F9003D3730B5EFCDB /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + 7A4C73E435EEA5EC22B3F000D820592F /* Pods-Paco */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; + CA41948F98F4FC269D8F4ADC5323B690 /* Pods */ = { + isa = PBXGroup; + children = ( + A8EF8624149D3249B4399D63FD5361BA /* AppAuth */, + 3114B152F89D59258D7C9990E20DC8FE /* GTMAppAuth */, + 9450EC1BF1AC142753FEEE807DE5F46E /* GTMSessionFetcher */, + ); + name = Pods; + sourceTree = ""; + }; + CE609F1D0F0E9D1EB19F7726DF8EE6C1 /* Full */ = { + isa = PBXGroup; + children = ( + 900EFC7D2DA62CD97F4ACD702402511F /* GTMGatherInputStream.h */, + E6A55F3CADD407F51B351E9EEF0F2B82 /* GTMGatherInputStream.m */, + 77488C3AE29F66A2DD169A7A0B8E9132 /* GTMMIMEDocument.h */, + 49A516AF90D0109B7E9E61A5EDE08A62 /* GTMMIMEDocument.m */, + FA1D03E0948398398A3A16B820B1DA64 /* GTMReadMonitorInputStream.h */, + AB21958B56BDE59D9716A5A40371064D /* GTMReadMonitorInputStream.m */, + ); + name = Full; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 01D10CFEB30E37A1241A231C6B1CA782 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 14263EAA67C8A8CA4A2B48B7100B637E /* Pods-Paco-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7F2E9E53855806568E72EE49154B542F /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 79D65A3B66B05DE9E521580E8D80E219 /* GTMAppAuth-umbrella.h in Headers */, + 453D96A62E3FBB4BE3E12F23A3EB2A09 /* GTMAppAuth.h in Headers */, + 226F07E34ED202CDD7C7F44C39A6C3F9 /* GTMAppAuthFetcherAuthorization+Keychain.h in Headers */, + BBF4EDA4ED288153AE21D05F16F9EF53 /* GTMAppAuthFetcherAuthorization.h in Headers */, + C747B9FFA800FC0593BBB37CB06BE6C1 /* GTMKeychain.h in Headers */, + 3BC4EC25BB6F740A9838D434E61F8D19 /* GTMOAuth2KeychainCompatibility.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 92D0AD81CB7CE16E04DD3B59C791C8D4 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 9B284B633436E76EE5B54F22C585DE09 /* GTMGatherInputStream.h in Headers */, + FF028FF4F8EB620939BE52B7EBABA355 /* GTMMIMEDocument.h in Headers */, + 255EBA8DEE85FE7DED245F4A102C1E62 /* GTMReadMonitorInputStream.h in Headers */, + 13F08C9FFA156E469A237C814BA78B9A /* GTMSessionFetcher-umbrella.h in Headers */, + 73A31127AD73F6377798FE097D131CA9 /* GTMSessionFetcher.h in Headers */, + 7896642E95A419F50D4CB35328226EAE /* GTMSessionFetcherLogging.h in Headers */, + 6B42CE645116C6EF7729C037835427FC /* GTMSessionFetcherService.h in Headers */, + 42024D4D8FF7CE2F399C987DB77A6B69 /* GTMSessionUploadFetcher.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FCC04571BAB847A89D51C4D94615A2A1 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + F84E02BC0092D6F89AE53914666769E1 /* AppAuth-umbrella.h in Headers */, + 8C1D6E61F8BC5C4DF16764609C831D39 /* AppAuth.h in Headers */, + 1AD85EA85FBBF6FAEB77DD550510C129 /* OIDAuthorizationRequest.h in Headers */, + 1DBDE74E7234F7F13CB7B03DBDB6943C /* OIDAuthorizationResponse.h in Headers */, + 1E18489D34047F312C152B31425F582F /* OIDAuthorizationService+IOS.h in Headers */, + 0897A26B3804CF0309918D2AF586634C /* OIDAuthorizationService.h in Headers */, + C66DF94893571FFFC3D18360A57029F0 /* OIDAuthorizationUICoordinator.h in Headers */, + 855F3C5D3D9DD7B1DC76C2F23BB15C7F /* OIDAuthorizationUICoordinatorIOS.h in Headers */, + 988551E340F39E9DDF2F0D0A37697025 /* OIDAuthState+IOS.h in Headers */, + C1EDD4B78D81BD3E32E4F75AD3731C80 /* OIDAuthState.h in Headers */, + D85F0BB3FF73D05B3FAA19CBFF350F05 /* OIDAuthStateChangeDelegate.h in Headers */, + 8DF27A4C9B970CD0A1383C04516DBF3C /* OIDAuthStateErrorDelegate.h in Headers */, + 426B9B1010FD474F3413B7B2AD4A0709 /* OIDDefines.h in Headers */, + 3EC50952B6EF2E750AE2D40DD9CED6B4 /* OIDError.h in Headers */, + CCFB094368B5345A86D7D44850313D2C /* OIDErrorUtilities.h in Headers */, + 3123B6E28D40FD4096EE2C5198B7D5E6 /* OIDFieldMapping.h in Headers */, + 8A49B374D458711BCFAFC14CBEF468B9 /* OIDGrantTypes.h in Headers */, + 3C05DF646F6067AE76ED2B2707392109 /* OIDResponseTypes.h in Headers */, + A5D95128D92A21426818F15534A55F87 /* OIDScopes.h in Headers */, + 13A8FA59BBD37888DAF84309AF8E38E9 /* OIDScopeUtilities.h in Headers */, + CC01F710ADECFF21C80CD635CCAC0D4B /* OIDServiceConfiguration.h in Headers */, + 04FE4B8DF889CDC972F9DDB10B4309F2 /* OIDServiceDiscovery.h in Headers */, + DC25CE95F2F1A02BC9FAF78590C15E72 /* OIDTokenRequest.h in Headers */, + 8DAE14D02A9CDCA2A37FB8663616D52E /* OIDTokenResponse.h in Headers */, + 0D1B02523FAD4FEA08532986C2CC4D9E /* OIDTokenUtilities.h in Headers */, + 550A0254DC3B4C648FB1A9D8121CB728 /* OIDURLQueryComponent.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 53F6FDC13F620DEF25DC511D8B05C851 /* AppAuth */ = { + isa = PBXNativeTarget; + buildConfigurationList = 24BAC270C6F051FBBFDE777EEB9D98E5 /* Build configuration list for PBXNativeTarget "AppAuth" */; + buildPhases = ( + 9165463CAB6ADC4A8E2C97B7500001A8 /* Sources */, + A5B184DEAE747D9FC762B59357862417 /* Frameworks */, + FCC04571BAB847A89D51C4D94615A2A1 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = AppAuth; + productName = AppAuth; + productReference = 7339935E270AC81C7E3530A07439629F /* AppAuth.framework */; + productType = "com.apple.product-type.framework"; + }; + 998731B0C21D3DB32F5A1AECC0AC2721 /* GTMAppAuth */ = { + isa = PBXNativeTarget; + buildConfigurationList = AEBF9D39845E24C56E1978EB78EBD7A6 /* Build configuration list for PBXNativeTarget "GTMAppAuth" */; + buildPhases = ( + 85891994FCF8BC037C5566AF38EB4B0D /* Sources */, + 9DF15C87226E44BF5463E100252D6101 /* Frameworks */, + 7F2E9E53855806568E72EE49154B542F /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + 95372E27C0911E66F5CEECA7B11EEDCA /* PBXTargetDependency */, + 4ED86225CFCA588ECEB722A8534DC2A3 /* PBXTargetDependency */, + ); + name = GTMAppAuth; + productName = GTMAppAuth; + productReference = A41F1AC66D55F42B54354AC887B28908 /* GTMAppAuth.framework */; + productType = "com.apple.product-type.framework"; + }; + C665EB3E404B4D22FC56B866BD32E74F /* GTMSessionFetcher */ = { + isa = PBXNativeTarget; + buildConfigurationList = A5E5841D32E7249B3964A72A1096EBB8 /* Build configuration list for PBXNativeTarget "GTMSessionFetcher" */; + buildPhases = ( + B52D4093904ABA250580FA3D910E453B /* Sources */, + 39CFA73041FCEE6EC27B030755DCAAC3 /* Frameworks */, + 92D0AD81CB7CE16E04DD3B59C791C8D4 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = GTMSessionFetcher; + productName = GTMSessionFetcher; + productReference = 3ED390BB7B6E7AB1E9C3BBA283009B2B /* GTMSessionFetcher.framework */; + productType = "com.apple.product-type.framework"; + }; + F965C96C077F1A948F66ACA60DCCDFA8 /* Pods-Paco */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3332BCD539DE55034487DBAA18D02C6C /* Build configuration list for PBXNativeTarget "Pods-Paco" */; + buildPhases = ( + 549CCE5D7410EF9A78DADBD92EC674BA /* Sources */, + 036EDA244A5C125BC0AB43768BFA8F35 /* Frameworks */, + 01D10CFEB30E37A1241A231C6B1CA782 /* Headers */, + ); + buildRules = ( + ); + dependencies = ( + CECE4AAE5A2C2CC19D29E06B6F8A9C1E /* PBXTargetDependency */, + A81097C713CB86802206E3035ACB9CC4 /* PBXTargetDependency */, + 0CD440725A0C2962237EF0BBF8800C04 /* PBXTargetDependency */, + ); + name = "Pods-Paco"; + productName = "Pods-Paco"; + productReference = 9B29E431B8F86498A840C1820E9D1B14 /* Pods_Paco.framework */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + D41D8CD98F00B204E9800998ECF8427E /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0830; + LastUpgradeCheck = 0700; + }; + buildConfigurationList = 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = 7DB346D0F39D3F0E887471402A8071AB; + productRefGroup = 0B306B82CAA0C4C9A1E83AEDA2CDBA5D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 53F6FDC13F620DEF25DC511D8B05C851 /* AppAuth */, + 998731B0C21D3DB32F5A1AECC0AC2721 /* GTMAppAuth */, + C665EB3E404B4D22FC56B866BD32E74F /* GTMSessionFetcher */, + F965C96C077F1A948F66ACA60DCCDFA8 /* Pods-Paco */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXSourcesBuildPhase section */ + 549CCE5D7410EF9A78DADBD92EC674BA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 19862760A53F3A6CA4E9067DA0139873 /* Pods-Paco-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 85891994FCF8BC037C5566AF38EB4B0D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1547A2BE902B31084257BA060D3574CA /* GTMAppAuth-dummy.m in Sources */, + 9D3116436BD43AD6F1377E42D25376C4 /* GTMAppAuthFetcherAuthorization+Keychain.m in Sources */, + 1A29B9533EBED91F61FACEE36967AFED /* GTMAppAuthFetcherAuthorization.m in Sources */, + 1D2434AB7550BCA92BA72756EB19EA98 /* GTMKeychain_iOS.m in Sources */, + A9895734D64C7E6DC6FD0F3A9FAD585E /* GTMOAuth2KeychainCompatibility.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9165463CAB6ADC4A8E2C97B7500001A8 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E41651F835F25741B73DC31E1FD93C69 /* AppAuth-dummy.m in Sources */, + A4D092754C00EFE99B711BC5A7BFA1E4 /* OIDAuthorizationRequest.m in Sources */, + 3DE044FE8D403D23E7B5F122E7A8D39D /* OIDAuthorizationResponse.m in Sources */, + F07647738909A3B29A44E33E63FC9F16 /* OIDAuthorizationService+IOS.m in Sources */, + 0D4ADE285EF78D3A06163A71A6445013 /* OIDAuthorizationService.m in Sources */, + B71DB8CCBF93A0737DA9E5F2FCE256A4 /* OIDAuthorizationUICoordinatorIOS.m in Sources */, + A85F9D92F3A2E727F577B226FD0F1C67 /* OIDAuthState+IOS.m in Sources */, + 1BA66882265D3E2F6DEAB16CEED26995 /* OIDAuthState.m in Sources */, + 6D8B8CFB7E83A8CA0B809FDBEB4A47C2 /* OIDError.m in Sources */, + C74FBC64C6F6693F1F27E1A37B63A5DA /* OIDErrorUtilities.m in Sources */, + D8C453620219B0AC299BA9FA765E6003 /* OIDFieldMapping.m in Sources */, + 981D75064EE46576327BC6AB5EED0B50 /* OIDGrantTypes.m in Sources */, + E4BD9365CB59C3786D727EED1508316E /* OIDResponseTypes.m in Sources */, + 7A75848963423CABE76715841215F587 /* OIDScopes.m in Sources */, + ADFBD87F7A0E559CDC45046C19E2BFFA /* OIDScopeUtilities.m in Sources */, + 97019F23C62401D00CB9092967FE6BA1 /* OIDServiceConfiguration.m in Sources */, + 2E43631F412FBF781740B299FD1ADD59 /* OIDServiceDiscovery.m in Sources */, + 445174A094F252E5237E9A4E4D0672A4 /* OIDTokenRequest.m in Sources */, + E91F9A4BA5D8957F697D099FFB2F3424 /* OIDTokenResponse.m in Sources */, + D70DD8B1042EA6582C7E84B4578AEFEB /* OIDTokenUtilities.m in Sources */, + D8EF474E1E5A1F8AF6C0191245B91A1B /* OIDURLQueryComponent.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + B52D4093904ABA250580FA3D910E453B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 831BCE3FB4505EADD68B4710897F2EBD /* GTMGatherInputStream.m in Sources */, + 547E49212790E32BF7785C73E946475D /* GTMMIMEDocument.m in Sources */, + 748248840E5671419F2DC48D0771B385 /* GTMReadMonitorInputStream.m in Sources */, + 8C065922E821A04F5646393CECA0480F /* GTMSessionFetcher-dummy.m in Sources */, + EF539B12034051C27D021FE541A31600 /* GTMSessionFetcher.m in Sources */, + 95FF8657E90CC8AB09546A3F28191513 /* GTMSessionFetcherLogging.m in Sources */, + 4FA537437D014D26081F0A200E42E8D7 /* GTMSessionFetcherService.m in Sources */, + 342F900F20D11C76722E8AF404C4472C /* GTMSessionUploadFetcher.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 0CD440725A0C2962237EF0BBF8800C04 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GTMSessionFetcher; + target = C665EB3E404B4D22FC56B866BD32E74F /* GTMSessionFetcher */; + targetProxy = D9EFFA527DFFA69CC49EE421456D8D8E /* PBXContainerItemProxy */; + }; + 4ED86225CFCA588ECEB722A8534DC2A3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GTMSessionFetcher; + target = C665EB3E404B4D22FC56B866BD32E74F /* GTMSessionFetcher */; + targetProxy = 647DCA78031140F7F7D91B499B7A52EF /* PBXContainerItemProxy */; + }; + 95372E27C0911E66F5CEECA7B11EEDCA /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = AppAuth; + target = 53F6FDC13F620DEF25DC511D8B05C851 /* AppAuth */; + targetProxy = AD38F83A38C4B937C5F5C1A73FCFBCF3 /* PBXContainerItemProxy */; + }; + A81097C713CB86802206E3035ACB9CC4 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GTMAppAuth; + target = 998731B0C21D3DB32F5A1AECC0AC2721 /* GTMAppAuth */; + targetProxy = A2D198D08D70F04175CFE2BE9ACD28CB /* PBXContainerItemProxy */; + }; + CECE4AAE5A2C2CC19D29E06B6F8A9C1E /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = AppAuth; + target = 53F6FDC13F620DEF25DC511D8B05C851 /* AppAuth */; + targetProxy = 5C1E171E52B0C3159400DB12221A5D44 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 1F58D15C0AD9C3624DEC156A3E5BF148 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 141AD2DDDB8351799E53BB553944F383 /* AppAuth.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/AppAuth/AppAuth-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/AppAuth/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/AppAuth/AppAuth.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = AppAuth; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 318C7CD3BDAA8A4F0526B8F79C7F6AD5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1CA011FF44771AE399909E798657E01D /* GTMAppAuth.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/GTMAppAuth/GTMAppAuth-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GTMAppAuth/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/GTMAppAuth/GTMAppAuth.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = GTMAppAuth; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 42587B5EC6B73D6CC1CDFDE5671891CF /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 19F85B128AFFE15CA245DF15B79B091E /* Pods-Paco.release.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-Paco/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Paco/Pods-Paco.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_Paco; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 484202E5D995CC81716F3E6C33CF15E9 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 91F6ECB2DBEDACB96ECFB893C93C529A /* GTMSessionFetcher.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GTMSessionFetcher/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = GTMSessionFetcher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 4E487F173E6C9664F4E9E26B9635D23C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + 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_OBJC_ROOT_CLASS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + ONLY_ACTIVE_ARCH = YES; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 5095AD76B3CAADF2CA49F6A354D9E52B /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 6A446BD3F07C1E721D3002146B260DB6 /* Pods-Paco.debug.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + INFOPLIST_FILE = "Target Support Files/Pods-Paco/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Paco/Pods-Paco.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = Pods_Paco; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 649A0ADDBD5C82B18A94CD99F045FCD1 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1CA011FF44771AE399909E798657E01D /* GTMAppAuth.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/GTMAppAuth/GTMAppAuth-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GTMAppAuth/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/GTMAppAuth/GTMAppAuth.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = GTMAppAuth; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 6E50CE3E886BF27E42404DF0AE6E4F53 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 91F6ECB2DBEDACB96ECFB893C93C529A /* GTMSessionFetcher.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/GTMSessionFetcher/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap"; + MTL_ENABLE_DEBUG_INFO = NO; + PRODUCT_NAME = GTMSessionFetcher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + BDD0139D6EB93FA375F887ABD62DAB2E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES; + 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_OBJC_ROOT_CLASS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGNING_REQUIRED = NO; + COPY_PHASE_STRIP = YES; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + PROVISIONING_PROFILE_SPECIFIER = NO_SIGNING/; + STRIP_INSTALLED_PRODUCT = NO; + SYMROOT = "${SRCROOT}/../build"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + F07E6331E4937000D1A40DBF0F447643 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 141AD2DDDB8351799E53BB553944F383 /* AppAuth.xcconfig */; + buildSettings = { + CODE_SIGN_IDENTITY = ""; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEBUG_INFORMATION_FORMAT = dwarf; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREFIX_HEADER = "Target Support Files/AppAuth/AppAuth-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/AppAuth/Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MODULEMAP_FILE = "Target Support Files/AppAuth/AppAuth.modulemap"; + MTL_ENABLE_DEBUG_INFO = YES; + PRODUCT_NAME = AppAuth; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 24BAC270C6F051FBBFDE777EEB9D98E5 /* Build configuration list for PBXNativeTarget "AppAuth" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + F07E6331E4937000D1A40DBF0F447643 /* Debug */, + 1F58D15C0AD9C3624DEC156A3E5BF148 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2D8E8EC45A3A1A1D94AE762CB5028504 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 4E487F173E6C9664F4E9E26B9635D23C /* Debug */, + BDD0139D6EB93FA375F887ABD62DAB2E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3332BCD539DE55034487DBAA18D02C6C /* Build configuration list for PBXNativeTarget "Pods-Paco" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 5095AD76B3CAADF2CA49F6A354D9E52B /* Debug */, + 42587B5EC6B73D6CC1CDFDE5671891CF /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A5E5841D32E7249B3964A72A1096EBB8 /* Build configuration list for PBXNativeTarget "GTMSessionFetcher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 484202E5D995CC81716F3E6C33CF15E9 /* Debug */, + 6E50CE3E886BF27E42404DF0AE6E4F53 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + AEBF9D39845E24C56E1978EB78EBD7A6 /* Build configuration list for PBXNativeTarget "GTMAppAuth" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 318C7CD3BDAA8A4F0526B8F79C7F6AD5 /* Debug */, + 649A0ADDBD5C82B18A94CD99F045FCD1 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = D41D8CD98F00B204E9800998ECF8427E /* Project object */; +} diff --git a/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/AppAuth.xcscheme b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/AppAuth.xcscheme new file mode 100644 index 000000000..7c6789929 --- /dev/null +++ b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/AppAuth.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/GTMAppAuth.xcscheme b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/GTMAppAuth.xcscheme new file mode 100644 index 000000000..0c8e9494b --- /dev/null +++ b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/GTMAppAuth.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme new file mode 100644 index 000000000..678400a2a --- /dev/null +++ b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/GTMSessionFetcher.xcscheme @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/Pods-Paco.xcscheme b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/Pods-Paco.xcscheme new file mode 100644 index 000000000..fcb14dcb1 --- /dev/null +++ b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/Pods-Paco.xcscheme @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/xcschememanagement.plist b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 000000000..94f509ccd --- /dev/null +++ b/Paco-iOS/Pods/Pods.xcodeproj/xcuserdata/bobevans.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,52 @@ + + + + + SchemeUserState + + AppAuth.xcscheme + + isShown + + + GTMAppAuth.xcscheme + + isShown + + + GTMSessionFetcher.xcscheme + + isShown + + + Pods-Paco.xcscheme + + isShown + + + + SuppressBuildableAutocreation + + 53F6FDC13F620DEF25DC511D8B05C851 + + primary + + + 998731B0C21D3DB32F5A1AECC0AC2721 + + primary + + + C665EB3E404B4D22FC56B866BD32E74F + + primary + + + F965C96C077F1A948F66ACA60DCCDFA8 + + primary + + + + + diff --git a/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-dummy.m b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-dummy.m new file mode 100644 index 000000000..0f45668e3 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_AppAuth : NSObject +@end +@implementation PodsDummy_AppAuth +@end diff --git a/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-prefix.pch b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-umbrella.h b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-umbrella.h new file mode 100644 index 000000000..02fab43d6 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth-umbrella.h @@ -0,0 +1,41 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "AppAuth.h" +#import "OIDAuthorizationRequest.h" +#import "OIDAuthorizationResponse.h" +#import "OIDAuthorizationService.h" +#import "OIDAuthorizationUICoordinator.h" +#import "OIDAuthState.h" +#import "OIDAuthStateChangeDelegate.h" +#import "OIDAuthStateErrorDelegate.h" +#import "OIDDefines.h" +#import "OIDError.h" +#import "OIDErrorUtilities.h" +#import "OIDFieldMapping.h" +#import "OIDGrantTypes.h" +#import "OIDResponseTypes.h" +#import "OIDScopes.h" +#import "OIDScopeUtilities.h" +#import "OIDServiceConfiguration.h" +#import "OIDServiceDiscovery.h" +#import "OIDTokenRequest.h" +#import "OIDTokenResponse.h" +#import "OIDTokenUtilities.h" +#import "OIDURLQueryComponent.h" +#import "OIDAuthorizationService+IOS.h" +#import "OIDAuthorizationUICoordinatorIOS.h" +#import "OIDAuthState+IOS.h" + +FOUNDATION_EXPORT double AppAuthVersionNumber; +FOUNDATION_EXPORT const unsigned char AppAuthVersionString[]; + diff --git a/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth.modulemap b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth.modulemap new file mode 100644 index 000000000..9299d0a39 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth.modulemap @@ -0,0 +1,6 @@ +framework module AppAuth { + umbrella header "AppAuth-umbrella.h" + + export * + module * { export * } +} diff --git a/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth.xcconfig b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth.xcconfig new file mode 100644 index 000000000..8952a227a --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/AppAuth/AppAuth.xcconfig @@ -0,0 +1,11 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/AppAuth +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +GCC_TREAT_WARNINGS_AS_ERRORS = YES +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "SafariServices" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/AppAuth +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Paco-iOS/Pods/Target Support Files/AppAuth/Info.plist b/Paco-iOS/Pods/Target Support Files/AppAuth/Info.plist new file mode 100644 index 000000000..cc1a0c65f --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/AppAuth/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.7.1 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-dummy.m b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-dummy.m new file mode 100644 index 000000000..04b91f318 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_GTMAppAuth : NSObject +@end +@implementation PodsDummy_GTMAppAuth +@end diff --git a/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-prefix.pch b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-umbrella.h b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-umbrella.h new file mode 100644 index 000000000..4ab5f86a3 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth-umbrella.h @@ -0,0 +1,21 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "GTMAppAuth.h" +#import "GTMAppAuthFetcherAuthorization+Keychain.h" +#import "GTMAppAuthFetcherAuthorization.h" +#import "GTMKeychain.h" +#import "GTMOAuth2KeychainCompatibility.h" + +FOUNDATION_EXPORT double GTMAppAuthVersionNumber; +FOUNDATION_EXPORT const unsigned char GTMAppAuthVersionString[]; + diff --git a/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth.modulemap b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth.modulemap new file mode 100644 index 000000000..b23c8d072 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth.modulemap @@ -0,0 +1,6 @@ +framework module GTMAppAuth { + umbrella header "GTMAppAuth-umbrella.h" + + export * + module * { export * } +} diff --git a/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth.xcconfig b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth.xcconfig new file mode 100644 index 000000000..3c244ab71 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/GTMAppAuth.xcconfig @@ -0,0 +1,11 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/GTMAppAuth +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/AppAuth" "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "SafariServices" -framework "Security" -framework "SystemConfiguration" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/GTMAppAuth +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Paco-iOS/Pods/Target Support Files/GTMAppAuth/Info.plist b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/Info.plist new file mode 100644 index 000000000..324eeb2de --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMAppAuth/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 0.5.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m new file mode 100644 index 000000000..13d68b3fc --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_GTMSessionFetcher : NSObject +@end +@implementation PodsDummy_GTMSessionFetcher +@end diff --git a/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch new file mode 100644 index 000000000..beb2a2441 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-prefix.pch @@ -0,0 +1,12 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + diff --git a/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h new file mode 100644 index 000000000..b9e0b3de3 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher-umbrella.h @@ -0,0 +1,23 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + +#import "GTMSessionFetcher.h" +#import "GTMSessionFetcherLogging.h" +#import "GTMSessionFetcherService.h" +#import "GTMSessionUploadFetcher.h" +#import "GTMGatherInputStream.h" +#import "GTMMIMEDocument.h" +#import "GTMReadMonitorInputStream.h" + +FOUNDATION_EXPORT double GTMSessionFetcherVersionNumber; +FOUNDATION_EXPORT const unsigned char GTMSessionFetcherVersionString[]; + diff --git a/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap new file mode 100644 index 000000000..5121a4dc0 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.modulemap @@ -0,0 +1,6 @@ +framework module GTMSessionFetcher { + umbrella header "GTMSessionFetcher-umbrella.h" + + export * + module * { export * } +} diff --git a/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig new file mode 100644 index 000000000..087f15f8e --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/GTMSessionFetcher.xcconfig @@ -0,0 +1,10 @@ +CONFIGURATION_BUILD_DIR = $PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers/Private" "${PODS_ROOT}/Headers/Public" +OTHER_LDFLAGS = -framework "Security" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_ROOT = ${SRCROOT} +PODS_TARGET_SRCROOT = ${PODS_ROOT}/GTMSessionFetcher +PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} +SKIP_INSTALL = YES diff --git a/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/Info.plist b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/Info.plist new file mode 100644 index 000000000..05bf6cb44 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/GTMSessionFetcher/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.1.9 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Info.plist b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Info.plist new file mode 100644 index 000000000..2243fe6e2 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + ${PRODUCT_BUNDLE_IDENTIFIER} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0.0 + CFBundleSignature + ???? + CFBundleVersion + ${CURRENT_PROJECT_VERSION} + NSPrincipalClass + + + diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-acknowledgements.markdown b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-acknowledgements.markdown new file mode 100644 index 000000000..5aa6beb89 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-acknowledgements.markdown @@ -0,0 +1,621 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## AppAuth + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## GTMAppAuth + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +## GTMSessionFetcher + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +Generated by CocoaPods - https://cocoapods.org diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-acknowledgements.plist b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-acknowledgements.plist new file mode 100644 index 000000000..da8a61a64 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-acknowledgements.plist @@ -0,0 +1,665 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache License, Version 2.0 + Title + AppAuth + Type + PSGroupSpecifier + + + FooterText + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache License, Version 2.0 + Title + GTMAppAuth + Type + PSGroupSpecifier + + + FooterText + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + License + Apache + Title + GTMSessionFetcher + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - https://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-dummy.m b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-dummy.m new file mode 100644 index 000000000..89a4bb31c --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_Paco : NSObject +@end +@implementation PodsDummy_Pods_Paco +@end diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-frameworks.sh b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-frameworks.sh new file mode 100755 index 000000000..c59326b09 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-frameworks.sh @@ -0,0 +1,103 @@ +#!/bin/sh +set -e + +echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" +mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + +SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" + +install_framework() +{ + if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then + local source="${BUILT_PRODUCTS_DIR}/$1" + elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then + local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" + elif [ -r "$1" ]; then + local source="$1" + fi + + local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + + if [ -L "${source}" ]; then + echo "Symlinked..." + source="$(readlink "${source}")" + fi + + # use filter instead of exclude so missing patterns dont' throw errors + echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" + rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" + + local basename + basename="$(basename -s .framework "$1")" + binary="${destination}/${basename}.framework/${basename}" + if ! [ -r "$binary" ]; then + binary="${destination}/${basename}" + fi + + # Strip invalid architectures so "fat" simulator / device frameworks work on device + if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then + strip_invalid_archs "$binary" + fi + + # Resign the code if required by the build settings to avoid unstable apps + code_sign_if_enabled "${destination}/$(basename "$1")" + + # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. + if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then + local swift_runtime_libs + swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) + for lib in $swift_runtime_libs; do + echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" + rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" + code_sign_if_enabled "${destination}/${lib}" + done + fi +} + +# Signs a framework with the provided identity +code_sign_if_enabled() { + if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then + # Use the current code_sign_identitiy + echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" + local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" + + if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + code_sign_cmd="$code_sign_cmd &" + fi + echo "$code_sign_cmd" + eval "$code_sign_cmd" + fi +} + +# Strip invalid architectures +strip_invalid_archs() { + binary="$1" + # Get architectures for current file + archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" + stripped="" + for arch in $archs; do + if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then + # Strip non-valid architectures in-place + lipo -remove "$arch" -output "$binary" "$binary" || exit 1 + stripped="$stripped $arch" + fi + done + if [[ "$stripped" ]]; then + echo "Stripped $binary of architectures:$stripped" + fi +} + + +if [[ "$CONFIGURATION" == "Debug" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/AppAuth/AppAuth.framework" + install_framework "$BUILT_PRODUCTS_DIR/GTMAppAuth/GTMAppAuth.framework" + install_framework "$BUILT_PRODUCTS_DIR/GTMSessionFetcher/GTMSessionFetcher.framework" +fi +if [[ "$CONFIGURATION" == "Release" ]]; then + install_framework "$BUILT_PRODUCTS_DIR/AppAuth/AppAuth.framework" + install_framework "$BUILT_PRODUCTS_DIR/GTMAppAuth/GTMAppAuth.framework" + install_framework "$BUILT_PRODUCTS_DIR/GTMSessionFetcher/GTMSessionFetcher.framework" +fi +if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then + wait +fi diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-resources.sh b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-resources.sh new file mode 100755 index 000000000..aed060f04 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-resources.sh @@ -0,0 +1,102 @@ +#!/bin/sh +set -e + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +XCASSET_FILES=() + +case "${TARGETED_DEVICE_FAMILY}" in + 1,2) + TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone" + ;; + 1) + TARGET_DEVICE_ARGS="--target-device iphone" + ;; + 2) + TARGET_DEVICE_ARGS="--target-device ipad" + ;; + 3) + TARGET_DEVICE_ARGS="--target-device tv" + ;; + 4) + TARGET_DEVICE_ARGS="--target-device watch" + ;; + *) + TARGET_DEVICE_ARGS="--target-device mac" + ;; +esac + +install_resource() +{ + if [[ "$1" = /* ]] ; then + RESOURCE_PATH="$1" + else + RESOURCE_PATH="${PODS_ROOT}/$1" + fi + if [[ ! -e "$RESOURCE_PATH" ]] ; then + cat << EOM +error: Resource "$RESOURCE_PATH" not found. Run 'pod install' to update the copy resources script. +EOM + exit 1 + fi + case $RESOURCE_PATH in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .storyboard`.storyboardc" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile ${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib $RESOURCE_PATH --sdk ${SDKROOT} ${TARGET_DEVICE_ARGS}" + ibtool --reference-external-strings-file --errors --warnings --notices --minimum-deployment-target ${!DEPLOYMENT_TARGET_SETTING_NAME} --output-format human-readable-text --compile "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$RESOURCE_PATH\" .xib`.nib" "$RESOURCE_PATH" --sdk "${SDKROOT}" ${TARGET_DEVICE_ARGS} + ;; + *.framework) + echo "mkdir -p ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av $RESOURCE_PATH ${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH"`.mom\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd\"" + xcrun momc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcdatamodeld`.momd" + ;; + *.xcmappingmodel) + echo "xcrun mapc \"$RESOURCE_PATH\" \"${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm\"" + xcrun mapc "$RESOURCE_PATH" "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$RESOURCE_PATH" .xcmappingmodel`.cdm" + ;; + *.xcassets) + ABSOLUTE_XCASSET_FILE="$RESOURCE_PATH" + XCASSET_FILES+=("$ABSOLUTE_XCASSET_FILE") + ;; + *) + echo "$RESOURCE_PATH" + echo "$RESOURCE_PATH" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +mkdir -p "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]] && [[ "${SKIP_INSTALL}" == "NO" ]]; then + mkdir -p "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" + +if [[ -n "${WRAPPER_EXTENSION}" ]] && [ "`xcrun --find actool`" ] && [ -n "$XCASSET_FILES" ] +then + # Find all other xcassets (this unfortunately includes those of path pods and other targets). + OTHER_XCASSETS=$(find "$PWD" -iname "*.xcassets" -type d) + while read line; do + if [[ $line != "${PODS_ROOT}*" ]]; then + XCASSET_FILES+=("$line") + fi + done <<<"$OTHER_XCASSETS" + + printf "%s\0" "${XCASSET_FILES[@]}" | xargs -0 xcrun actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${!DEPLOYMENT_TARGET_SETTING_NAME}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-umbrella.h b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-umbrella.h new file mode 100644 index 000000000..977ebd9c7 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco-umbrella.h @@ -0,0 +1,16 @@ +#ifdef __OBJC__ +#import +#else +#ifndef FOUNDATION_EXPORT +#if defined(__cplusplus) +#define FOUNDATION_EXPORT extern "C" +#else +#define FOUNDATION_EXPORT extern +#endif +#endif +#endif + + +FOUNDATION_EXPORT double Pods_PacoVersionNumber; +FOUNDATION_EXPORT const unsigned char Pods_PacoVersionString[]; + diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.debug.xcconfig b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.debug.xcconfig new file mode 100644 index 000000000..6d5c364ac --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.debug.xcconfig @@ -0,0 +1,9 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/AppAuth" "$PODS_CONFIGURATION_BUILD_DIR/GTMAppAuth" "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/AppAuth/AppAuth.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GTMAppAuth/GTMAppAuth.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "AppAuth" -framework "GTMAppAuth" -framework "GTMSessionFetcher" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.modulemap b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.modulemap new file mode 100644 index 000000000..bc3fa2571 --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.modulemap @@ -0,0 +1,6 @@ +framework module Pods_Paco { + umbrella header "Pods-Paco-umbrella.h" + + export * + module * { export * } +} diff --git a/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.release.xcconfig b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.release.xcconfig new file mode 100644 index 000000000..6d5c364ac --- /dev/null +++ b/Paco-iOS/Pods/Target Support Files/Pods-Paco/Pods-Paco.release.xcconfig @@ -0,0 +1,9 @@ +FRAMEWORK_SEARCH_PATHS = $(inherited) "$PODS_CONFIGURATION_BUILD_DIR/AppAuth" "$PODS_CONFIGURATION_BUILD_DIR/GTMAppAuth" "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher" +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' +OTHER_CFLAGS = $(inherited) -iquote "$PODS_CONFIGURATION_BUILD_DIR/AppAuth/AppAuth.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GTMAppAuth/GTMAppAuth.framework/Headers" -iquote "$PODS_CONFIGURATION_BUILD_DIR/GTMSessionFetcher/GTMSessionFetcher.framework/Headers" +OTHER_LDFLAGS = $(inherited) -framework "AppAuth" -framework "GTMAppAuth" -framework "GTMSessionFetcher" +PODS_BUILD_DIR = $BUILD_DIR +PODS_CONFIGURATION_BUILD_DIR = $PODS_BUILD_DIR/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) +PODS_PODFILE_DIR_PATH = ${SRCROOT}/. +PODS_ROOT = ${SRCROOT}/Pods diff --git a/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMGarbageCollection.h b/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMGarbageCollection.h deleted file mode 100644 index 93d4efabf..000000000 --- a/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMGarbageCollection.h +++ /dev/null @@ -1,72 +0,0 @@ -// -// GTMGarbageCollection.h -// -// Copyright 2007-2008 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations under -// the License. -// - -#import - -#import "GTMDefines.h" - -// This allows us to easily move our code from GC to non GC. -// They are no-ops unless we are require Leopard or above. -// See -// http://developer.apple.com/documentation/Cocoa/Conceptual/GarbageCollection/index.html -// and -// http://developer.apple.com/documentation/Cocoa/Conceptual/GarbageCollection/Articles/gcCoreFoundation.html#//apple_ref/doc/uid/TP40006687-SW1 -// for details. - -#if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5) && !GTM_IPHONE_SDK -// General use would be to call this through GTMCFAutorelease -// but there may be a reason the you want to make something collectable -// but not autoreleased, especially in pure GC code where you don't -// want to bother with the nop autorelease. Done as a define instead of an -// inline so that tools like Clang's scan-build don't report code as leaking. -#define GTMNSMakeCollectable(cf) ((id)NSMakeCollectable(cf)) - -// GTMNSMakeUncollectable is for global maps, etc. that we don't -// want released ever. You should still retain these in non-gc code. -GTM_INLINE void GTMNSMakeUncollectable(id object) { - [[NSGarbageCollector defaultCollector] disableCollectorForPointer:object]; -} - -// Hopefully no code really needs this, but GTMIsGarbageCollectionEnabled is -// a common way to check at runtime if GC is on. -// There are some places where GC doesn't work w/ things w/in Apple's -// frameworks, so this is here so GTM unittests and detect it, and not run -// individual tests to work around bugs in Apple's frameworks. -GTM_INLINE BOOL GTMIsGarbageCollectionEnabled(void) { - return ([NSGarbageCollector defaultCollector] != nil); -} - -#else - -#define GTMNSMakeCollectable(cf) ((id)(cf)) - -GTM_INLINE void GTMNSMakeUncollectable(id object) { -} - -GTM_INLINE BOOL GTMIsGarbageCollectionEnabled(void) { - return NO; -} - -#endif - -// GTMCFAutorelease makes a CF object collectable in GC mode, or adds it -// to the autorelease pool in non-GC mode. Either way it is taken care -// of. Done as a define instead of an inline so that tools like Clang's -// scan-build don't report code as leaking. -#define GTMCFAutorelease(cf) ([GTMNSMakeCollectable(cf) autorelease]) - diff --git a/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.h b/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.h deleted file mode 100644 index d4c7e09a2..000000000 --- a/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.h +++ /dev/null @@ -1,41 +0,0 @@ -// -// GTMNSString+URLArguments.h -// -// Copyright 2006-2008 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations under -// the License. -// - -#import - -/// Utilities for encoding and decoding URL arguments. -@interface NSString (GTMNSStringURLArgumentsAdditions) - -/// Returns a string that is escaped properly to be a URL argument. -// -/// This differs from stringByAddingPercentEscapesUsingEncoding: in that it -/// will escape all the reserved characters (per RFC 3986 -/// ) which -/// stringByAddingPercentEscapesUsingEncoding would leave. -/// -/// This will also escape '%', so this should not be used on a string that has -/// already been escaped unless double-escaping is the desired result. -- (NSString*)gtm_stringByEscapingForURLArgument; - -/// Returns the unescaped version of a URL argument -// -/// This has the same behavior as stringByReplacingPercentEscapesUsingEncoding:, -/// except that it will also convert '+' to space. -- (NSString*)gtm_stringByUnescapingFromURLArgument; - -@end diff --git a/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.m b/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.m deleted file mode 100644 index 46d2c99ed..000000000 --- a/Paco-iOS/vendor/google-toolbox-for-mac/Foundation/GTMNSString+URLArguments.m +++ /dev/null @@ -1,45 +0,0 @@ -// -// GTMNSString+URLArguments.m -// -// Copyright 2006-2008 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations under -// the License. -// - -#import "GTMNSString+URLArguments.h" -#import "GTMGarbageCollection.h" - -@implementation NSString (GTMNSStringURLArgumentsAdditions) - -- (NSString*)gtm_stringByEscapingForURLArgument { - // Encode all the reserved characters, per RFC 3986 - // () - CFStringRef escaped = - CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, - (CFStringRef)self, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8); - return GTMCFAutorelease(escaped); -} - -- (NSString*)gtm_stringByUnescapingFromURLArgument { - NSMutableString *resultString = [NSMutableString stringWithString:self]; - [resultString replaceOccurrencesOfString:@"+" - withString:@" " - options:NSLiteralSearch - range:NSMakeRange(0, [resultString length])]; - return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; -} - -@end diff --git a/Paco-iOS/vendor/google-toolbox-for-mac/GTMDefines.h b/Paco-iOS/vendor/google-toolbox-for-mac/GTMDefines.h deleted file mode 100644 index b970d69c8..000000000 --- a/Paco-iOS/vendor/google-toolbox-for-mac/GTMDefines.h +++ /dev/null @@ -1,444 +0,0 @@ -// -// GTMDefines.h -// -// Copyright 2008 Google Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may not -// use this file except in compliance with the License. You may obtain a copy -// of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations under -// the License. -// - -// ============================================================================ - -#include -#include - -#ifdef __OBJC__ -#include -#endif // __OBJC__ - -#if TARGET_OS_IPHONE -#include -#endif // TARGET_OS_IPHONE - -// Not all MAC_OS_X_VERSION_10_X macros defined in past SDKs -#ifndef MAC_OS_X_VERSION_10_5 - #define MAC_OS_X_VERSION_10_5 1050 -#endif -#ifndef MAC_OS_X_VERSION_10_6 - #define MAC_OS_X_VERSION_10_6 1060 -#endif -#ifndef MAC_OS_X_VERSION_10_7 - #define MAC_OS_X_VERSION_10_7 1070 -#endif - -// Not all __IPHONE_X macros defined in past SDKs -#ifndef __IPHONE_3_0 - #define __IPHONE_3_0 30000 -#endif -#ifndef __IPHONE_3_1 - #define __IPHONE_3_1 30100 -#endif -#ifndef __IPHONE_3_2 - #define __IPHONE_3_2 30200 -#endif -#ifndef __IPHONE_4_0 - #define __IPHONE_4_0 40000 -#endif -#ifndef __IPHONE_4_3 - #define __IPHONE_4_3 40300 -#endif -#ifndef __IPHONE_5_0 - #define __IPHONE_5_0 50000 -#endif - -// ---------------------------------------------------------------------------- -// CPP symbols that can be overridden in a prefix to control how the toolbox -// is compiled. -// ---------------------------------------------------------------------------- - - -// By setting the GTM_CONTAINERS_VALIDATION_FAILED_LOG and -// GTM_CONTAINERS_VALIDATION_FAILED_ASSERT macros you can control what happens -// when a validation fails. If you implement your own validators, you may want -// to control their internals using the same macros for consistency. -#ifndef GTM_CONTAINERS_VALIDATION_FAILED_ASSERT - #define GTM_CONTAINERS_VALIDATION_FAILED_ASSERT 0 -#endif - -// Give ourselves a consistent way to do inlines. Apple's macros even use -// a few different actual definitions, so we're based off of the foundation -// one. -#if !defined(GTM_INLINE) - #if (defined (__GNUC__) && (__GNUC__ == 4)) || defined (__clang__) - #define GTM_INLINE static __inline__ __attribute__((always_inline)) - #else - #define GTM_INLINE static __inline__ - #endif -#endif - -// Give ourselves a consistent way of doing externs that links up nicely -// when mixing objc and objc++ -#if !defined (GTM_EXTERN) - #if defined __cplusplus - #define GTM_EXTERN extern "C" - #define GTM_EXTERN_C_BEGIN extern "C" { - #define GTM_EXTERN_C_END } - #else - #define GTM_EXTERN extern - #define GTM_EXTERN_C_BEGIN - #define GTM_EXTERN_C_END - #endif -#endif - -// Give ourselves a consistent way of exporting things if we have visibility -// set to hidden. -#if !defined (GTM_EXPORT) - #define GTM_EXPORT __attribute__((visibility("default"))) -#endif - -// Give ourselves a consistent way of declaring something as unused. This -// doesn't use __unused because that is only supported in gcc 4.2 and greater. -#if !defined (GTM_UNUSED) -#define GTM_UNUSED(x) ((void)(x)) -#endif - -// _GTMDevLog & _GTMDevAssert -// -// _GTMDevLog & _GTMDevAssert are meant to be a very lightweight shell for -// developer level errors. This implementation simply macros to NSLog/NSAssert. -// It is not intended to be a general logging/reporting system. -// -// Please see http://code.google.com/p/google-toolbox-for-mac/wiki/DevLogNAssert -// for a little more background on the usage of these macros. -// -// _GTMDevLog log some error/problem in debug builds -// _GTMDevAssert assert if conditon isn't met w/in a method/function -// in all builds. -// -// To replace this system, just provide different macro definitions in your -// prefix header. Remember, any implementation you provide *must* be thread -// safe since this could be called by anything in what ever situtation it has -// been placed in. -// - -// We only define the simple macros if nothing else has defined this. -#ifndef _GTMDevLog - -#ifdef DEBUG - #define _GTMDevLog(...) NSLog(__VA_ARGS__) -#else - #define _GTMDevLog(...) do { } while (0) -#endif - -#endif // _GTMDevLog - -#ifndef _GTMDevAssert -// we directly invoke the NSAssert handler so we can pass on the varargs -// (NSAssert doesn't have a macro we can use that takes varargs) -#if !defined(NS_BLOCK_ASSERTIONS) - #define _GTMDevAssert(condition, ...) \ - do { \ - if (!(condition)) { \ - [[NSAssertionHandler currentHandler] \ - handleFailureInFunction:[NSString stringWithUTF8String:__PRETTY_FUNCTION__] \ - file:[NSString stringWithUTF8String:__FILE__] \ - lineNumber:__LINE__ \ - description:__VA_ARGS__]; \ - } \ - } while(0) -#else // !defined(NS_BLOCK_ASSERTIONS) - #define _GTMDevAssert(condition, ...) do { } while (0) -#endif // !defined(NS_BLOCK_ASSERTIONS) - -#endif // _GTMDevAssert - -// _GTMCompileAssert -// _GTMCompileAssert is an assert that is meant to fire at compile time if you -// want to check things at compile instead of runtime. For example if you -// want to check that a wchar is 4 bytes instead of 2 you would use -// _GTMCompileAssert(sizeof(wchar_t) == 4, wchar_t_is_4_bytes_on_OS_X) -// Note that the second "arg" is not in quotes, and must be a valid processor -// symbol in it's own right (no spaces, punctuation etc). - -// Wrapping this in an #ifndef allows external groups to define their own -// compile time assert scheme. -#ifndef _GTMCompileAssert - // We got this technique from here: - // http://unixjunkie.blogspot.com/2007/10/better-compile-time-asserts_29.html - - #define _GTMCompileAssertSymbolInner(line, msg) _GTMCOMPILEASSERT ## line ## __ ## msg - #define _GTMCompileAssertSymbol(line, msg) _GTMCompileAssertSymbolInner(line, msg) - #define _GTMCompileAssert(test, msg) \ - typedef char _GTMCompileAssertSymbol(__LINE__, msg) [ ((test) ? 1 : -1) ] -#endif // _GTMCompileAssert - -// ---------------------------------------------------------------------------- -// CPP symbols defined based on the project settings so the GTM code has -// simple things to test against w/o scattering the knowledge of project -// setting through all the code. -// ---------------------------------------------------------------------------- - -// Provide a single constant CPP symbol that all of GTM uses for ifdefing -// iPhone code. -#if TARGET_OS_IPHONE // iPhone SDK - // For iPhone specific stuff - #define GTM_IPHONE_SDK 1 - #if TARGET_IPHONE_SIMULATOR - #define GTM_IPHONE_SIMULATOR 1 - #else - #define GTM_IPHONE_DEVICE 1 - #endif // TARGET_IPHONE_SIMULATOR - // By default, GTM has provided it's own unittesting support, define this - // to use the support provided by Xcode, especially for the Xcode4 support - // for unittesting. - #ifndef GTM_IPHONE_USE_SENTEST - #define GTM_IPHONE_USE_SENTEST 0 - #endif -#else - // For MacOS specific stuff - #define GTM_MACOS_SDK 1 -#endif - -// Some of our own availability macros -#if GTM_MACOS_SDK -#define GTM_AVAILABLE_ONLY_ON_IPHONE UNAVAILABLE_ATTRIBUTE -#define GTM_AVAILABLE_ONLY_ON_MACOS -#else -#define GTM_AVAILABLE_ONLY_ON_IPHONE -#define GTM_AVAILABLE_ONLY_ON_MACOS UNAVAILABLE_ATTRIBUTE -#endif - -// Provide a symbol to include/exclude extra code for GC support. (This mainly -// just controls the inclusion of finalize methods). -#ifndef GTM_SUPPORT_GC - #if GTM_IPHONE_SDK - // iPhone never needs GC - #define GTM_SUPPORT_GC 0 - #else - // We can't find a symbol to tell if GC is supported/required, so best we - // do on Mac targets is include it if we're on 10.5 or later. - #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5 - #define GTM_SUPPORT_GC 0 - #else - #define GTM_SUPPORT_GC 1 - #endif - #endif -#endif - -// To simplify support for 64bit (and Leopard in general), we provide the type -// defines for non Leopard SDKs -#if !(MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5) - // NSInteger/NSUInteger and Max/Mins - #ifndef NSINTEGER_DEFINED - #if __LP64__ || NS_BUILD_32_LIKE_64 - typedef long NSInteger; - typedef unsigned long NSUInteger; - #else - typedef int NSInteger; - typedef unsigned int NSUInteger; - #endif - #define NSIntegerMax LONG_MAX - #define NSIntegerMin LONG_MIN - #define NSUIntegerMax ULONG_MAX - #define NSINTEGER_DEFINED 1 - #endif // NSINTEGER_DEFINED - // CGFloat - #ifndef CGFLOAT_DEFINED - #if defined(__LP64__) && __LP64__ - // This really is an untested path (64bit on Tiger?) - typedef double CGFloat; - #define CGFLOAT_MIN DBL_MIN - #define CGFLOAT_MAX DBL_MAX - #define CGFLOAT_IS_DOUBLE 1 - #else /* !defined(__LP64__) || !__LP64__ */ - typedef float CGFloat; - #define CGFLOAT_MIN FLT_MIN - #define CGFLOAT_MAX FLT_MAX - #define CGFLOAT_IS_DOUBLE 0 - #endif /* !defined(__LP64__) || !__LP64__ */ - #define CGFLOAT_DEFINED 1 - #endif // CGFLOAT_DEFINED -#endif // MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5 - -// Some support for advanced clang static analysis functionality -// See http://clang-analyzer.llvm.org/annotations.html -#ifndef __has_feature // Optional. - #define __has_feature(x) 0 // Compatibility with non-clang compilers. -#endif - -#ifndef NS_RETURNS_RETAINED - #if __has_feature(attribute_ns_returns_retained) - #define NS_RETURNS_RETAINED __attribute__((ns_returns_retained)) - #else - #define NS_RETURNS_RETAINED - #endif -#endif - -#ifndef NS_RETURNS_NOT_RETAINED - #if __has_feature(attribute_ns_returns_not_retained) - #define NS_RETURNS_NOT_RETAINED __attribute__((ns_returns_not_retained)) - #else - #define NS_RETURNS_NOT_RETAINED - #endif -#endif - -#ifndef CF_RETURNS_RETAINED - #if __has_feature(attribute_cf_returns_retained) - #define CF_RETURNS_RETAINED __attribute__((cf_returns_retained)) - #else - #define CF_RETURNS_RETAINED - #endif -#endif - -#ifndef CF_RETURNS_NOT_RETAINED - #if __has_feature(attribute_cf_returns_not_retained) - #define CF_RETURNS_NOT_RETAINED __attribute__((cf_returns_not_retained)) - #else - #define CF_RETURNS_NOT_RETAINED - #endif -#endif - -#ifndef NS_CONSUMED - #if __has_feature(attribute_ns_consumed) - #define NS_CONSUMED __attribute__((ns_consumed)) - #else - #define NS_CONSUMED - #endif -#endif - -#ifndef CF_CONSUMED - #if __has_feature(attribute_cf_consumed) - #define CF_CONSUMED __attribute__((cf_consumed)) - #else - #define CF_CONSUMED - #endif -#endif - -#ifndef NS_CONSUMES_SELF - #if __has_feature(attribute_ns_consumes_self) - #define NS_CONSUMES_SELF __attribute__((ns_consumes_self)) - #else - #define NS_CONSUMES_SELF - #endif -#endif - -// Defined on 10.6 and above. -#ifndef NS_FORMAT_ARGUMENT - #define NS_FORMAT_ARGUMENT(A) -#endif - -// Defined on 10.6 and above. -#ifndef NS_FORMAT_FUNCTION - #define NS_FORMAT_FUNCTION(F,A) -#endif - -// Defined on 10.6 and above. -#ifndef CF_FORMAT_ARGUMENT - #define CF_FORMAT_ARGUMENT(A) -#endif - -// Defined on 10.6 and above. -#ifndef CF_FORMAT_FUNCTION - #define CF_FORMAT_FUNCTION(F,A) -#endif - -#ifndef GTM_NONNULL - #define GTM_NONNULL(x) __attribute__((nonnull(x))) -#endif - -// Invalidates the initializer from which it's called. -#ifndef GTMInvalidateInitializer - #if __has_feature(objc_arc) - #define GTMInvalidateInitializer() \ - do { \ - [self class]; /* Avoid warning of dead store to |self|. */ \ - _GTMDevAssert(NO, @"Invalid initializer."); \ - return nil; \ - } while (0) - #else - #define GTMInvalidateInitializer() \ - do { \ - [self release]; \ - _GTMDevAssert(NO, @"Invalid initializer."); \ - return nil; \ - } while (0) - #endif -#endif - -#ifdef __OBJC__ - -// Declared here so that it can easily be used for logging tracking if -// necessary. See GTMUnitTestDevLog.h for details. -@class NSString; -GTM_EXTERN void _GTMUnitTestDevLog(NSString *format, ...) NS_FORMAT_FUNCTION(1, 2); - -// Macro to allow you to create NSStrings out of other macros. -// #define FOO foo -// NSString *fooString = GTM_NSSTRINGIFY(FOO); -#if !defined (GTM_NSSTRINGIFY) - #define GTM_NSSTRINGIFY_INNER(x) @#x - #define GTM_NSSTRINGIFY(x) GTM_NSSTRINGIFY_INNER(x) -#endif - -// Macro to allow fast enumeration when building for 10.5 or later, and -// reliance on NSEnumerator for 10.4. Remember, NSDictionary w/ FastEnumeration -// does keys, so pick the right thing, nothing is done on the FastEnumeration -// side to be sure you're getting what you wanted. -#ifndef GTM_FOREACH_OBJECT - #if TARGET_OS_IPHONE || !(MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5) - #define GTM_FOREACH_ENUMEREE(element, enumeration) \ - for (element in enumeration) - #define GTM_FOREACH_OBJECT(element, collection) \ - for (element in collection) - #define GTM_FOREACH_KEY(element, collection) \ - for (element in collection) - #else - #define GTM_FOREACH_ENUMEREE(element, enumeration) \ - for (NSEnumerator *_ ## element ## _enum = enumeration; \ - (element = [_ ## element ## _enum nextObject]) != nil; ) - #define GTM_FOREACH_OBJECT(element, collection) \ - GTM_FOREACH_ENUMEREE(element, [collection objectEnumerator]) - #define GTM_FOREACH_KEY(element, collection) \ - GTM_FOREACH_ENUMEREE(element, [collection keyEnumerator]) - #endif -#endif - -// ============================================================================ - -// To simplify support for both Leopard and Snow Leopard we declare -// the Snow Leopard protocols that we need here. -#if !defined(GTM_10_6_PROTOCOLS_DEFINED) && !(MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6) -#define GTM_10_6_PROTOCOLS_DEFINED 1 -@protocol NSConnectionDelegate -@end -@protocol NSAnimationDelegate -@end -@protocol NSImageDelegate -@end -@protocol NSTabViewDelegate -@end -#endif // !defined(GTM_10_6_PROTOCOLS_DEFINED) && !(MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6) - -// GTM_SEL_STRING is for specifying selector (usually property) names to KVC -// or KVO methods. -// In debug it will generate warnings for undeclared selectors if -// -Wunknown-selector is turned on. -// In release it will have no runtime overhead. -#ifndef GTM_SEL_STRING - #ifdef DEBUG - #define GTM_SEL_STRING(selName) NSStringFromSelector(@selector(selName)) - #else - #define GTM_SEL_STRING(selName) @#selName - #endif // DEBUG -#endif // GTM_SEL_STRING - -#endif // __OBJC__ diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMGatherInputStream.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMGatherInputStream.h deleted file mode 100644 index 280ff97df..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMGatherInputStream.h +++ /dev/null @@ -1,64 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -// The GTMGatherInput stream is an input stream implementation that is to be -// instantiated with an NSArray of NSData objects. It works in the traditional -// scatter/gather vector I/O model. Rather than allocating a big NSData object -// to hold all of the data and performing a copy into that object, the -// GTMGatherInputStream will maintain a reference to the NSArray and read from -// each NSData in turn as the read method is called. You should not alter the -// underlying set of NSData objects until all read operations on this input -// stream have completed. - -#import - -#if defined(GTL_TARGET_NAMESPACE) - // we need NSInteger for the 10.4 SDK, or we're using target namespace macros - #import "GTLDefines.h" -#elif defined(GDATA_TARGET_NAMESPACE) - #import "GDataDefines.h" -#endif - -// Define only for Mac OS X 10.6+ or iPhone OS 4.0+. -#undef GTM_NSSTREAM_DELEGATE -#if (TARGET_OS_MAC && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)) || \ - (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 40000)) - #define GTM_NSSTREAM_DELEGATE -#else - #define GTM_NSSTREAM_DELEGATE -#endif - -@interface GTMGatherInputStream : NSInputStream GTM_NSSTREAM_DELEGATE { - - NSArray* dataArray_; // NSDatas that should be "gathered" and streamed. - NSUInteger arrayIndex_; // Index in the array of the current NSData. - long long dataOffset_; // Offset in the current NSData we are processing. - - id delegate_; // WEAK, stream delegate, defaults to self - - // Since various undocumented methods get called on a stream, we'll - // use a 1-byte dummy stream object to handle all unexpected messages. - // Actual reads from the stream we will perform using the data array, not - // from the dummy stream. - NSInputStream* dummyStream_; - NSData* dummyData_; -} - -+ (NSInputStream *)streamWithArray:(NSArray *)dataArray; - -- (id)initWithArray:(NSArray *)dataArray; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMGatherInputStream.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMGatherInputStream.m deleted file mode 100644 index 771398226..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMGatherInputStream.m +++ /dev/null @@ -1,197 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import "GTMGatherInputStream.h" - -@implementation GTMGatherInputStream - -+ (NSInputStream *)streamWithArray:(NSArray *)dataArray { - return [[[self alloc] initWithArray:dataArray] autorelease]; -} - -- (id)initWithArray:(NSArray *)dataArray { - self = [super init]; - if (self) { - dataArray_ = [dataArray retain]; - arrayIndex_ = 0; - dataOffset_ = 0; - - [self setDelegate:self]; // An NSStream's default delegate should be self. - - // We use a dummy input stream to handle all the various undocumented - // messages the system sends to an input stream. - // - // Contrary to documentation, inputStreamWithData neither copies nor - // retains the data in Mac OS X 10.4, so we must retain it. - // (Radar 5167591) - - dummyData_ = [[NSData alloc] initWithBytes:"x" length:1]; - dummyStream_ = [[NSInputStream alloc] initWithData:dummyData_]; - } - return self; -} - -- (void)dealloc { - [dataArray_ release]; - [dummyStream_ release]; - [dummyData_ release]; - - [super dealloc]; -} - -- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len { - - NSInteger bytesRead = 0; - NSUInteger bytesRemaining = len; - - // read bytes from the currently-indexed array - while ((bytesRemaining > 0) && (arrayIndex_ < [dataArray_ count])) { - - NSData* data = [dataArray_ objectAtIndex:arrayIndex_]; - - NSUInteger dataLen = [data length]; - NSUInteger dataBytesLeft = dataLen - (NSUInteger)dataOffset_; - - NSUInteger bytesToCopy = MIN(bytesRemaining, dataBytesLeft); - NSRange range = NSMakeRange((NSUInteger) dataOffset_, bytesToCopy); - - [data getBytes:(buffer + bytesRead) range:range]; - - bytesRead += bytesToCopy; - dataOffset_ += bytesToCopy; - bytesRemaining -= bytesToCopy; - - if (dataOffset_ == (long long)dataLen) { - dataOffset_ = 0; - arrayIndex_++; - } - } - - if (bytesRead == 0) { - // We are at the end our our stream, so we read all of the data on our - // dummy input stream to make sure it is in the "fully read" state. - uint8_t leftOverBytes[2]; - (void) [dummyStream_ read:leftOverBytes maxLength:sizeof(leftOverBytes)]; - } - - return bytesRead; -} - -- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len { - return NO; // We don't support this style of reading. -} - -- (BOOL)hasBytesAvailable { - // if we return no, the read never finishes, even if we've already - // delivered all the bytes - return YES; -} - -#pragma mark - - -// Pass other expected messages on to the dummy input stream - -- (void)open { - [dummyStream_ open]; -} - -- (void)close { - [dummyStream_ close]; - - // 10.4's NSURLConnection tends to retain streams needlessly, - // so we'll free up the data array right away - [dataArray_ release]; - dataArray_ = nil; -} - -- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent { - if (delegate_ != self) { - [delegate_ stream:self handleEvent:streamEvent]; - } -} - -- (id)delegate { - return delegate_; -} - -- (void)setDelegate:(id)delegate { - if (delegate == nil) { - delegate_ = self; - [dummyStream_ setDelegate:nil]; - } else { - delegate_ = delegate; - [dummyStream_ setDelegate:self]; - } -} - -- (id)propertyForKey:(NSString *)key { - return [dummyStream_ propertyForKey:key]; -} - -- (BOOL)setProperty:(id)property forKey:(NSString *)key { - return [dummyStream_ setProperty:property forKey:key]; -} - -- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { - [dummyStream_ scheduleInRunLoop:aRunLoop forMode:mode]; -} - -- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { - [dummyStream_ removeFromRunLoop:aRunLoop forMode:mode]; -} - -- (NSStreamStatus)streamStatus { - return [dummyStream_ streamStatus]; -} -- (NSError *)streamError { - return [dummyStream_ streamError]; -} - -#pragma mark - - -// We'll forward all unexpected messages to our dummy stream - -+ (NSMethodSignature*)methodSignatureForSelector:(SEL)selector { - return [NSInputStream methodSignatureForSelector:selector]; -} - -+ (void)forwardInvocation:(NSInvocation*)invocation { - [invocation invokeWithTarget:[NSInputStream class]]; -} - -- (BOOL)respondsToSelector:(SEL)selector { - return [dummyStream_ respondsToSelector:selector]; -} - -- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector { - return [dummyStream_ methodSignatureForSelector:selector]; -} - -- (void)forwardInvocation:(NSInvocation*)invocation { - -#if 0 - // uncomment this section to see the messages the NSInputStream receives - SEL selector; - NSString *selName; - - selector=[invocation selector]; - selName=NSStringFromSelector(selector); - NSLog(@"-forwardInvocation: %@",selName); -#endif - - [invocation invokeWithTarget:dummyStream_]; -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetchHistory.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetchHistory.h deleted file mode 100755 index 9c7eed963..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetchHistory.h +++ /dev/null @@ -1,175 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPFetchHistory.h -// - -// -// Users of the GTMHTTPFetcher class may optionally create and set a fetch -// history object. The fetch history provides "memory" between subsequent -// fetches, including: -// -// - For fetch responses with Etag headers, the fetch history -// remembers the response headers. Future fetcher requests to the same URL -// will be given an "If-None-Match" header, telling the server to return -// a 304 Not Modified status if the response is unchanged, reducing the -// server load and network traffic. -// -// - Optionally, the fetch history can cache the ETagged data that was returned -// in the responses that contained Etag headers. If a later fetch -// results in a 304 status, the fetcher will return the cached ETagged data -// to the client along with a 200 status, hiding the 304. -// -// - The fetch history can track cookies. -// - -#pragma once - -#import - -#import "GTMHTTPFetcher.h" - -// default data cache size for when we're caching responses to handle "not -// modified" errors for the client - -#ifdef __cplusplus -extern "C" { -#endif - -extern const NSUInteger kGTMDefaultETaggedDataCacheMemoryCapacity; - -#ifdef __cplusplus -} -#endif - -// forward declarations -@class GTMURLCache; -@class GTMCookieStorage; - -@interface GTMHTTPFetchHistory : NSObject { - @private - GTMURLCache *etaggedDataCache_; - BOOL shouldRememberETags_; - BOOL shouldCacheETaggedData_; // if NO, then only headers are cached - GTMCookieStorage *cookieStorage_; -} - -// With caching enabled, previously-cached data will be returned instead of -// 304 Not Modified responses when repeating a fetch of an URL that previously -// included an ETag header in its response -@property (assign) BOOL shouldRememberETags; // default: NO -@property (assign) BOOL shouldCacheETaggedData; // default: NO - -// the default ETag data cache capacity is kGTMDefaultETaggedDataCacheMemoryCapacity -@property (assign) NSUInteger memoryCapacity; - -@property (retain) GTMCookieStorage *cookieStorage; - -- (id)initWithMemoryCapacity:(NSUInteger)totalBytes - shouldCacheETaggedData:(BOOL)shouldCacheETaggedData; - -- (void)updateRequest:(NSMutableURLRequest *)request isHTTPGet:(BOOL)isHTTPGet; - -- (void)clearETaggedDataCache; -- (void)clearHistory; - -- (void)removeAllCookies; - -@end - - -// GTMURLCache and GTMCachedURLResponse have interfaces similar to their -// NSURLCache counterparts, in hopes that someday the NSURLCache versions -// can be used. But in 10.5.8, those are not reliable enough except when -// used with +setSharedURLCache. Our goal here is just to cache -// responses for handling If-None-Match requests that return -// "Not Modified" responses, not for replacing the general URL -// caches. - -@interface GTMCachedURLResponse : NSObject { - @private - NSURLResponse *response_; - NSData *data_; - NSDate *useDate_; // date this response was last saved or used - NSDate *reservationDate_; // date this response's ETag was used -} - -@property (readonly) NSURLResponse* response; -@property (readonly) NSData* data; - -// date the response was saved or last accessed -@property (retain) NSDate *useDate; - -// date the response's ETag header was last used for a fetch request -@property (retain) NSDate *reservationDate; - -- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data; -@end - -@interface GTMURLCache : NSObject { - NSMutableDictionary *responses_; // maps request URL to GTMCachedURLResponse - NSUInteger memoryCapacity_; // capacity of NSDatas in the responses - NSUInteger totalDataSize_; // sum of sizes of NSDatas of all responses - NSTimeInterval reservationInterval_; // reservation expiration interval -} - -@property (assign) NSUInteger memoryCapacity; - -- (id)initWithMemoryCapacity:(NSUInteger)totalBytes; - -- (GTMCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request; -- (void)storeCachedResponse:(GTMCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request; -- (void)removeCachedResponseForRequest:(NSURLRequest *)request; -- (void)removeAllCachedResponses; - -// for unit testing -- (void)setReservationInterval:(NSTimeInterval)secs; -- (NSDictionary *)responses; -- (NSUInteger)totalDataSize; -@end - -@interface GTMCookieStorage : NSObject { - @private - // The cookie storage object manages an array holding cookies, but the array - // is allocated externally (it may be in a fetcher object or the static - // fetcher cookie array.) See the fetcher's setCookieStorageMethod: - // for allocation of this object and assignment of its cookies array. - NSMutableArray *cookies_; -} - -// add all NSHTTPCookies in the supplied array to the storage array, -// replacing cookies in the storage array as appropriate -// Side effect: removes expired cookies from the storage array -- (void)setCookies:(NSArray *)newCookies; - -// retrieve all cookies appropriate for the given URL, considering -// domain, path, cookie name, expiration, security setting. -// Side effect: removes expired cookies from the storage array -- (NSArray *)cookiesForURL:(NSURL *)theURL; - -// return a cookie with the same name, domain, and path as the -// given cookie, or else return nil if none found -// -// Both the cookie being tested and all stored cookies should -// be valid (non-nil name, domains, paths) -- (NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie; - -// remove any expired cookies, excluding cookies with nil expirations -- (void)removeExpiredCookies; - -- (void)removeAllCookies; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetchHistory.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetchHistory.m deleted file mode 100755 index cc78ea61b..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetchHistory.m +++ /dev/null @@ -1,612 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPFetchHistory.m -// - -#import "GTMHTTPFetchHistory.h" - -static const NSTimeInterval kCachedURLReservationInterval = 60.0; // 1 minute -static NSString* const kGTMIfNoneMatchHeader = @"If-None-Match"; -static NSString* const kGTMETagHeader = @"Etag"; - -#if GTM_IPHONE -// iPhone: up to 1MB memory -const NSUInteger kGTMDefaultETaggedDataCacheMemoryCapacity = 1 * 1024 * 1024; -#else -// Mac OS X: up to 15MB memory -const NSUInteger kGTMDefaultETaggedDataCacheMemoryCapacity = 15 * 1024 * 1024; -#endif - - -@implementation GTMCookieStorage - -- (id)init { - self = [super init]; - if (self != nil) { - cookies_ = [[NSMutableArray alloc] init]; - } - return self; -} - -- (void)dealloc { - [cookies_ release]; - [super dealloc]; -} - -// Add all cookies in the new cookie array to the storage, -// replacing stored cookies as appropriate. -// -// Side effect: removes expired cookies from the storage array. -- (void)setCookies:(NSArray *)newCookies { - - @synchronized(cookies_) { - [self removeExpiredCookies]; - - for (NSHTTPCookie *newCookie in newCookies) { - if ([[newCookie name] length] > 0 - && [[newCookie domain] length] > 0 - && [[newCookie path] length] > 0) { - - // remove the cookie if it's currently in the array - NSHTTPCookie *oldCookie = [self cookieMatchingCookie:newCookie]; - if (oldCookie) { - [cookies_ removeObjectIdenticalTo:oldCookie]; - } - - // make sure the cookie hasn't already expired - NSDate *expiresDate = [newCookie expiresDate]; - if ((!expiresDate) || [expiresDate timeIntervalSinceNow] > 0) { - [cookies_ addObject:newCookie]; - } - - } else { - NSAssert1(NO, @"Cookie incomplete: %@", newCookie); - } - } - } -} - -- (void)deleteCookie:(NSHTTPCookie *)cookie { - @synchronized(cookies_) { - NSHTTPCookie *foundCookie = [self cookieMatchingCookie:cookie]; - if (foundCookie) { - [cookies_ removeObjectIdenticalTo:foundCookie]; - } - } -} - -// Retrieve all cookies appropriate for the given URL, considering -// domain, path, cookie name, expiration, security setting. -// Side effect: removed expired cookies from the storage array. -- (NSArray *)cookiesForURL:(NSURL *)theURL { - - NSMutableArray *foundCookies = nil; - - @synchronized(cookies_) { - [self removeExpiredCookies]; - - // We'll prepend "." to the desired domain, since we want the - // actual domain "nytimes.com" to still match the cookie domain - // ".nytimes.com" when we check it below with hasSuffix. - NSString *host = [[theURL host] lowercaseString]; - NSString *path = [theURL path]; - NSString *scheme = [theURL scheme]; - - NSString *domain = nil; - BOOL isLocalhostRetrieval = NO; - - if ([host isEqual:@"localhost"]) { - isLocalhostRetrieval = YES; - } else { - if (host) { - domain = [@"." stringByAppendingString:host]; - } - } - - NSUInteger numberOfCookies = [cookies_ count]; - for (NSUInteger idx = 0; idx < numberOfCookies; idx++) { - - NSHTTPCookie *storedCookie = [cookies_ objectAtIndex:idx]; - - NSString *cookieDomain = [[storedCookie domain] lowercaseString]; - NSString *cookiePath = [storedCookie path]; - BOOL cookieIsSecure = [storedCookie isSecure]; - - BOOL isDomainOK; - - if (isLocalhostRetrieval) { - // prior to 10.5.6, the domain stored into NSHTTPCookies for localhost - // is "localhost.local" - isDomainOK = [cookieDomain isEqual:@"localhost"] - || [cookieDomain isEqual:@"localhost.local"]; - } else { - isDomainOK = [domain hasSuffix:cookieDomain]; - } - - BOOL isPathOK = [cookiePath isEqual:@"/"] || [path hasPrefix:cookiePath]; - BOOL isSecureOK = (!cookieIsSecure) || [scheme isEqual:@"https"]; - - if (isDomainOK && isPathOK && isSecureOK) { - if (foundCookies == nil) { - foundCookies = [NSMutableArray arrayWithCapacity:1]; - } - [foundCookies addObject:storedCookie]; - } - } - } - return foundCookies; -} - -// Return a cookie from the array with the same name, domain, and path as the -// given cookie, or else return nil if none found. -// -// Both the cookie being tested and all cookies in the storage array should -// be valid (non-nil name, domains, paths). -// -// Note: this should only be called from inside a @synchronized(cookies_) block -- (NSHTTPCookie *)cookieMatchingCookie:(NSHTTPCookie *)cookie { - - NSUInteger numberOfCookies = [cookies_ count]; - NSString *name = [cookie name]; - NSString *domain = [cookie domain]; - NSString *path = [cookie path]; - - NSAssert3(name && domain && path, @"Invalid cookie (name:%@ domain:%@ path:%@)", - name, domain, path); - - for (NSUInteger idx = 0; idx < numberOfCookies; idx++) { - - NSHTTPCookie *storedCookie = [cookies_ objectAtIndex:idx]; - - if ([[storedCookie name] isEqual:name] - && [[storedCookie domain] isEqual:domain] - && [[storedCookie path] isEqual:path]) { - - return storedCookie; - } - } - return nil; -} - - -// Internal routine to remove any expired cookies from the array, excluding -// cookies with nil expirations. -// -// Note: this should only be called from inside a @synchronized(cookies_) block -- (void)removeExpiredCookies { - - // count backwards since we're deleting items from the array - for (NSInteger idx = (NSInteger)[cookies_ count] - 1; idx >= 0; idx--) { - - NSHTTPCookie *storedCookie = [cookies_ objectAtIndex:(NSUInteger)idx]; - - NSDate *expiresDate = [storedCookie expiresDate]; - if (expiresDate && [expiresDate timeIntervalSinceNow] < 0) { - [cookies_ removeObjectAtIndex:(NSUInteger)idx]; - } - } -} - -- (void)removeAllCookies { - @synchronized(cookies_) { - [cookies_ removeAllObjects]; - } -} -@end - -// -// GTMCachedURLResponse -// - -@implementation GTMCachedURLResponse - -@synthesize response = response_; -@synthesize data = data_; -@synthesize reservationDate = reservationDate_; -@synthesize useDate = useDate_; - -- (id)initWithResponse:(NSURLResponse *)response data:(NSData *)data { - self = [super init]; - if (self != nil) { - response_ = [response retain]; - data_ = [data retain]; - useDate_ = [[NSDate alloc] init]; - } - return self; -} - -- (void)dealloc { - [response_ release]; - [data_ release]; - [useDate_ release]; - [reservationDate_ release]; - [super dealloc]; -} - -- (NSString *)description { - NSString *reservationStr = reservationDate_ ? - [NSString stringWithFormat:@" resDate:%@", reservationDate_] : @""; - - return [NSString stringWithFormat:@"%@ %p: {bytes:%@ useDate:%@%@}", - [self class], self, - data_ ? [NSNumber numberWithInt:(int)[data_ length]] : nil, - useDate_, - reservationStr]; -} - -- (NSComparisonResult)compareUseDate:(GTMCachedURLResponse *)other { - return [useDate_ compare:[other useDate]]; -} - -@end - -// -// GTMURLCache -// - -@implementation GTMURLCache - -@dynamic memoryCapacity; - -- (id)init { - return [self initWithMemoryCapacity:kGTMDefaultETaggedDataCacheMemoryCapacity]; -} - -- (id)initWithMemoryCapacity:(NSUInteger)totalBytes { - self = [super init]; - if (self != nil) { - memoryCapacity_ = totalBytes; - - responses_ = [[NSMutableDictionary alloc] initWithCapacity:5]; - - reservationInterval_ = kCachedURLReservationInterval; - } - return self; -} - -- (void)dealloc { - [responses_ release]; - [super dealloc]; -} - -- (NSString *)description { - return [NSString stringWithFormat:@"%@ %p: {responses:%@}", - [self class], self, [responses_ allValues]]; -} - -// Setters/getters - -- (void)pruneCacheResponses { - // Internal routine to remove the least-recently-used responses when the - // cache has grown too large - if (memoryCapacity_ >= totalDataSize_) return; - - // Sort keys by date - SEL sel = @selector(compareUseDate:); - NSArray *sortedKeys = [responses_ keysSortedByValueUsingSelector:sel]; - - // The least-recently-used keys are at the beginning of the sorted array; - // remove those (except ones still reserved) until the total data size is - // reduced sufficiently - for (NSURL *key in sortedKeys) { - GTMCachedURLResponse *response = [responses_ objectForKey:key]; - - NSDate *resDate = [response reservationDate]; - BOOL isResponseReserved = (resDate != nil) - && ([resDate timeIntervalSinceNow] > -reservationInterval_); - - if (!isResponseReserved) { - // We can remove this response from the cache - NSUInteger storedSize = [[response data] length]; - totalDataSize_ -= storedSize; - [responses_ removeObjectForKey:key]; - } - - // If we've removed enough response data, then we're done - if (memoryCapacity_ >= totalDataSize_) break; - } -} - -- (void)storeCachedResponse:(GTMCachedURLResponse *)cachedResponse - forRequest:(NSURLRequest *)request { - @synchronized(self) { - // Remove any previous entry for this request - [self removeCachedResponseForRequest:request]; - - // cache this one only if it's not bigger than our cache - NSUInteger storedSize = [[cachedResponse data] length]; - if (storedSize < memoryCapacity_) { - - NSURL *key = [request URL]; - [responses_ setObject:cachedResponse forKey:key]; - totalDataSize_ += storedSize; - - [self pruneCacheResponses]; - } - } -} - -- (GTMCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request { - GTMCachedURLResponse *response; - - @synchronized(self) { - NSURL *key = [request URL]; - response = [[[responses_ objectForKey:key] retain] autorelease]; - - // Touch the date to indicate this was recently retrieved - [response setUseDate:[NSDate date]]; - } - return response; -} - -- (void)removeCachedResponseForRequest:(NSURLRequest *)request { - @synchronized(self) { - NSURL *key = [request URL]; - totalDataSize_ -= [[[responses_ objectForKey:key] data] length]; - [responses_ removeObjectForKey:key]; - } -} - -- (void)removeAllCachedResponses { - @synchronized(self) { - [responses_ removeAllObjects]; - totalDataSize_ = 0; - } -} - -- (NSUInteger)memoryCapacity { - return memoryCapacity_; -} - -- (void)setMemoryCapacity:(NSUInteger)totalBytes { - @synchronized(self) { - BOOL didShrink = (totalBytes < memoryCapacity_); - memoryCapacity_ = totalBytes; - - if (didShrink) { - [self pruneCacheResponses]; - } - } -} - -// Methods for unit testing. -- (void)setReservationInterval:(NSTimeInterval)secs { - reservationInterval_ = secs; -} - -- (NSDictionary *)responses { - return responses_; -} - -- (NSUInteger)totalDataSize { - return totalDataSize_; -} - -@end - -// -// GTMHTTPFetchHistory -// - -@interface GTMHTTPFetchHistory () -- (NSString *)cachedETagForRequest:(NSURLRequest *)request; -- (void)removeCachedDataForRequest:(NSURLRequest *)request; -@end - -@implementation GTMHTTPFetchHistory - -@synthesize cookieStorage = cookieStorage_; - -@dynamic shouldRememberETags; -@dynamic shouldCacheETaggedData; -@dynamic memoryCapacity; - -- (id)init { - return [self initWithMemoryCapacity:kGTMDefaultETaggedDataCacheMemoryCapacity - shouldCacheETaggedData:NO]; -} - -- (id)initWithMemoryCapacity:(NSUInteger)totalBytes - shouldCacheETaggedData:(BOOL)shouldCacheETaggedData { - self = [super init]; - if (self != nil) { - etaggedDataCache_ = [[GTMURLCache alloc] initWithMemoryCapacity:totalBytes]; - shouldRememberETags_ = shouldCacheETaggedData; - shouldCacheETaggedData_ = shouldCacheETaggedData; - cookieStorage_ = [[GTMCookieStorage alloc] init]; - } - return self; -} - -- (void)dealloc { - [etaggedDataCache_ release]; - [cookieStorage_ release]; - [super dealloc]; -} - -- (void)updateRequest:(NSMutableURLRequest *)request isHTTPGet:(BOOL)isHTTPGet { - @synchronized(self) { - if ([self shouldRememberETags]) { - // If this URL is in the history, and no ETag has been set, then - // set the ETag header field - - // If we have a history, we're tracking across fetches, so we don't - // want to pull results from any other cache - [request setCachePolicy:NSURLRequestReloadIgnoringCacheData]; - - if (isHTTPGet) { - // We'll only add an ETag if there's no ETag specified in the user's - // request - NSString *specifiedETag = [request valueForHTTPHeaderField:kGTMIfNoneMatchHeader]; - if (specifiedETag == nil) { - // No ETag: extract the previous ETag for this request from the - // fetch history, and add it to the request - NSString *cachedETag = [self cachedETagForRequest:request]; - - if (cachedETag != nil) { - [request addValue:cachedETag forHTTPHeaderField:kGTMIfNoneMatchHeader]; - } - } else { - // Has an ETag: remove any stored response in the fetch history - // for this request, as the If-None-Match header could lead to - // a 304 Not Modified, and we want that error delivered to the - // user since they explicitly specified the ETag - [self removeCachedDataForRequest:request]; - } - } - } - } -} - -- (void)updateFetchHistoryWithRequest:(NSURLRequest *)request - response:(NSURLResponse *)response - downloadedData:(NSData *)downloadedData { - @synchronized(self) { - if (![self shouldRememberETags]) return; - - if (![response respondsToSelector:@selector(allHeaderFields)]) return; - - NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; - - if (statusCode != kGTMHTTPFetcherStatusNotModified) { - // Save this ETag string for successful results (<300) - // If there's no last modified string, clear the dictionary - // entry for this URL. Also cache or delete the data, if appropriate - // (when etaggedDataCache is non-nil.) - NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; - NSString* etag = [headers objectForKey:kGTMETagHeader]; - - if (etag != nil && statusCode < 300) { - - // we want to cache responses for the headers, even if the client - // doesn't want the response body data caches - NSData *dataToStore = shouldCacheETaggedData_ ? downloadedData : nil; - - GTMCachedURLResponse *cachedResponse; - cachedResponse = [[[GTMCachedURLResponse alloc] initWithResponse:response - data:dataToStore] autorelease]; - [etaggedDataCache_ storeCachedResponse:cachedResponse - forRequest:request]; - } else { - [etaggedDataCache_ removeCachedResponseForRequest:request]; - } - } - } -} - -- (NSString *)cachedETagForRequest:(NSURLRequest *)request { - // Internal routine. - GTMCachedURLResponse *cachedResponse; - cachedResponse = [etaggedDataCache_ cachedResponseForRequest:request]; - - NSURLResponse *response = [cachedResponse response]; - NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; - NSString *cachedETag = [headers objectForKey:kGTMETagHeader]; - if (cachedETag) { - // Since the request having an ETag implies this request is about - // to be fetched again, reserve the cached response to ensure that - // that it will be around at least until the fetch completes. - // - // When the fetch completes, either the cached response will be replaced - // with a new response, or the cachedDataForRequest: method below will - // clear the reservation. - [cachedResponse setReservationDate:[NSDate date]]; - } - return cachedETag; -} - -- (NSData *)cachedDataForRequest:(NSURLRequest *)request { - @synchronized(self) { - GTMCachedURLResponse *cachedResponse; - cachedResponse = [etaggedDataCache_ cachedResponseForRequest:request]; - - NSData *cachedData = [cachedResponse data]; - - // Since the data for this cached request is being obtained from the cache, - // we can clear the reservation as the fetch has completed. - [cachedResponse setReservationDate:nil]; - - return cachedData; - } -} - -- (void)removeCachedDataForRequest:(NSURLRequest *)request { - @synchronized(self) { - [etaggedDataCache_ removeCachedResponseForRequest:request]; - } -} - -- (void)clearETaggedDataCache { - @synchronized(self) { - [etaggedDataCache_ removeAllCachedResponses]; - } -} - -- (void)clearHistory { - @synchronized(self) { - [self clearETaggedDataCache]; - [cookieStorage_ removeAllCookies]; - } -} - -- (void)removeAllCookies { - @synchronized(self) { - [cookieStorage_ removeAllCookies]; - } -} - -- (BOOL)shouldRememberETags { - return shouldRememberETags_; -} - -- (void)setShouldRememberETags:(BOOL)flag { - BOOL wasRemembering = shouldRememberETags_; - shouldRememberETags_ = flag; - - if (wasRemembering && !flag) { - // Free up the cache memory - [self clearETaggedDataCache]; - } -} - -- (BOOL)shouldCacheETaggedData { - return shouldCacheETaggedData_; -} - -- (void)setShouldCacheETaggedData:(BOOL)flag { - BOOL wasCaching = shouldCacheETaggedData_; - shouldCacheETaggedData_ = flag; - - if (flag) { - self.shouldRememberETags = YES; - } - - if (wasCaching && !flag) { - // users expect turning off caching to free up the cache memory - [self clearETaggedDataCache]; - } -} - -- (NSUInteger)memoryCapacity { - return [etaggedDataCache_ memoryCapacity]; -} - -- (void)setMemoryCapacity:(NSUInteger)totalBytes { - [etaggedDataCache_ setMemoryCapacity:totalBytes]; -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.h deleted file mode 100755 index 8cf612126..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.h +++ /dev/null @@ -1,847 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPFetcher.h -// - -// This is essentially a wrapper around NSURLConnection for POSTs and GETs. -// If setPostData: is called, then POST is assumed. -// -// When would you use this instead of NSURLConnection? -// -// - When you just want the result from a GET, POST, or PUT -// - When you want the "standard" behavior for connections (redirection handling -// an so on) -// - When you want automatic retry on failures -// - When you want to avoid cookie collisions with Safari and other applications -// - When you are fetching resources with ETags and want to avoid the overhead -// of repeated fetches of unchanged data -// - When you need to set a credential for the http operation -// -// This is assumed to be a one-shot fetch request; don't reuse the object -// for a second fetch. -// -// The fetcher may be created auto-released, in which case it will release -// itself after the fetch completion callback. The fetcher is implicitly -// retained as long as a connection is pending. -// -// But if you may need to cancel the fetcher, retain it and have the delegate -// release the fetcher in the callbacks. -// -// Sample usage: -// -// NSURLRequest *request = [NSURLRequest requestWithURL:myURL]; -// GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; -// -// // optional upload body data -// [myFetcher setPostData:[postString dataUsingEncoding:NSUTF8StringEncoding]]; -// -// [myFetcher beginFetchWithDelegate:self -// didFinishSelector:@selector(myFetcher:finishedWithData:error:)]; -// -// Upon fetch completion, the callback selector is invoked; it should have -// this signature (you can use any callback method name you want so long as -// the signature matches this): -// -// - (void)myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)retrievedData error:(NSError *)error; -// -// The block callback version looks like: -// -// [myFetcher beginFetchWithCompletionHandler:^(NSData *retrievedData, NSError *error) { -// if (error != nil) { -// // status code or network error -// } else { -// // succeeded -// } -// }]; - -// -// NOTE: Fetches may retrieve data from the server even though the server -// returned an error. The failure selector is called when the server -// status is >= 300, with an NSError having domain -// kGTMHTTPFetcherStatusDomain and code set to the server status. -// -// Status codes are at -// -// -// Threading and queue support: -// -// Callbacks require either that the thread used to start the fetcher have a run -// loop spinning (typically the main thread), or that an NSOperationQueue be -// provided upon which the delegate callbacks will be called. Starting with -// iOS 6 and Mac OS X 10.7, clients may simply create an operation queue for -// callbacks on a background thread: -// -// NSOperationQueue *queue = [[[NSOperationQueue alloc] init] autorelease]; -// [queue setMaxConcurrentOperationCount:1]; -// fetcher.delegateQueue = queue; -// -// or specify the main queue for callbacks on the main thread: -// -// fetcher.delegateQueue = [NSOperationQueue mainQueue]; -// -// The client may also re-dispatch from the callbacks and notifications to -// a known dispatch queue: -// -// [myFetcher beginFetchWithCompletionHandler:^(NSData *retrievedData, NSError *error) { -// if (error == nil) { -// dispatch_async(myDispatchQueue, ^{ -// ... -// }); -// } -// }]; -// -// -// -// Downloading to disk: -// -// To have downloaded data saved directly to disk, specify either a path for the -// downloadPath property, or a file handle for the downloadFileHandle property. -// When downloading to disk, callbacks will be passed a nil for the NSData* -// arguments. -// -// -// HTTP methods and headers: -// -// Alternative HTTP methods, like PUT, and custom headers can be specified by -// creating the fetcher with an appropriate NSMutableURLRequest -// -// -// Proxies: -// -// Proxy handling is invisible so long as the system has a valid credential in -// the keychain, which is normally true (else most NSURL-based apps would have -// difficulty.) But when there is a proxy authetication error, the the fetcher -// will call the failedWithError: method with the NSURLChallenge in the error's -// userInfo. The error method can get the challenge info like this: -// -// NSURLAuthenticationChallenge *challenge -// = [[error userInfo] objectForKey:kGTMHTTPFetcherErrorChallengeKey]; -// BOOL isProxyChallenge = [[challenge protectionSpace] isProxy]; -// -// If a proxy error occurs, you can ask the user for the proxy username/password -// and call fetcher's setProxyCredential: to provide those for the -// next attempt to fetch. -// -// -// Cookies: -// -// There are three supported mechanisms for remembering cookies between fetches. -// -// By default, GTMHTTPFetcher uses a mutable array held statically to track -// cookies for all instantiated fetchers. This avoids server cookies being set -// by servers for the application from interfering with Safari cookie settings, -// and vice versa. The fetcher cookies are lost when the application quits. -// -// To rely instead on WebKit's global NSHTTPCookieStorage, call -// setCookieStorageMethod: with kGTMHTTPFetcherCookieStorageMethodSystemDefault. -// -// If the fetcher is created from a GTMHTTPFetcherService object -// then the cookie storage mechanism is set to use the cookie storage in the -// service object rather than the static storage. -// -// -// Fetching for periodic checks: -// -// The fetcher object tracks ETag headers from responses and -// provide an "If-None-Match" header. This allows the server to save -// bandwidth by providing a status message instead of repeated response -// data. -// -// To get this behavior, create the fetcher from an GTMHTTPFetcherService object -// and look for a fetch callback error with code 304 -// (kGTMHTTPFetcherStatusNotModified) like this: -// -// - (void)myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error { -// if ([error code] == kGTMHTTPFetcherStatusNotModified) { -// // |data| is empty; use the data from the previous finishedWithData: for this URL -// } else { -// // handle other server status code -// } -// } -// -// -// Monitoring received data -// -// The optional received data selector can be set with setReceivedDataSelector: -// and should have the signature -// -// - (void)myFetcher:(GTMHTTPFetcher *)fetcher receivedData:(NSData *)dataReceivedSoFar; -// -// The number bytes received so far is available as [fetcher downloadedLength]. -// This number may go down if a redirect causes the download to begin again from -// a new server. -// -// If supplied by the server, the anticipated total download size is available -// as [[myFetcher response] expectedContentLength] (and may be -1 for unknown -// download sizes.) -// -// -// Automatic retrying of fetches -// -// The fetcher can optionally create a timer and reattempt certain kinds of -// fetch failures (status codes 408, request timeout; 503, service unavailable; -// 504, gateway timeout; networking errors NSURLErrorTimedOut and -// NSURLErrorNetworkConnectionLost.) The user may set a retry selector to -// customize the type of errors which will be retried. -// -// Retries are done in an exponential-backoff fashion (that is, after 1 second, -// 2, 4, 8, and so on.) -// -// Enabling automatic retries looks like this: -// [myFetcher setRetryEnabled:YES]; -// -// With retries enabled, the success or failure callbacks are called only -// when no more retries will be attempted. Calling the fetcher's stopFetching -// method will terminate the retry timer, without the finished or failure -// selectors being invoked. -// -// Optionally, the client may set the maximum retry interval: -// [myFetcher setMaxRetryInterval:60.0]; // in seconds; default is 60 seconds -// // for downloads, 600 for uploads -// -// Also optionally, the client may provide a callback selector to determine -// if a status code or other error should be retried. -// [myFetcher setRetrySelector:@selector(myFetcher:willRetry:forError:)]; -// -// If set, the retry selector should have the signature: -// -(BOOL)fetcher:(GTMHTTPFetcher *)fetcher willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error -// and return YES to set the retry timer or NO to fail without additional -// fetch attempts. -// -// The retry method may return the |suggestedWillRetry| argument to get the -// default retry behavior. Server status codes are present in the -// error argument, and have the domain kGTMHTTPFetcherStatusDomain. The -// user's method may look something like this: -// -// -(BOOL)myFetcher:(GTMHTTPFetcher *)fetcher willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error { -// -// // perhaps examine [error domain] and [error code], or [fetcher retryCount] -// // -// // return YES to start the retry timer, NO to proceed to the failure -// // callback, or |suggestedWillRetry| to get default behavior for the -// // current error domain and code values. -// return suggestedWillRetry; -// } - - - -#pragma once - -#import - -#if defined(GTL_TARGET_NAMESPACE) - // we're using target namespace macros - #import "GTLDefines.h" -#elif defined(GDATA_TARGET_NAMESPACE) - #import "GDataDefines.h" -#else - #if TARGET_OS_IPHONE - #ifndef GTM_FOUNDATION_ONLY - #define GTM_FOUNDATION_ONLY 1 - #endif - #ifndef GTM_IPHONE - #define GTM_IPHONE 1 - #endif - #endif -#endif - -#if TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 40000) - #define GTM_BACKGROUND_FETCHING 1 -#endif - -#ifndef GTM_ALLOW_INSECURE_REQUESTS - // For builds prior to the iOS 8/10.10 SDKs, default to ignoring insecure requests for backwards - // compatibility unless the project has smartly set GTM_ALLOW_INSECURE_REQUESTS explicitly. - #if (!TARGET_OS_IPHONE && defined(MAC_OS_X_VERSION_10_10) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_10) \ - || (TARGET_OS_IPHONE && defined(__IPHONE_8_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_8_0) - #define GTM_ALLOW_INSECURE_REQUESTS 0 - #else - #define GTM_ALLOW_INSECURE_REQUESTS 1 - #endif -#endif - -#if !defined(GTMBridgeFetcher) - // These bridge macros should be identical in GTMHTTPFetcher.h and GTMSessionFetcher.h - #if GTM_USE_SESSION_FETCHER - // Macros to new fetcher class. - #define GTMBridgeFetcher GTMSessionFetcher - #define GTMBridgeFetcherService GTMSessionFetcherService - #define GTMBridgeFetcherServiceProtocol GTMSessionFetcherServiceProtocol - #define GTMBridgeAssertValidSelector GTMSessionFetcherAssertValidSelector - #define GTMBridgeCookieStorage GTMSessionCookieStorage - #define GTMBridgeCleanedUserAgentString GTMFetcherCleanedUserAgentString - #define GTMBridgeSystemVersionString GTMFetcherSystemVersionString - #define GTMBridgeApplicationIdentifier GTMFetcherApplicationIdentifier - #define kGTMBridgeFetcherStatusDomain kGTMSessionFetcherStatusDomain - #define kGTMBridgeFetcherStatusBadRequest kGTMSessionFetcherStatusBadRequest - #else - // Macros to old fetcher class. - #define GTMBridgeFetcher GTMHTTPFetcher - #define GTMBridgeFetcherService GTMHTTPFetcherService - #define GTMBridgeFetcherServiceProtocol GTMHTTPFetcherServiceProtocol - #define GTMBridgeAssertValidSelector GTMAssertSelectorNilOrImplementedWithArgs - #define GTMBridgeCookieStorage GTMCookieStorage - #define GTMBridgeCleanedUserAgentString GTMCleanedUserAgentString - #define GTMBridgeSystemVersionString GTMSystemVersionString - #define GTMBridgeApplicationIdentifier GTMApplicationIdentifier - #define kGTMBridgeFetcherStatusDomain kGTMHTTPFetcherStatusDomain - #define kGTMBridgeFetcherStatusBadRequest kGTMHTTPFetcherStatusBadRequest - #endif // GTM_USE_SESSION_FETCHER -#endif // !defined(GTMBridgeFetcher) - -#ifdef __cplusplus -extern "C" { -#endif - -// notifications -// -// fetch started and stopped, and fetch retry delay started and stopped -extern NSString *const kGTMHTTPFetcherStartedNotification; -extern NSString *const kGTMHTTPFetcherStoppedNotification; -extern NSString *const kGTMHTTPFetcherRetryDelayStartedNotification; -extern NSString *const kGTMHTTPFetcherRetryDelayStoppedNotification; - -// callback constants - -extern NSString *const kGTMHTTPFetcherErrorDomain; -extern NSString *const kGTMHTTPFetcherStatusDomain; -extern NSString *const kGTMHTTPFetcherErrorChallengeKey; -extern NSString *const kGTMHTTPFetcherStatusDataKey; // data returned with a kGTMHTTPFetcherStatusDomain error - -#ifdef __cplusplus -} -#endif - -enum { - kGTMHTTPFetcherErrorDownloadFailed = -1, - kGTMHTTPFetcherErrorAuthenticationChallengeFailed = -2, - kGTMHTTPFetcherErrorChunkUploadFailed = -3, - kGTMHTTPFetcherErrorFileHandleException = -4, - kGTMHTTPFetcherErrorBackgroundExpiration = -6, - - // The code kGTMHTTPFetcherErrorAuthorizationFailed (-5) has been removed; - // look for status 401 instead. - - kGTMHTTPFetcherStatusNotModified = 304, - kGTMHTTPFetcherStatusBadRequest = 400, - kGTMHTTPFetcherStatusUnauthorized = 401, - kGTMHTTPFetcherStatusForbidden = 403, - kGTMHTTPFetcherStatusPreconditionFailed = 412 -}; - -// cookie storage methods -enum { - kGTMHTTPFetcherCookieStorageMethodStatic = 0, - kGTMHTTPFetcherCookieStorageMethodFetchHistory = 1, - kGTMHTTPFetcherCookieStorageMethodSystemDefault = 2, - kGTMHTTPFetcherCookieStorageMethodNone = 3 -}; - -#ifdef __cplusplus -extern "C" { -#endif - -void GTMAssertSelectorNilOrImplementedWithArgs(id obj, SEL sel, ...); - -// Utility functions for applications self-identifying to servers via a -// user-agent header - -// Make a proper app name without whitespace from the given string, removing -// whitespace and other characters that may be special parsed marks of -// the full user-agent string. -NSString *GTMCleanedUserAgentString(NSString *str); - -// Make an identifier like "MacOSX/10.7.1" or "iPod_Touch/4.1 hw/iPod1_1" -NSString *GTMSystemVersionString(void); - -// Make a generic name and version for the current application, like -// com.example.MyApp/1.2.3 relying on the bundle identifier and the -// CFBundleShortVersionString or CFBundleVersion. -// -// The bundle ID may be overridden as the base identifier string by -// adding to the bundle's Info.plist a "GTMUserAgentID" key. -// -// If no bundle ID or override is available, the process name preceded -// by "proc_" is used. -NSString *GTMApplicationIdentifier(NSBundle *bundle); - -#ifdef __cplusplus -} // extern "C" -#endif - -@class GTMHTTPFetcher; - -@protocol GTMCookieStorageProtocol -// This protocol allows us to call into the service without requiring -// GTMCookieStorage sources in this project -// -// The public interface for cookie handling is the GTMCookieStorage class, -// accessible from a fetcher service object's fetchHistory or from the fetcher's -// +staticCookieStorage method. -- (NSArray *)cookiesForURL:(NSURL *)theURL; -- (void)setCookies:(NSArray *)newCookies; -@end - -@protocol GTMHTTPFetchHistoryProtocol -// This protocol allows us to call the fetch history object without requiring -// GTMHTTPFetchHistory sources in this project -- (void)updateRequest:(NSMutableURLRequest *)request isHTTPGet:(BOOL)isHTTPGet; -- (BOOL)shouldCacheETaggedData; -- (NSData *)cachedDataForRequest:(NSURLRequest *)request; -- (id )cookieStorage; -- (void)updateFetchHistoryWithRequest:(NSURLRequest *)request - response:(NSURLResponse *)response - downloadedData:(NSData *)downloadedData; -- (void)removeCachedDataForRequest:(NSURLRequest *)request; -@end - -#if GTM_USE_SESSION_FETCHER -@protocol GTMSessionFetcherServiceProtocol; -#endif - -@protocol GTMHTTPFetcherServiceProtocol -// This protocol allows us to call into the service without requiring -// GTMHTTPFetcherService sources in this project - -@property (retain) NSOperationQueue *delegateQueue; - -- (BOOL)fetcherShouldBeginFetching:(GTMHTTPFetcher *)fetcher; -- (void)fetcherDidStop:(GTMHTTPFetcher *)fetcher; - -- (GTMHTTPFetcher *)fetcherWithRequest:(NSURLRequest *)request; -- (BOOL)isDelayingFetcher:(GTMHTTPFetcher *)fetcher; -@end - -#if !defined(GTM_FETCHER_AUTHORIZATION_PROTOCOL) -#define GTM_FETCHER_AUTHORIZATION_PROTOCOL 1 -@protocol GTMFetcherAuthorizationProtocol -@required -// This protocol allows us to call the authorizer without requiring its sources -// in this project. -- (void)authorizeRequest:(NSMutableURLRequest *)request - delegate:(id)delegate - didFinishSelector:(SEL)sel; - -- (void)stopAuthorization; - -- (void)stopAuthorizationForRequest:(NSURLRequest *)request; - -- (BOOL)isAuthorizingRequest:(NSURLRequest *)request; - -- (BOOL)isAuthorizedRequest:(NSURLRequest *)request; - -@property (retain, readonly) NSString *userEmail; - -@optional - -// Indicate if authorization may be attempted. Even if this succeeds, -// authorization may fail if the user's permissions have been revoked. -@property (readonly) BOOL canAuthorize; - -// For development only, allow authorization of non-SSL requests, allowing -// transmission of the bearer token unencrypted. -@property (assign) BOOL shouldAuthorizeAllRequests; - -#if NS_BLOCKS_AVAILABLE -- (void)authorizeRequest:(NSMutableURLRequest *)request - completionHandler:(void (^)(NSError *error))handler; -#endif - -#if GTM_USE_SESSION_FETCHER -@property (assign) id fetcherService; // WEAK -#else -@property (assign) id fetcherService; // WEAK -#endif - -- (BOOL)primeForRefresh; - -@end -#endif // !defined(GTM_FETCHER_AUTHORIZATION_PROTOCOL) - - -// GTMHTTPFetcher objects are used for async retrieval of an http get or post -// -// See additional comments at the beginning of this file -@interface GTMHTTPFetcher : NSObject { - @protected - NSMutableURLRequest *request_; - NSURLConnection *connection_; - NSMutableData *downloadedData_; - NSString *downloadPath_; - NSString *temporaryDownloadPath_; - NSFileHandle *downloadFileHandle_; - unsigned long long downloadedLength_; - NSArray *allowedInsecureSchemes_; - BOOL allowLocalhostRequest_; - NSURLCredential *credential_; // username & password - NSURLCredential *proxyCredential_; // credential supplied to proxy servers - NSData *postData_; - NSInputStream *postStream_; - NSMutableData *loggedStreamData_; - NSURLResponse *response_; // set in connection:didReceiveResponse: - id delegate_; - SEL finishedSel_; // should by implemented by delegate - SEL sentDataSel_; // optional, set with setSentDataSelector - SEL receivedDataSel_; // optional, set with setReceivedDataSelector -#if NS_BLOCKS_AVAILABLE - void (^completionBlock_)(NSData *, NSError *); - void (^receivedDataBlock_)(NSData *); - void (^sentDataBlock_)(NSInteger, NSInteger, NSInteger); - BOOL (^retryBlock_)(BOOL, NSError *); -#elif !__LP64__ - // placeholders: for 32-bit builds, keep the size of the object's ivar section - // the same with and without blocks - id completionPlaceholder_; - id receivedDataPlaceholder_; - id sentDataPlaceholder_; - id retryPlaceholder_; -#endif - BOOL hasConnectionEnded_; // set if the connection need not be cancelled - BOOL isCancellingChallenge_; // set only when cancelling an auth challenge - BOOL isStopNotificationNeeded_; // set when start notification has been sent - BOOL shouldFetchInBackground_; -#if GTM_BACKGROUND_FETCHING - NSUInteger backgroundTaskIdentifer_; // UIBackgroundTaskIdentifier -#endif - id userData_; // retained, if set by caller - NSMutableDictionary *properties_; // more data retained for caller - NSArray *runLoopModes_; // optional - NSOperationQueue *delegateQueue_; // optional; available iOS 6/10.7 and later - id fetchHistory_; // if supplied by the caller, used for Last-Modified-Since checks and cookies - NSInteger cookieStorageMethod_; // constant from above - id cookieStorage_; - - id authorizer_; - - // the service object that created and monitors this fetcher, if any - id service_; - NSString *serviceHost_; - NSInteger servicePriority_; - NSThread *thread_; - - BOOL isRetryEnabled_; // user wants auto-retry - SEL retrySel_; // optional; set with setRetrySelector - NSTimer *retryTimer_; - NSUInteger retryCount_; - NSTimeInterval maxRetryInterval_; // default 600 seconds - NSTimeInterval minRetryInterval_; // random between 1 and 2 seconds - NSTimeInterval retryFactor_; // default interval multiplier is 2 - NSTimeInterval lastRetryInterval_; - NSDate *initialRequestDate_; - BOOL hasAttemptedAuthRefresh_; - - NSString *comment_; // comment for log - NSString *log_; -#if !STRIP_GTM_FETCH_LOGGING - NSURL *redirectedFromURL_; - NSString *logRequestBody_; - NSString *logResponseBody_; - BOOL hasLoggedError_; - BOOL shouldDeferResponseBodyLogging_; -#endif -} - -// Create a fetcher -// -// fetcherWithRequest will return an autoreleased fetcher, but if -// the connection is successfully created, the connection should retain the -// fetcher for the life of the connection as well. So the caller doesn't have -// to retain the fetcher explicitly unless they want to be able to cancel it. -+ (GTMHTTPFetcher *)fetcherWithRequest:(NSURLRequest *)request; - -// Convenience methods that make a request, like +fetcherWithRequest -+ (GTMHTTPFetcher *)fetcherWithURL:(NSURL *)requestURL; -+ (GTMHTTPFetcher *)fetcherWithURLString:(NSString *)requestURLString; - -// Designated initializer -- (id)initWithRequest:(NSURLRequest *)request; - -// Fetcher request -// -// The underlying request is mutable and may be modified by the caller -@property (retain) NSMutableURLRequest *mutableRequest; - -// By default, the fetcher allows only secure (https) schemes unless this -// property is set, or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. -// -// For example, during debugging when fetching from a development server that lacks SSL support, -// this may be set to @[ @"http" ], or when the fetcher is used to retrieve local files, -// this may be set to @[ @"file" ]. -// -// This should be left as nil for release builds to avoid creating the opportunity for -// leaking private user behavior and data. If a server is providing insecure URLs -// for fetching by the client app, report the problem as server security & privacy bug. -@property(copy) NSArray *allowedInsecureSchemes; - -// By default, the fetcher prohibits localhost requests unless this property is set, -// or the GTM_ALLOW_INSECURE_REQUESTS build flag is set. -// -// For localhost requests, the URL scheme is not checked when this property is set. -@property(assign) BOOL allowLocalhostRequest; - -// Setting the credential is optional; it is used if the connection receives -// an authentication challenge -@property (retain) NSURLCredential *credential; - -// Setting the proxy credential is optional; it is used if the connection -// receives an authentication challenge from a proxy -@property (retain) NSURLCredential *proxyCredential; - -// If post data or stream is not set, then a GET retrieval method is assumed -@property (retain) NSData *postData; -@property (retain) NSInputStream *postStream; - -// The default cookie storage method is kGTMHTTPFetcherCookieStorageMethodStatic -// without a fetch history set, and kGTMHTTPFetcherCookieStorageMethodFetchHistory -// with a fetch history set -// -// Applications needing control of cookies across a sequence of fetches should -// create fetchers from a GTMHTTPFetcherService object (which encapsulates -// fetch history) for a well-defined cookie store -@property (assign) NSInteger cookieStorageMethod; - -+ (id )staticCookieStorage; - -// Object to add authorization to the request, if needed -@property (retain) id authorizer; - -// The service object that created and monitors this fetcher, if any -@property (retain) id service; - -// The host, if any, used to classify this fetcher in the fetcher service -@property (copy) NSString *serviceHost; - -// The priority, if any, used for starting fetchers in the fetcher service -// -// Lower values are higher priority; the default is 0, and values may -// be negative or positive. This priority affects only the start order of -// fetchers that are being delayed by a fetcher service. -@property (assign) NSInteger servicePriority; - -// The thread used to run this fetcher in the fetcher service when no operation -// queue is provided. -@property (retain) NSThread *thread; - -// The delegate is retained during the connection -@property (retain) id delegate; - -// On iOS 4 and later, the fetch may optionally continue while the app is in the -// background until finished or stopped by OS expiration -// -// The default value is NO -// -// For Mac OS X, background fetches are always supported, and this property -// is ignored -@property (assign) BOOL shouldFetchInBackground; - -// The delegate's optional sentData selector may be used to monitor upload -// progress. It should have a signature like: -// - (void)myFetcher:(GTMHTTPFetcher *)fetcher -// didSendBytes:(NSInteger)bytesSent -// totalBytesSent:(NSInteger)totalBytesSent -// totalBytesExpectedToSend:(NSInteger)totalBytesExpectedToSend; -// -// +doesSupportSentDataCallback indicates if this delegate method is supported -+ (BOOL)doesSupportSentDataCallback; - -@property (assign) SEL sentDataSelector; - -// The delegate's optional receivedData selector may be used to monitor download -// progress. It should have a signature like: -// - (void)myFetcher:(GTMHTTPFetcher *)fetcher -// receivedData:(NSData *)dataReceivedSoFar; -// -// The dataReceived argument will be nil when downloading to a path or to a -// file handle. -// -// Applications should not use this method to accumulate the received data; -// the callback method or block supplied to the beginFetch call will have -// the complete NSData received. -@property (assign) SEL receivedDataSelector; - -#if NS_BLOCKS_AVAILABLE -// The full interface to the block is provided rather than just a typedef for -// its parameter list in order to get more useful code completion in the Xcode -// editor -@property (copy) void (^sentDataBlock)(NSInteger bytesSent, NSInteger totalBytesSent, NSInteger bytesExpectedToSend); - -// The dataReceived argument will be nil when downloading to a path or to -// a file handle -@property (copy) void (^receivedDataBlock)(NSData *dataReceivedSoFar); -#endif - -// retrying; see comments at the top of the file. Calling -// setRetryEnabled(YES) resets the min and max retry intervals. -@property (assign, getter=isRetryEnabled) BOOL retryEnabled; - -// Retry selector or block is optional for retries. -// -// If present, it should have the signature: -// -(BOOL)fetcher:(GTMHTTPFetcher *)fetcher willRetry:(BOOL)suggestedWillRetry forError:(NSError *)error -// and return YES to cause a retry. See comments at the top of this file. -@property (assign) SEL retrySelector; - -#if NS_BLOCKS_AVAILABLE -@property (copy) BOOL (^retryBlock)(BOOL suggestedWillRetry, NSError *error); -#endif - -// Retry intervals must be strictly less than maxRetryInterval, else -// they will be limited to maxRetryInterval and no further retries will -// be attempted. Setting maxRetryInterval to 0.0 will reset it to the -// default value, 600 seconds. - -@property (assign) NSTimeInterval maxRetryInterval; - -// Starting retry interval. Setting minRetryInterval to 0.0 will reset it -// to a random value between 1.0 and 2.0 seconds. Clients should normally not -// call this except for unit testing. -@property (assign) NSTimeInterval minRetryInterval; - -// Multiplier used to increase the interval between retries, typically 2.0. -// Clients should not need to call this. -@property (assign) double retryFactor; - -// Number of retries attempted -@property (readonly) NSUInteger retryCount; - -// interval delay to precede next retry -@property (readonly) NSTimeInterval nextRetryInterval; - -// Begin fetching the request -// -// The delegate can optionally implement the finished selectors or pass NULL -// for it. -// -// Returns YES if the fetch is initiated. The delegate is retained between -// the beginFetch call until after the finish callback. -// -// An error is passed to the callback for server statuses 300 or -// higher, with the status stored as the error object's code. -// -// finishedSEL has a signature like: -// - (void)fetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)data error:(NSError *)error; -// -// If the application has specified a downloadPath or downloadFileHandle -// for the fetcher, the data parameter passed to the callback will be nil. - -- (BOOL)beginFetchWithDelegate:(id)delegate - didFinishSelector:(SEL)finishedSEL; - -#if NS_BLOCKS_AVAILABLE -- (BOOL)beginFetchWithCompletionHandler:(void (^)(NSData *data, NSError *error))handler; -#endif - - -// Returns YES if this is in the process of fetching a URL -- (BOOL)isFetching; - -// Cancel the fetch of the request that's currently in progress -- (void)stopFetching; - -// Return the status code from the server response -@property (readonly) NSInteger statusCode; - -// Return the http headers from the response -@property (retain, readonly) NSDictionary *responseHeaders; - -// The response, once it's been received -@property (retain) NSURLResponse *response; - -// Bytes downloaded so far -@property (readonly) unsigned long long downloadedLength; - -// Buffer of currently-downloaded data -@property (readonly, retain) NSData *downloadedData; - -// Path in which to non-atomically create a file for storing the downloaded data -// -// The path must be set before fetching begins. The download file handle -// will be created for the path, and can be used to monitor progress. If a file -// already exists at the path, it will be overwritten. -@property (copy) NSString *downloadPath; - -// If downloadFileHandle is set, data received is immediately appended to -// the file handle rather than being accumulated in the downloadedData property -// -// The file handle supplied must allow writing and support seekToFileOffset:, -// and must be set before fetching begins. Setting a download path will -// override the file handle property. -@property (retain) NSFileHandle *downloadFileHandle; - -// The optional fetchHistory object is used for a sequence of fetchers to -// remember ETags, cache ETagged data, and store cookies. Typically, this -// is set by a GTMFetcherService object when it creates a fetcher. -// -// Side effect: setting fetch history implicitly calls setCookieStorageMethod: -@property (retain) id fetchHistory; - -// userData is retained for the convenience of the caller -@property (retain) id userData; - -// Stored property values are retained for the convenience of the caller -@property (copy) NSMutableDictionary *properties; - -- (void)setProperty:(id)obj forKey:(NSString *)key; // pass nil obj to remove property -- (id)propertyForKey:(NSString *)key; - -- (void)addPropertiesFromDictionary:(NSDictionary *)dict; - -// Comments are useful for logging -@property (copy) NSString *comment; - -- (void)setCommentWithFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1, 2); - -// Log of request and response, if logging is enabled -@property (copy) NSString *log; - -// Callbacks can be invoked on an operation queue rather than via the run loop, -// starting on 10.7 and iOS 6. If a delegate queue is supplied. the run loop -// modes are ignored. If no delegateQueue is supplied, and run loop modes are -// not supplied, and the fetcher is started off of the main thread, then a -// delegateQueue of [NSOperationQueue mainQueue] is assumed. -@property (retain) NSOperationQueue *delegateQueue; - -// Using the fetcher while a modal dialog is displayed requires setting the -// run-loop modes to include NSModalPanelRunLoopMode -@property (retain) NSArray *runLoopModes; - -// Users who wish to replace GTMHTTPFetcher's use of NSURLConnection -// can do so globally here. The replacement should be a subclass of -// NSURLConnection. -+ (Class)connectionClass; -+ (void)setConnectionClass:(Class)theClass; - -// -// Method for compatibility with GTMSessionFetcher -// -@property (retain) NSData *bodyData; - -// Spin the run loop, discarding events, until the fetch has completed -// -// This is only for use in testing or in tools without a user interface. -// -// Synchronous fetches should never be done by shipping apps; they are -// sufficient reason for rejection from the app store. -- (void)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds; - -#if STRIP_GTM_FETCH_LOGGING -// if logging is stripped, provide a stub for the main method -// for controlling logging -+ (void)setLoggingEnabled:(BOOL)flag; -#endif // STRIP_GTM_FETCH_LOGGING - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.m deleted file mode 100755 index 99e189258..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.m +++ /dev/null @@ -1,2156 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPFetcher.m -// - -#import "GTMHTTPFetcher.h" - -#if GTM_BACKGROUND_FETCHING -#import -#endif - -#import - -static id gGTMFetcherStaticCookieStorage = nil; -static Class gGTMFetcherConnectionClass = nil; - - -NSString *const kGTMHTTPFetcherStartedNotification = @"kGTMHTTPFetcherStartedNotification"; -NSString *const kGTMHTTPFetcherStoppedNotification = @"kGTMHTTPFetcherStoppedNotification"; -NSString *const kGTMHTTPFetcherRetryDelayStartedNotification = @"kGTMHTTPFetcherRetryDelayStartedNotification"; -NSString *const kGTMHTTPFetcherRetryDelayStoppedNotification = @"kGTMHTTPFetcherRetryDelayStoppedNotification"; - -NSString *const kGTMHTTPFetcherErrorDomain = @"com.google.GTMHTTPFetcher"; -NSString *const kGTMHTTPFetcherStatusDomain = @"com.google.HTTPStatus"; -NSString *const kGTMHTTPFetcherErrorChallengeKey = @"challenge"; -NSString *const kGTMHTTPFetcherStatusDataKey = @"data"; // data returned with a kGTMHTTPFetcherStatusDomain error - -// The default max retry interview is 10 minutes for uploads (POST/PUT/PATCH), -// 1 minute for downloads. -static const NSTimeInterval kUnsetMaxRetryInterval = -1; -static const NSTimeInterval kDefaultMaxDownloadRetryInterval = 60.0; -static const NSTimeInterval kDefaultMaxUploadRetryInterval = 60.0 * 10.; - -// delegateQueue callback parameters -static NSString *const kCallbackTarget = @"target"; -static NSString *const kCallbackSelector = @"sel"; -static NSString *const kCallbackBlock = @"block"; -static NSString *const kCallbackData = @"data"; -static NSString *const kCallbackError = @"error"; - -// -// GTMHTTPFetcher -// - -@interface GTMHTTPFetcher () - -@property (copy) NSString *temporaryDownloadPath; -@property (retain) id cookieStorage; -@property (readwrite, retain) NSData *downloadedData; -#if NS_BLOCKS_AVAILABLE -@property (copy) void (^completionBlock)(NSData *, NSError *); -#endif - -- (BOOL)beginFetchMayDelay:(BOOL)mayDelay - mayAuthorize:(BOOL)mayAuthorize; -- (void)failToBeginFetchWithError:(NSError *)error; -- (void)failToBeginFetchDeferWithError:(NSError *)error; - -#if GTM_BACKGROUND_FETCHING -- (void)endBackgroundTask; -- (void)backgroundFetchExpired; -#endif - -- (BOOL)authorizeRequest; -- (void)authorizer:(id )auth - request:(NSMutableURLRequest *)request - finishedWithError:(NSError *)error; - -- (NSString *)createTempDownloadFilePathForPath:(NSString *)targetPath; -- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks; -- (BOOL)shouldReleaseCallbacksUponCompletion; - -- (void)addCookiesToRequest:(NSMutableURLRequest *)request; -- (void)handleCookiesForResponse:(NSURLResponse *)response; - -- (void)invokeFetchCallbacksWithData:(NSData *)data - error:(NSError *)error; -- (void)invokeFetchCallbacksWithTarget:(id)target - selector:(SEL)sel - block:(id)block - data:(NSData *)data - error:(NSError *)error; -- (void)invokeFetchCallback:(SEL)sel - target:(id)target - data:(NSData *)data - error:(NSError *)error; -- (void)invokeFetchCallbacksOnDelegateQueueWithData:(NSData *)data - error:(NSError *)error; -- (void)invokeOnQueueWithDictionary:(NSDictionary *)dict; -- (void)releaseCallbacks; - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; - -- (BOOL)shouldRetryNowForStatus:(NSInteger)status error:(NSError *)error; -- (void)destroyRetryTimer; -- (void)beginRetryTimer; -- (void)primeRetryTimerWithNewTimeInterval:(NSTimeInterval)secs; -- (void)sendStopNotificationIfNeeded; -- (void)retryFetch; -- (void)retryTimerFired:(NSTimer *)timer; -@end - -@interface GTMHTTPFetcher (GTMHTTPFetcherLoggingInternal) -- (void)setupStreamLogging; -- (void)logFetchWithError:(NSError *)error; -- (void)logNowWithError:(NSError *)error; -@end - -@implementation GTMHTTPFetcher - -+ (GTMHTTPFetcher *)fetcherWithRequest:(NSURLRequest *)request { - return [[[[self class] alloc] initWithRequest:request] autorelease]; -} - -+ (GTMHTTPFetcher *)fetcherWithURL:(NSURL *)requestURL { - return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; -} - -+ (GTMHTTPFetcher *)fetcherWithURLString:(NSString *)requestURLString { - return [self fetcherWithURL:[NSURL URLWithString:requestURLString]]; -} - -+ (void)initialize { - // initialize is guaranteed by the runtime to be called in a - // thread-safe manner - if (!gGTMFetcherStaticCookieStorage) { - Class cookieStorageClass = NSClassFromString(@"GTMCookieStorage"); - if (cookieStorageClass) { - gGTMFetcherStaticCookieStorage = [[cookieStorageClass alloc] init]; - } - } -} - -- (id)init { - return [self initWithRequest:nil]; -} - -- (id)initWithRequest:(NSURLRequest *)request { - self = [super init]; - if (self) { - request_ = [request mutableCopy]; - - if (gGTMFetcherStaticCookieStorage != nil) { - // The user has compiled with the cookie storage class available; - // default to static cookie storage, so our cookies are independent - // of the cookies of other apps. - [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic]; - } else { - // Default to system default cookie storage - [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodSystemDefault]; - } -#if !STRIP_GTM_FETCH_LOGGING - // Encourage developers to set the comment property or use - // setCommentWithFormat: by providing a default string. - comment_ = @"(No fetcher comment set)"; -#endif - } - return self; -} - -- (id)copyWithZone:(NSZone *)zone { - // disallow use of fetchers in a copy property - [self doesNotRecognizeSelector:_cmd]; - return nil; -} - -- (NSString *)description { - return [NSString stringWithFormat:@"%@ %p (%@)", - [self class], self, [self.mutableRequest URL]]; -} - -#if !GTM_IPHONE -- (void)finalize { - [self stopFetchReleasingCallbacks:YES]; // releases connection_, destroys timers - [super finalize]; -} -#endif - -- (void)dealloc { -#if DEBUG - NSAssert(!isStopNotificationNeeded_, - @"unbalanced fetcher notification for %@", [request_ URL]); -#endif - - // Note: if a connection or a retry timer was pending, then this instance - // would be retained by those so it wouldn't be getting dealloc'd, - // hence we don't need to stopFetch here - [request_ release]; - [connection_ release]; - [downloadedData_ release]; - [downloadPath_ release]; - [temporaryDownloadPath_ release]; - [downloadFileHandle_ release]; - [credential_ release]; - [proxyCredential_ release]; - [postData_ release]; - [postStream_ release]; - [loggedStreamData_ release]; - [response_ release]; -#if NS_BLOCKS_AVAILABLE - [completionBlock_ release]; - [receivedDataBlock_ release]; - [sentDataBlock_ release]; - [retryBlock_ release]; -#endif - [userData_ release]; - [properties_ release]; - [delegateQueue_ release]; - [runLoopModes_ release]; - [fetchHistory_ release]; - [cookieStorage_ release]; - [authorizer_ release]; - [service_ release]; - [serviceHost_ release]; - [thread_ release]; - [retryTimer_ release]; - [initialRequestDate_ release]; - [comment_ release]; - [log_ release]; -#if !STRIP_GTM_FETCH_LOGGING - [redirectedFromURL_ release]; - [logRequestBody_ release]; - [logResponseBody_ release]; -#endif - - [super dealloc]; -} - -#pragma mark - - -// Begin fetching the URL (or begin a retry fetch). The delegate is retained -// for the duration of the fetch connection. - -- (BOOL)beginFetchWithDelegate:(id)delegate - didFinishSelector:(SEL)finishedSelector { - GTMAssertSelectorNilOrImplementedWithArgs(delegate, finishedSelector, @encode(GTMHTTPFetcher *), @encode(NSData *), @encode(NSError *), 0); - GTMAssertSelectorNilOrImplementedWithArgs(delegate, receivedDataSel_, @encode(GTMHTTPFetcher *), @encode(NSData *), 0); - GTMAssertSelectorNilOrImplementedWithArgs(delegate, retrySel_, @encode(GTMHTTPFetcher *), @encode(BOOL), @encode(NSError *), 0); - - // We'll retain the delegate only during the outstanding connection (similar - // to what Cocoa does with performSelectorOnMainThread:) and during - // authorization or delays, since the app would crash - // if the delegate was released before the fetch calls back - [self setDelegate:delegate]; - finishedSel_ = finishedSelector; - - return [self beginFetchMayDelay:YES - mayAuthorize:YES]; -} - -- (BOOL)beginFetchMayDelay:(BOOL)mayDelay - mayAuthorize:(BOOL)mayAuthorize { - // This is the internal entry point for re-starting fetches - NSError *error = nil; - - if (connection_ != nil) { - NSAssert1(connection_ != nil, @"fetch object %@ being reused; this should never happen", self); - goto CannotBeginFetch; - } - - NSURL *requestURL = [request_ URL]; - if (request_ == nil || requestURL == nil) { - NSAssert(request_ != nil, @"beginFetchWithDelegate requires a request with a URL"); - goto CannotBeginFetch; - } - -#if !GTM_ALLOW_INSECURE_REQUESTS - if (requestURL != nil) { - // Allow https only for requests, unless overridden by the client. - // - // Non-https requests may too easily be snooped, so we disallow them by default. - // - // file: and data: schemes are usually safe if they are hardcoded in the client or provided - // by a trusted source, but since it's fairly rare to need them, it's safest to make clients - // explicitly whitelist them. - NSString *requestScheme = [requestURL scheme]; - BOOL isSecure = ([requestScheme caseInsensitiveCompare:@"https"] == NSOrderedSame); - if (!isSecure) { - BOOL allowRequest = NO; - NSString *host = [requestURL host]; - BOOL isLocalhost = ([host caseInsensitiveCompare:@"localhost"] == NSOrderedSame - || [host isEqual:@"::1"] - || [host isEqual:@"127.0.0.1"]); - if (isLocalhost) { - if (allowLocalhostRequest_) { - allowRequest = YES; - } else { - // To fetch from localhost, the fetcher must specifically have the allowLocalhostRequest - // property set. -#if DEBUG - NSAssert(NO, @"Fetch request for localhost but fetcher allowLocalhostRequest" - @" is not set: %@", requestURL); -#else - NSLog(@"Localhost fetch disallowed for %@", requestURL); -#endif - } - } else { - // Not localhost; check schemes. - for (NSString *allowedScheme in allowedInsecureSchemes_) { - if ([requestScheme caseInsensitiveCompare:allowedScheme] == NSOrderedSame) { - allowRequest = YES; - break; - } - } - if (!allowRequest) { - // To make a request other than https:, the client must specify an array for the - // allowedInsecureSchemes property. -#if DEBUG - NSAssert(NO, @"Insecure fetch request has a scheme (%@)" - @" not found in fetcher allowedInsecureSchemes (%@): %@", - requestScheme, allowedInsecureSchemes_, requestURL); -#else - NSLog(@"Fetch disallowed for %@", requestURL); -#endif - } - } - if (!allowRequest) { - goto CannotBeginFetch; - } - } // !isSecure - } // requestURL != nil -#endif // GTM_ALLOW_INSECURE_REQUESTS - - self.downloadedData = nil; - downloadedLength_ = 0; - - if (mayDelay && service_) { - BOOL shouldFetchNow = [service_ fetcherShouldBeginFetching:self]; - if (!shouldFetchNow) { - // the fetch is deferred, but will happen later - return YES; - } - } - - NSString *effectiveHTTPMethod = [request_ valueForHTTPHeaderField:@"X-HTTP-Method-Override"]; - if (effectiveHTTPMethod == nil) { - effectiveHTTPMethod = [request_ HTTPMethod]; - } - BOOL isEffectiveHTTPGet = (effectiveHTTPMethod == nil - || [effectiveHTTPMethod isEqual:@"GET"]); - - if (postData_ || postStream_) { - if (isEffectiveHTTPGet) { - [request_ setHTTPMethod:@"POST"]; - isEffectiveHTTPGet = NO; - } - - if (postData_) { - [request_ setHTTPBody:postData_]; - } else { - if ([self respondsToSelector:@selector(setupStreamLogging)]) { - [self performSelector:@selector(setupStreamLogging)]; - } - - [request_ setHTTPBodyStream:postStream_]; - } - } - - // We authorize after setting up the http method and body in the request - // because OAuth 1 may need to sign the request body - if (mayAuthorize && authorizer_) { - BOOL isAuthorized = [authorizer_ isAuthorizedRequest:request_]; - if (!isAuthorized) { - // authorization needed - return [self authorizeRequest]; - } - } - - [fetchHistory_ updateRequest:request_ isHTTPGet:isEffectiveHTTPGet]; - - // set the default upload or download retry interval, if necessary - if (isRetryEnabled_ - && maxRetryInterval_ <= kUnsetMaxRetryInterval) { - if (isEffectiveHTTPGet || [effectiveHTTPMethod isEqual:@"HEAD"]) { - [self setMaxRetryInterval:kDefaultMaxDownloadRetryInterval]; - } else { - [self setMaxRetryInterval:kDefaultMaxUploadRetryInterval]; - } - } - - [self addCookiesToRequest:request_]; - - if (downloadPath_ != nil) { - // downloading to a path, so create a temporary file and a file handle for - // downloading - NSString *tempPath = [self createTempDownloadFilePathForPath:downloadPath_]; - - BOOL didCreate = [[NSData data] writeToFile:tempPath - options:0 - error:&error]; - if (!didCreate) goto CannotBeginFetch; - - [self setTemporaryDownloadPath:tempPath]; - - NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:tempPath]; - if (fh == nil) goto CannotBeginFetch; - - [self setDownloadFileHandle:fh]; - } - - // finally, start the connection - - Class connectionClass = [[self class] connectionClass]; - - NSOperationQueue *delegateQueue = delegateQueue_; - if (delegateQueue && - ![connectionClass instancesRespondToSelector:@selector(setDelegateQueue:)]) { - // NSURLConnection has no setDelegateQueue: on iOS 4 and Mac OS X 10.5. - delegateQueue = nil; - self.delegateQueue = nil; - } else if (delegateQueue == nil && runLoopModes_ == nil && ![NSThread isMainThread]) { - // Neither a delegate queue nor runLoopModes were supplied, and we're not on the - // main thread, so assume the user really wants callbacks and provide a queue. - // - // We don't have a way to verify that this thread has a run loop spinning, but - // it's fairly rare that a background thread does have one. A client that - // does want to rely on spinning a run loop should specify run loop modes. - delegateQueue = [NSOperationQueue mainQueue]; - self.delegateQueue = delegateQueue; - } - -#if DEBUG && TARGET_OS_IPHONE - BOOL isPreIOS6 = (NSFoundationVersionNumber <= 890.1); - if (isPreIOS6 && delegateQueue) { - NSLog(@"GTMHTTPFetcher delegateQueue not safe in iOS 5"); - } -#endif - - if (downloadFileHandle_ != nil) { - // Downloading to a file, so downloadedData_ remains nil. - } else { - self.downloadedData = [NSMutableData data]; - } - - hasConnectionEnded_ = NO; - if ([runLoopModes_ count] == 0 && delegateQueue == nil) { - // No custom callback modes or queue were specified, so start the connection - // on the current run loop in the current mode - connection_ = [[connectionClass connectionWithRequest:request_ - delegate:self] retain]; - } else { - // Specify callbacks be on an operation queue or on the current run loop - // in the specified modes - connection_ = [[connectionClass alloc] initWithRequest:request_ - delegate:self - startImmediately:NO]; - if (delegateQueue) { - [connection_ performSelector:@selector(setDelegateQueue:) - withObject:delegateQueue]; - } else if (runLoopModes_) { - NSRunLoop *rl = [NSRunLoop currentRunLoop]; - for (NSString *mode in runLoopModes_) { - [connection_ scheduleInRunLoop:rl forMode:mode]; - } - } - [connection_ start]; - } - - if (!connection_) { - NSAssert(connection_ != nil, @"beginFetchWithDelegate could not create a connection"); - self.downloadedData = nil; - goto CannotBeginFetch; - } - -#if GTM_BACKGROUND_FETCHING - backgroundTaskIdentifer_ = 0; // UIBackgroundTaskInvalid is 0 on iOS 4 - if (shouldFetchInBackground_) { - // For iOS 3 compatibility, ensure that UIApp supports backgrounding - UIApplication *app = [UIApplication sharedApplication]; - if ([app respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) { - // Tell UIApplication that we want to continue even when the app is in the - // background. - NSThread *thread = delegateQueue_ ? nil : [NSThread currentThread]; - backgroundTaskIdentifer_ = [app beginBackgroundTaskWithExpirationHandler:^{ - // Background task expiration callback - this block is always invoked by - // UIApplication on the main thread. - if (thread) { - // Run the user's callbacks on the thread used to start the - // fetch. - [self performSelector:@selector(backgroundFetchExpired) - onThread:thread - withObject:nil - waitUntilDone:YES]; - } else { - // backgroundFetchExpired invokes callbacks on the provided delegate - // queue. - [self backgroundFetchExpired]; - } - }]; - } - } -#endif - - if (!initialRequestDate_) { - initialRequestDate_ = [[NSDate alloc] init]; - } - -#if DEBUG - // For testing only, look for a property indicating the fetch should immediately fail. - if ([self propertyForKey:@"_CannotBeginFetch"] != nil) { - goto CannotBeginFetch; - } -#endif - - // Once connection_ is non-nil we can send the start notification - isStopNotificationNeeded_ = YES; - NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter]; - [defaultNC postNotificationName:kGTMHTTPFetcherStartedNotification - object:self]; - return YES; - -CannotBeginFetch: - [self failToBeginFetchDeferWithError:error]; - return NO; -} - -- (void)failToBeginFetchDeferWithError:(NSError *)error { - if (delegateQueue_) { - // Deferring will happen by the callback being invoked on the specified - // queue. - [self failToBeginFetchWithError:error]; - } else { - // No delegate queue has been specified, so put the callback - // on an appropriate run loop. - NSArray *modes = (runLoopModes_ ? runLoopModes_ : - [NSArray arrayWithObject:NSRunLoopCommonModes]); - [self performSelector:@selector(failToBeginFetchWithError:) - onThread:[NSThread currentThread] - withObject:error - waitUntilDone:NO - modes:modes]; - } -} - -- (void)failToBeginFetchWithError:(NSError *)error { - if (error == nil) { - error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain - code:kGTMHTTPFetcherErrorDownloadFailed - userInfo:nil]; - } - - [[self retain] autorelease]; // In case the callback releases us - - [self invokeFetchCallbacksOnDelegateQueueWithData:nil - error:error]; - - [self releaseCallbacks]; - - [service_ fetcherDidStop:self]; - - self.authorizer = nil; - - if (temporaryDownloadPath_) { - [[NSFileManager defaultManager] removeItemAtPath:temporaryDownloadPath_ - error:NULL]; - self.temporaryDownloadPath = nil; - } -} - -#if GTM_BACKGROUND_FETCHING -- (void)backgroundFetchExpired { - // On background expiration, we stop the fetch and invoke the callbacks - NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain - code:kGTMHTTPFetcherErrorBackgroundExpiration - userInfo:nil]; - [self invokeFetchCallbacksOnDelegateQueueWithData:nil - error:error]; - @synchronized(self) { - // Stopping the fetch here will indirectly call endBackgroundTask - [self stopFetchReleasingCallbacks:NO]; - - [self releaseCallbacks]; - self.authorizer = nil; - } -} - -- (void)endBackgroundTask { - @synchronized(self) { - // Whenever the connection stops or background execution expires, - // we need to tell UIApplication we're done - if (backgroundTaskIdentifer_) { - // If backgroundTaskIdentifer_ is non-zero, we know we're on iOS 4 - UIApplication *app = [UIApplication sharedApplication]; - [app endBackgroundTask:backgroundTaskIdentifer_]; - - backgroundTaskIdentifer_ = 0; - } - } -} -#endif // GTM_BACKGROUND_FETCHING - -- (BOOL)authorizeRequest { - id authorizer = self.authorizer; - SEL asyncAuthSel = @selector(authorizeRequest:delegate:didFinishSelector:); - if ([authorizer respondsToSelector:asyncAuthSel]) { - SEL callbackSel = @selector(authorizer:request:finishedWithError:); - [authorizer authorizeRequest:request_ - delegate:self - didFinishSelector:callbackSel]; - return YES; - } else { - NSAssert(authorizer == nil, @"invalid authorizer for fetch"); - - // No authorizing possible, and authorizing happens only after any delay; - // just begin fetching - return [self beginFetchMayDelay:NO - mayAuthorize:NO]; - } -} - -- (void)authorizer:(id )auth - request:(NSMutableURLRequest *)request - finishedWithError:(NSError *)error { - if (error != nil) { - // We can't fetch without authorization - [self failToBeginFetchDeferWithError:error]; - } else { - [self beginFetchMayDelay:NO - mayAuthorize:NO]; - } -} - -#if NS_BLOCKS_AVAILABLE -- (BOOL)beginFetchWithCompletionHandler:(void (^)(NSData *data, NSError *error))handler { - self.completionBlock = handler; - - // The user may have called setDelegate: earlier if they want to use other - // delegate-style callbacks during the fetch; otherwise, the delegate is nil, - // which is fine. - return [self beginFetchWithDelegate:[self delegate] - didFinishSelector:nil]; -} -#endif - -- (NSString *)createTempDownloadFilePathForPath:(NSString *)targetPath { - NSString *tempDir = nil; - -#if (!TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)) - // Find an appropriate directory for the download, ideally on the same disk - // as the final target location so the temporary file won't have to be moved - // to a different disk. - // - // Available in SDKs for 10.6 and iOS 4 - // - // Oct 2011: We previously also used URLForDirectory for - // (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 40000)) - // but that is returning a non-temporary directory for iOS, unfortunately - - SEL sel = @selector(URLForDirectory:inDomain:appropriateForURL:create:error:); - if ([NSFileManager instancesRespondToSelector:sel]) { - NSError *error = nil; - NSURL *targetURL = [NSURL fileURLWithPath:targetPath]; - NSFileManager *fileMgr = [NSFileManager defaultManager]; - - NSURL *tempDirURL = [fileMgr URLForDirectory:NSItemReplacementDirectory - inDomain:NSUserDomainMask - appropriateForURL:targetURL - create:YES - error:&error]; - tempDir = [tempDirURL path]; - } -#endif - - if (tempDir == nil) { - tempDir = NSTemporaryDirectory(); - } - - static unsigned int counter = 0; - NSString *name = [NSString stringWithFormat:@"gtmhttpfetcher_%u_%u", - ++counter, (unsigned int) arc4random()]; - NSString *result = [tempDir stringByAppendingPathComponent:name]; - return result; -} - -- (void)addCookiesToRequest:(NSMutableURLRequest *)request { - // Get cookies for this URL from our storage array, if - // we have a storage array - if (cookieStorageMethod_ != kGTMHTTPFetcherCookieStorageMethodSystemDefault - && cookieStorageMethod_ != kGTMHTTPFetcherCookieStorageMethodNone) { - - NSArray *cookies = [cookieStorage_ cookiesForURL:[request URL]]; - if ([cookies count] > 0) { - - NSDictionary *headerFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; - NSString *cookieHeader = [headerFields objectForKey:@"Cookie"]; // key used in header dictionary - if (cookieHeader) { - [request addValue:cookieHeader forHTTPHeaderField:@"Cookie"]; // header name - } - } - } -} - -// Returns YES if this is in the process of fetching a URL, or waiting to -// retry, or waiting for authorization, or waiting to be issued by the -// service object -- (BOOL)isFetching { - if (connection_ != nil || retryTimer_ != nil) return YES; - - BOOL isAuthorizing = [authorizer_ isAuthorizingRequest:request_]; - if (isAuthorizing) return YES; - - BOOL isDelayed = [service_ isDelayingFetcher:self]; - return isDelayed; -} - -// Returns the status code set in connection:didReceiveResponse: -- (NSInteger)statusCode { - - NSInteger statusCode; - - if (response_ != nil - && [response_ respondsToSelector:@selector(statusCode)]) { - - statusCode = [(NSHTTPURLResponse *)response_ statusCode]; - } else { - // Default to zero, in hopes of hinting "Unknown" (we can't be - // sure that things are OK enough to use 200). - statusCode = 0; - } - return statusCode; -} - -- (NSDictionary *)responseHeaders { - if (response_ != nil - && [response_ respondsToSelector:@selector(allHeaderFields)]) { - - NSDictionary *headers = [(NSHTTPURLResponse *)response_ allHeaderFields]; - return headers; - } - return nil; -} - -- (void)releaseCallbacks { - [delegate_ autorelease]; - delegate_ = nil; - - [delegateQueue_ autorelease]; - delegateQueue_ = nil; - -#if NS_BLOCKS_AVAILABLE - self.completionBlock = nil; - self.sentDataBlock = nil; - self.receivedDataBlock = nil; - self.retryBlock = nil; -#endif -} - -// Cancel the fetch of the URL that's currently in progress. -- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks { - id service; - - // if the connection or the retry timer is all that's retaining the fetcher, - // we want to be sure this instance survives stopping at least long enough for - // the stack to unwind - [[self retain] autorelease]; - - [self destroyRetryTimer]; - - @synchronized(self) { - service = [[service_ retain] autorelease]; - - if (connection_) { - // in case cancelling the connection calls this recursively, we want - // to ensure that we'll only release the connection and delegate once, - // so first set connection_ to nil - NSURLConnection* oldConnection = connection_; - connection_ = nil; - - if (!hasConnectionEnded_) { - [oldConnection cancel]; - } - - // this may be called in a callback from the connection, so use autorelease - [oldConnection autorelease]; - } - } // @synchronized(self) - - // send the stopped notification - [self sendStopNotificationIfNeeded]; - - @synchronized(self) { - [authorizer_ stopAuthorizationForRequest:request_]; - - if (shouldReleaseCallbacks) { - [self releaseCallbacks]; - - self.authorizer = nil; - } - - if (temporaryDownloadPath_) { - [[NSFileManager defaultManager] removeItemAtPath:temporaryDownloadPath_ - error:NULL]; - self.temporaryDownloadPath = nil; - } - } // @synchronized(self) - - [service fetcherDidStop:self]; - -#if GTM_BACKGROUND_FETCHING - [self endBackgroundTask]; -#endif -} - -// External stop method -- (void)stopFetching { - [self stopFetchReleasingCallbacks:YES]; -} - -- (void)sendStopNotificationIfNeeded { - BOOL sendNow = NO; - @synchronized(self) { - if (isStopNotificationNeeded_) { - isStopNotificationNeeded_ = NO; - sendNow = YES; - } - } - - if (sendNow) { - NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter]; - [defaultNC postNotificationName:kGTMHTTPFetcherStoppedNotification - object:self]; - } -} - -- (void)retryFetch { - [self stopFetchReleasingCallbacks:NO]; - - [self beginFetchWithDelegate:delegate_ - didFinishSelector:finishedSel_]; -} - -- (void)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { - NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; - - // Loop until the callbacks have been called and released, and until - // the connection is no longer pending, or until the timeout has expired - BOOL isMainThread = [NSThread isMainThread]; - - while ((!hasConnectionEnded_ -#if NS_BLOCKS_AVAILABLE - || completionBlock_ != nil -#endif - || delegate_ != nil) - && [giveUpDate timeIntervalSinceNow] > 0) { - - // Run the current run loop 1/1000 of a second to give the networking - // code a chance to work - if (isMainThread || delegateQueue_ == nil) { - NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001]; - [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; - } else { - [NSThread sleepForTimeInterval:0.001]; - } - } -} - -#pragma mark NSURLConnection Delegate Methods - -// -// NSURLConnection Delegate Methods -// - -// This method just says "follow all redirects", which _should_ be the default behavior, -// According to file:///Developer/ADC%20Reference%20Library/documentation/Cocoa/Conceptual/URLLoadingSystem -// but the redirects were not being followed until I added this method. May be -// a bug in the NSURLConnection code, or the documentation. -// -// In OS X 10.4.8 and earlier, the redirect request doesn't -// get the original's headers and body. This causes POSTs to fail. -// So we construct a new request, a copy of the original, with overrides from the -// redirect. -// -// Docs say that if redirectResponse is nil, just return the redirectRequest. - -- (NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)redirectRequest - redirectResponse:(NSURLResponse *)redirectResponse { - @synchronized(self) { - if (redirectRequest && redirectResponse) { - // save cookies from the response - [self handleCookiesForResponse:redirectResponse]; - - NSMutableURLRequest *newRequest = [[request_ mutableCopy] autorelease]; - // copy the URL - NSURL *redirectURL = [redirectRequest URL]; - NSURL *url = [newRequest URL]; - - // disallow scheme changes (say, from https to http) - NSString *redirectScheme = [url scheme]; - NSString *newScheme = [redirectURL scheme]; - NSString *newResourceSpecifier = [redirectURL resourceSpecifier]; - - if ([redirectScheme caseInsensitiveCompare:@"http"] == NSOrderedSame - && newScheme != nil - && [newScheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { - - // allow the change from http to https - redirectScheme = newScheme; - } - - NSString *newUrlString = [NSString stringWithFormat:@"%@:%@", - redirectScheme, newResourceSpecifier]; - - NSURL *newURL = [NSURL URLWithString:newUrlString]; - [newRequest setURL:newURL]; - - // any headers in the redirect override headers in the original. - NSDictionary *redirectHeaders = [redirectRequest allHTTPHeaderFields]; - for (NSString *key in redirectHeaders) { - NSString *value = [redirectHeaders objectForKey:key]; - [newRequest setValue:value forHTTPHeaderField:key]; - } - - [self addCookiesToRequest:newRequest]; - - redirectRequest = newRequest; - - // log the response we just received - [self setResponse:redirectResponse]; - [self logNowWithError:nil]; - - // update the request for future logging - NSMutableURLRequest *mutable = [[redirectRequest mutableCopy] autorelease]; - [self setMutableRequest:mutable]; - } - return redirectRequest; - } // @synchronized(self) -} - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { - @synchronized(self) { - // This method is called when the server has determined that it - // has enough information to create the NSURLResponse - // it can be called multiple times, for example in the case of a - // redirect, so each time we reset the data. - [downloadedData_ setLength:0]; - [downloadFileHandle_ truncateFileAtOffset:0]; - downloadedLength_ = 0; - - [self setResponse:response]; - - // Save cookies from the response - [self handleCookiesForResponse:response]; - } -} - - -// handleCookiesForResponse: handles storage of cookies for responses passed to -// connection:willSendRequest:redirectResponse: and connection:didReceiveResponse: -- (void)handleCookiesForResponse:(NSURLResponse *)response { - - if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodSystemDefault - || cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodNone) { - - // do nothing special for NSURLConnection's default storage mechanism - // or when we're ignoring cookies - - } else if ([response respondsToSelector:@selector(allHeaderFields)]) { - - // grab the cookies from the header as NSHTTPCookies and store them either - // into our static array or into the fetchHistory - - NSDictionary *responseHeaderFields = [(NSHTTPURLResponse *)response allHeaderFields]; - if (responseHeaderFields) { - - NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseHeaderFields - forURL:[response URL]]; - if ([cookies count] > 0) { - [cookieStorage_ setCookies:cookies]; - } - } - } -} - --(void)connection:(NSURLConnection *)connection -didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { - @synchronized(self) { - if ([challenge previousFailureCount] <= 2) { - - NSURLCredential *credential = credential_; - - if ([[challenge protectionSpace] isProxy] && proxyCredential_ != nil) { - credential = proxyCredential_; - } - - // Here, if credential is still nil, then we *could* try to get it from - // NSURLCredentialStorage's defaultCredentialForProtectionSpace:. - // We don't, because we're assuming: - // - // - for server credentials, we only want ones supplied by the program - // calling http fetcher - // - for proxy credentials, if one were necessary and available in the - // keychain, it would've been found automatically by NSURLConnection - // and this challenge delegate method never would've been called - // anyway - - if (credential) { - // try the credential - [[challenge sender] useCredential:credential - forAuthenticationChallenge:challenge]; - return; - } - } // @synchronized(self) - - // If we don't have credentials, or we've already failed auth 3x, - // report the error, putting the challenge as a value in the userInfo - // dictionary. -#if DEBUG - NSAssert(!isCancellingChallenge_, @"isCancellingChallenge_ unexpected"); -#endif - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:challenge - forKey:kGTMHTTPFetcherErrorChallengeKey]; - NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain - code:kGTMHTTPFetcherErrorAuthenticationChallengeFailed - userInfo:userInfo]; - - // cancelAuthenticationChallenge seems to indirectly call - // connection:didFailWithError: now, though that isn't documented - // - // We'll use an ivar to make the indirect invocation of the - // delegate method do nothing. - isCancellingChallenge_ = YES; - [[challenge sender] cancelAuthenticationChallenge:challenge]; - isCancellingChallenge_ = NO; - - [self connection:connection didFailWithError:error]; - } -} - -- (void)invokeFetchCallbacksWithData:(NSData *)data - error:(NSError *)error { - // To avoid deadlocks, this should not be called inside of @synchronized(self) - id target; - SEL sel; -#if NS_BLOCKS_AVAILABLE - void (^block)(NSData *, NSError *); -#else - id block = nil; -#endif - - // If -stopFetching is called in another thread directly after this @synchronized stanza finishes - // on this thread, then target and block could be released before being used in this method. So - // retain each until this method is done with them. - @synchronized(self) { - target = [[delegate_ retain] autorelease]; - sel = finishedSel_; -#if NS_BLOCKS_AVAILABLE - block = [[completionBlock_ retain] autorelease]; -#endif - } - [self invokeFetchCallbacksWithTarget:target - selector:sel - block:block - data:data - error:error]; -} - -- (void)invokeFetchCallbacksWithTarget:(id)target - selector:(SEL)sel - block:(id)block - data:(NSData *)data - error:(NSError *)error { - [[self retain] autorelease]; // In case the callback releases us - - [self invokeFetchCallback:sel - target:target - data:data - error:error]; - -#if NS_BLOCKS_AVAILABLE - if (block) { - ((void (^)(NSData *, NSError *))block)(data, error); - } -#endif -} - -- (void)invokeFetchCallback:(SEL)sel - target:(id)target - data:(NSData *)data - error:(NSError *)error { - // This method is available to subclasses which may provide a customized - // target pointer. - if (target && sel) { - NSMethodSignature *sig = [target methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:target]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&data atIndex:3]; - [invocation setArgument:&error atIndex:4]; - [invocation invoke]; - } -} - -- (void)invokeFetchCallbacksOnDelegateQueueWithData:(NSData *)data - error:(NSError *)error { - // This is called by methods that are not already on the delegateQueue - // (as NSURLConnection callbacks should already be, but other failures - // are not.) - if (!delegateQueue_) { - [self invokeFetchCallbacksWithData:data error:error]; - } - - // Values may be nil. - NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2]; - [dict setValue:data forKey:kCallbackData]; - [dict setValue:error forKey:kCallbackError]; - - // If -stopFetching is called in another thread directly after this @synchronized stanza finishes - // on this thread, then target and block could be released before being used in this method. So - // retain each until this method is done with them. - @synchronized(self) { - id target = delegate_; - NSString *sel = finishedSel_ ? NSStringFromSelector(finishedSel_) : nil; -#if NS_BLOCKS_AVAILABLE - void (^block)(NSData *, NSError *) = completionBlock_; -#else - id block = nil; -#endif - [dict setValue:target forKey:kCallbackTarget]; - [dict setValue:sel forKey:kCallbackSelector]; - [dict setValue:block forKey:kCallbackBlock]; - } - - NSInvocationOperation *op = - [[[NSInvocationOperation alloc] initWithTarget:self - selector:@selector(invokeOnQueueWithDictionary:) - object:dict] autorelease]; - [delegateQueue_ addOperation:op]; -} - -- (void)invokeOnQueueWithDictionary:(NSDictionary *)dict { - id target = [dict objectForKey:kCallbackTarget]; - NSString *selStr = [dict objectForKey:kCallbackSelector]; - SEL sel = selStr ? NSSelectorFromString(selStr) : NULL; - id block = [dict objectForKey:kCallbackBlock]; - - NSData *data = [dict objectForKey:kCallbackData]; - NSError *error = [dict objectForKey:kCallbackError]; - - [self invokeFetchCallbacksWithTarget:target - selector:sel - block:block - data:data - error:error]; -} - -- (void)invokeSentDataCallback:(SEL)sel - target:(id)target - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten - totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { - if (target && sel) { - NSMethodSignature *sig = [target methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:target]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&bytesWritten atIndex:3]; - [invocation setArgument:&totalBytesWritten atIndex:4]; - [invocation setArgument:&totalBytesExpectedToWrite atIndex:5]; - [invocation invoke]; - } -} - -- (BOOL)invokeRetryCallback:(SEL)sel - target:(id)target - willRetry:(BOOL)willRetry - error:(NSError *)error { - if (target && sel) { - NSMethodSignature *sig = [target methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:target]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&willRetry atIndex:3]; - [invocation setArgument:&error atIndex:4]; - [invocation invoke]; - - [invocation getReturnValue:&willRetry]; - } - return willRetry; -} - -- (void)connection:(NSURLConnection *)connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { - @synchronized(self) { - SEL sel = [self sentDataSelector]; - [self invokeSentDataCallback:sel - target:delegate_ - didSendBodyData:bytesWritten - totalBytesWritten:totalBytesWritten - totalBytesExpectedToWrite:totalBytesExpectedToWrite]; - -#if NS_BLOCKS_AVAILABLE - if (sentDataBlock_) { - sentDataBlock_(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - } -#endif - } -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { - @synchronized(self) { -#if DEBUG - NSAssert(!hasConnectionEnded_, @"Connection received data after ending"); - - // The download file handle should be set or the data object allocated - // before the fetch is started. - NSAssert((downloadFileHandle_ == nil) != (downloadedData_ == nil), - @"received data accumulates as either NSData (%d) or" - @" NSFileHandle (%d)", - (downloadedData_ != nil), (downloadFileHandle_ != nil)); -#endif - // Hopefully, we'll never see this execute out-of-order, receiving data - // after we've received the finished or failed callback. - if (hasConnectionEnded_) return; - - if (downloadFileHandle_ != nil) { - // Append to file - @try { - [downloadFileHandle_ writeData:data]; - - downloadedLength_ = [downloadFileHandle_ offsetInFile]; - } - @catch (NSException *exc) { - // Couldn't write to file, probably due to a full disk - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[exc reason] - forKey:NSLocalizedDescriptionKey]; - NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:kGTMHTTPFetcherErrorFileHandleException - userInfo:userInfo]; - [self connection:connection didFailWithError:error]; - return; - } - } else { - // append to mutable data - [downloadedData_ appendData:data]; - - downloadedLength_ = [downloadedData_ length]; - } - - if (receivedDataSel_) { - [delegate_ performSelector:receivedDataSel_ - withObject:self - withObject:downloadedData_]; - } - -#if NS_BLOCKS_AVAILABLE - if (receivedDataBlock_) { - receivedDataBlock_(downloadedData_); - } -#endif - } // @synchronized(self) -} - -// For error 304's ("Not Modified") where we've cached the data, return -// status 200 ("OK") to the caller (but leave the fetcher status as 304) -// and copy the cached data. -// -// For other errors or if there's no cached data, just return the actual status. -- (NSData *)cachedDataForStatus { - if ([self statusCode] == kGTMHTTPFetcherStatusNotModified - && [fetchHistory_ shouldCacheETaggedData]) { - NSData *cachedData = [fetchHistory_ cachedDataForRequest:request_]; - return cachedData; - } - return nil; -} - -- (NSInteger)statusAfterHandlingNotModifiedError { - NSInteger status = [self statusCode]; - NSData *cachedData = [self cachedDataForStatus]; - if (cachedData) { - // Forge the status to pass on to the delegate - status = 200; - - // Copy our stored data - if (downloadFileHandle_ != nil) { - @try { - // Downloading to a file handle won't save to the cache (the data is - // likely inappropriately large for caching), but will still read from - // the cache, on the unlikely chance that the response was Not Modified - // and the URL response was indeed present in the cache. - [downloadFileHandle_ truncateFileAtOffset:0]; - [downloadFileHandle_ writeData:cachedData]; - downloadedLength_ = [downloadFileHandle_ offsetInFile]; - } - @catch (NSException *) { - // Failed to write data, likely due to lack of disk space - status = kGTMHTTPFetcherErrorFileHandleException; - } - } else { - [downloadedData_ setData:cachedData]; - downloadedLength_ = [cachedData length]; - } - } - return status; -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection { - BOOL shouldStopFetching = YES; - BOOL shouldSendStopNotification = NO; - NSError *error = nil; - NSData *downloadedData; -#if !STRIP_GTM_FETCH_LOGGING - BOOL shouldDeferLogging = NO; -#endif - BOOL shouldBeginRetryTimer = NO; - - @synchronized(self) { - // We no longer need to cancel the connection - hasConnectionEnded_ = YES; - - // Skip caching ETagged results when the data is being saved to a file - if (downloadFileHandle_ == nil) { - [fetchHistory_ updateFetchHistoryWithRequest:request_ - response:response_ - downloadedData:downloadedData_]; - } else { - [fetchHistory_ removeCachedDataForRequest:request_]; - } - - [[self retain] autorelease]; // in case the callback releases us - - NSInteger status = [self statusCode]; - if ([self cachedDataForStatus] != nil) { -#if !STRIP_GTM_FETCH_LOGGING - // Log the pre-cache response. - [self logNowWithError:nil]; - hasLoggedError_ = YES; -#endif - status = [self statusAfterHandlingNotModifiedError]; - } - - shouldSendStopNotification = YES; - - if (status >= 0 && status < 300) { - // success - if (downloadPath_) { - // Avoid deleting the downloaded file when the fetch stops - [downloadFileHandle_ closeFile]; - self.downloadFileHandle = nil; - - NSFileManager *fileMgr = [NSFileManager defaultManager]; - [fileMgr removeItemAtPath:downloadPath_ - error:NULL]; - - if ([fileMgr moveItemAtPath:temporaryDownloadPath_ - toPath:downloadPath_ - error:&error]) { - self.temporaryDownloadPath = nil; - } - } - } else { - // unsuccessful -#if !STRIP_GTM_FETCH_LOGGING - if (!hasLoggedError_) { - [self logNowWithError:nil]; - hasLoggedError_ = YES; - } -#endif - // Status over 300; retry or notify the delegate of failure - if ([self shouldRetryNowForStatus:status error:nil]) { - // retrying - shouldBeginRetryTimer = YES; - shouldStopFetching = NO; - } else { - NSDictionary *userInfo = nil; - if ([downloadedData_ length] > 0) { - userInfo = [NSDictionary dictionaryWithObject:downloadedData_ - forKey:kGTMHTTPFetcherStatusDataKey]; - } - error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:status - userInfo:userInfo]; - } - } - downloadedData = downloadedData_; -#if !STRIP_GTM_FETCH_LOGGING - shouldDeferLogging = shouldDeferResponseBodyLogging_; -#endif - } // @synchronized(self) - - if (shouldBeginRetryTimer) { - [self beginRetryTimer]; - } - - if (shouldSendStopNotification) { - // We want to send the stop notification before calling the delegate's - // callback selector, since the callback selector may release all of - // the fetcher properties that the client is using to track the fetches. - // - // We'll also stop now so that, to any observers watching the notifications, - // it doesn't look like our wait for a retry (which may be long, - // 30 seconds or more) is part of the network activity. - [self sendStopNotificationIfNeeded]; - } - - if (shouldStopFetching) { - // Call the callbacks (outside of the @synchronized to avoid deadlocks.) - [self invokeFetchCallbacksWithData:downloadedData - error:error]; - BOOL shouldRelease = [self shouldReleaseCallbacksUponCompletion]; - [self stopFetchReleasingCallbacks:shouldRelease]; - } - -#if !STRIP_GTM_FETCH_LOGGING - @synchronized(self) { - if (!shouldDeferLogging && !hasLoggedError_) { - [self logNowWithError:nil]; - } - } -#endif -} - -- (BOOL)shouldReleaseCallbacksUponCompletion { - // A subclass can override this to keep callbacks around after the - // connection has finished successfully - return YES; -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - @synchronized(self) { - // Prevent the failure callback from being called twice, since the stopFetch - // call below (either the explicit one at the end of this method, or the - // implicit one when the retry occurs) will release the delegate. - if (connection_ == nil) return; - - // If this method was invoked indirectly by cancellation of an authentication - // challenge, defer this until it is called again with the proper error object - if (isCancellingChallenge_) return; - - // We no longer need to cancel the connection - hasConnectionEnded_ = YES; - - [self logNowWithError:error]; - } - - // See comment about sendStopNotificationIfNeeded - // in connectionDidFinishLoading: - [self sendStopNotificationIfNeeded]; - - if ([self shouldRetryNowForStatus:0 error:error]) { - [self beginRetryTimer]; - } else { - [[self retain] autorelease]; // in case the callback releases us - - [self invokeFetchCallbacksWithData:nil - error:error]; - - [self stopFetchReleasingCallbacks:YES]; - } -} - -- (void)logNowWithError:(NSError *)error { - // If the logging category is available, then log the current request, - // response, data, and error - if ([self respondsToSelector:@selector(logFetchWithError:)]) { - [self performSelector:@selector(logFetchWithError:) withObject:error]; - } -} - -#pragma mark Retries - -- (BOOL)isRetryError:(NSError *)error { - - struct retryRecord { - NSString *const domain; - int code; - }; - - struct retryRecord retries[] = { - { kGTMHTTPFetcherStatusDomain, 408 }, // request timeout - { kGTMHTTPFetcherStatusDomain, 503 }, // service unavailable - { kGTMHTTPFetcherStatusDomain, 504 }, // request timeout - { NSURLErrorDomain, NSURLErrorTimedOut }, - { NSURLErrorDomain, NSURLErrorNetworkConnectionLost }, - { nil, 0 } - }; - - // NSError's isEqual always returns false for equal but distinct instances - // of NSError, so we have to compare the domain and code values explicitly - - for (int idx = 0; retries[idx].domain != nil; idx++) { - - if ([[error domain] isEqual:retries[idx].domain] - && [error code] == retries[idx].code) { - - return YES; - } - } - return NO; -} - - -// shouldRetryNowForStatus:error: returns YES if the user has enabled retries -// and the status or error is one that is suitable for retrying. "Suitable" -// means either the isRetryError:'s list contains the status or error, or the -// user's retrySelector: is present and returns YES when called, or the -// authorizer may be able to fix. -- (BOOL)shouldRetryNowForStatus:(NSInteger)status - error:(NSError *)error { - // Determine if a refreshed authorizer may avoid an authorization error - BOOL shouldRetryForAuthRefresh = NO; - BOOL isFirstAuthError = (authorizer_ != nil) - && !hasAttemptedAuthRefresh_ - && (status == kGTMHTTPFetcherStatusUnauthorized); // 401 - - if (isFirstAuthError) { - if ([authorizer_ respondsToSelector:@selector(primeForRefresh)]) { - BOOL hasPrimed = [authorizer_ primeForRefresh]; - if (hasPrimed) { - shouldRetryForAuthRefresh = YES; - hasAttemptedAuthRefresh_ = YES; - [request_ setValue:nil forHTTPHeaderField:@"Authorization"]; - } - } - } - - // Determine if we're doing exponential backoff retries - BOOL shouldDoIntervalRetry = [self isRetryEnabled] - && ([self nextRetryInterval] < [self maxRetryInterval]); - - if (shouldDoIntervalRetry) { - // If an explicit max retry interval was set, we expect repeated backoffs to take - // up to roughly twice that for repeated fast failures. If the initial attempt is - // already more than 3 times the max retry interval, then failures have taken a long time - // (such as from network timeouts) so don't retry again to avoid the app becoming - // unexpectedly unresponsive. - if (maxRetryInterval_ > kUnsetMaxRetryInterval) { - NSTimeInterval maxAllowedIntervalBeforeRetry = maxRetryInterval_ * 3; - NSTimeInterval timeSinceInitialRequest = -[initialRequestDate_ timeIntervalSinceNow]; - if (timeSinceInitialRequest > maxAllowedIntervalBeforeRetry) { - shouldDoIntervalRetry = NO; - } - } - } - - BOOL willRetry = NO; - BOOL canRetry = shouldRetryForAuthRefresh || shouldDoIntervalRetry; - if (canRetry) { - // Check if this is a retryable error - if (error == nil) { - // Make an error for the status - NSDictionary *userInfo = nil; - if ([downloadedData_ length] > 0) { - userInfo = [NSDictionary dictionaryWithObject:downloadedData_ - forKey:kGTMHTTPFetcherStatusDataKey]; - } - error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:status - userInfo:userInfo]; - } - - willRetry = shouldRetryForAuthRefresh || [self isRetryError:error]; - - // If the user has installed a retry callback, consult that - willRetry = [self invokeRetryCallback:retrySel_ - target:delegate_ - willRetry:willRetry - error:error]; -#if NS_BLOCKS_AVAILABLE - if (retryBlock_) { - willRetry = retryBlock_(willRetry, error); - } -#endif - } - return willRetry; -} - -- (void)beginRetryTimer { - @synchronized(self) { - if (delegateQueue_ != nil && ![NSThread isMainThread]) { - // A delegate queue is set, so the thread we're running on may not - // have a run loop. We'll defer creating and starting the timer - // until we're on the main thread to ensure it has a run loop. - // (If we weren't supporting 10.5, we could use dispatch_after instead - // of an NSTimer.) - [self performSelectorOnMainThread:_cmd - withObject:nil - waitUntilDone:NO]; - return; - } - } - - NSTimeInterval nextInterval = [self nextRetryInterval]; - NSTimeInterval maxInterval = [self maxRetryInterval]; - NSTimeInterval newInterval = MIN(nextInterval, maxInterval); - - [self primeRetryTimerWithNewTimeInterval:newInterval]; - - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:kGTMHTTPFetcherRetryDelayStartedNotification - object:self]; -} - -- (void)primeRetryTimerWithNewTimeInterval:(NSTimeInterval)secs { - - [self destroyRetryTimer]; - - @synchronized(self) { - lastRetryInterval_ = secs; - - retryTimer_ = [NSTimer timerWithTimeInterval:secs - target:self - selector:@selector(retryTimerFired:) - userInfo:nil - repeats:NO]; - [retryTimer_ retain]; - - NSRunLoop *timerRL = (self.delegateQueue ? - [NSRunLoop mainRunLoop] : [NSRunLoop currentRunLoop]); - [timerRL addTimer:retryTimer_ - forMode:NSDefaultRunLoopMode]; - } -} - -- (void)retryTimerFired:(NSTimer *)timer { - [self destroyRetryTimer]; - - @synchronized(self) { - retryCount_++; - - [self retryFetch]; - } -} - -- (void)destroyRetryTimer { - BOOL shouldNotify = NO; - @synchronized(self) { - if (retryTimer_) { - [retryTimer_ invalidate]; - [retryTimer_ autorelease]; - retryTimer_ = nil; - shouldNotify = YES; - } - } // @synchronized(self) - - if (shouldNotify) { - NSNotificationCenter *defaultNC = [NSNotificationCenter defaultCenter]; - [defaultNC postNotificationName:kGTMHTTPFetcherRetryDelayStoppedNotification - object:self]; - } -} - -- (NSUInteger)retryCount { - return retryCount_; -} - -- (NSTimeInterval)nextRetryInterval { - // The next wait interval is the factor (2.0) times the last interval, - // but never less than the minimum interval. - NSTimeInterval secs = lastRetryInterval_ * retryFactor_; - secs = MIN(secs, maxRetryInterval_); - secs = MAX(secs, minRetryInterval_); - - return secs; -} - -- (BOOL)isRetryEnabled { - return isRetryEnabled_; -} - -- (void)setRetryEnabled:(BOOL)flag { - - if (flag && !isRetryEnabled_) { - // We defer initializing these until the user calls setRetryEnabled - // to avoid using the random number generator if it's not needed. - // However, this means min and max intervals for this fetcher are reset - // as a side effect of calling setRetryEnabled. - // - // Make an initial retry interval random between 1.0 and 2.0 seconds - [self setMinRetryInterval:0.0]; - [self setMaxRetryInterval:kUnsetMaxRetryInterval]; - [self setRetryFactor:2.0]; - lastRetryInterval_ = 0.0; - } - isRetryEnabled_ = flag; -}; - -- (NSTimeInterval)maxRetryInterval { - return maxRetryInterval_; -} - -- (void)setMaxRetryInterval:(NSTimeInterval)secs { - if (secs > 0) { - maxRetryInterval_ = secs; - } else { - maxRetryInterval_ = kUnsetMaxRetryInterval; - } -} - -- (double)minRetryInterval { - return minRetryInterval_; -} - -- (void)setMinRetryInterval:(NSTimeInterval)secs { - if (secs > 0) { - minRetryInterval_ = secs; - } else { - // Set min interval to a random value between 1.0 and 2.0 seconds - // so that if multiple clients start retrying at the same time, they'll - // repeat at different times and avoid overloading the server - minRetryInterval_ = 1.0 + ((double)(arc4random() & 0x0FFFF) / (double) 0x0FFFF); - } -} - -#pragma mark Getters and Setters - -@dynamic cookieStorageMethod, - retryEnabled, - maxRetryInterval, - minRetryInterval, - retryCount, - nextRetryInterval, - statusCode, - responseHeaders, - fetchHistory, - userData, - properties; - -@synthesize mutableRequest = request_, - allowedInsecureSchemes = allowedInsecureSchemes_, - allowLocalhostRequest = allowLocalhostRequest_, - credential = credential_, - proxyCredential = proxyCredential_, - postData = postData_, - postStream = postStream_, - delegate = delegate_, - authorizer = authorizer_, - service = service_, - serviceHost = serviceHost_, - servicePriority = servicePriority_, - thread = thread_, - sentDataSelector = sentDataSel_, - receivedDataSelector = receivedDataSel_, - retrySelector = retrySel_, - retryFactor = retryFactor_, - response = response_, - downloadedLength = downloadedLength_, - downloadedData = downloadedData_, - downloadPath = downloadPath_, - temporaryDownloadPath = temporaryDownloadPath_, - downloadFileHandle = downloadFileHandle_, - delegateQueue = delegateQueue_, - runLoopModes = runLoopModes_, - comment = comment_, - log = log_, - cookieStorage = cookieStorage_; - -#if NS_BLOCKS_AVAILABLE -@synthesize completionBlock = completionBlock_, - sentDataBlock = sentDataBlock_, - receivedDataBlock = receivedDataBlock_, - retryBlock = retryBlock_; -#endif - -@synthesize shouldFetchInBackground = shouldFetchInBackground_; - -- (NSInteger)cookieStorageMethod { - return cookieStorageMethod_; -} - -- (void)setCookieStorageMethod:(NSInteger)method { - - cookieStorageMethod_ = method; - - if (method == kGTMHTTPFetcherCookieStorageMethodSystemDefault) { - // System default - [request_ setHTTPShouldHandleCookies:YES]; - - // No need for a cookie storage object - self.cookieStorage = nil; - - } else { - // Not system default - [request_ setHTTPShouldHandleCookies:NO]; - - if (method == kGTMHTTPFetcherCookieStorageMethodStatic) { - // Store cookies in the static array - NSAssert(gGTMFetcherStaticCookieStorage != nil, - @"cookie storage requires GTMHTTPFetchHistory"); - - self.cookieStorage = gGTMFetcherStaticCookieStorage; - } else if (method == kGTMHTTPFetcherCookieStorageMethodFetchHistory) { - // store cookies in the fetch history - self.cookieStorage = [fetchHistory_ cookieStorage]; - } else { - // kGTMHTTPFetcherCookieStorageMethodNone - ignore cookies - self.cookieStorage = nil; - } - } -} - -+ (id )staticCookieStorage { - return gGTMFetcherStaticCookieStorage; -} - -+ (BOOL)doesSupportSentDataCallback { -#if GTM_IPHONE - // NSURLConnection's didSendBodyData: delegate support appears to be - // available starting in iPhone OS 3.0 - return (NSFoundationVersionNumber >= 678.47); -#else - // Per WebKit's MaxFoundationVersionWithoutdidSendBodyDataDelegate - // - // Indicates if NSURLConnection will invoke the didSendBodyData: delegate - // method - return (NSFoundationVersionNumber > 677.21); -#endif -} - -- (id )fetchHistory { - return fetchHistory_; -} - -- (void)setFetchHistory:(id )fetchHistory { - [fetchHistory_ autorelease]; - fetchHistory_ = [fetchHistory retain]; - - if (fetchHistory_ != nil) { - // set the fetch history's cookie array to be the cookie store - [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodFetchHistory]; - - } else { - // The fetch history was removed - if (cookieStorageMethod_ == kGTMHTTPFetcherCookieStorageMethodFetchHistory) { - // Fall back to static storage - [self setCookieStorageMethod:kGTMHTTPFetcherCookieStorageMethodStatic]; - } - } -} - -- (id)userData { - @synchronized(self) { - return [[userData_ retain] autorelease]; - } -} - -- (void)setUserData:(id)theObj { - @synchronized(self) { - [userData_ autorelease]; - userData_ = [theObj retain]; - } -} - -- (void)setProperties:(NSMutableDictionary *)dict { - @synchronized(self) { - [properties_ autorelease]; - - // This copies rather than retains the parameter for compatiblity with - // an earlier version that took an immutable parameter and copied it. - properties_ = [dict mutableCopy]; - } -} - -- (NSMutableDictionary *)properties { - @synchronized(self) { - return [[properties_ retain] autorelease]; - } -} - -- (void)setProperty:(id)obj forKey:(NSString *)key { - @synchronized(self) { - if (properties_ == nil && obj != nil) { - [self setProperties:[NSMutableDictionary dictionary]]; - } - [properties_ setValue:obj forKey:key]; - } -} - -- (id)propertyForKey:(NSString *)key { - @synchronized(self) { - return [[[properties_ objectForKey:key] retain] autorelease]; - } -} - -- (void)addPropertiesFromDictionary:(NSDictionary *)dict { - @synchronized(self) { - if (properties_ == nil && dict != nil) { - [self setProperties:[[dict mutableCopy] autorelease]]; - } else { - [properties_ addEntriesFromDictionary:dict]; - } - } -} - -- (NSData *)bodyData { - return self.postData; -} - -- (void)setBodyData:(NSData *)postData { - self.postData = postData; -} - -- (void)setCommentWithFormat:(id)format, ... { -#if !STRIP_GTM_FETCH_LOGGING - NSString *result = format; - if (format) { - va_list argList; - va_start(argList, format); - - result = [[[NSString alloc] initWithFormat:format - arguments:argList] autorelease]; - va_end(argList); - } - [self setComment:result]; -#endif -} - -+ (Class)connectionClass { - if (gGTMFetcherConnectionClass == nil) { - gGTMFetcherConnectionClass = [NSURLConnection class]; - } - return gGTMFetcherConnectionClass; -} - -+ (void)setConnectionClass:(Class)theClass { - gGTMFetcherConnectionClass = theClass; -} - -#if STRIP_GTM_FETCH_LOGGING -+ (void)setLoggingEnabled:(BOOL)flag { -} -#endif // STRIP_GTM_FETCH_LOGGING - -@end - -void GTMAssertSelectorNilOrImplementedWithArgs(id obj, SEL sel, ...) { - - // Verify that the object's selector is implemented with the proper - // number and type of arguments -#if DEBUG - va_list argList; - va_start(argList, sel); - - if (obj && sel) { - // Check that the selector is implemented - if (![obj respondsToSelector:sel]) { - NSLog(@"\"%@\" selector \"%@\" is unimplemented or misnamed", - NSStringFromClass([obj class]), - NSStringFromSelector(sel)); - NSCAssert(0, @"callback selector unimplemented or misnamed"); - } else { - const char *expectedArgType; - unsigned int argCount = 2; // skip self and _cmd - NSMethodSignature *sig = [obj methodSignatureForSelector:sel]; - - // Check that each expected argument is present and of the correct type - while ((expectedArgType = va_arg(argList, const char*)) != 0) { - - if ([sig numberOfArguments] > argCount) { - const char *foundArgType = [sig getArgumentTypeAtIndex:argCount]; - - if(0 != strncmp(foundArgType, expectedArgType, strlen(expectedArgType))) { - NSLog(@"\"%@\" selector \"%@\" argument %d should be type %s", - NSStringFromClass([obj class]), - NSStringFromSelector(sel), (argCount - 2), expectedArgType); - NSCAssert(0, @"callback selector argument type mistake"); - } - } - argCount++; - } - - // Check that the proper number of arguments are present in the selector - if (argCount != [sig numberOfArguments]) { - NSLog( @"\"%@\" selector \"%@\" should have %d arguments", - NSStringFromClass([obj class]), - NSStringFromSelector(sel), (argCount - 2)); - NSCAssert(0, @"callback selector arguments incorrect"); - } - } - } - - va_end(argList); -#endif -} - -NSString *GTMCleanedUserAgentString(NSString *str) { - // Reference http://www.w3.org/Protocols/rfc2616/rfc2616-sec2.html - // and http://www-archive.mozilla.org/build/user-agent-strings.html - - if (str == nil) return nil; - - NSMutableString *result = [NSMutableString stringWithString:str]; - - // Replace spaces and commas with underscores - [result replaceOccurrencesOfString:@" " - withString:@"_" - options:0 - range:NSMakeRange(0, [result length])]; - [result replaceOccurrencesOfString:@"," - withString:@"_" - options:0 - range:NSMakeRange(0, [result length])]; - - // Delete http token separators and remaining whitespace - static NSCharacterSet *charsToDelete = nil; - if (charsToDelete == nil) { - // Make a set of unwanted characters - NSString *const kSeparators = @"()<>@;:\\\"/[]?={}"; - - NSMutableCharacterSet *mutableChars; - mutableChars = [[[NSCharacterSet whitespaceAndNewlineCharacterSet] mutableCopy] autorelease]; - [mutableChars addCharactersInString:kSeparators]; - charsToDelete = [mutableChars copy]; // hang on to an immutable copy - } - - while (1) { - NSRange separatorRange = [result rangeOfCharacterFromSet:charsToDelete]; - if (separatorRange.location == NSNotFound) break; - - [result deleteCharactersInRange:separatorRange]; - }; - - return result; -} - -NSString *GTMSystemVersionString(void) { - NSString *systemString = @""; - -#if TARGET_OS_MAC && !TARGET_OS_IPHONE - // Mac build - static NSString *savedSystemString = nil; - if (savedSystemString == nil) { - // With Gestalt inexplicably deprecated in 10.8, we're reduced to reading - // the system plist file. - NSString *const kPath = @"/System/Library/CoreServices/SystemVersion.plist"; - NSDictionary *plist = [NSDictionary dictionaryWithContentsOfFile:kPath]; - NSString *versString = [plist objectForKey:@"ProductVersion"]; - if ([versString length] == 0) { - versString = @"10.?.?"; - } - savedSystemString = [[NSString alloc] initWithFormat:@"MacOSX/%@", versString]; - } - systemString = savedSystemString; -#elif TARGET_OS_IPHONE - // Compiling against the iPhone SDK - - static NSString *savedSystemString = nil; - if (savedSystemString == nil) { - // Avoid the slowness of calling currentDevice repeatedly on the iPhone - UIDevice* currentDevice = [UIDevice currentDevice]; - - NSString *model = [currentDevice model]; - NSString *cleanedModel = GTMCleanedUserAgentString(model); - NSString *systemVersion = [currentDevice systemVersion]; - -#if TARGET_IPHONE_SIMULATOR - NSString *hardwareModel = @"sim"; -#else - NSString *hardwareModel; - struct utsname unameRecord; - if (uname(&unameRecord) == 0) { - NSString *machineName = [NSString stringWithCString:unameRecord.machine - encoding:NSUTF8StringEncoding]; - hardwareModel = GTMCleanedUserAgentString(machineName); - } else { - hardwareModel = @"unk"; - } -#endif - savedSystemString = [[NSString alloc] initWithFormat:@"%@/%@ hw/%@", - cleanedModel, systemVersion, hardwareModel]; - // Example: iPod_Touch/2.2 hw/iPod1_1 - } - systemString = savedSystemString; - -#elif (GTL_IPHONE || GDATA_IPHONE) - // Compiling iOS libraries against the Mac SDK - systemString = @"iPhone/x.x"; - -#elif defined(_SYS_UTSNAME_H) - // Foundation-only build - struct utsname unameRecord; - uname(&unameRecord); - - systemString = [NSString stringWithFormat:@"%s/%s", - unameRecord.sysname, unameRecord.release]; // "Darwin/8.11.1" -#endif - - return systemString; -} - -// Return a generic name and version for the current application; this avoids -// anonymous server transactions. -NSString *GTMApplicationIdentifier(NSBundle *bundle) { - @synchronized([GTMHTTPFetcher class]) { - static NSMutableDictionary *sAppIDMap = nil; - - // If there's a bundle ID, use that; otherwise, use the process name - if (bundle == nil) { - bundle = [NSBundle mainBundle]; - } - NSString *bundleID = [bundle bundleIdentifier]; - if (bundleID == nil) { - bundleID = @""; - } - - NSString *identifier = [sAppIDMap objectForKey:bundleID]; - if (identifier) return identifier; - - // Apps may add a string to the info.plist to uniquely identify different builds. - identifier = [bundle objectForInfoDictionaryKey:@"GTMUserAgentID"]; - if ([identifier length] == 0) { - if ([bundleID length] > 0) { - identifier = bundleID; - } else { - // Fall back on the procname, prefixed by "proc" to flag that it's - // autogenerated and perhaps unreliable - NSString *procName = [[NSProcessInfo processInfo] processName]; - identifier = [NSString stringWithFormat:@"proc_%@", procName]; - } - } - - // Clean up whitespace and special characters - identifier = GTMCleanedUserAgentString(identifier); - - // If there's a version number, append that - NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - if ([version length] == 0) { - version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; - } - - // Clean up whitespace and special characters - version = GTMCleanedUserAgentString(version); - - // Glue the two together (cleanup done above or else cleanup would strip the - // slash) - if ([version length] > 0) { - identifier = [identifier stringByAppendingFormat:@"/%@", version]; - } - - if (sAppIDMap == nil) { - sAppIDMap = [[NSMutableDictionary alloc] init]; - } - [sAppIDMap setObject:identifier forKey:bundleID]; - return identifier; - } -} diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.xcodeproj/project.pbxproj b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.xcodeproj/project.pbxproj deleted file mode 100644 index e78c9d4ae..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcher.xcodeproj/project.pbxproj +++ /dev/null @@ -1,461 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 4F2FCAC41267882800A74543 /* GTMHTTPFetcherUtilityTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F2FCAC31267882800A74543 /* GTMHTTPFetcherUtilityTest.m */; }; - 4F3471FB11DD58D700CB050E /* GTMGatherInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F211DD58D700CB050E /* GTMGatherInputStream.m */; }; - 4F3471FC11DD58D700CB050E /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F411DD58D700CB050E /* GTMHTTPFetcher.m */; }; - 4F3471FD11DD58D700CB050E /* GTMHTTPFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F611DD58D700CB050E /* GTMHTTPFetcherLogging.m */; }; - 4F3471FE11DD58D700CB050E /* GTMHTTPUploadFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F811DD58D700CB050E /* GTMHTTPUploadFetcher.m */; }; - 4F3471FF11DD58D700CB050E /* GTMMIMEDocument.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471FA11DD58D700CB050E /* GTMMIMEDocument.m */; }; - 4F74D93811E68BFB00F2D927 /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F411DD58D700CB050E /* GTMHTTPFetcher.m */; }; - 4F74D93A11E68BFB00F2D927 /* GTMHTTPFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F611DD58D700CB050E /* GTMHTTPFetcherLogging.m */; }; - 4F74D93C11E68BFB00F2D927 /* GTMHTTPUploadFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F811DD58D700CB050E /* GTMHTTPUploadFetcher.m */; }; - 4F74D93E11E68BFB00F2D927 /* GTMGatherInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471F211DD58D700CB050E /* GTMGatherInputStream.m */; }; - 4F74D94011E68BFB00F2D927 /* GTMMIMEDocument.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F3471FA11DD58D700CB050E /* GTMMIMEDocument.m */; }; - 4F74D94A11E68C1500F2D927 /* GTMMIMEDocumentTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F74D94911E68C1500F2D927 /* GTMMIMEDocumentTest.m */; }; - 4F74D9FF11E6A18100F2D927 /* GTMHTTPFetcherTestServer.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F74D9FE11E6A18100F2D927 /* GTMHTTPFetcherTestServer.m */; }; - 4F74DA0411E6A19B00F2D927 /* GTMHTTPServer.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F74DA0311E6A19B00F2D927 /* GTMHTTPServer.m */; }; - 4F74DAF811E7C7C900F2D927 /* GTMHTTPFetcherFetchingTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F74DAF711E7C7C900F2D927 /* GTMHTTPFetcherFetchingTest.m */; }; - 4F74DAFC11E7C7CF00F2D927 /* GTMHTTPFetcherCachingTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F74DAFB11E7C7CF00F2D927 /* GTMHTTPFetcherCachingTest.m */; }; - 4F74DB4411E7CF4200F2D927 /* gettysburgaddress.txt in Resources */ = {isa = PBXBuildFile; fileRef = 4F74DB4311E7CF4200F2D927 /* gettysburgaddress.txt */; }; - 4F8DB2BE13FC9AE30001DD6C /* GTMReadMonitorInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F8DB2BD13FC9AE30001DD6C /* GTMReadMonitorInputStream.m */; }; - 4F8DB2BF13FC9AE30001DD6C /* GTMReadMonitorInputStream.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F8DB2BD13FC9AE30001DD6C /* GTMReadMonitorInputStream.m */; }; - 4F8DB32213FC9CB70001DD6C /* GTMReadMonitorInputStreamTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F8DB32113FC9CB70001DD6C /* GTMReadMonitorInputStreamTest.m */; }; - 4F92DBC51379E9CB0071BAC1 /* GTMHTTPFetcherServiceTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F92DBC41379E9CB0071BAC1 /* GTMHTTPFetcherServiceTest.m */; }; - 4FC6EF351852B270007D0854 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4FC6EF341852B270007D0854 /* XCTest.framework */; }; - 4FCC71F711EBF5970097924C /* GTMGatherInputStreamTest.m in Sources */ = {isa = PBXBuildFile; fileRef = 4FCC71F611EBF5970097924C /* GTMGatherInputStreamTest.m */; }; - 4FCC75E511EE6B1C0097924C /* GTMHTTPFetcherService.m in Sources */ = {isa = PBXBuildFile; fileRef = 4FCC75E411EE6B1C0097924C /* GTMHTTPFetcherService.m */; }; - 4FCC75E611EE6B1C0097924C /* GTMHTTPFetcherService.m in Sources */ = {isa = PBXBuildFile; fileRef = 4FCC75E411EE6B1C0097924C /* GTMHTTPFetcherService.m */; }; - 4FCC787A11EFA6030097924C /* GTMHTTPFetchHistory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4FCC787911EFA6030097924C /* GTMHTTPFetchHistory.m */; }; - 4FCC787B11EFA6030097924C /* GTMHTTPFetchHistory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4FCC787911EFA6030097924C /* GTMHTTPFetchHistory.m */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 4F2FCAC31267882800A74543 /* GTMHTTPFetcherUtilityTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcherUtilityTest.m; path = Tests/GTMHTTPFetcherUtilityTest.m; sourceTree = ""; }; - 4F3471F111DD58D700CB050E /* GTMGatherInputStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMGatherInputStream.h; sourceTree = ""; }; - 4F3471F211DD58D700CB050E /* GTMGatherInputStream.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMGatherInputStream.m; sourceTree = ""; }; - 4F3471F311DD58D700CB050E /* GTMHTTPFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcher.h; sourceTree = ""; }; - 4F3471F411DD58D700CB050E /* GTMHTTPFetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcher.m; sourceTree = ""; }; - 4F3471F511DD58D700CB050E /* GTMHTTPFetcherLogging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcherLogging.h; sourceTree = ""; }; - 4F3471F611DD58D700CB050E /* GTMHTTPFetcherLogging.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcherLogging.m; sourceTree = ""; }; - 4F3471F711DD58D700CB050E /* GTMHTTPUploadFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPUploadFetcher.h; sourceTree = ""; }; - 4F3471F811DD58D700CB050E /* GTMHTTPUploadFetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPUploadFetcher.m; sourceTree = ""; }; - 4F3471F911DD58D700CB050E /* GTMMIMEDocument.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMMIMEDocument.h; sourceTree = ""; }; - 4F3471FA11DD58D700CB050E /* GTMMIMEDocument.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMMIMEDocument.m; sourceTree = ""; }; - 4F74D92F11E68BD300F2D927 /* UnitTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = UnitTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 4F74D93011E68BD300F2D927 /* UnitTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "UnitTests-Info.plist"; sourceTree = ""; }; - 4F74D94911E68C1500F2D927 /* GTMMIMEDocumentTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMMIMEDocumentTest.m; path = Tests/GTMMIMEDocumentTest.m; sourceTree = ""; }; - 4F74D9FE11E6A18100F2D927 /* GTMHTTPFetcherTestServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcherTestServer.m; path = Tests/GTMHTTPFetcherTestServer.m; sourceTree = ""; }; - 4F74DA0211E6A19B00F2D927 /* GTMHTTPServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GTMHTTPServer.h; path = Tests/GTMHTTPServer.h; sourceTree = ""; }; - 4F74DA0311E6A19B00F2D927 /* GTMHTTPServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPServer.m; path = Tests/GTMHTTPServer.m; sourceTree = ""; }; - 4F74DAF711E7C7C900F2D927 /* GTMHTTPFetcherFetchingTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcherFetchingTest.m; path = Tests/GTMHTTPFetcherFetchingTest.m; sourceTree = ""; }; - 4F74DAFB11E7C7CF00F2D927 /* GTMHTTPFetcherCachingTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcherCachingTest.m; path = Tests/GTMHTTPFetcherCachingTest.m; sourceTree = ""; }; - 4F74DB4311E7CF4200F2D927 /* gettysburgaddress.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = gettysburgaddress.txt; path = Tests/Data/gettysburgaddress.txt; sourceTree = ""; }; - 4F8D22D81253E0960095BBF5 /* ReleaseNotes.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReleaseNotes.txt; sourceTree = ""; }; - 4F8DB2BD13FC9AE30001DD6C /* GTMReadMonitorInputStream.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMReadMonitorInputStream.m; sourceTree = ""; }; - 4F8DB2C013FC9AE90001DD6C /* GTMReadMonitorInputStream.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMReadMonitorInputStream.h; sourceTree = ""; }; - 4F8DB32113FC9CB70001DD6C /* GTMReadMonitorInputStreamTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMReadMonitorInputStreamTest.m; path = Tests/GTMReadMonitorInputStreamTest.m; sourceTree = SOURCE_ROOT; }; - 4F92DBC41379E9CB0071BAC1 /* GTMHTTPFetcherServiceTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcherServiceTest.m; path = Tests/GTMHTTPFetcherServiceTest.m; sourceTree = ""; }; - 4FC6EF341852B270007D0854 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; - 4FCC71F611EBF5970097924C /* GTMGatherInputStreamTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMGatherInputStreamTest.m; path = Tests/GTMGatherInputStreamTest.m; sourceTree = ""; }; - 4FCC75E411EE6B1C0097924C /* GTMHTTPFetcherService.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetcherService.m; sourceTree = ""; }; - 4FCC75E711EE6B230097924C /* GTMHTTPFetcherService.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetcherService.h; sourceTree = ""; }; - 4FCC787911EFA6030097924C /* GTMHTTPFetchHistory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMHTTPFetchHistory.m; sourceTree = ""; }; - 4FCC787C11EFA6090097924C /* GTMHTTPFetchHistory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMHTTPFetchHistory.h; sourceTree = ""; }; - D2AAC07E0554694100DB518D /* libGTMHTTPFetcher.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libGTMHTTPFetcher.a; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 4F74D92C11E68BD300F2D927 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 4FC6EF351852B270007D0854 /* XCTest.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D2AAC07C0554694100DB518D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 034768DFFF38A50411DB9C8B /* Products */ = { - isa = PBXGroup; - children = ( - D2AAC07E0554694100DB518D /* libGTMHTTPFetcher.a */, - 4F74D92F11E68BD300F2D927 /* UnitTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 0867D691FE84028FC02AAC07 /* OAuthTouchStaticLibrary */ = { - isa = PBXGroup; - children = ( - 4FC6EF341852B270007D0854 /* XCTest.framework */, - 4F74D91D11E68AD600F2D927 /* Sources */, - 4F74D94711E68C0B00F2D927 /* Tests */, - 034768DFFF38A50411DB9C8B /* Products */, - 4F8D22D81253E0960095BBF5 /* ReleaseNotes.txt */, - 4F74D93011E68BD300F2D927 /* UnitTests-Info.plist */, - ); - name = OAuthTouchStaticLibrary; - sourceTree = ""; - }; - 4F74D91D11E68AD600F2D927 /* Sources */ = { - isa = PBXGroup; - children = ( - 4F3471F311DD58D700CB050E /* GTMHTTPFetcher.h */, - 4F3471F411DD58D700CB050E /* GTMHTTPFetcher.m */, - 4FCC787C11EFA6090097924C /* GTMHTTPFetchHistory.h */, - 4FCC787911EFA6030097924C /* GTMHTTPFetchHistory.m */, - 4FCC75E711EE6B230097924C /* GTMHTTPFetcherService.h */, - 4FCC75E411EE6B1C0097924C /* GTMHTTPFetcherService.m */, - 4F3471F511DD58D700CB050E /* GTMHTTPFetcherLogging.h */, - 4F3471F611DD58D700CB050E /* GTMHTTPFetcherLogging.m */, - 4F3471F711DD58D700CB050E /* GTMHTTPUploadFetcher.h */, - 4F3471F811DD58D700CB050E /* GTMHTTPUploadFetcher.m */, - 4F3471F111DD58D700CB050E /* GTMGatherInputStream.h */, - 4F3471F211DD58D700CB050E /* GTMGatherInputStream.m */, - 4F3471F911DD58D700CB050E /* GTMMIMEDocument.h */, - 4F3471FA11DD58D700CB050E /* GTMMIMEDocument.m */, - 4F8DB2C013FC9AE90001DD6C /* GTMReadMonitorInputStream.h */, - 4F8DB2BD13FC9AE30001DD6C /* GTMReadMonitorInputStream.m */, - ); - name = Sources; - sourceTree = ""; - }; - 4F74D94711E68C0B00F2D927 /* Tests */ = { - isa = PBXGroup; - children = ( - 4F74DAF711E7C7C900F2D927 /* GTMHTTPFetcherFetchingTest.m */, - 4F92DBC41379E9CB0071BAC1 /* GTMHTTPFetcherServiceTest.m */, - 4F74DAFB11E7C7CF00F2D927 /* GTMHTTPFetcherCachingTest.m */, - 4F2FCAC31267882800A74543 /* GTMHTTPFetcherUtilityTest.m */, - 4FCC71F611EBF5970097924C /* GTMGatherInputStreamTest.m */, - 4F74D94911E68C1500F2D927 /* GTMMIMEDocumentTest.m */, - 4F8DB32113FC9CB70001DD6C /* GTMReadMonitorInputStreamTest.m */, - 4FCC71A911EBEFBF0097924C /* Server */, - 4F74DB4111E7CF3500F2D927 /* Data */, - ); - name = Tests; - sourceTree = ""; - }; - 4F74DB4111E7CF3500F2D927 /* Data */ = { - isa = PBXGroup; - children = ( - 4F74DB4311E7CF4200F2D927 /* gettysburgaddress.txt */, - ); - name = Data; - sourceTree = ""; - }; - 4FCC71A911EBEFBF0097924C /* Server */ = { - isa = PBXGroup; - children = ( - 4F74DA0211E6A19B00F2D927 /* GTMHTTPServer.h */, - 4F74DA0311E6A19B00F2D927 /* GTMHTTPServer.m */, - 4F74D9FE11E6A18100F2D927 /* GTMHTTPFetcherTestServer.m */, - ); - name = Server; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 4F74D92E11E68BD300F2D927 /* UnitTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4F74D93411E68BD300F2D927 /* Build configuration list for PBXNativeTarget "UnitTests" */; - buildPhases = ( - 4F74D92A11E68BD300F2D927 /* Resources */, - 4F74D92B11E68BD300F2D927 /* Sources */, - 4F74D92C11E68BD300F2D927 /* Frameworks */, - 4F74D92D11E68BD300F2D927 /* ShellScript */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = UnitTests; - productName = UnitTests; - productReference = 4F74D92F11E68BD300F2D927 /* UnitTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - D2AAC07D0554694100DB518D /* GTMHTTPFetcherLib */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "GTMHTTPFetcherLib" */; - buildPhases = ( - D2AAC07B0554694100DB518D /* Sources */, - D2AAC07C0554694100DB518D /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = GTMHTTPFetcherLib; - productName = OAuthTouchStaticLibrary; - productReference = D2AAC07E0554694100DB518D /* libGTMHTTPFetcher.a */; - productType = "com.apple.product-type.library.static"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 0867D690FE84028FC02AAC07 /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0500; - }; - buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "GTMHTTPFetcher" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 1; - knownRegions = ( - English, - Japanese, - French, - German, - ); - mainGroup = 0867D691FE84028FC02AAC07 /* OAuthTouchStaticLibrary */; - productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - D2AAC07D0554694100DB518D /* GTMHTTPFetcherLib */, - 4F74D92E11E68BD300F2D927 /* UnitTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 4F74D92A11E68BD300F2D927 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F74DB4411E7CF4200F2D927 /* gettysburgaddress.txt in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 4F74D92D11E68BD300F2D927 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 4F74D92B11E68BD300F2D927 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F74D93811E68BFB00F2D927 /* GTMHTTPFetcher.m in Sources */, - 4F74D93A11E68BFB00F2D927 /* GTMHTTPFetcherLogging.m in Sources */, - 4F74D93C11E68BFB00F2D927 /* GTMHTTPUploadFetcher.m in Sources */, - 4F74D93E11E68BFB00F2D927 /* GTMGatherInputStream.m in Sources */, - 4F74D94011E68BFB00F2D927 /* GTMMIMEDocument.m in Sources */, - 4F74D94A11E68C1500F2D927 /* GTMMIMEDocumentTest.m in Sources */, - 4F74D9FF11E6A18100F2D927 /* GTMHTTPFetcherTestServer.m in Sources */, - 4F74DA0411E6A19B00F2D927 /* GTMHTTPServer.m in Sources */, - 4F74DAF811E7C7C900F2D927 /* GTMHTTPFetcherFetchingTest.m in Sources */, - 4F74DAFC11E7C7CF00F2D927 /* GTMHTTPFetcherCachingTest.m in Sources */, - 4FCC71F711EBF5970097924C /* GTMGatherInputStreamTest.m in Sources */, - 4FCC75E511EE6B1C0097924C /* GTMHTTPFetcherService.m in Sources */, - 4FCC787A11EFA6030097924C /* GTMHTTPFetchHistory.m in Sources */, - 4F2FCAC41267882800A74543 /* GTMHTTPFetcherUtilityTest.m in Sources */, - 4F92DBC51379E9CB0071BAC1 /* GTMHTTPFetcherServiceTest.m in Sources */, - 4F8DB2BE13FC9AE30001DD6C /* GTMReadMonitorInputStream.m in Sources */, - 4F8DB32213FC9CB70001DD6C /* GTMReadMonitorInputStreamTest.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D2AAC07B0554694100DB518D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F3471FB11DD58D700CB050E /* GTMGatherInputStream.m in Sources */, - 4F3471FC11DD58D700CB050E /* GTMHTTPFetcher.m in Sources */, - 4F3471FD11DD58D700CB050E /* GTMHTTPFetcherLogging.m in Sources */, - 4F3471FE11DD58D700CB050E /* GTMHTTPUploadFetcher.m in Sources */, - 4F3471FF11DD58D700CB050E /* GTMMIMEDocument.m in Sources */, - 4FCC75E611EE6B1C0097924C /* GTMHTTPFetcherService.m in Sources */, - 4FCC787B11EFA6030097924C /* GTMHTTPFetchHistory.m in Sources */, - 4F8DB2BF13FC9AE30001DD6C /* GTMReadMonitorInputStream.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 1DEB921F08733DC00010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - "ARCHS[sdk=iphoneos*]" = ( - armv6, - armv7, - ); - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - INSTALL_PATH = /usr/local/lib; - PRODUCT_NAME = GTMHTTPFetcher; - SDKROOT = iphoneos; - }; - name = Debug; - }; - 1DEB922008733DC00010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - "ARCHS[sdk=iphoneos*]" = ( - armv6, - armv7, - ); - GCC_MODEL_TUNING = G5; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - INSTALL_PATH = /usr/local/lib; - PRODUCT_NAME = GTMHTTPFetcher; - SDKROOT = iphoneos; - }; - name = Release; - }; - 1DEB922308733DC00010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - "ARCHS[sdk=iphoneos*]" = ( - armv6, - armv7, - ); - GCC_C_LANGUAGE_STANDARD = c99; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - ONLY_ACTIVE_ARCH = YES; - OTHER_CFLAGS = "-DDEBUG=1"; - OTHER_LDFLAGS = "-ObjC"; - SDKROOT = macosx; - }; - name = Debug; - }; - 1DEB922408733DC00010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - "ARCHS[sdk=iphoneos*]" = ( - armv6, - armv7, - ); - GCC_C_LANGUAGE_STANDARD = c99; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - OTHER_LDFLAGS = "-ObjC"; - SDKROOT = macosx; - }; - name = Release; - }; - 4F74D93211E68BD300F2D927 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = NO; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - ); - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h"; - INFOPLIST_FILE = "UnitTests-Info.plist"; - INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles"; - OTHER_LDFLAGS = ( - "-framework", - Cocoa, - ); - PRODUCT_NAME = UnitTests; - RUN_CLANG_STATIC_ANALYZER = YES; - }; - name = Debug; - }; - 4F74D93311E68BD300F2D927 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COMBINE_HIDPI_IMAGES = YES; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "$(DEVELOPER_FRAMEWORKS_DIR)", - ); - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_MODEL_TUNING = G5; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/Cocoa.framework/Headers/Cocoa.h"; - INFOPLIST_FILE = "UnitTests-Info.plist"; - INSTALL_PATH = "$(USER_LIBRARY_DIR)/Bundles"; - OTHER_LDFLAGS = ( - "-framework", - Cocoa, - ); - PRODUCT_NAME = UnitTests; - RUN_CLANG_STATIC_ANALYZER = YES; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "GTMHTTPFetcherLib" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB921F08733DC00010E9CD /* Debug */, - 1DEB922008733DC00010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "GTMHTTPFetcher" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB922308733DC00010E9CD /* Debug */, - 1DEB922408733DC00010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4F74D93411E68BD300F2D927 /* Build configuration list for PBXNativeTarget "UnitTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4F74D93211E68BD300F2D927 /* Debug */, - 4F74D93311E68BD300F2D927 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 0867D690FE84028FC02AAC07 /* Project object */; -} diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogViewController.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogViewController.h deleted file mode 100644 index 65494120e..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogViewController.h +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if !STRIP_GTM_FETCH_LOGGING && !STRIP_GTM_HTTPLOGVIEWCONTROLLER - -#import - -// GTMHTTPFetcherLogViewController allows browsing of GTMHTTPFetcher's logs on -// the iOS device. Logging must have been enabled with -// -// [GTMHTTPFetcher setLoggingEnabled:YES]; -// -// A table will display one entry for each run of the app, with the most recent -// run's log listed first. A simple web view is used to browse the contents of -// an individual run's log. -// -// To use, push the view controller onto your app's navigation controller. -// -// GTMHTTPFetcherLogViewController *logViewController = -// [[[GTMHTTPFetcherLogViewController alloc] init] autorelease]; -// [navController pushViewController:logViewController -// animated:YES]; -// -// Apps without a UINavigationController may use controllerWithTarget:selector: -// convenience method to make one. For example: -// -// UINavigationController *nc = -// [GTMHTTPFetcherLogViewController controllerWithTarget:self -// selector:@selector(logsDone:)]; -// [self presentViewController:nc animated:YES completion:NULL]; -// -// - (void)logsDone:(UINavigationController *)navController { -// [self dismissViewControllerAnimated:YES completion:NULL]; -// } - -@interface GTMHTTPFetcherLogViewController : UITableViewController - -/// Sets whether to automatically scroll to the bottom of a run's log when viewed, to show the most -/// recent entry (a run log's entries are written in chronological order). Default is NO. -- (void)setOpensScrolledToEnd:(BOOL)opensScrolledToEnd; - -// This optional convenience method created a nav controller for use -// by apps that do not have a standard UINavigationController, as shown -// in the code snippet above. -// -// The selector should be for a method with a signature matching -// - (void)logsDone:(UINavigationController *)navController -// -// The target and selector may be nil. -+ (UINavigationController *)controllerWithTarget:(id)target - selector:(SEL)selector; -@end - -#endif diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogViewController.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogViewController.m deleted file mode 100644 index 43b313383..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogViewController.m +++ /dev/null @@ -1,275 +0,0 @@ -/* Copyright (c) 2013 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if defined(__has_feature) && __has_feature(objc_arc) -#error "This file uses manual reference counting. Compile with -fno-objc-arc" -#endif - -#import "GTMHTTPFetcherLogViewController.h" - -#if !STRIP_GTM_FETCH_LOGGING && !STRIP_GTM_HTTPLOGVIEWCONTROLLER - -#import - -#import "GTMHTTPFetcher.h" -#import "GTMHTTPFetcherLogging.h" - -static NSString *const kHTTPLogsCell = @"kGTMHTTPLogsCell"; - -// A minimal controller will be used to wrap a web view for displaying the -// log files. -@interface GTMHTTPFetcherLoggingWebViewController : UIViewController -- (id)initWithURL:(NSURL *)htmlURL title:(NSString *)title opensScrolledToEnd:(BOOL)opensScrolled; -@end - -#pragma mark - Table View Controller - -@interface GTMHTTPFetcherLogViewController () -@property (nonatomic, copy) void (^callbackBlock)(void); -@end - -@implementation GTMHTTPFetcherLogViewController { - NSArray *logsFolderURLs_; - BOOL opensScrolledToEnd_; -} - -@synthesize callbackBlock = callbackBlock_; - -- (instancetype)initWithStyle:(UITableViewStyle)style { - self = [super initWithStyle:style]; - if (self) { - self.title = @"HTTP Logs"; - - // Find all folders containing logs. - NSError *error; - NSFileManager *fm = [NSFileManager defaultManager]; - NSString *logsFolderPath = [GTMHTTPFetcher loggingDirectory]; - NSString *processName = [GTMHTTPFetcher loggingProcessName]; - - NSURL *logsURL = [NSURL fileURLWithPath:logsFolderPath]; - NSMutableArray *mutableURLs = - [[fm contentsOfDirectoryAtURL:logsURL - includingPropertiesForKeys:@[ NSURLCreationDateKey ] - options:0 - error:&error] mutableCopy]; - - // Remove non-log files that lack the process name prefix, - // and remove the "newest" symlink. - NSString *symlinkSuffix = [GTMHTTPFetcher symlinkNameSuffix]; - NSIndexSet *nonLogIndexes = [mutableURLs indexesOfObjectsPassingTest: - ^BOOL(id obj, NSUInteger idx, BOOL *stop) { - NSString *name = [obj lastPathComponent]; - return (![name hasPrefix:processName] - || [name hasSuffix:symlinkSuffix]); - }]; - [mutableURLs removeObjectsAtIndexes:nonLogIndexes]; - - // Sort to put the newest logs at the top of the list. - [mutableURLs sortUsingComparator:^NSComparisonResult(NSURL *url1, - NSURL *url2) { - NSDate *date1, *date2; - [url1 getResourceValue:&date1 forKey:NSURLCreationDateKey error:NULL]; - [url2 getResourceValue:&date2 forKey:NSURLCreationDateKey error:NULL]; - return [date2 compare:date1]; - }]; - logsFolderURLs_ = mutableURLs; - } - return self; -} - -- (void)dealloc { - [logsFolderURLs_ release]; - [super dealloc]; -} - -- (void)viewDidLoad { - [super viewDidLoad]; - - // Avoid silent failure if this was not added to a UINavigationController. - // - // The method +controllerWithTarget:selector: can be used to create a - // temporary UINavigationController. - NSAssert(self.navigationController != nil, @"Need a UINavigationController"); -} - -- (void)setOpensScrolledToEnd:(BOOL)opensScrolledToEnd { - opensScrolledToEnd_ = opensScrolledToEnd; -} - -#pragma mark - - -- (NSString *)shortenedNameForURL:(NSURL *)url { - // Remove "Processname_log_" from the start of the file name. - NSString *name = [url lastPathComponent]; - NSString *prefix = [GTMHTTPFetcher processNameLogPrefix]; - if ([name hasPrefix:prefix]) { - name = [name substringFromIndex:[prefix length]]; - } - return name; -} - -#pragma mark - Table view data source - -- (NSInteger)tableView:(UITableView *)tableView - numberOfRowsInSection:(NSInteger)section { - return [logsFolderURLs_ count]; -} - -- (UITableViewCell *)tableView:(UITableView *)tableView - cellForRowAtIndexPath:(NSIndexPath *)indexPath { - UITableViewCell *cell = - [tableView dequeueReusableCellWithIdentifier:kHTTPLogsCell]; - if (cell == nil) { - cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault - reuseIdentifier:kHTTPLogsCell] autorelease]; - [cell.textLabel setAdjustsFontSizeToFitWidth:YES]; - } - - NSURL *url = [logsFolderURLs_ objectAtIndex:indexPath.row]; - cell.textLabel.text = [self shortenedNameForURL:url]; - - return cell; -} - -#pragma mark - Table view delegate - -- (void)tableView:(UITableView *)tableView - didSelectRowAtIndexPath:(NSIndexPath *)indexPath { - NSURL *folderURL = [logsFolderURLs_ objectAtIndex:indexPath.row]; - NSString *htmlName = [GTMHTTPFetcher htmlFileName]; - NSURL *htmlURL = [folderURL URLByAppendingPathComponent:htmlName]; - - // Show the webview controller. - NSString *title = [self shortenedNameForURL:folderURL]; - UIViewController *webViewController = - [[[GTMHTTPFetcherLoggingWebViewController alloc] initWithURL:htmlURL - title:title - opensScrolledToEnd:opensScrolledToEnd_] autorelease]; - - UINavigationController *navController = [self navigationController]; - [navController pushViewController:webViewController animated:YES]; - - [tableView deselectRowAtIndexPath:indexPath animated:YES]; -} - -#pragma mark - - -+ (UINavigationController *)controllerWithTarget:(id)target - selector:(SEL)selector { - UINavigationController *navController = - [[[UINavigationController alloc] init] autorelease]; - GTMHTTPFetcherLogViewController *logViewController = - [[[GTMHTTPFetcherLogViewController alloc] init] autorelease]; - UIBarButtonItem *barButtonItem = - [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone - target:logViewController - action:@selector(doneButtonClicked:)] autorelease]; - logViewController.navigationItem.leftBarButtonItem = barButtonItem; - - // Make a block to capture the callback and nav controller. - void (^block)(void) = ^{ - if (target && selector) { - [target performSelector:selector withObject:navController]; - } - }; - logViewController.callbackBlock = block; - - navController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal; - - [navController pushViewController:logViewController animated:NO]; - return navController; -} - -- (void)doneButtonClicked:(UIBarButtonItem *)barButtonItem { - void (^block)() = self.callbackBlock; - block(); - self.callbackBlock = nil; -} - -@end - -#pragma mark - Minimal WebView Controller - -@implementation GTMHTTPFetcherLoggingWebViewController { - BOOL opensScrolledToEnd_; - NSURL *htmlURL_; -} - -- (instancetype)initWithURL:(NSURL *)htmlURL - title:(NSString *)title - opensScrolledToEnd:(BOOL)opensScrolledToEnd { - self = [super initWithNibName:nil bundle:nil]; - if (self) { - self.title = title; - htmlURL_ = [htmlURL retain]; - opensScrolledToEnd_ = opensScrolledToEnd; - } - return self; -} - -- (void)dealloc { - [htmlURL_ release]; - [super dealloc]; -} - -- (void)loadView { - UIWebView *webView = [[UIWebView alloc] init]; - webView.autoresizingMask = (UIViewAutoresizingFlexibleWidth - | UIViewAutoresizingFlexibleHeight); - webView.delegate = self; - self.view = webView; -} - -- (void)viewDidLoad { - [super viewDidLoad]; - NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL_]; - [[self webView] loadRequest:request]; -} - -- (void)didTapBackButton:(UIButton *)button { - [[self webView] goBack]; -} - -- (UIWebView *)webView { - return (UIWebView *)self.view; -} - -#pragma mark - WebView delegate - -- (void)webViewDidFinishLoad:(UIWebView *)webView { - if (opensScrolledToEnd_) { - // Scroll to the bottom, because the most recent entry is at the end. - NSString* javascript = [NSString stringWithFormat:@"window.scrollBy(0, %ld);", NSIntegerMax]; - [[self webView] stringByEvaluatingJavaScriptFromString:javascript]; - opensScrolledToEnd_ = NO; - } - - // Instead of the nav controller's back button, provide a simple - // webview back button when it's needed. - BOOL canGoBack = [webView canGoBack]; - UIBarButtonItem *backItem = nil; - if (canGoBack) { - // This hides the nav back button. - backItem = [[[UIBarButtonItem alloc] initWithTitle:@"⏎" - style:UIBarButtonItemStylePlain - target:self - action:@selector(didTapBackButton:)] autorelease]; - } - self.navigationItem.leftBarButtonItem = backItem; -} - -@end - -#endif // !STRIP_GTM_FETCH_LOGGING && !STRIP_GTM_HTTPLOGVIEWCONTROLLER diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogging.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogging.m deleted file mode 100644 index 54a4d95d6..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherLogging.m +++ /dev/null @@ -1,1134 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if !STRIP_GTM_FETCH_LOGGING - -#include -#include - -#import "GTMHTTPFetcherLogging.h" - -// Sensitive credential strings are replaced in logs with _snip_ -// -// Apps that must see the contents of sensitive tokens can set this to 1 -#ifndef SKIP_GTM_FETCH_LOGGING_SNIPPING -#define SKIP_GTM_FETCH_LOGGING_SNIPPING 0 -#endif - -// If GTMReadMonitorInputStream is available, it can be used for -// capturing uploaded streams of data -// -// We locally declare methods of GTMReadMonitorInputStream so we -// do not need to import the header, as some projects may not have it available -#ifndef GTM_NSSTREAM_DELEGATE -@interface GTMReadMonitorInputStream : NSInputStream -+ (id)inputStreamWithStream:(NSInputStream *)input; -@property (assign) id readDelegate; -@property (assign) SEL readSelector; -@property (retain) NSArray *runLoopModes; -@end -#endif - -// If GTMNSJSONSerialization is available, it is used for formatting JSON -#if (TARGET_OS_MAC && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED < 1070)) || \ - (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED < 50000)) -@interface GTMNSJSONSerialization : NSObject -+ (NSData *)dataWithJSONObject:(id)obj options:(NSUInteger)opt error:(NSError **)error; -+ (id)JSONObjectWithData:(NSData *)data options:(NSUInteger)opt error:(NSError **)error; -@end -#endif - -// Otherwise, if SBJSON is available, it is used for formatting JSON -@interface GTMFetcherSBJSON -- (void)setHumanReadable:(BOOL)flag; -- (NSString*)stringWithObject:(id)value error:(NSError**)error; -- (id)objectWithString:(NSString*)jsonrep error:(NSError**)error; -@end - -@interface GTMHTTPFetcher (GTMHTTPFetcherLoggingUtilities) -+ (NSString *)headersStringForDictionary:(NSDictionary *)dict; - -- (void)inputStream:(GTMReadMonitorInputStream *)stream - readIntoBuffer:(void *)buffer - length:(NSUInteger)length; - -// internal file utilities for logging -+ (BOOL)fileOrDirExistsAtPath:(NSString *)path; -+ (BOOL)makeDirectoryUpToPath:(NSString *)path; -+ (BOOL)removeItemAtPath:(NSString *)path; -+ (BOOL)createSymbolicLinkAtPath:(NSString *)newPath - withDestinationPath:(NSString *)targetPath; - -+ (NSString *)snipSubstringOfString:(NSString *)originalStr - betweenStartString:(NSString *)startStr - endString:(NSString *)endStr; - -+ (id)JSONObjectWithData:(NSData *)data; -+ (id)stringWithJSONObject:(id)obj; -@end - -@implementation GTMHTTPFetcher (GTMHTTPFetcherLogging) - -// fetchers come and fetchers go, but statics are forever -static BOOL gIsLoggingEnabled = NO; -static BOOL gIsLoggingToFile = YES; -static NSString *gLoggingDirectoryPath = nil; -static NSString *gLoggingDateStamp = nil; -static NSString* gLoggingProcessName = nil; - -+ (void)setLoggingDirectory:(NSString *)path { - [gLoggingDirectoryPath autorelease]; - gLoggingDirectoryPath = [path copy]; -} - -+ (NSString *)loggingDirectory { - - if (!gLoggingDirectoryPath) { - NSArray *arr = nil; -#if GTM_IPHONE && TARGET_IPHONE_SIMULATOR - // default to a directory called GTMHTTPDebugLogs into a sandbox-safe - // directory that a developer can find easily, the application home - arr = [NSArray arrayWithObject:NSHomeDirectory()]; -#elif GTM_IPHONE - // Neither ~/Desktop nor ~/Home is writable on an actual iPhone device. - // Put it in ~/Documents. - arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, - NSUserDomainMask, YES); -#else - // default to a directory called GTMHTTPDebugLogs in the desktop folder - arr = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, - NSUserDomainMask, YES); -#endif - - if ([arr count] > 0) { - NSString *const kGTMLogFolderName = @"GTMHTTPDebugLogs"; - - NSString *desktopPath = [arr objectAtIndex:0]; - NSString *logsFolderPath = [desktopPath stringByAppendingPathComponent:kGTMLogFolderName]; - - BOOL doesFolderExist = [[self class] fileOrDirExistsAtPath:logsFolderPath]; - - if (!doesFolderExist) { - // make the directory - doesFolderExist = [self makeDirectoryUpToPath:logsFolderPath]; - } - - if (doesFolderExist) { - // it's there; store it in the global - gLoggingDirectoryPath = [logsFolderPath copy]; - } - } - } - return gLoggingDirectoryPath; -} - -+ (void)setLoggingEnabled:(BOOL)flag { - gIsLoggingEnabled = flag; -} - -+ (BOOL)isLoggingEnabled { - return gIsLoggingEnabled; -} - -+ (void)setLoggingToFileEnabled:(BOOL)flag { - gIsLoggingToFile = flag; -} - -+ (BOOL)isLoggingToFileEnabled { - return gIsLoggingToFile; -} - -+ (void)setLoggingProcessName:(NSString *)str { - [gLoggingProcessName release]; - gLoggingProcessName = [str copy]; -} - -+ (NSString *)loggingProcessName { - - // get the process name (once per run) replacing spaces with underscores - if (!gLoggingProcessName) { - - NSString *procName = [[NSProcessInfo processInfo] processName]; - NSMutableString *loggingProcessName; - loggingProcessName = [[NSMutableString alloc] initWithString:procName]; - - [loggingProcessName replaceOccurrencesOfString:@" " - withString:@"_" - options:0 - range:NSMakeRange(0, [loggingProcessName length])]; - gLoggingProcessName = loggingProcessName; - } - return gLoggingProcessName; -} - -+ (void)setLoggingDateStamp:(NSString *)str { - [gLoggingDateStamp release]; - gLoggingDateStamp = [str copy]; -} - -+ (NSString *)loggingDateStamp { - // we'll pick one date stamp per run, so a run that starts at a later second - // will get a unique results html file - if (!gLoggingDateStamp) { - // produce a string like 08-21_01-41-23PM - - NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; - [formatter setFormatterBehavior:NSDateFormatterBehavior10_4]; - [formatter setDateFormat:@"M-dd_hh-mm-ssa"]; - - gLoggingDateStamp = [[formatter stringFromDate:[NSDate date]] retain] ; - } - return gLoggingDateStamp; -} - -+ (NSString *)processNameLogPrefix { - static NSString *prefix = nil; - if (!prefix) { - NSString *processName = [[self class] loggingProcessName]; - prefix = [[NSString alloc] initWithFormat:@"%@_log_", processName]; - } - return prefix; -} - -+ (NSString *)symlinkNameSuffix { - return @"_log_newest.html"; -} - -+ (NSString *)htmlFileName { - return @"aperçu_http_log.html"; -} - -// formattedStringFromData returns a prettyprinted string for XML or JSON input, -// and a plain string for other input data -- (NSString *)formattedStringFromData:(NSData *)inputData - contentType:(NSString *)contentType - JSON:(NSDictionary **)outJSON { - if (inputData == nil) return nil; - - // if the content type is JSON and we have the parsing class available, - // use that - if ([contentType hasPrefix:@"application/json"] - && [inputData length] > 5) { - // convert from JSON string to NSObjects and back to a formatted string - NSMutableDictionary *obj = [[self class] JSONObjectWithData:inputData]; - if (obj) { - if (outJSON) *outJSON = obj; - if ([obj isKindOfClass:[NSMutableDictionary class]]) { - // for security and privacy, omit OAuth 2 response access and refresh - // tokens - if ([obj valueForKey:@"refresh_token"] != nil) { - [obj setObject:@"_snip_" forKey:@"refresh_token"]; - } - if ([obj valueForKey:@"access_token"] != nil) { - [obj setObject:@"_snip_" forKey:@"access_token"]; - } - } - NSString *formatted = [[self class] stringWithJSONObject:obj]; - if (formatted) return formatted; - } - } - -#if !GTM_FOUNDATION_ONLY && !GTM_SKIP_LOG_XMLFORMAT - // verify that this data starts with the bytes indicating XML - - NSString *const kXMLLintPath = @"/usr/bin/xmllint"; - static BOOL hasCheckedAvailability = NO; - static BOOL isXMLLintAvailable; - - if (!hasCheckedAvailability) { - isXMLLintAvailable = [[self class] fileOrDirExistsAtPath:kXMLLintPath]; - hasCheckedAvailability = YES; - } - - if (isXMLLintAvailable - && [inputData length] > 5 - && strncmp([inputData bytes], " 0) { - // success - inputData = formattedData; - } - } -#else - // we can't call external tasks on the iPhone; leave the XML unformatted -#endif - - NSString *dataStr = [[[NSString alloc] initWithData:inputData - encoding:NSUTF8StringEncoding] autorelease]; - return dataStr; -} - -- (void)setupStreamLogging { - // if logging is enabled, it needs a buffer to accumulate data from any - // NSInputStream used for uploading. Logging will wrap the input - // stream with a stream that lets us keep a copy the data being read. - if ([GTMHTTPFetcher isLoggingEnabled] - && loggedStreamData_ == nil - && postStream_ != nil) { - loggedStreamData_ = [[NSMutableData alloc] init]; - - BOOL didCapture = [self logCapturePostStream]; - if (!didCapture) { - // upload stream logging requires the class - // GTMReadMonitorInputStream be available - NSString const *str = @"<>"; - [loggedStreamData_ setData:[str dataUsingEncoding:NSUTF8StringEncoding]]; - } - } -} - -- (void)setLogRequestBody:(NSString *)bodyString { - @synchronized(self) { - [logRequestBody_ release]; - logRequestBody_ = [bodyString copy]; - } -} - -- (NSString *)logRequestBody { - @synchronized(self) { - return logRequestBody_; - } -} - -- (void)setLogResponseBody:(NSString *)bodyString { - @synchronized(self) { - [logResponseBody_ release]; - logResponseBody_ = [bodyString copy]; - } -} - -- (NSString *)logResponseBody { - @synchronized(self) { - return logResponseBody_; - } -} - -- (void)setShouldDeferResponseBodyLogging:(BOOL)flag { - @synchronized(self) { - if (flag != shouldDeferResponseBodyLogging_) { - shouldDeferResponseBodyLogging_ = flag; - if (!flag && !hasLoggedError_) { - [self performSelectorOnMainThread:@selector(logFetchWithError:) - withObject:nil - waitUntilDone:NO]; - } - } - } -} - -- (BOOL)shouldDeferResponseBodyLogging { - @synchronized(self) { - return shouldDeferResponseBodyLogging_; - } -} - -// stringFromStreamData creates a string given the supplied data -// -// If NSString can create a UTF-8 string from the data, then that is returned. -// -// Otherwise, this routine tries to find a MIME boundary at the beginning of -// the data block, and uses that to break up the data into parts. Each part -// will be used to try to make a UTF-8 string. For parts that fail, a -// replacement string showing the part header and <> is supplied -// in place of the binary data. - -- (NSString *)stringFromStreamData:(NSData *)data - contentType:(NSString *)contentType { - - if (data == nil) return nil; - - // optimistically, see if the whole data block is UTF-8 - NSString *streamDataStr = [self formattedStringFromData:data - contentType:contentType - JSON:NULL]; - if (streamDataStr) return streamDataStr; - - // Munge a buffer by replacing non-ASCII bytes with underscores, - // and turn that munged buffer an NSString. That gives us a string - // we can use with NSScanner. - NSMutableData *mutableData = [NSMutableData dataWithData:data]; - unsigned char *bytes = [mutableData mutableBytes]; - - for (unsigned int idx = 0; idx < [mutableData length]; idx++) { - if (bytes[idx] > 0x7F || bytes[idx] == 0) { - bytes[idx] = '_'; - } - } - - NSString *mungedStr = [[[NSString alloc] initWithData:mutableData - encoding:NSUTF8StringEncoding] autorelease]; - if (mungedStr != nil) { - - // scan for the boundary string - NSString *boundary = nil; - NSScanner *scanner = [NSScanner scannerWithString:mungedStr]; - - if ([scanner scanUpToString:@"\r\n" intoString:&boundary] - && [boundary hasPrefix:@"--"]) { - - // we found a boundary string; use it to divide the string into parts - NSArray *mungedParts = [mungedStr componentsSeparatedByString:boundary]; - - // look at each of the munged parts in the original string, and try to - // convert those into UTF-8 - NSMutableArray *origParts = [NSMutableArray array]; - NSUInteger offset = 0; - for (NSString *mungedPart in mungedParts) { - NSUInteger partSize = [mungedPart length]; - - NSRange range = NSMakeRange(offset, partSize); - NSData *origPartData = [data subdataWithRange:range]; - - NSString *origPartStr = [[[NSString alloc] initWithData:origPartData - encoding:NSUTF8StringEncoding] autorelease]; - if (origPartStr) { - // we could make this original part into UTF-8; use the string - [origParts addObject:origPartStr]; - } else { - // this part can't be made into UTF-8; scan the header, if we can - NSString *header = nil; - NSScanner *headerScanner = [NSScanner scannerWithString:mungedPart]; - if (![headerScanner scanUpToString:@"\r\n\r\n" intoString:&header]) { - // we couldn't find a header - header = @""; - } - - // make a part string with the header and <> - NSString *binStr = [NSString stringWithFormat:@"\r%@\r<<%lu bytes>>\r", - header, (long)(partSize - [header length])]; - [origParts addObject:binStr]; - } - offset += partSize + [boundary length]; - } - - // rejoin the original parts - streamDataStr = [origParts componentsJoinedByString:boundary]; - } - } - - if (!streamDataStr) { - // give up; just make a string showing the uploaded bytes - streamDataStr = [NSString stringWithFormat:@"<<%u bytes>>", - (unsigned int)[data length]]; - } - return streamDataStr; -} - -// logFetchWithError is called following a successful or failed fetch attempt -// -// This method does all the work for appending to and creating log files - -- (void)logFetchWithError:(NSError *)error { - - if (![[self class] isLoggingEnabled]) return; - - // TODO: (grobbins) add Javascript to display response data formatted in hex - - NSString *parentDir = [[self class] loggingDirectory]; - NSString *processName = [[self class] loggingProcessName]; - NSString *dateStamp = [[self class] loggingDateStamp]; - NSString *logNamePrefix = [[self class] processNameLogPrefix]; - - // make a directory for this run's logs, like - // SyncProto_logs_10-16_01-56-58PM - NSString *dirName = [NSString stringWithFormat:@"%@%@", - logNamePrefix, dateStamp]; - NSString *logDirectory = [parentDir stringByAppendingPathComponent:dirName]; - - if (gIsLoggingToFile) { - // be sure that the first time this app runs, it's not writing to - // a preexisting folder - static BOOL shouldReuseFolder = NO; - if (!shouldReuseFolder) { - shouldReuseFolder = YES; - NSString *origLogDir = logDirectory; - for (int ctr = 2; ctr < 20; ctr++) { - if (![[self class] fileOrDirExistsAtPath:logDirectory]) break; - - // append a digit - logDirectory = [origLogDir stringByAppendingFormat:@"_%d", ctr]; - } - } - if (![[self class] makeDirectoryUpToPath:logDirectory]) return; - } - // each response's NSData goes into its own xml or txt file, though all - // responses for this run of the app share a main html file. This - // counter tracks all fetch responses for this run of the app. - // - // we'll use a local variable since this routine may be reentered while - // waiting for XML formatting to be completed by an external task - static int zResponseCounter = 0; - int responseCounter = ++zResponseCounter; - - // file name for an image data file - NSString *responseDataFileName = nil; - NSUInteger responseDataLength; - if (downloadFileHandle_) { - responseDataLength = (NSUInteger) [downloadFileHandle_ offsetInFile]; - } else { - responseDataLength = [downloadedData_ length]; - } - - NSURLResponse *response = [self response]; - NSDictionary *responseHeaders = [self responseHeaders]; - - NSString *responseBaseName = nil; - NSString *responseDataStr = nil; - NSDictionary *responseJSON = nil; - - // if there's response data, decide what kind of file to put it in based - // on the first bytes of the file or on the mime type supplied by the server - NSString *responseMIMEType = [response MIMEType]; - BOOL isResponseImage = NO; - NSData *dataToWrite = nil; - - if (responseDataLength > 0) { - NSString *responseDataExtn = nil; - - // generate a response file base name like - responseBaseName = [NSString stringWithFormat:@"fetch_%d_response", - responseCounter]; - - NSString *responseType = [responseHeaders valueForKey:@"Content-Type"]; - responseDataStr = [self formattedStringFromData:downloadedData_ - contentType:responseType - JSON:&responseJSON]; - if (responseDataStr) { - // we were able to make a UTF-8 string from the response data - if ([responseMIMEType isEqual:@"application/atom+xml"] - || [responseMIMEType hasSuffix:@"/xml"]) { - responseDataExtn = @"xml"; - dataToWrite = [responseDataStr dataUsingEncoding:NSUTF8StringEncoding]; - } - } else if ([responseMIMEType isEqual:@"image/jpeg"]) { - responseDataExtn = @"jpg"; - dataToWrite = downloadedData_; - isResponseImage = YES; - } else if ([responseMIMEType isEqual:@"image/gif"]) { - responseDataExtn = @"gif"; - dataToWrite = downloadedData_; - isResponseImage = YES; - } else if ([responseMIMEType isEqual:@"image/png"]) { - responseDataExtn = @"png"; - dataToWrite = downloadedData_; - isResponseImage = YES; - } else { - // add more non-text types here - } - - // if we have an extension, save the raw data in a file with that - // extension - if (responseDataExtn && dataToWrite) { - responseDataFileName = [responseBaseName stringByAppendingPathExtension:responseDataExtn]; - NSString *responseDataFilePath = [logDirectory stringByAppendingPathComponent:responseDataFileName]; - - NSError *downloadedError = nil; - if (gIsLoggingToFile - && ![dataToWrite writeToFile:responseDataFilePath - options:0 - error:&downloadedError]) { - NSLog(@"%@ logging write error:%@ (%@)", - [self class], downloadedError, responseDataFileName); - } - } - } - - // we'll have one main html file per run of the app - NSString *htmlName = [[self class] htmlFileName]; - NSString *htmlPath =[logDirectory stringByAppendingPathComponent:htmlName]; - - // if the html file exists (from logging previous fetches) we don't need - // to re-write the header or the scripts - BOOL didFileExist = [[self class] fileOrDirExistsAtPath:htmlPath]; - - NSMutableString* outputHTML = [NSMutableString string]; - NSURLRequest *request = [self mutableRequest]; - - // we need a header to say we'll have UTF-8 text - if (!didFileExist) { - [outputHTML appendFormat:@"%@ HTTP fetch log %@", - processName, dateStamp]; - } - - // now write the visible html elements - NSString *copyableFileName = [NSString stringWithFormat:@"fetch_%d.txt", - responseCounter]; - - // write the date & time, the comment, and the link to the plain-text - // (copyable) log - NSString *const dateLineFormat = @"%@      "; - [outputHTML appendFormat:dateLineFormat, [NSDate date]]; - - NSString *comment = [self comment]; - if (comment) { - NSString *const commentFormat = @"%@      "; - [outputHTML appendFormat:commentFormat, comment]; - } - - NSString *const reqRespFormat = @"request/response log
"; - [outputHTML appendFormat:reqRespFormat, copyableFileName]; - - // write the request URL - NSString *requestMethod = [request HTTPMethod]; - NSURL *requestURL = [request URL]; - - NSURL *redirectedFromHost = [[[redirectedFromURL_ host] copy] autorelease]; - // Save the request URL for next time in case this redirects. - [redirectedFromURL_ release]; - redirectedFromURL_ = [requestURL copy]; - if (redirectedFromHost) { - [outputHTML appendFormat:@"redirected from %@
", - redirectedFromHost]; - } - - [outputHTML appendFormat:@"request: %@ %@
\n", - requestMethod, requestURL]; - - // write the request headers - NSDictionary *requestHeaders = [request allHTTPHeaderFields]; - NSUInteger numberOfRequestHeaders = [requestHeaders count]; - if (numberOfRequestHeaders > 0) { - // Indicate if the request is authorized; warn if the request is - // authorized but non-SSL - NSString *auth = [requestHeaders objectForKey:@"Authorization"]; - NSString *headerDetails = @""; - if (auth) { - headerDetails = @"   authorized"; - BOOL isInsecure = [[requestURL scheme] isEqual:@"http"]; - if (isInsecure) { - headerDetails = @"   authorized, non-SSL" - " "; // 26A0 = ⚠ - } - } - NSString *cookiesHdr = [requestHeaders objectForKey:@"Cookie"]; - if (cookiesHdr) { - headerDetails = [headerDetails stringByAppendingString: - @"   cookies"]; - } - NSString *matchHdr = [requestHeaders objectForKey:@"If-Match"]; - if (matchHdr) { - headerDetails = [headerDetails stringByAppendingString: - @"   if-match"]; - } - matchHdr = [requestHeaders objectForKey:@"If-None-Match"]; - if (matchHdr) { - headerDetails = [headerDetails stringByAppendingString: - @"   if-none-match"]; - } - [outputHTML appendFormat:@"   headers: %d %@
", - (int)numberOfRequestHeaders, headerDetails]; - } else { - [outputHTML appendFormat:@"   headers: none
"]; - } - - // write the request post data, toggleable - NSData *postData; - if (loggedStreamData_) { - postData = loggedStreamData_; - } else if (postData_) { - postData = postData_; - } else { - postData = [request_ HTTPBody]; - } - - NSString *postDataStr = nil; - NSUInteger postDataLength = [postData length]; - NSString *postType = [requestHeaders valueForKey:@"Content-Type"]; - - if (postDataLength > 0) { - [outputHTML appendFormat:@"   data: %d bytes, %@
\n", - (int)postDataLength, postType ? postType : @""]; - - if (logRequestBody_) { - postDataStr = [[logRequestBody_ copy] autorelease]; - [logRequestBody_ release]; - logRequestBody_ = nil; - } else { - postDataStr = [self stringFromStreamData:postData - contentType:postType]; - if (postDataStr) { - // remove OAuth 2 client secret and refresh token - postDataStr = [[self class] snipSubstringOfString:postDataStr - betweenStartString:@"client_secret=" - endString:@"&"]; - - postDataStr = [[self class] snipSubstringOfString:postDataStr - betweenStartString:@"refresh_token=" - endString:@"&"]; - - // remove ClientLogin password - postDataStr = [[self class] snipSubstringOfString:postDataStr - betweenStartString:@"&Passwd=" - endString:@"&"]; - } - } - } else { - // no post data - } - - // write the response status, MIME type, URL - NSInteger status = [self statusCode]; - if (response) { - NSString *statusString = @""; - if (status != 0) { - if (status == 200 || status == 201) { - statusString = [NSString stringWithFormat:@"%ld", (long)status]; - - // report any JSON-RPC error - if ([responseJSON isKindOfClass:[NSDictionary class]]) { - NSDictionary *jsonError = [responseJSON objectForKey:@"error"]; - if ([jsonError isKindOfClass:[NSDictionary class]]) { - NSString *jsonCode = [[jsonError valueForKey:@"code"] description]; - NSString *jsonMessage = [jsonError valueForKey:@"message"]; - if (jsonCode || jsonMessage) { - NSString *const jsonErrFmt = @"   JSON error: %@ %@  ⚑"; // 2691 = ⚑ - statusString = [statusString stringByAppendingFormat:jsonErrFmt, - jsonCode ? jsonCode : @"", - jsonMessage ? jsonMessage : @""]; - } - } - } - } else { - // purple for anything other than 200 or 201 - NSString *flag = (status >= 400 ? @" ⚑" : @""); // 2691 = ⚑ - NSString *const statusFormat = @"%ld %@"; - statusString = [NSString stringWithFormat:statusFormat, - (long)status, flag]; - } - } - - // show the response URL only if it's different from the request URL - NSString *responseURLStr = @""; - NSURL *responseURL = [response URL]; - - if (responseURL && ![responseURL isEqual:[request URL]]) { - NSString *const responseURLFormat = @"response URL:" - " %@
\n"; - responseURLStr = [NSString stringWithFormat:responseURLFormat, - [responseURL absoluteString]]; - } - - [outputHTML appendFormat:@"response:  status %@
\n%@", - statusString, responseURLStr]; - - // Write the response headers - NSUInteger numberOfResponseHeaders = [responseHeaders count]; - if (numberOfResponseHeaders > 0) { - // Indicate if the server is setting cookies - NSString *cookiesSet = [responseHeaders valueForKey:@"Set-Cookie"]; - NSString *cookiesStr = (cookiesSet ? @"  " - "sets cookies" : @""); - // Indicate if the server is redirecting - NSString *location = [responseHeaders valueForKey:@"Location"]; - BOOL isRedirect = (status >= 300 && status <= 399 && location != nil); - NSString *redirectsStr = (isRedirect ? @"  " - "redirects" : @""); - - [outputHTML appendFormat:@"   headers: %d %@ %@
\n", - (int)numberOfResponseHeaders, cookiesStr, redirectsStr]; - } else { - [outputHTML appendString:@"   headers: none
\n"]; - } - } - - // error - if (error) { - [outputHTML appendFormat:@"Error: %@
\n", [error description]]; - } - - // Write the response data - if (responseDataFileName) { - NSString *escapedResponseFile = [responseDataFileName stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - if (isResponseImage) { - // Make a small inline image that links to the full image file - [outputHTML appendFormat:@"   data: %d bytes, %@
", - (int)responseDataLength, responseMIMEType]; - NSString *const fmt = @"image\n"; - [outputHTML appendFormat:fmt, - escapedResponseFile, escapedResponseFile]; - } else { - // The response data was XML; link to the xml file - NSString *const fmt = @"   data: %d bytes, " - "%@   %@\n"; - [outputHTML appendFormat:fmt, - (int)responseDataLength, responseMIMEType, - escapedResponseFile, [escapedResponseFile pathExtension]]; - } - } else { - // The response data was not an image; just show the length and MIME type - [outputHTML appendFormat:@"   data: %d bytes, %@\n", - (int)responseDataLength, responseMIMEType]; - } - - // Make a single string of the request and response, suitable for copying - // to the clipboard and pasting into a bug report - NSMutableString *copyable = [NSMutableString string]; - if (comment) { - [copyable appendFormat:@"%@\n\n", comment]; - } - [copyable appendFormat:@"%@\n", [NSDate date]]; - if (redirectedFromHost) { - [copyable appendFormat:@"Redirected from %@\n", redirectedFromHost]; - } - [copyable appendFormat:@"Request: %@ %@\n", requestMethod, requestURL]; - if ([requestHeaders count] > 0) { - [copyable appendFormat:@"Request headers:\n%@\n", - [[self class] headersStringForDictionary:requestHeaders]]; - } - - if (postDataLength > 0) { - [copyable appendFormat:@"Request body: (%u bytes)\n", - (unsigned int) postDataLength]; - if (postDataStr) { - [copyable appendFormat:@"%@\n", postDataStr]; - } - [copyable appendString:@"\n"]; - } - - if (response) { - [copyable appendFormat:@"Response: status %d\n", (int) status]; - [copyable appendFormat:@"Response headers:\n%@\n", - [[self class] headersStringForDictionary:responseHeaders]]; - [copyable appendFormat:@"Response body: (%u bytes)\n", - (unsigned int) responseDataLength]; - if (responseDataLength > 0) { - if (logResponseBody_) { - responseDataStr = [[logResponseBody_ copy] autorelease]; - [logResponseBody_ release]; - logResponseBody_ = nil; - } - if (responseDataStr != nil) { - [copyable appendFormat:@"%@\n", responseDataStr]; - } else if (status >= 400 && [temporaryDownloadPath_ length] > 0) { - // Try to read in the saved data, which is probably a server error - // message - NSStringEncoding enc; - responseDataStr = [NSString stringWithContentsOfFile:temporaryDownloadPath_ - usedEncoding:&enc - error:NULL]; - if ([responseDataStr length] > 0) { - [copyable appendFormat:@"%@\n", responseDataStr]; - } else { - [copyable appendFormat:@"<<%u bytes to file>>\n", - (unsigned int) responseDataLength]; - } - } else { - // Even though it's redundant, we'll put in text to indicate that all - // the bytes are binary - [copyable appendFormat:@"<<%u bytes>>\n", - (unsigned int) responseDataLength]; - } - } - } - - if (error) { - [copyable appendFormat:@"Error: %@\n", error]; - } - - // Save to log property before adding the separator - self.log = copyable; - - [copyable appendString:@"-----------------------------------------------------------\n"]; - - - // Write the copyable version to another file (linked to at the top of the - // html file, above) - // - // Ideally, something to just copy this to the clipboard like - // Copy here." - // would work everywhere, but it only works in Safari as of 8/2010 - if (gIsLoggingToFile) { - NSString *copyablePath = [logDirectory stringByAppendingPathComponent:copyableFileName]; - NSError *copyableError = nil; - if (![copyable writeToFile:copyablePath - atomically:NO - encoding:NSUTF8StringEncoding - error:©ableError]) { - // Error writing to file - NSLog(@"%@ logging write error:%@ (%@)", - [self class], copyableError, copyablePath); - } - - [outputHTML appendString:@"


"]; - - // Append the HTML to the main output file - const char* htmlBytes = [outputHTML UTF8String]; - NSOutputStream *stream = [NSOutputStream outputStreamToFileAtPath:htmlPath - append:YES]; - [stream open]; - [stream write:(const uint8_t *) htmlBytes maxLength:strlen(htmlBytes)]; - [stream close]; - - // Make a symlink to the latest html - NSString *const symlinkNameSuffix = [[self class] symlinkNameSuffix]; - NSString *symlinkName = [processName stringByAppendingString:symlinkNameSuffix]; - NSString *symlinkPath = [parentDir stringByAppendingPathComponent:symlinkName]; - - [[self class] removeItemAtPath:symlinkPath]; - [[self class] createSymbolicLinkAtPath:symlinkPath - withDestinationPath:htmlPath]; - -#if GTM_IPHONE - static BOOL gReportedLoggingPath = NO; - if (!gReportedLoggingPath) { - gReportedLoggingPath = YES; - NSLog(@"GTMHTTPFetcher logging to \"%@\"", parentDir); - } -#endif - } -} - -- (BOOL)logCapturePostStream { - // This is called when beginning a fetch. The caller should have already - // verified that logging is enabled, and should have allocated - // loggedStreamData_ as a mutable object. - - // If the class GTMReadMonitorInputStream is not available, bail now, since - // we cannot capture this upload stream - Class monitorClass = NSClassFromString(@"GTMReadMonitorInputStream"); - if (!monitorClass) return NO; - - // If we're logging, we need to wrap the upload stream with our monitor - // stream that will call us back with the bytes being read from the stream - - // Our wrapper will retain the old post stream - [postStream_ autorelease]; - - postStream_ = [monitorClass inputStreamWithStream:postStream_]; - [postStream_ retain]; - - [(GTMReadMonitorInputStream *)postStream_ setReadDelegate:self]; - [(GTMReadMonitorInputStream *)postStream_ setRunLoopModes:[self runLoopModes]]; - - SEL readSel = @selector(inputStream:readIntoBuffer:length:); - [(GTMReadMonitorInputStream *)postStream_ setReadSelector:readSel]; - - return YES; -} - -@end - -@implementation GTMHTTPFetcher (GTMHTTPFetcherLoggingUtilities) - -- (void)inputStream:(GTMReadMonitorInputStream *)stream - readIntoBuffer:(void *)buffer - length:(NSUInteger)length { - // append the captured data - [loggedStreamData_ appendBytes:buffer length:length]; -} - -#pragma mark Internal file routines - -// We implement plain Unix versions of NSFileManager methods to avoid -// NSFileManager's issues with being used from multiple threads - -+ (BOOL)fileOrDirExistsAtPath:(NSString *)path { - struct stat buffer; - int result = stat([path fileSystemRepresentation], &buffer); - return (result == 0); -} - -+ (BOOL)makeDirectoryUpToPath:(NSString *)path { - int result = 0; - - // Recursively create the parent directory of the requested path - NSString *parent = [path stringByDeletingLastPathComponent]; - if (![self fileOrDirExistsAtPath:parent]) { - result = [self makeDirectoryUpToPath:parent]; - } - - // Make the leaf directory - if (result == 0 && ![self fileOrDirExistsAtPath:path]) { - result = mkdir([path fileSystemRepresentation], S_IRWXU); // RWX for owner - } - return (result == 0); -} - -+ (BOOL)removeItemAtPath:(NSString *)path { - int result = unlink([path fileSystemRepresentation]); - return (result == 0); -} - -+ (BOOL)createSymbolicLinkAtPath:(NSString *)newPath - withDestinationPath:(NSString *)targetPath { - int result = symlink([targetPath fileSystemRepresentation], - [newPath fileSystemRepresentation]); - return (result == 0); -} - -#pragma mark Fomatting Utilities - -+ (NSString *)snipSubstringOfString:(NSString *)originalStr - betweenStartString:(NSString *)startStr - endString:(NSString *)endStr { -#if SKIP_GTM_FETCH_LOGGING_SNIPPING - return originalStr; -#else - if (originalStr == nil) return nil; - - // Find the start string, and replace everything between it - // and the end string (or the end of the original string) with "_snip_" - NSRange startRange = [originalStr rangeOfString:startStr]; - if (startRange.location == NSNotFound) return originalStr; - - // We found the start string - NSUInteger originalLength = [originalStr length]; - NSUInteger startOfTarget = NSMaxRange(startRange); - NSRange targetAndRest = NSMakeRange(startOfTarget, - originalLength - startOfTarget); - NSRange endRange = [originalStr rangeOfString:endStr - options:0 - range:targetAndRest]; - NSRange replaceRange; - if (endRange.location == NSNotFound) { - // Found no end marker so replace to end of string - replaceRange = targetAndRest; - } else { - // Replace up to the endStr - replaceRange = NSMakeRange(startOfTarget, - endRange.location - startOfTarget); - } - - NSString *result = [originalStr stringByReplacingCharactersInRange:replaceRange - withString:@"_snip_"]; - return result; -#endif // SKIP_GTM_FETCH_LOGGING_SNIPPING -} - -+ (NSString *)headersStringForDictionary:(NSDictionary *)dict { - // Format the dictionary in http header style, like - // Accept: application/json - // Cache-Control: no-cache - // Content-Type: application/json; charset=utf-8 - // - // Pad the key names, but not beyond 16 chars, since long custom header - // keys just create too much whitespace - NSArray *keys = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)]; - - NSMutableString *str = [NSMutableString string]; - for (NSString *key in keys) { - NSString *value = [dict valueForKey:key]; - if ([key isEqual:@"Authorization"]) { - // Remove OAuth 1 token - value = [[self class] snipSubstringOfString:value - betweenStartString:@"oauth_token=\"" - endString:@"\""]; - - // Remove OAuth 2 bearer token (draft 16, and older form) - value = [[self class] snipSubstringOfString:value - betweenStartString:@"Bearer " - endString:@"\n"]; - value = [[self class] snipSubstringOfString:value - betweenStartString:@"OAuth " - endString:@"\n"]; - - // Remove Google ClientLogin - value = [[self class] snipSubstringOfString:value - betweenStartString:@"GoogleLogin auth=" - endString:@"\n"]; - } - [str appendFormat:@" %@: %@\n", key, value]; - } - return str; -} - -+ (id)JSONObjectWithData:(NSData *)data { - Class serializer = NSClassFromString(@"NSJSONSerialization"); - if (serializer) { - const NSUInteger kOpts = (1UL << 0); // NSJSONReadingMutableContainers - NSMutableDictionary *obj; - obj = [serializer JSONObjectWithData:data - options:kOpts - error:NULL]; - return obj; - } else { - // Try SBJsonParser or SBJSON - Class jsonParseClass = NSClassFromString(@"SBJsonParser"); - if (!jsonParseClass) { - jsonParseClass = NSClassFromString(@"SBJSON"); - } - if (jsonParseClass) { - GTMFetcherSBJSON *parser = [[[jsonParseClass alloc] init] autorelease]; - NSString *jsonStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - if (jsonStr) { - NSMutableDictionary *obj = [parser objectWithString:jsonStr error:NULL]; - return obj; - } - } - } - return nil; -} - -+ (id)stringWithJSONObject:(id)obj { - Class serializer = NSClassFromString(@"NSJSONSerialization"); - if (serializer) { - const NSUInteger kOpts = (1UL << 0); // NSJSONWritingPrettyPrinted - NSData *data; - data = [serializer dataWithJSONObject:obj - options:kOpts - error:NULL]; - if (data) { - NSString *jsonStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - return jsonStr; - } - } else { - // Try SBJsonParser or SBJSON - Class jsonWriterClass = NSClassFromString(@"SBJsonWriter"); - if (!jsonWriterClass) { - jsonWriterClass = NSClassFromString(@"SBJSON"); - } - if (jsonWriterClass) { - GTMFetcherSBJSON *writer = [[[jsonWriterClass alloc] init] autorelease]; - [writer setHumanReadable:YES]; - NSString *jsonStr = [writer stringWithObject:obj error:NULL]; - return jsonStr; - } - } - return nil; -} - -@end - -#endif // !STRIP_GTM_FETCH_LOGGING diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherService.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherService.h deleted file mode 100755 index 94912b6da..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherService.h +++ /dev/null @@ -1,130 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPFetcherService.h -// - -// The fetcher service class maintains a history to be used by a sequence -// of fetchers objects generated by the service. -// -// Fetchers that do not need to share a history may be generated independently, -// like -// -// GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request]; -// -// Fetchers that should share cookies or an ETagged data cache should be -// generated by a common GTMHTTPFetcherService instance, like -// -// GTMHTTPFetcherService *myFetcherService = [[GTMHTTPFetcherService alloc] init]; -// GTMHTTPFetcher* myFirstFetcher = [myFetcherService fetcherWithRequest:request1]; -// GTMHTTPFetcher* mySecondFetcher = [myFetcherService fetcherWithRequest:request2]; - -#import "GTMHTTPFetcher.h" -#import "GTMHTTPFetchHistory.h" - -@interface GTMHTTPFetcherService : NSObject { - @private - NSMutableDictionary *delayedHosts_; - NSMutableDictionary *runningHosts_; - NSUInteger maxRunningFetchersPerHost_; - - GTMHTTPFetchHistory *fetchHistory_; - NSOperationQueue *delegateQueue_; - NSArray *runLoopModes_; - NSString *userAgent_; - NSTimeInterval timeout_; - NSURLCredential *credential_; // username & password - NSURLCredential *proxyCredential_; // credential supplied to proxy servers - NSInteger cookieStorageMethod_; - - NSArray *allowedInsecureSchemes_; - BOOL allowLocalhostRequest_; - - BOOL shouldFetchInBackground_; - - id authorizer_; -} - -// Create a fetcher -// -// These methods will return an autoreleased fetcher, but if -// the fetcher is successfully created, the connection will retain the -// fetcher for the life of the connection as well. So the caller doesn't have -// to retain the fetcher explicitly unless they want to be able to monitor -// or cancel it. -- (GTMHTTPFetcher *)fetcherWithRequest:(NSURLRequest *)request; -- (GTMHTTPFetcher *)fetcherWithURL:(NSURL *)requestURL; -- (GTMHTTPFetcher *)fetcherWithURLString:(NSString *)requestURLString; -- (id)fetcherWithRequest:(NSURLRequest *)request - fetcherClass:(Class)fetcherClass; - -// Queues of delayed and running fetchers. Each dictionary contains arrays -// of fetchers, keyed by host -// -// A max value of 0 means no fetchers should be delayed. -// -// The default limit is 10 simultaneous fetchers targeting each host. -@property (assign) NSUInteger maxRunningFetchersPerHost; -@property (retain, readonly) NSDictionary *delayedHosts; -@property (retain, readonly) NSDictionary *runningHosts; - -- (BOOL)isDelayingFetcher:(GTMHTTPFetcher *)fetcher; - -- (NSUInteger)numberOfFetchers; // running + delayed fetchers -- (NSUInteger)numberOfRunningFetchers; -- (NSUInteger)numberOfDelayedFetchers; - -// Search for running or delayed fetchers with the specified URL. -// -// Returns an array of fetcher objects found, or nil if none found. -- (NSArray *)issuedFetchersWithRequestURL:(NSURL *)requestURL; - -- (void)stopAllFetchers; - -// Properties to be applied to each fetcher; -// see GTMHTTPFetcher.h for descriptions -@property (copy) NSString *userAgent; -@property (assign) NSTimeInterval timeout; -@property (retain) NSOperationQueue *delegateQueue; -@property (retain) NSArray *runLoopModes; -@property (retain) NSURLCredential *credential; -@property (retain) NSURLCredential *proxyCredential; -@property (assign) BOOL shouldFetchInBackground; -@property (copy) NSArray *allowedInsecureSchemes; -@property (assign) BOOL allowLocalhostRequest; - -// Fetch history -@property (retain) GTMHTTPFetchHistory *fetchHistory; - -@property (assign) NSInteger cookieStorageMethod; -@property (assign) BOOL shouldRememberETags; // default: NO -@property (assign) BOOL shouldCacheETaggedData; // default: NO - -- (void)clearETaggedDataCache; -- (void)clearHistory; - -@property (nonatomic, retain) id authorizer; - -// Spin the run loop, discarding events, until all running and delayed fetchers -// have completed -// -// This is only for use in testing or in tools without a user interface. -// -// Synchronous fetches should never be done by shipping apps; they are -// sufficient reason for rejection from the app store. -- (void)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherService.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherService.m deleted file mode 100755 index 4a00e5810..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPFetcherService.m +++ /dev/null @@ -1,507 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPFetcherService.m -// - -#import "GTMHTTPFetcherService.h" - -@interface GTMHTTPFetcher (ServiceMethods) -- (BOOL)beginFetchMayDelay:(BOOL)mayDelay - mayAuthorize:(BOOL)mayAuthorize; -@end - -@interface GTMHTTPFetcherService () -@property (retain, readwrite) NSDictionary *delayedHosts; -@property (retain, readwrite) NSDictionary *runningHosts; - -- (void)detachAuthorizer; -@end - -@implementation GTMHTTPFetcherService - -@synthesize maxRunningFetchersPerHost = maxRunningFetchersPerHost_, - userAgent = userAgent_, - timeout = timeout_, - delegateQueue = delegateQueue_, - runLoopModes = runLoopModes_, - credential = credential_, - proxyCredential = proxyCredential_, - cookieStorageMethod = cookieStorageMethod_, - shouldFetchInBackground = shouldFetchInBackground_, - allowedInsecureSchemes = allowedInsecureSchemes_, - allowLocalhostRequest = allowLocalhostRequest_, - fetchHistory = fetchHistory_; - -- (id)init { - self = [super init]; - if (self) { - fetchHistory_ = [[GTMHTTPFetchHistory alloc] init]; - delayedHosts_ = [[NSMutableDictionary alloc] init]; - runningHosts_ = [[NSMutableDictionary alloc] init]; - cookieStorageMethod_ = kGTMHTTPFetcherCookieStorageMethodFetchHistory; - - maxRunningFetchersPerHost_ = 10; -} - return self; -} - -- (void)dealloc { - [self detachAuthorizer]; - - [delayedHosts_ release]; - [runningHosts_ release]; - [fetchHistory_ release]; - [userAgent_ release]; - [delegateQueue_ release]; - [runLoopModes_ release]; - [credential_ release]; - [proxyCredential_ release]; - [authorizer_ release]; - - [super dealloc]; -} - -#pragma mark Generate a new fetcher - -- (id)fetcherWithRequest:(NSURLRequest *)request - fetcherClass:(Class)fetcherClass { - GTMHTTPFetcher *fetcher = [fetcherClass fetcherWithRequest:request]; - - fetcher.fetchHistory = self.fetchHistory; - fetcher.delegateQueue = self.delegateQueue; - fetcher.runLoopModes = self.runLoopModes; - fetcher.cookieStorageMethod = self.cookieStorageMethod; - fetcher.credential = self.credential; - fetcher.proxyCredential = self.proxyCredential; - fetcher.shouldFetchInBackground = self.shouldFetchInBackground; - fetcher.allowedInsecureSchemes = self.allowedInsecureSchemes; - fetcher.allowLocalhostRequest = self.allowLocalhostRequest; - fetcher.authorizer = self.authorizer; - fetcher.service = self; - - NSString *userAgent = self.userAgent; - if ([userAgent length] > 0 - && [request valueForHTTPHeaderField:@"User-Agent"] == nil) { - [fetcher.mutableRequest setValue:userAgent - forHTTPHeaderField:@"User-Agent"]; - } - - NSTimeInterval timeout = self.timeout; - if (timeout > 0.0) { - [fetcher.mutableRequest setTimeoutInterval:timeout]; - } - - return fetcher; -} - -- (GTMHTTPFetcher *)fetcherWithRequest:(NSURLRequest *)request { - return [self fetcherWithRequest:request - fetcherClass:[GTMHTTPFetcher class]]; -} - -- (GTMHTTPFetcher *)fetcherWithURL:(NSURL *)requestURL { - return [self fetcherWithRequest:[NSURLRequest requestWithURL:requestURL]]; -} - -- (GTMHTTPFetcher *)fetcherWithURLString:(NSString *)requestURLString { - return [self fetcherWithURL:[NSURL URLWithString:requestURLString]]; -} - -#pragma mark Queue Management - -- (void)addRunningFetcher:(GTMHTTPFetcher *)fetcher - forHost:(NSString *)host { - // Add to the array of running fetchers for this host, creating the array - // if needed - NSMutableArray *runningForHost = [runningHosts_ objectForKey:host]; - if (runningForHost == nil) { - runningForHost = [NSMutableArray arrayWithObject:fetcher]; - [runningHosts_ setObject:runningForHost forKey:host]; - } else { - [runningForHost addObject:fetcher]; - } -} - -- (void)addDelayedFetcher:(GTMHTTPFetcher *)fetcher - forHost:(NSString *)host { - // Add to the array of delayed fetchers for this host, creating the array - // if needed - NSMutableArray *delayedForHost = [delayedHosts_ objectForKey:host]; - if (delayedForHost == nil) { - delayedForHost = [NSMutableArray arrayWithObject:fetcher]; - [delayedHosts_ setObject:delayedForHost forKey:host]; - } else { - [delayedForHost addObject:fetcher]; - } -} - -- (BOOL)isDelayingFetcher:(GTMHTTPFetcher *)fetcher { - @synchronized(self) { - NSString *host = [[[fetcher mutableRequest] URL] host]; - NSArray *delayedForHost = [delayedHosts_ objectForKey:host]; - NSUInteger idx = [delayedForHost indexOfObjectIdenticalTo:fetcher]; - BOOL isDelayed = (delayedForHost != nil) && (idx != NSNotFound); - return isDelayed; - } -} - -- (BOOL)fetcherShouldBeginFetching:(GTMHTTPFetcher *)fetcher { - // Entry point from the fetcher - @synchronized(self) { - NSURL *requestURL = [[fetcher mutableRequest] URL]; - NSString *host = [requestURL host]; - - // Addresses "file:///path" case where localhost is the implicit host. - if ([host length] == 0 && [requestURL isFileURL]) { - host = @"localhost"; - } - - if ([host length] == 0) { -#if DEBUG - // Data URIs legitimately have no host, reject other hostless URLs. - NSAssert1([[requestURL scheme] isEqual:@"data"], @"%@ lacks host", fetcher); -#endif - return YES; - } - - NSMutableArray *runningForHost = [runningHosts_ objectForKey:host]; - if (runningForHost != nil - && [runningForHost indexOfObjectIdenticalTo:fetcher] != NSNotFound) { -#if DEBUG - NSAssert1(0, @"%@ was already running", fetcher); -#endif - return YES; - } - - // We'll save the host that serves as the key for this fetcher's array - // to avoid any chance of the underlying request changing, stranding - // the fetcher in the wrong array - fetcher.serviceHost = host; - fetcher.thread = [NSThread currentThread]; - - if (maxRunningFetchersPerHost_ == 0 - || maxRunningFetchersPerHost_ > [runningForHost count]) { - [self addRunningFetcher:fetcher forHost:host]; - return YES; - } else { - [self addDelayedFetcher:fetcher forHost:host]; - return NO; - } - } - return YES; -} - -// Fetcher start and stop methods, invoked on the appropriate thread for -// the fetcher -- (void)performSelector:(SEL)sel onStartThreadForFetcher:(GTMHTTPFetcher *)fetcher { - NSOperationQueue *delegateQueue = fetcher.delegateQueue; - NSThread *thread = fetcher.thread; - if (delegateQueue != nil || [thread isEqual:[NSThread currentThread]]) { - // The fetcher should run on the thread we're on now, or there's a delegate - // queue specified so it doesn't matter what thread the fetcher is started - // on, since it will call back on the queue. - [self performSelector:sel withObject:fetcher]; - } else { - // Fetcher must run on a specified thread (and that thread must have a - // run loop.) - [self performSelector:sel - onThread:thread - withObject:fetcher - waitUntilDone:NO]; - } -} - -- (void)startFetcherOnCurrentThread:(GTMHTTPFetcher *)fetcher { - [fetcher beginFetchMayDelay:NO - mayAuthorize:YES]; -} - -- (void)startFetcher:(GTMHTTPFetcher *)fetcher { - [self performSelector:@selector(startFetcherOnCurrentThread:) - onStartThreadForFetcher:fetcher]; -} - -- (void)stopFetcherOnCurrentThread:(GTMHTTPFetcher *)fetcher { - [fetcher stopFetching]; -} - -- (void)stopFetcher:(GTMHTTPFetcher *)fetcher { - [self performSelector:@selector(stopFetcherOnCurrentThread:) - onStartThreadForFetcher:fetcher]; -} - -- (void)fetcherDidStop:(GTMHTTPFetcher *)fetcher { - // Entry point from the fetcher - @synchronized(self) { - NSString *host = fetcher.serviceHost; - if (!host) { - // fetcher has been stopped previously - return; - } - - NSMutableArray *runningForHost = [runningHosts_ objectForKey:host]; - [runningForHost removeObject:fetcher]; - - NSMutableArray *delayedForHost = [delayedHosts_ objectForKey:host]; - [delayedForHost removeObject:fetcher]; - - while ([delayedForHost count] > 0 - && [runningForHost count] < maxRunningFetchersPerHost_) { - // Start another delayed fetcher running, scanning for the minimum - // priority value, defaulting to FIFO for equal priorities - GTMHTTPFetcher *nextFetcher = nil; - for (GTMHTTPFetcher *delayedFetcher in delayedForHost) { - if (nextFetcher == nil - || delayedFetcher.servicePriority < nextFetcher.servicePriority) { - nextFetcher = delayedFetcher; - } - } - - if (nextFetcher) { - [self addRunningFetcher:nextFetcher forHost:host]; - runningForHost = [runningHosts_ objectForKey:host]; - - [delayedForHost removeObjectIdenticalTo:nextFetcher]; - [self startFetcher:nextFetcher]; - } - } - - if ([runningForHost count] == 0) { - // None left; remove the empty array - [runningHosts_ removeObjectForKey:host]; - } - - if ([delayedForHost count] == 0) { - [delayedHosts_ removeObjectForKey:host]; - } - - // The fetcher is no longer in the running or the delayed array, - // so remove its host and thread properties - fetcher.serviceHost = nil; - fetcher.thread = nil; - } -} - -- (NSUInteger)numberOfFetchers { - @synchronized(self) { - NSUInteger running = [self numberOfRunningFetchers]; - NSUInteger delayed = [self numberOfDelayedFetchers]; - return running + delayed; - } -} - -- (NSUInteger)numberOfRunningFetchers { - @synchronized(self) { - NSUInteger sum = 0; - for (NSString *host in runningHosts_) { - NSArray *fetchers = [runningHosts_ objectForKey:host]; - sum += [fetchers count]; - } - return sum; - } -} - -- (NSUInteger)numberOfDelayedFetchers { - @synchronized(self) { - NSUInteger sum = 0; - for (NSString *host in delayedHosts_) { - NSArray *fetchers = [delayedHosts_ objectForKey:host]; - sum += [fetchers count]; - } - return sum; - } -} - -- (NSArray *)issuedFetchersWithRequestURL:(NSURL *)requestURL { - @synchronized(self) { - NSMutableArray *array = nil; - NSString *host = [requestURL host]; - if ([host length] == 0) return nil; - - NSURL *absRequestURL = [requestURL absoluteURL]; - - NSArray *runningForHost = [runningHosts_ objectForKey:host]; - for (GTMHTTPFetcher *fetcher in runningForHost) { - NSURL *fetcherURL = [[[fetcher mutableRequest] URL] absoluteURL]; - if ([fetcherURL isEqual:absRequestURL]) { - if (array == nil) { - array = [NSMutableArray array]; - } - [array addObject:fetcher]; - } - } - - NSArray *delayedForHost = [delayedHosts_ objectForKey:host]; - for (GTMHTTPFetcher *fetcher in delayedForHost) { - NSURL *fetcherURL = [[[fetcher mutableRequest] URL] absoluteURL]; - if ([fetcherURL isEqual:absRequestURL]) { - if (array == nil) { - array = [NSMutableArray array]; - } - [array addObject:fetcher]; - } - } - return array; - } -} - -- (void)stopAllFetchers { - @synchronized(self) { - // Remove fetchers from the delayed list to avoid fetcherDidStop: from - // starting more fetchers running as a side effect of stopping one - NSArray *delayedForHosts = [delayedHosts_ allValues]; - [delayedHosts_ removeAllObjects]; - - for (NSArray *delayedForHost in delayedForHosts) { - for (GTMHTTPFetcher *fetcher in delayedForHost) { - [self stopFetcher:fetcher]; - } - } - - NSArray *runningForHosts = [runningHosts_ allValues]; - [runningHosts_ removeAllObjects]; - - for (NSArray *runningForHost in runningForHosts) { - for (GTMHTTPFetcher *fetcher in runningForHost) { - [self stopFetcher:fetcher]; - } - } - } -} - -#pragma mark Fetch History Settings - -// Turn on data caching to receive a copy of previously-retrieved objects. -// Otherwise, fetches may return status 304 (No Change) rather than actual data -- (void)setShouldCacheETaggedData:(BOOL)flag { - self.fetchHistory.shouldCacheETaggedData = flag; -} - -- (BOOL)shouldCacheETaggedData { - return self.fetchHistory.shouldCacheETaggedData; -} - -- (void)setETaggedDataCacheCapacity:(NSUInteger)totalBytes { - self.fetchHistory.memoryCapacity = totalBytes; -} - -- (NSUInteger)ETaggedDataCacheCapacity { - return self.fetchHistory.memoryCapacity; -} - -- (void)setShouldRememberETags:(BOOL)flag { - self.fetchHistory.shouldRememberETags = flag; -} - -- (BOOL)shouldRememberETags { - return self.fetchHistory.shouldRememberETags; -} - -// reset the ETag cache to avoid getting a Not Modified status -// based on prior queries -- (void)clearETaggedDataCache { - [self.fetchHistory clearETaggedDataCache]; -} - -- (void)clearHistory { - [self clearETaggedDataCache]; - [self.fetchHistory removeAllCookies]; -} - -#pragma mark Synchronous Wait for Unit Testing - -- (void)waitForCompletionOfAllFetchersWithTimeout:(NSTimeInterval)timeoutInSeconds { - NSDate* giveUpDate = [NSDate dateWithTimeIntervalSinceNow:timeoutInSeconds]; - BOOL isMainThread = [NSThread isMainThread]; - - while ([self numberOfFetchers] > 0 - && [giveUpDate timeIntervalSinceNow] > 0) { - // Run the current run loop 1/1000 of a second to give the networking - // code a chance to work - if (isMainThread || delegateQueue_ == nil) { - NSDate *stopDate = [NSDate dateWithTimeIntervalSinceNow:0.001]; - [[NSRunLoop currentRunLoop] runUntilDate:stopDate]; - } else { - // Sleep on the delegate queue's background thread. - [NSThread sleepForTimeInterval:0.001]; - } - } -} - -#pragma mark Accessors - -- (NSDictionary *)runningHosts { - return runningHosts_; -} - -- (void)setRunningHosts:(NSDictionary *)dict { - [runningHosts_ autorelease]; - runningHosts_ = [dict mutableCopy]; -} - -- (NSDictionary *)delayedHosts { - return delayedHosts_; -} - -- (void)setDelayedHosts:(NSDictionary *)dict { - [delayedHosts_ autorelease]; - delayedHosts_ = [dict mutableCopy]; -} - -- (id )authorizer { - return authorizer_; -} - -- (void)setAuthorizer:(id )obj { - if (obj != authorizer_) { - [self detachAuthorizer]; - } - - [authorizer_ autorelease]; - authorizer_ = [obj retain]; - - // Use the fetcher service for the authorization fetches if the auth - // object supports fetcher services - if ([authorizer_ respondsToSelector:@selector(setFetcherService:)]) { -#if GTM_USE_SESSION_FETCHER - [authorizer_ setFetcherService:(id)self]; -#else - [authorizer_ setFetcherService:self]; -#endif - } -} - -- (void)detachAuthorizer { - // This method is called by the fetcher service's dealloc and setAuthorizer: - // methods; do not override. - // - // The fetcher service retains the authorizer, and the authorizer has a - // weak pointer to the fetcher service (a non-zeroing pointer for - // compatibility with iOS 4 and Mac OS X 10.5/10.6.) - // - // When this fetcher service no longer uses the authorizer, we want to remove - // the authorizer's dependence on the fetcher service. Authorizers can still - // function without a fetcher service. - if ([authorizer_ respondsToSelector:@selector(fetcherService)]) { - id authFetcherService = [authorizer_ fetcherService]; - if (authFetcherService == self) { - [authorizer_ setFetcherService:nil]; - } - } -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPUploadFetcher.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPUploadFetcher.h deleted file mode 100755 index b0ce3b6ad..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPUploadFetcher.h +++ /dev/null @@ -1,139 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPUploadFetcher.h -// - -#if (!GDATA_REQUIRE_SERVICE_INCLUDES) || GDATA_INCLUDE_DOCS_SERVICE || \ - GDATA_INCLUDE_YOUTUBE_SERVICE || GDATA_INCLUDE_PHOTOS_SERVICE - -// -// This subclass of GTMHTTPFetcher simulates the series of fetches -// needed for chunked upload as a single fetch operation. -// -// Protocol document: -// http://code.google.com/p/gears/wiki/ResumableHttpRequestsProposal -// -// To the client, the only fetcher that exists is this class; the subsidiary -// fetchers needed for uploading chunks are not visible (though the most recent -// chunk fetcher may be accessed via the -activeFetcher method, and -// -responseHeaders and -statusCode reflect results from the most recent chunk -// fetcher.) -// -// Chunk fetchers are discarded as soon as they have completed. -// - -#pragma once - -#import "GTMHTTPFetcher.h" -#import "GTMHTTPFetcherService.h" - -// async retrieval of an http get or post -@interface GTMHTTPUploadFetcher : GTMHTTPFetcher { - GTMHTTPFetcher *chunkFetcher_; - - // we'll call through to the delegate's sentData and finished selectors - SEL delegateSentDataSEL_; - SEL delegateFinishedSEL_; - - BOOL needsManualProgress_; - - // the initial fetch's body length and bytes actually sent are - // needed for calculating progress during subsequent chunk uploads - NSUInteger initialBodyLength_; - NSUInteger initialBodySent_; - - NSURL *locationURL_; -#if NS_BLOCKS_AVAILABLE - void (^locationChangeBlock_)(NSURL *); -#elif !__LP64__ - // placeholders: for 32-bit builds, keep the size of the object's ivar section - // the same with and without blocks -#ifndef __clang_analyzer__ - id locationChangePlaceholder_; -#endif -#endif - - // uploadData_ or uploadFileHandle_ may be set, but not both - NSData *uploadData_; - NSFileHandle *uploadFileHandle_; - NSInteger uploadFileHandleLength_; - NSString *uploadMIMEType_; - NSUInteger chunkSize_; - BOOL isPaused_; - BOOL isRestartedUpload_; - - // we keep the latest offset into the upload data just for - // progress reporting - NSUInteger currentOffset_; - - // we store the response headers and status code for the most recent - // chunk fetcher - NSDictionary *responseHeaders_; - NSInteger statusCode_; -} - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request - uploadData:(NSData *)data - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize - fetcherService:(GTMHTTPFetcherService *)fetcherServiceOrNil; - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request - uploadFileHandle:(NSFileHandle *)fileHandle - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize - fetcherService:(GTMHTTPFetcherService *)fetcherServiceOrNil; - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithLocation:(NSURL *)locationURL - uploadFileHandle:(NSFileHandle *)fileHandle - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize - fetcherService:(GTMHTTPFetcherService *)fetcherServiceOrNil; -- (void)pauseFetching; -- (void)resumeFetching; -- (BOOL)isPaused; - -@property (retain) NSURL *locationURL; -@property (retain) NSData *uploadData; -@property (retain) NSFileHandle *uploadFileHandle; -@property (copy) NSString *uploadMIMEType; -@property (assign) NSUInteger chunkSize; -@property (assign) NSUInteger currentOffset; - -#if NS_BLOCKS_AVAILABLE -// When the upload location changes, the optional locationChangeBlock will be -// called. It will be called with nil once upload succeeds or can no longer -// be attempted. -@property (copy) void (^locationChangeBlock)(NSURL *locationURL); -#endif - -// the fetcher for the current data chunk, if any -@property (retain) GTMHTTPFetcher *chunkFetcher; - -// the active fetcher is the last chunk fetcher, or the upload fetcher itself -// if no chunk fetcher has yet been created -@property (readonly) GTMHTTPFetcher *activeFetcher; - -// the response headers from the most recently-completed fetch -@property (retain) NSDictionary *responseHeaders; - -// the status code from the most recently-completed fetch -@property (assign) NSInteger statusCode; - -@end - -#endif // #if !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPUploadFetcher.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPUploadFetcher.m deleted file mode 100755 index a7cea247a..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMHTTPUploadFetcher.m +++ /dev/null @@ -1,947 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMHTTPUploadFetcher.m -// - -#if (!GDATA_REQUIRE_SERVICE_INCLUDES) || GDATA_INCLUDE_DOCS_SERVICE || \ - GDATA_INCLUDE_YOUTUBE_SERVICE || GDATA_INCLUDE_PHOTOS_SERVICE - -#import "GTMHTTPUploadFetcher.h" - -static NSUInteger const kQueryServerForOffset = NSUIntegerMax; - -@interface GTMHTTPFetcher (ProtectedMethods) -@property (readwrite, retain) NSData *downloadedData; -- (void)releaseCallbacks; -- (void)stopFetchReleasingCallbacks:(BOOL)shouldReleaseCallbacks; -- (void)connectionDidFinishLoading:(NSURLConnection *)connection; -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; -@end - -@interface GTMHTTPUploadFetcher () -+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request - fetcherService:(GTMHTTPFetcherService *)fetcherService; -- (void)setLocationURL:(NSURL *)location - uploadData:(NSData *)data - uploadFileHandle:(NSFileHandle *)fileHandle - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize; - -- (void)uploadNextChunkWithOffset:(NSUInteger)offset; -- (void)uploadNextChunkWithOffset:(NSUInteger)offset - fetcherProperties:(NSMutableDictionary *)props; -- (void)destroyChunkFetcher; - -- (void)handleResumeIncompleteStatusForChunkFetcher:(GTMHTTPFetcher *)chunkFetcher; - -- (void)uploadFetcher:(GTMHTTPFetcher *)fetcher - didSendBytes:(NSInteger)bytesSent - totalBytesSent:(NSInteger)totalBytesSent -totalBytesExpectedToSend:(NSInteger)totalBytesExpected; - -- (void)reportProgressManually; - -- (NSUInteger)fullUploadLength; - --(BOOL)chunkFetcher:(GTMHTTPFetcher *)chunkFetcher - willRetry:(BOOL)willRetry - forError:(NSError *)error; - -- (void)chunkFetcher:(GTMHTTPFetcher *)chunkFetcher - finishedWithData:(NSData *)data - error:(NSError *)error; -@end - -@interface GTMHTTPUploadFetcher (PrivateMethods) -// private methods of the superclass -- (void)invokeSentDataCallback:(SEL)sel - target:(id)target - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten - totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite; - -- (void)invokeFetchCallback:(SEL)sel - target:(id)target - data:(NSData *)data - error:(NSError *)error; - -- (BOOL)invokeRetryCallback:(SEL)sel - target:(id)target - willRetry:(BOOL)willRetry - error:(NSError *)error; -@end - -@implementation GTMHTTPUploadFetcher - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request - uploadData:(NSData *)data - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize - fetcherService:(GTMHTTPFetcherService *)fetcherService { - GTMHTTPUploadFetcher *fetcher = [self uploadFetcherWithRequest:request - fetcherService:fetcherService]; - [fetcher setLocationURL:nil - uploadData:data - uploadFileHandle:nil - uploadMIMEType:uploadMIMEType - chunkSize:chunkSize]; - return fetcher; -} - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request - uploadFileHandle:(NSFileHandle *)fileHandle - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize - fetcherService:(GTMHTTPFetcherService *)fetcherService { - GTMHTTPUploadFetcher *fetcher = [self uploadFetcherWithRequest:request - fetcherService:fetcherService]; - [fetcher setLocationURL:nil - uploadData:nil - uploadFileHandle:fileHandle - uploadMIMEType:uploadMIMEType - chunkSize:chunkSize]; - return fetcher; -} - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithLocation:(NSURL *)locationURL - uploadFileHandle:(NSFileHandle *)fileHandle - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize - fetcherService:(GTMHTTPFetcherService *)fetcherService { - GTMHTTPUploadFetcher *fetcher = [self uploadFetcherWithRequest:nil - fetcherService:fetcherService]; - [fetcher setLocationURL:locationURL - uploadData:nil - uploadFileHandle:fileHandle - uploadMIMEType:uploadMIMEType - chunkSize:chunkSize]; - return fetcher; -} - -+ (GTMHTTPUploadFetcher *)uploadFetcherWithRequest:(NSURLRequest *)request - fetcherService:(GTMHTTPFetcherService *)fetcherService { - // Internal utility method for instantiating fetchers - GTMHTTPUploadFetcher *fetcher; - if (fetcherService) { - fetcher = [fetcherService fetcherWithRequest:request - fetcherClass:self]; - } else { - fetcher = (GTMHTTPUploadFetcher *) [self fetcherWithRequest:request]; - } - return fetcher; -} - -- (void)setLocationURL:(NSURL *)location - uploadData:(NSData *)data - uploadFileHandle:(NSFileHandle *)fileHandle - uploadMIMEType:(NSString *)uploadMIMEType - chunkSize:(NSUInteger)chunkSize { -#if DEBUG - NSAssert((data == nil) != (fileHandle == nil), - @"upload data and fileHandle are mutually exclusive"); - NSAssert((self.mutableRequest == nil) != (location == nil), - @"request and location are mutually exclusive"); - NSAssert(chunkSize > 0,@"chunk size is zero"); - NSAssert(chunkSize != NSUIntegerMax, @"chunk size is sentinel value"); -#endif - [self setLocationURL:location]; - [self setUploadData:data]; - [self setUploadFileHandle:fileHandle]; - [self setUploadMIMEType:uploadMIMEType]; - [self setChunkSize:chunkSize]; - - // indicate that we've not yet determined the file handle's length - uploadFileHandleLength_ = -1; - - // indicate that we've not yet determined the upload fetcher status - statusCode_ = -1; - - // if this is restarting an upload begun by another fetcher, - // the location is specified but the request is nil - isRestartedUpload_ = (location != nil); - - // add our custom headers to the initial request indicating the data - // type and total size to be delivered later in the chunk requests - NSMutableURLRequest *mutableReq = [self mutableRequest]; - - NSNumber *lengthNum = [NSNumber numberWithUnsignedInteger:[self fullUploadLength]]; - [mutableReq setValue:[lengthNum stringValue] - forHTTPHeaderField:@"X-Upload-Content-Length"]; - - [mutableReq setValue:uploadMIMEType - forHTTPHeaderField:@"X-Upload-Content-Type"]; -} - -- (void)dealloc { - [self releaseCallbacks]; - - [chunkFetcher_ release]; - [locationURL_ release]; -#if NS_BLOCKS_AVAILABLE - [locationChangeBlock_ release]; -#endif - [uploadData_ release]; - [uploadFileHandle_ release]; - [uploadMIMEType_ release]; - [responseHeaders_ release]; - [super dealloc]; -} - -#pragma mark - - -- (NSUInteger)fullUploadLength { - if (uploadData_) { - return [uploadData_ length]; - } else { - if (uploadFileHandleLength_ == -1) { - // first time through, seek to end to determine file length - uploadFileHandleLength_ = (NSInteger) [uploadFileHandle_ seekToEndOfFile]; - } - return (NSUInteger)uploadFileHandleLength_; - } -} - -- (NSData *)uploadSubdataWithOffset:(NSUInteger)offset - length:(NSUInteger)length { - NSData *resultData = nil; - - if (uploadData_) { - NSRange range = NSMakeRange(offset, length); - resultData = [uploadData_ subdataWithRange:range]; - } else { - @try { - [uploadFileHandle_ seekToFileOffset:offset]; - resultData = [uploadFileHandle_ readDataOfLength:length]; - } - @catch (NSException *exception) { - NSLog(@"uploadFileHandle exception: %@", exception); - } - } - - return resultData; -} - -#pragma mark Method overrides affecting the initial fetch only - -- (BOOL)beginFetchWithDelegate:(id)delegate - didFinishSelector:(SEL)finishedSEL { - - GTMAssertSelectorNilOrImplementedWithArgs(delegate, finishedSEL, - @encode(GTMHTTPFetcher *), @encode(NSData *), @encode(NSError *), 0); - - // replace the finishedSEL with our own, since the initial finish callback - // is just the beginning of the upload experience - delegateFinishedSEL_ = finishedSEL; - - // if the client is running early 10.5 or iPhone 2, we may need to manually - // send progress indication since NSURLConnection won't be calling back - // to us during uploads - needsManualProgress_ = ![GTMHTTPFetcher doesSupportSentDataCallback]; - - initialBodyLength_ = [[self postData] length]; - - if (isRestartedUpload_) { - if (![self isPaused]) { - if (delegate) { - [self setDelegate:delegate]; - finishedSel_ = finishedSEL; - } - [self uploadNextChunkWithOffset:kQueryServerForOffset]; - } - return YES; - } - - // we don't need a finish selector since we're overriding - // -connectionDidFinishLoading - return [super beginFetchWithDelegate:delegate - didFinishSelector:NULL]; -} - -#if NS_BLOCKS_AVAILABLE -- (BOOL)beginFetchWithCompletionHandler:(void (^)(NSData *data, NSError *error))handler { - // we don't want to call into the delegate's completion block immediately - // after the finish of the initial connection (the delegate is called only - // when uploading finishes), so we substitute our own completion block to be - // called when the initial connection finishes - void (^holdBlock)(NSData *data, NSError *error) = [[handler copy] autorelease]; - - BOOL flag = [super beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { - // callback - if (!isRestartedUpload_) { - if (error == nil) { - // swap in the actual completion block now, as it will be called later - // when the upload chunks have completed - [completionBlock_ autorelease]; - completionBlock_ = [holdBlock copy]; - } else { - // pass the error on to the actual completion block - holdBlock(nil, error); - } - } else { - // If there was no initial request, then this fetch is resuming some - // other uploadFetcher's initial request, and the superclass's connection - // is never used, so at this point we call the user's actual completion - // block. - holdBlock(data, error); - } - }]; - return flag; -} -#endif - -- (void)connection:(NSURLConnection *)connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { - - // ignore this callback if we're doing manual progress, mainly so that - // we won't see duplicate progress callbacks when testing with - // doesSupportSentDataCallback turned off - if (needsManualProgress_) return; - - [self uploadFetcher:self - didSendBytes:bytesWritten - totalBytesSent:totalBytesWritten -totalBytesExpectedToSend:totalBytesExpectedToWrite]; -} - -- (BOOL)shouldReleaseCallbacksUponCompletion { - // we don't want the superclass to release the delegate and callback - // blocks once the initial fetch has finished - // - // this is invoked for only successful completion of the connection; - // an error always will invoke and release the callbacks - return NO; -} - -- (void)invokeFinalCallbacksWithData:(NSData *)data - error:(NSError *)error - shouldInvalidateLocation:(BOOL)shouldInvalidateLocation { - // avoid issues due to being released indirectly by a callback - [[self retain] autorelease]; - - if (shouldInvalidateLocation) { - [self setLocationURL:nil]; - } - - if (delegate_ && delegateFinishedSEL_) { - [self invokeFetchCallback:delegateFinishedSEL_ - target:delegate_ - data:data - error:error]; - } - -#if NS_BLOCKS_AVAILABLE - if (completionBlock_) { - completionBlock_(data, error); - } - - [self setLocationChangeBlock:nil]; -#endif - - [self releaseCallbacks]; -} - -- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - // handle failure of the initial fetch as a simple fetcher failure, including - // calling the delegate, and allowing retry to happen if appropriate - SEL prevSel = finishedSel_; // should be null - finishedSel_ = delegateFinishedSEL_; - [super connection:connection didFailWithError:error]; - - // If retry later happens and succeeds, it shouldn't message the delegate - // since we'll continue to chunk uploads. - finishedSel_ = prevSel; -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection { - - // we land here once the initial fetch sending the initial POST body - // has completed - - // let the superclass end its connection - [super connectionDidFinishLoading:connection]; - - NSInteger statusCode = [super statusCode]; - [self setStatusCode:statusCode]; - - NSData *downloadedData = [self downloadedData]; - - // we need to get the upload URL from the location header to continue - NSDictionary *responseHeaders = [self responseHeaders]; - NSString *locationURLStr = [responseHeaders objectForKey:@"Location"]; - - NSError *error = nil; - - if (statusCode >= 300) { - if (retryTimer_) return; - - error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:statusCode - userInfo:nil]; - } else if ([downloadedData length] > 0) { - // The initial response of the resumable upload protocol should have an - // empty body - // - // This problem typically happens because the upload create/edit link URL was - // not supplied with the request, and the server is thus expecting a non- - // resumable request/response. It may also happen if an error JSON error body - // is returned. - // - // We'll consider this status 501 Not Implemented rather than try to parse - // the body to determine the actual error, but will provide the data - // as userInfo for clients to inspect. - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:downloadedData - forKey:kGTMHTTPFetcherStatusDataKey]; - error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:501 - userInfo:userInfo]; - } else { -#if DEBUG - NSAssert([locationURLStr length] > 0, @"need upload location hdr"); -#endif - - if ([locationURLStr length] == 0) { - // we cannot continue since we do not know the location to use - // as our upload destination - // - // we'll consider this status 501 Not Implemented - error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:501 - userInfo:nil]; - } - } - - if (error) { - [self invokeFinalCallbacksWithData:downloadedData - error:error - shouldInvalidateLocation:YES]; - return; - } - - [self setLocationURL:[NSURL URLWithString:locationURLStr]]; - - // we've now sent all of the initial post body data, so we need to include - // its size in future progress indicator callbacks - initialBodySent_ = initialBodyLength_; - - if (needsManualProgress_) { - [self reportProgressManually]; - } - - // just in case the user paused us during the initial fetch... - if (![self isPaused]) { - [self uploadNextChunkWithOffset:0]; - } -} - -- (void)retryFetch { - // Override the fetcher's retryFetch to retry with the saved delegateFinishedSEL_. - [self stopFetchReleasingCallbacks:NO]; - - [self beginFetchWithDelegate:delegate_ - didFinishSelector:delegateFinishedSEL_]; -} - -#pragma mark Chunk fetching methods - -- (void)uploadNextChunkWithOffset:(NSUInteger)offset { - // use the properties in each chunk fetcher - NSMutableDictionary *props = [self properties]; - - [self uploadNextChunkWithOffset:offset - fetcherProperties:props]; -} - -- (void)uploadNextChunkWithOffset:(NSUInteger)offset - fetcherProperties:(NSMutableDictionary *)props { - // upload another chunk - NSUInteger chunkSize = [self chunkSize]; - - NSString *rangeStr, *lengthStr; - NSData *chunkData; - - NSUInteger dataLen = [self fullUploadLength]; - - if (offset == kQueryServerForOffset) { - // resuming, so we'll initially send an empty data block and wait for the - // server to tell us where the current offset really is - chunkData = [NSData data]; - rangeStr = [NSString stringWithFormat:@"bytes */%llu", - (unsigned long long)dataLen]; - lengthStr = @"0"; - offset = 0; - } else { - // uploading the next data chunk - if (dataLen == 0) { -#if DEBUG - NSAssert(offset == 0, @"offset %llu for empty data length", (unsigned long long)offset); -#endif - chunkData = [NSData data]; - rangeStr = @"bytes */0"; - lengthStr = @"0"; - } else { -#if DEBUG - NSAssert(offset < dataLen , @"offset %llu exceeds data length %llu", - (unsigned long long)offset, (unsigned long long)dataLen); -#endif - NSUInteger thisChunkSize = chunkSize; - - // if the chunk size is bigger than the remaining data, or else - // it's close enough in size to the remaining data that we'd rather - // avoid having a whole extra http fetch for the leftover bit, then make - // this chunk size exactly match the remaining data size - BOOL isChunkTooBig = (thisChunkSize + offset > dataLen); - BOOL isChunkAlmostBigEnough = (dataLen - offset < thisChunkSize + 2500); - - if (isChunkTooBig || isChunkAlmostBigEnough) { - thisChunkSize = dataLen - offset; - } - - chunkData = [self uploadSubdataWithOffset:offset - length:thisChunkSize]; - - rangeStr = [NSString stringWithFormat:@"bytes %llu-%llu/%llu", - (unsigned long long)offset, - (unsigned long long)(offset + thisChunkSize - 1), - (unsigned long long)dataLen]; - lengthStr = [NSString stringWithFormat:@"%llu", - (unsigned long long)thisChunkSize]; - } - } - - // track the current offset for progress reporting - [self setCurrentOffset:offset]; - - // - // make the request for fetching - // - - // the chunk upload URL requires no authentication header - NSURL *locURL = [self locationURL]; - NSMutableURLRequest *chunkRequest = [NSMutableURLRequest requestWithURL:locURL]; - - [chunkRequest setHTTPMethod:@"PUT"]; - - // copy the user-agent from the original connection - NSURLRequest *origRequest = [self mutableRequest]; - NSString *userAgent = [origRequest valueForHTTPHeaderField:@"User-Agent"]; - if ([userAgent length] > 0) { - [chunkRequest setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - } - - [chunkRequest setValue:rangeStr forHTTPHeaderField:@"Content-Range"]; - [chunkRequest setValue:lengthStr forHTTPHeaderField:@"Content-Length"]; - - NSString *uploadMIMEType = [self uploadMIMEType]; - [chunkRequest setValue:uploadMIMEType forHTTPHeaderField:@"Content-Type"]; - - // - // make a new fetcher - // - GTMHTTPFetcher *chunkFetcher; - - chunkFetcher = [GTMHTTPFetcher fetcherWithRequest:chunkRequest]; - [chunkFetcher setDelegateQueue:[self delegateQueue]]; - [chunkFetcher setRunLoopModes:[self runLoopModes]]; - [chunkFetcher setAllowedInsecureSchemes:[self allowedInsecureSchemes]]; - [chunkFetcher setAllowLocalhostRequest:[self allowLocalhostRequest]]; - - // if the upload fetcher has a comment, use the same comment for chunks - NSString *baseComment = [self comment]; - if (baseComment) { - [chunkFetcher setCommentWithFormat:@"%@ (%@)", baseComment, rangeStr]; - } - - // give the chunk fetcher the same properties as the previous chunk fetcher - [chunkFetcher setProperties:props]; - - // post the appropriate subset of the full data - [chunkFetcher setPostData:chunkData]; - - // copy other fetcher settings to the new fetcher - [chunkFetcher setRetryEnabled:[self isRetryEnabled]]; - [chunkFetcher setMaxRetryInterval:[self maxRetryInterval]]; - [chunkFetcher setSentDataSelector:[self sentDataSelector]]; - [chunkFetcher setCookieStorageMethod:[self cookieStorageMethod]]; - - if ([self isRetryEnabled]) { - // we interpose our own retry method both so the sender is the upload - // fetcher, and so we can change the request to ask the server to - // tell us where to resume the chunk - [chunkFetcher setRetrySelector:@selector(chunkFetcher:willRetry:forError:)]; - } - - [self setMutableRequest:chunkRequest]; - - // when fetching chunks, a 308 status means "upload more chunks", but - // success (200 or 201 status) and other failures are no different than - // for the regular object fetchers - BOOL didFetch = [chunkFetcher beginFetchWithDelegate:self - didFinishSelector:@selector(chunkFetcher:finishedWithData:error:)]; - if (!didFetch) { - // something went horribly wrong, like the chunk upload URL is invalid - NSError *error = [NSError errorWithDomain:kGTMHTTPFetcherErrorDomain - code:kGTMHTTPFetcherErrorChunkUploadFailed - userInfo:nil]; - - [self invokeFinalCallbacksWithData:nil - error:error - shouldInvalidateLocation:YES]; - [self destroyChunkFetcher]; - } else { - // hang on to the fetcher in case we need to cancel it - [self setChunkFetcher:chunkFetcher]; - } -} - -- (void)reportProgressManually { - // reportProgressManually should be called only when there's no - // NSURLConnection support for sent data callbacks - - // the user wants upload progress, and there's no support in NSURLConnection - // for it, so we'll provide it here after each chunk - // - // the progress will be based on the uploadData and currentOffset, - // so we can pass zeros - [self uploadFetcher:self - didSendBytes:0 - totalBytesSent:0 -totalBytesExpectedToSend:0]; -} - -- (void)chunkFetcher:(GTMHTTPFetcher *)chunkFetcher finishedWithData:(NSData *)data error:(NSError *)error { - [self setStatusCode:[chunkFetcher statusCode]]; - [self setResponseHeaders:[chunkFetcher responseHeaders]]; - - if (error) { - int status = (int)[error code]; - - // status 308 is "resume incomplete", meaning we should get the offset - // from the Range header and upload the next chunk - // - // any other status really is an error - if (status == 308) { - [self handleResumeIncompleteStatusForChunkFetcher:chunkFetcher]; - return; - } else { - // some unexpected status has occurred; handle it as we would a regular - // object fetcher failure - error = [NSError errorWithDomain:kGTMHTTPFetcherStatusDomain - code:status - userInfo:nil]; - [self invokeFinalCallbacksWithData:data - error:error - shouldInvalidateLocation:NO]; - [self destroyChunkFetcher]; - return; - } - } else { - // the final chunk has uploaded successfully - #if DEBUG && !defined(NS_BLOCK_ASSERTIONS) - NSInteger status = [chunkFetcher statusCode]; - NSAssert1(status == 200 || status == 201, - @"unexpected chunks status %d", (int)status); - #endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) - - // take the chunk fetcher's data as our own - self.downloadedData = data; - - if (needsManualProgress_) { - // do a final upload progress report, indicating all of the chunk data - // has been sent - NSUInteger fullDataLength = [self fullUploadLength] + initialBodyLength_; - [self setCurrentOffset:fullDataLength]; - - [self reportProgressManually]; - } - - // we're done - [self invokeFinalCallbacksWithData:data - error:error - shouldInvalidateLocation:YES]; - - [self destroyChunkFetcher]; - } -} - -- (void)handleResumeIncompleteStatusForChunkFetcher:(GTMHTTPFetcher *)chunkFetcher { - - NSDictionary *responseHeaders = [chunkFetcher responseHeaders]; - - // parse the Range header from the server, since that tells us where we really - // want the next chunk to begin. - // - // lack of a range header means the server has no bytes stored for this upload - NSString *rangeStr = [responseHeaders objectForKey:@"Range"]; - NSUInteger newOffset = 0; - if (rangeStr != nil) { - // parse a content-range, like "bytes=0-999", to find where our new - // offset for uploading from the data really is (at the end of the - // range) - NSScanner *scanner = [NSScanner scannerWithString:rangeStr]; - long long rangeStart = 0, rangeEnd = 0; - if ([scanner scanString:@"bytes=" intoString:nil] - && [scanner scanLongLong:&rangeStart] - && [scanner scanString:@"-" intoString:nil] - && [scanner scanLongLong:&rangeEnd]) { - newOffset = (NSUInteger)rangeEnd + 1; - } - } - - [self setCurrentOffset:newOffset]; - - if (needsManualProgress_) { - [self reportProgressManually]; - } - - // if the response specifies a location, use that for future chunks - NSString *locationURLStr = [responseHeaders objectForKey:@"Location"]; - if ([locationURLStr length] > 0) { - [self setLocationURL:[NSURL URLWithString:locationURLStr]]; - } - - // we want to destroy this chunk fetcher before creating the next one, but - // we want to pass on its properties - NSMutableDictionary *props = [[[chunkFetcher properties] retain] autorelease]; - - // we no longer need to be able to cancel this chunkFetcher - [self destroyChunkFetcher]; - - // We may in the future handle Retry-After and ETag headers per - // http://code.google.com/p/gears/wiki/ResumableHttpRequestsProposal - // but they are not currently sent by the upload server - - [self uploadNextChunkWithOffset:newOffset - fetcherProperties:props]; -} - - --(BOOL)chunkFetcher:(GTMHTTPFetcher *)chunkFetcher willRetry:(BOOL)willRetry forError:(NSError *)error { - if ([error code] == 308 - && [[error domain] isEqual:kGTMHTTPFetcherStatusDomain]) { - // 308 is a normal chunk fethcher response, not an error - // that needs to be retried - return NO; - } - - if (delegate_ && retrySel_) { - - // call the client with the upload fetcher as the sender (not the chunk - // fetcher) to find out if it wants to retry - willRetry = [self invokeRetryCallback:retrySel_ - target:delegate_ - willRetry:willRetry - error:error]; - } - -#if NS_BLOCKS_AVAILABLE - if (retryBlock_) { - willRetry = retryBlock_(willRetry, error); - } -#endif - - if (willRetry) { - // change the request being retried into a query to the server to - // tell us where to resume - NSMutableURLRequest *chunkRequest = [chunkFetcher mutableRequest]; - - NSUInteger dataLen = [self fullUploadLength]; - NSString *rangeStr = [NSString stringWithFormat:@"bytes */%llu", - (unsigned long long)dataLen]; - - [chunkRequest setValue:rangeStr forHTTPHeaderField:@"Content-Range"]; - [chunkRequest setValue:@"0" forHTTPHeaderField:@"Content-Length"]; - [chunkFetcher setPostData:[NSData data]]; - - // we don't know what our actual offset is anymore, but the server - // will tell us - [self setCurrentOffset:0]; - } - - return willRetry; -} - -- (void)destroyChunkFetcher { - [chunkFetcher_ stopFetching]; - [chunkFetcher_ setProperties:nil]; - [chunkFetcher_ autorelease]; - chunkFetcher_ = nil; -} - -// the chunk fetchers use this as their sentData method -- (void)uploadFetcher:(GTMHTTPFetcher *)chunkFetcher - didSendBytes:(NSInteger)bytesSent - totalBytesSent:(NSInteger)totalBytesSent -totalBytesExpectedToSend:(NSInteger)totalBytesExpected { - // the actual total bytes sent include the initial XML sent, plus the - // offset into the batched data prior to this fetcher - totalBytesSent += initialBodySent_ + currentOffset_; - - // the total bytes expected include the initial XML and the full chunked - // data, independent of how big this fetcher's chunk is - totalBytesExpected = (NSInteger)(initialBodyLength_ + [self fullUploadLength]); - - if (delegate_ && delegateSentDataSEL_) { - // ensure the chunk fetcher survives the callback in case the user pauses - // the upload process - [[chunkFetcher retain] autorelease]; - - [self invokeSentDataCallback:delegateSentDataSEL_ - target:delegate_ - didSendBodyData:bytesSent - totalBytesWritten:totalBytesSent - totalBytesExpectedToWrite:totalBytesExpected]; - } - -#if NS_BLOCKS_AVAILABLE - if (sentDataBlock_) { - sentDataBlock_(bytesSent, totalBytesSent, totalBytesExpected); - } -#endif -} - -#pragma mark - - -- (BOOL)isPaused { - return isPaused_; -} - -- (void)pauseFetching { - isPaused_ = YES; - - // pausing just means stopping the current chunk from uploading; - // when we resume, the magic offset value will force us to send - // a request to the server to figure out what bytes to start sending - // - // we won't try to cancel the initial data upload, but rather will look for - // the magic offset value in -connectionDidFinishLoading before - // creating first initial chunk fetcher, just in case the user - // paused during the initial data upload - [self destroyChunkFetcher]; -} - -- (void)resumeFetching { - if (isPaused_) { - isPaused_ = NO; - - [self uploadNextChunkWithOffset:kQueryServerForOffset]; - } -} - -- (void)stopFetching { - // overrides the superclass - [self destroyChunkFetcher]; - - [super stopFetching]; -} - -#pragma mark - - -@synthesize uploadData = uploadData_, - uploadFileHandle = uploadFileHandle_, - uploadMIMEType = uploadMIMEType_, - chunkSize = chunkSize_, - currentOffset = currentOffset_, - chunkFetcher = chunkFetcher_; - -#if NS_BLOCKS_AVAILABLE -@synthesize locationChangeBlock = locationChangeBlock_; -#endif - -@dynamic activeFetcher; -@dynamic responseHeaders; -@dynamic statusCode; - -- (NSDictionary *)responseHeaders { - // overrides the superclass - - // if asked for the fetcher's response, use the most recent fetcher - if (responseHeaders_) { - return responseHeaders_; - } else { - // no chunk fetcher yet completed, so return whatever we have from the - // initial fetch - return [super responseHeaders]; - } -} - -- (void)setResponseHeaders:(NSDictionary *)dict { - [responseHeaders_ autorelease]; - responseHeaders_ = [dict retain]; -} - -- (NSInteger)statusCode { - if (statusCode_ != -1) { - // overrides the superclass to indicate status appropriate to the initial - // or latest chunk fetch - return statusCode_; - } else { - return [super statusCode]; - } -} - -- (void)setStatusCode:(NSInteger)val { - statusCode_ = val; -} - -- (SEL)sentDataSelector { - // overrides the superclass -#if NS_BLOCKS_AVAILABLE - BOOL hasSentDataBlock = (sentDataBlock_ != NULL); -#else - BOOL hasSentDataBlock = NO; -#endif - if ((delegateSentDataSEL_ || hasSentDataBlock) && !needsManualProgress_) { - return @selector(uploadFetcher:didSendBytes:totalBytesSent:totalBytesExpectedToSend:); - } else { - return NULL; - } -} - -- (void)setSentDataSelector:(SEL)theSelector { - // overrides the superclass - delegateSentDataSEL_ = theSelector; -} - -- (GTMHTTPFetcher *)activeFetcher { - if (chunkFetcher_) { - return chunkFetcher_; - } else { - return self; - } -} - -- (NSURL *)locationURL { - return locationURL_; -} - -- (void)setLocationURL:(NSURL *)url { - if (url != locationURL_) { - [locationURL_ release]; - locationURL_ = [url retain]; - -#if NS_BLOCKS_AVAILABLE - if (locationChangeBlock_) { - locationChangeBlock_(url); - } -#endif - } -} -@end - -#endif // #if !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMMIMEDocument.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMMIMEDocument.h deleted file mode 100644 index 62b037b04..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMMIMEDocument.h +++ /dev/null @@ -1,57 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -// This is a simple class to create a MIME document. To use, allocate -// a new GTMMIMEDocument and start adding parts as necessary. When you are -// done adding parts, call generateInputStream to get an NSInputStream -// containing the contents of your MIME document. -// -// A good reference for MIME is http://en.wikipedia.org/wiki/MIME - -#import - -#if defined(GTL_TARGET_NAMESPACE) - // we're using target namespace macros - #import "GTLDefines.h" -#elif defined(GDATA_TARGET_NAMESPACE) - #import "GDataDefines.h" -#endif - -@interface GTMMIMEDocument : NSObject { - NSMutableArray* parts_; // Contains an ordered set of MimeParts - unsigned long long length_; // Length in bytes of the document. - u_int32_t randomSeed_; // for testing -} - -+ (GTMMIMEDocument *)MIMEDocument; - -// Adds a new part to this mime document with the given headers and body. The -// headers keys and values should be NSStrings -- (void)addPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body; - -// An inputstream that can be used to efficiently read the contents of the -// mime document. -- (void)generateInputStream:(NSInputStream **)outStream - length:(unsigned long long*)outLength - boundary:(NSString **)outBoundary; - -// ------ UNIT TESTING ONLY BELOW ------ - -// For unittesting only, seeds the random number generator -- (void)seedRandomWith:(u_int32_t)seed; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMMIMEDocument.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMMIMEDocument.m deleted file mode 100644 index 38b9c25bd..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMMIMEDocument.m +++ /dev/null @@ -1,281 +0,0 @@ -/* Copyright (c) 2010 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#import "GTMMIMEDocument.h" -#import "GTMGatherInputStream.h" - -// memsrch -// -// Helper routine to search for the existence of a set of bytes (needle) within -// a presumed larger set of bytes (haystack). -// -static BOOL memsrch(const unsigned char* needle, NSUInteger needle_len, - const unsigned char* haystack, NSUInteger haystack_len); - -@interface GTMMIMEPart : NSObject { - NSData* headerData_; // Header content including the ending "\r\n". - NSData* bodyData_; // The body data. -} - -+ (GTMMIMEPart *)partWithHeaders:(NSDictionary *)headers body:(NSData *)body; -- (id)initWithHeaders:(NSDictionary *)headers body:(NSData *)body; -- (BOOL)containsBytes:(const unsigned char *)bytes length:(NSUInteger)length; -- (NSData *)header; -- (NSData *)body; -- (NSUInteger)length; -@end - -@implementation GTMMIMEPart - -+ (GTMMIMEPart *)partWithHeaders:(NSDictionary *)headers body:(NSData *)body { - - return [[[self alloc] initWithHeaders:headers - body:body] autorelease]; -} - -- (id)initWithHeaders:(NSDictionary *)headers - body:(NSData *)body { - - if ((self = [super init]) != nil) { - - bodyData_ = [body retain]; - - // generate the header data by coalescing the dictionary as - // lines of "key: value\r\m" - NSMutableString* headerString = [NSMutableString string]; - - // sort the header keys so we have a deterministic order for - // unit testing - SEL sortSel = @selector(caseInsensitiveCompare:); - NSArray *sortedKeys = [[headers allKeys] sortedArrayUsingSelector:sortSel]; - - for (NSString *key in sortedKeys) { - NSString* value = [headers objectForKey:key]; - -#if DEBUG && !defined(NS_BLOCK_ASSERTIONS) - // look for troublesome characters in the header keys & values - static NSCharacterSet *badChars = nil; - if (!badChars) { - badChars = [[NSCharacterSet characterSetWithCharactersInString:@":\r\n"] retain]; - } - - NSRange badRange = [key rangeOfCharacterFromSet:badChars]; - NSAssert1(badRange.location == NSNotFound, @"invalid key: %@", key); - - badRange = [value rangeOfCharacterFromSet:badChars]; - NSAssert1(badRange.location == NSNotFound, @"invalid value: %@", value); -#endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) - - [headerString appendFormat:@"%@: %@\r\n", key, value]; - } - - // headers end with an extra blank line - [headerString appendString:@"\r\n"]; - - headerData_ = [[headerString dataUsingEncoding:NSUTF8StringEncoding] retain]; - } - return self; -} - -- (void) dealloc { - [headerData_ release]; - [bodyData_ release]; - [super dealloc]; -} - -// Returns true if the parts contents contain the given set of bytes. -// -// NOTE: We assume that the 'bytes' we are checking for do not contain "\r\n", -// so we don't need to check the concatenation of the header and body bytes. -- (BOOL)containsBytes:(const unsigned char*)bytes length:(NSUInteger)length { - - // This uses custom memsrch() rather than strcpy because the encoded data may - // contain null values. - return memsrch(bytes, length, [headerData_ bytes], [headerData_ length]) || - memsrch(bytes, length, [bodyData_ bytes], [bodyData_ length]); -} - -- (NSData *)header { - return headerData_; -} - -- (NSData *)body { - return bodyData_; -} - -- (NSUInteger)length { - return [headerData_ length] + [bodyData_ length]; -} -@end - -@implementation GTMMIMEDocument - -+ (GTMMIMEDocument *)MIMEDocument { - return [[[self alloc] init] autorelease]; -} - -- (id)init { - if ((self = [super init]) != nil) { - - parts_ = [[NSMutableArray alloc] init]; - - // Seed the random number generator used to generate mime boundaries - srandomdev(); - } - return self; -} - -- (void)dealloc { - [parts_ release]; - [super dealloc]; -} - -// Adds a new part to this mime document with the given headers and body. -- (void)addPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body { - - GTMMIMEPart* part = [GTMMIMEPart partWithHeaders:headers body:body]; - [parts_ addObject:part]; -} - -// For unit testing only, seeds the random number generator so that we will -// have reproducible boundary strings. -- (void)seedRandomWith:(u_int32_t)seed { - randomSeed_ = seed; -} - -- (u_int32_t)random { - if (randomSeed_) { - // for testing only - return randomSeed_++; - } else { - return arc4random(); - } -} - -// Computes the mime boundary to use. This should only be called -// after all the desired document parts have been added since it must compute -// a boundary that does not exist in the document data. -- (NSString *)uniqueBoundary { - - // use an easily-readable boundary string - NSString *const kBaseBoundary = @"END_OF_PART"; - - NSString *boundary = kBaseBoundary; - - // if the boundary isn't unique, append random numbers, up to 10 attempts; - // if that's still not unique, use a random number sequence instead, - // and call it good - BOOL didCollide = NO; - - const int maxTries = 10; // Arbitrarily chosen maximum attempts. - for (int tries = 0; tries < maxTries; ++tries) { - - NSData *data = [boundary dataUsingEncoding:NSUTF8StringEncoding]; - const void *dataBytes = [data bytes]; - NSUInteger dataLen = [data length]; - - for (GTMMIMEPart *part in parts_) { - didCollide = [part containsBytes:dataBytes length:dataLen]; - if (didCollide) break; - } - - if (!didCollide) break; // we're fine, no more attempts needed - - // try again with a random number appended - boundary = [NSString stringWithFormat:@"%@_%08x", kBaseBoundary, - [self random]]; - } - - if (didCollide) { - // fallback... two random numbers - boundary = [NSString stringWithFormat:@"%08x_tedborg_%08x", - [self random], [self random]]; - } - - return boundary; -} - -- (void)generateInputStream:(NSInputStream **)outStream - length:(unsigned long long*)outLength - boundary:(NSString **)outBoundary { - - // The input stream is of the form: - // --boundary - // [part_1_headers] - // [part_1_data] - // --boundary - // [part_2_headers] - // [part_2_data] - // --boundary-- - - // First we set up our boundary NSData objects. - NSString *boundary = [self uniqueBoundary]; - - NSString *mainBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n", boundary]; - NSString *endBoundary = [NSString stringWithFormat:@"\r\n--%@--\r\n", boundary]; - - NSData *mainBoundaryData = [mainBoundary dataUsingEncoding:NSUTF8StringEncoding]; - NSData *endBoundaryData = [endBoundary dataUsingEncoding:NSUTF8StringEncoding]; - - // Now we add them all in proper order to our dataArray. - NSMutableArray* dataArray = [NSMutableArray array]; - unsigned long long length = 0; - - for (GTMMIMEPart* part in parts_) { - [dataArray addObject:mainBoundaryData]; - [dataArray addObject:[part header]]; - [dataArray addObject:[part body]]; - - length += [part length] + [mainBoundaryData length]; - } - - [dataArray addObject:endBoundaryData]; - length += [endBoundaryData length]; - - if (outLength) *outLength = length; - if (outStream) *outStream = [GTMGatherInputStream streamWithArray:dataArray]; - if (outBoundary) *outBoundary = boundary; -} - -@end - - -// memsrch - Return YES if needle is found in haystack, else NO. -static BOOL memsrch(const unsigned char* needle, NSUInteger needleLen, - const unsigned char* haystack, NSUInteger haystackLen) { - - // This is a simple approach. We start off by assuming that both memchr() and - // memcmp are implemented efficiently on the given platform. We search for an - // instance of the first char of our needle in the haystack. If the remaining - // size could fit our needle, then we memcmp to see if it occurs at this point - // in the haystack. If not, we move on to search for the first char again, - // starting from the next character in the haystack. - const unsigned char* ptr = haystack; - NSUInteger remain = haystackLen; - while ((ptr = memchr(ptr, needle[0], remain)) != 0) { - remain = haystackLen - (NSUInteger)(ptr - haystack); - if (remain < needleLen) { - return NO; - } - if (memcmp(ptr, needle, needleLen) == 0) { - return YES; - } - ptr++; - remain--; - } - return NO; -} diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMReadMonitorInputStream.h b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMReadMonitorInputStream.h deleted file mode 100644 index 9e4b3f78d..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMReadMonitorInputStream.h +++ /dev/null @@ -1,65 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import - - -// Define only for Mac OS X 10.6+ or iPhone OS 4.0+. -#ifndef GTM_NSSTREAM_DELEGATE - #if (TARGET_OS_MAC && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED >= 1060)) || \ - (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED >= 40000)) - #define GTM_NSSTREAM_DELEGATE - #else - #define GTM_NSSTREAM_DELEGATE - #endif -#endif // !defined(GTM_NSSTREAM_DELEGATE) - -#ifdef GTM_TARGET_NAMESPACE - // we're using target namespace macros - #import "GTMDefines.h" -#endif - -@interface GTMReadMonitorInputStream : NSInputStream GTM_NSSTREAM_DELEGATE { - @protected - NSInputStream *inputStream_; // encapsulated stream that does the work - - NSThread *thread_; // thread in which this object was created - NSArray *runLoopModes_; // modes for calling callbacks, when necessary - - @private - id readDelegate_; - SEL readSelector_; -} - -// length is passed to the progress callback; it may be zero -// if the progress callback can handle that -+ (id)inputStreamWithStream:(NSInputStream *)input; - -- (id)initWithStream:(NSInputStream *)input; - -// The read monitor selector is called when bytes have been read. It should -// have a signature matching -// -// - (void)inputStream:(GTMReadMonitorInputStream *)stream -// readIntoBuffer:(uint8_t *)buffer -// length:(NSUInteger)length; - -@property (assign) id readDelegate; // WEAK -@property (assign) SEL readSelector; - -// Modes for invoking callbacks, when necessary -@property (retain) NSArray *runLoopModes; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMReadMonitorInputStream.m b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMReadMonitorInputStream.m deleted file mode 100644 index 4a85de50b..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/GTMReadMonitorInputStream.m +++ /dev/null @@ -1,189 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import "GTMReadMonitorInputStream.h" - -@interface GTMReadMonitorInputStream () -- (void)invokeReadSelectorWithBuffer:(NSData *)data; -@end - -@implementation GTMReadMonitorInputStream - -@synthesize readDelegate = readDelegate_; -@synthesize readSelector = readSelector_; -@synthesize runLoopModes = runLoopModes_; - -// We'll forward all unhandled messages to the NSInputStream class -// or to the encapsulated input stream. This is needed -// for all messages sent to NSInputStream which aren't -// handled by our superclass; that includes various private run -// loop calls. -+ (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { - return [NSInputStream methodSignatureForSelector:selector]; -} - -+ (void)forwardInvocation:(NSInvocation*)invocation { - [invocation invokeWithTarget:[NSInputStream class]]; -} - -- (BOOL)respondsToSelector:(SEL)selector { - return [inputStream_ respondsToSelector:selector]; -} - -- (NSMethodSignature*)methodSignatureForSelector:(SEL)selector { - return [inputStream_ methodSignatureForSelector:selector]; -} - -- (void)forwardInvocation:(NSInvocation*)invocation { - [invocation invokeWithTarget:inputStream_]; -} - -#pragma mark - - -+ (id)inputStreamWithStream:(NSInputStream *)input { - return [[[self alloc] initWithStream:input] autorelease]; -} - -- (id)initWithStream:(NSInputStream *)input { - self = [super init]; - if (self) { - inputStream_ = [input retain]; - thread_ = [[NSThread currentThread] retain]; - } - return self; -} - -- (id)init { - return [self initWithStream:nil]; -} - -- (void)dealloc { - [inputStream_ release]; - [thread_ release]; - [runLoopModes_ release]; - [super dealloc]; -} - -#pragma mark - - -- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len { - // Read from the encapsulated stream - NSInteger numRead = [inputStream_ read:buffer maxLength:len]; - if (numRead > 0) { - - BOOL isOnOriginalThread = [thread_ isEqual:[NSThread currentThread]]; - - if (readDelegate_ && readSelector_) { - // call the read selector with the buffer and number of bytes actually - // read into it - SEL sel = @selector(invokeReadSelectorWithBuffer:); - - if (isOnOriginalThread) { - // invoke immediately - NSData *data = [NSData dataWithBytesNoCopy:buffer - length:(NSUInteger)numRead - freeWhenDone:NO]; - [self performSelector:sel withObject:data]; - } else { - // copy the buffer into an NSData to be retained by the - // performSelector, and invoke on the proper thread - NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numRead]; - if (runLoopModes_) { - [self performSelector:sel - onThread:thread_ - withObject:data - waitUntilDone:NO - modes:runLoopModes_]; - } else { - [self performSelector:sel - onThread:thread_ - withObject:data - waitUntilDone:NO]; - } - } - } - } - - return numRead; -} - -- (void)invokeReadSelectorWithBuffer:(NSData *)data { - const void *buffer = [data bytes]; - NSUInteger length = [data length]; - - NSMethodSignature *signature = [readDelegate_ methodSignatureForSelector:readSelector_]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; - [invocation setSelector:readSelector_]; - [invocation setTarget:readDelegate_]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&buffer atIndex:3]; - [invocation setArgument:&length atIndex:4]; - [invocation invoke]; -} - -- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len { - return [inputStream_ getBuffer:buffer length:len]; -} - -- (BOOL)hasBytesAvailable { - return [inputStream_ hasBytesAvailable]; -} - -#pragma mark Standard messages - -// Pass expected messages to our encapsulated stream. -// -// We want our encapsulated NSInputStream to handle the standard messages; -// we don't want the superclass to handle them. -- (void)open { - [inputStream_ open]; -} - -- (void)close { - [inputStream_ close]; -} - -- (id)delegate { - return [inputStream_ delegate]; -} - -- (void)setDelegate:(id)delegate { - [inputStream_ setDelegate:delegate]; -} - -- (id)propertyForKey:(NSString *)key { - return [inputStream_ propertyForKey:key]; -} -- (BOOL)setProperty:(id)property forKey:(NSString *)key { - return [inputStream_ setProperty:property forKey:key]; -} - -- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { - [inputStream_ scheduleInRunLoop:aRunLoop forMode:mode]; -} - -- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { - [inputStream_ removeFromRunLoop:aRunLoop forMode:mode]; -} - -- (NSStreamStatus)streamStatus { - return [inputStream_ streamStatus]; -} - -- (NSError *)streamError { - return [inputStream_ streamError]; -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/ReleaseNotes.txt b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/ReleaseNotes.txt deleted file mode 100644 index cb2d97063..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/ReleaseNotes.txt +++ /dev/null @@ -1,84 +0,0 @@ -GTM HTTP Fetcher Release Notes - -Project site: http://code.google.com/p/gtm-http-fetcher/ -Discussion group: http://groups.google.com/group/google-toolbox-for-mac - -28-September-2012 - -Added delegateQueue support to fetcher and fetcher service, allowing fetches -to begin on a thread without a run loop and to invoke callbacks on the main -thread or a background thread, beginning with iOS 6 and Mac OS X 10.7. - - -9-January-2012 - -Fetcher now includes user-agent string utility functions - -Fetcher service has properties for request userAgent and timeout - - -22-November-2011 - -Fetchers now support a servicePriority property which affects the order in -which the fetcher service object dequeues delayed fetchers - - -1-November-2011 - -On status 401 results when using an authorizer, the fetcher will attempt a -single retry if the authorizer implements a primeForRefresh method - - -7-October-2011 - -Changed isFetching method to return YES during service and authorization delays - - -9-September-2011 - -Added support for creating an upload fetcher from a location URL to allow -restarting uploads with a new upload fetcher instance - - -18-August-2011 - -Added GTMReadMonitorInputStream for logging uploaded NSInputStreams - - -8-July-2011 - -Added shouldFetchInBackground property (thanks justin a) - - -24-Mar-2011 - -Added authorizer support - - -7-Feb-2011 - -Made cookies set by a redirect immediately available in the new request (thanks ehoracek) -Added getter for static cookie storage - - -16-Nov-2010 - -Added fetcher comment property for logging - - -27-Oct-2010 - -Added downloadPath and downloadFileHandle properties -Added waitForCompletionWithTimeout: -Renamed GTMAssertSelectorNilOrImplementedWithArgs() - - -4-Oct-2010 - -Ensure that delegate is nil when not retained. - - -Release 1.0.0 -9-Sept-2010 - -Initial public release. diff --git a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/UnitTests-Info.plist b/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/UnitTests-Info.plist deleted file mode 100644 index c285a472c..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/HTTPFetcher/UnitTests-Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - com.yourcompany.${PRODUCT_NAME:rfc1034identifier} - CFBundleInfoDictionaryVersion - 6.0 - CFBundlePackageType - BNDL - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1 - - diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/JSON.h b/Paco-iOS/vendor/gtm-oauth2/JSON/JSON.h deleted file mode 100644 index db3c516db..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/JSON.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (C) 2009-2010 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -/** - @mainpage A strict JSON parser and generator for Objective-C - - JSON (JavaScript Object Notation) is a lightweight data-interchange - format. This framework provides two apis for parsing and generating - JSON. One standard object-based and a higher level api consisting of - categories added to existing Objective-C classes. - - This framework does its best to be as strict as possible, both in what it accepts and what it generates. For example, it does not support trailing commas in arrays or objects. Nor does it support embedded comments, or anything else not in the JSON specification. This is considered a feature. - - @section Links - - @li Project home page. - @li Online version of the API documentation. - -*/ - - -// This setting of 1 is best if you copy the source into your project. -// The build transforms the 1 to a 0 when building the framework and static lib. - -#if 1 - -#import "SBJsonParser.h" -#import "SBJsonWriter.h" -#import "NSObject+SBJSON.h" -#import "NSString+SBJSON.h" - -#else - -#import -#import -#import -#import - -#endif diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/NSObject+SBJSON.h b/Paco-iOS/vendor/gtm-oauth2/JSON/NSObject+SBJSON.h deleted file mode 100644 index 8e9620e68..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/NSObject+SBJSON.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import - - -/** - @brief Adds JSON generation to Foundation classes - - This is a category on NSObject that adds methods for returning JSON representations - of standard objects to the objects themselves. This means you can call the - -JSONRepresentation method on an NSArray object and it'll do what you want. - */ -@interface NSObject (NSObject_SBJSON) - -/** - @brief Returns a string containing the receiver encoded in JSON. - - This method is added as a category on NSObject but is only actually - supported for the following objects: - @li NSDictionary - @li NSArray - */ -- (NSString *)JSONRepresentation; - -@end - diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/NSObject+SBJSON.m b/Paco-iOS/vendor/gtm-oauth2/JSON/NSObject+SBJSON.m deleted file mode 100644 index 30570b593..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/NSObject+SBJSON.m +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "NSObject+SBJSON.h" -#import "SBJsonWriter.h" - -@implementation NSObject (NSObject_SBJSON) - -- (NSString *)JSONRepresentation { - SBJsonWriter *jsonWriter = [SBJsonWriter new]; - NSString *json = [jsonWriter stringWithObject:self]; - if (!json) - NSLog(@"-JSONRepresentation failed. Error trace is: %@", [jsonWriter errorTrace]); - [jsonWriter release]; - return json; -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/NSString+SBJSON.h b/Paco-iOS/vendor/gtm-oauth2/JSON/NSString+SBJSON.h deleted file mode 100644 index 029aa309d..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/NSString+SBJSON.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import - -/** - @brief Adds JSON parsing methods to NSString - -This is a category on NSString that adds methods for parsing the target string. -*/ -@interface NSString (NSString_SBJSON) - -/** - @brief Returns the NSDictionary or NSArray represented by the current string's JSON representation. - - Returns the dictionary or array represented in the receiver, or nil on error. - - Returns the NSDictionary or NSArray represented by the current string's JSON representation. - */ -- (id)JSONValue; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/NSString+SBJSON.m b/Paco-iOS/vendor/gtm-oauth2/JSON/NSString+SBJSON.m deleted file mode 100644 index bb132e1eb..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/NSString+SBJSON.m +++ /dev/null @@ -1,45 +0,0 @@ -/* - Copyright (C) 2007-2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "NSString+SBJSON.h" -#import "SBJsonParser.h" - -@implementation NSString (NSString_SBJSON) - -- (id)JSONValue -{ - SBJsonParser *jsonParser = [SBJsonParser new]; - id repr = [jsonParser objectWithString:self]; - if (!repr) - NSLog(@"-JSONValue failed. Error trace is: %@", [jsonParser errorTrace]); - [jsonParser release]; - return repr; -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonBase.h b/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonBase.h deleted file mode 100644 index 7b108440f..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonBase.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import - -extern NSString * SBJSONErrorDomain; - - -enum { - EUNSUPPORTED = 1, - EPARSENUM, - EPARSE, - EFRAGMENT, - ECTRL, - EUNICODE, - EDEPTH, - EESCAPE, - ETRAILCOMMA, - ETRAILGARBAGE, - EEOF, - EINPUT -}; - -/** - @brief Common base class for parsing & writing. - - This class contains the common error-handling code and option between the parser/writer. - */ -@interface SBJsonBase : NSObject { - NSMutableArray *errorTrace; - -@protected - NSUInteger depth, maxDepth; -} - -/** - @brief The maximum recursing depth. - - Defaults to 512. If the input is nested deeper than this the input will be deemed to be - malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can - turn off this security feature by setting the maxDepth value to 0. - */ -@property NSUInteger maxDepth; - -/** - @brief Return an error trace, or nil if there was no errors. - - Note that this method returns the trace of the last method that failed. - You need to check the return value of the call you're making to figure out - if the call actually failed, before you know call this method. - */ - @property(copy,readonly) NSArray* errorTrace; - -/// @internal for use in subclasses to add errors to the stack trace -- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str; - -/// @internal for use in subclasess to clear the error before a new parsing attempt -- (void)clearErrorTrace; - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonBase.m b/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonBase.m deleted file mode 100644 index 6684325d1..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonBase.m +++ /dev/null @@ -1,78 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "SBJsonBase.h" -NSString * SBJSONErrorDomain = @"org.brautaset.JSON.ErrorDomain"; - - -@implementation SBJsonBase - -@synthesize errorTrace; -@synthesize maxDepth; - -- (id)init { - self = [super init]; - if (self) - self.maxDepth = 512; - return self; -} - -- (void)dealloc { - [errorTrace release]; - [super dealloc]; -} - -- (void)addErrorWithCode:(NSUInteger)code description:(NSString*)str { - NSDictionary *userInfo; - if (!errorTrace) { - errorTrace = [NSMutableArray new]; - userInfo = [NSDictionary dictionaryWithObject:str forKey:NSLocalizedDescriptionKey]; - - } else { - userInfo = [NSDictionary dictionaryWithObjectsAndKeys: - str, NSLocalizedDescriptionKey, - [errorTrace lastObject], NSUnderlyingErrorKey, - nil]; - } - - NSError *error = [NSError errorWithDomain:SBJSONErrorDomain code:code userInfo:userInfo]; - - [self willChangeValueForKey:@"errorTrace"]; - [errorTrace addObject:error]; - [self didChangeValueForKey:@"errorTrace"]; -} - -- (void)clearErrorTrace { - [self willChangeValueForKey:@"errorTrace"]; - [errorTrace release]; - errorTrace = nil; - [self didChangeValueForKey:@"errorTrace"]; -} - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonParser.h b/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonParser.h deleted file mode 100644 index feaccd863..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonParser.h +++ /dev/null @@ -1,86 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import -#import "SBJsonBase.h" - -/** - @brief The JSON parser class. - - JSON is mapped to Objective-C types in the following way: - - @li Null -> NSNull - @li String -> NSMutableString - @li Array -> NSMutableArray - @li Object -> NSMutableDictionary - @li Boolean -> NSNumber (initialised with -initWithBool:) - @li Number -> (NSNumber | NSDecimalNumber) - - Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber - instances. These are initialised with the -initWithBool: method, and - round-trip back to JSON properly. (They won't silently suddenly become 0 or 1; they'll be - represented as 'true' and 'false' again.) - - As an optimisation short JSON integers turn into NSNumber instances, while complex ones turn into NSDecimalNumber instances. - We can thus avoid any loss of precision as JSON allows ridiculously large numbers. - - */ -@interface SBJsonParser : SBJsonBase { - -@private - const char *c; -} - -/** - @brief Return the object represented by the given string - - Returns the object represented by the passed-in string or nil on error. The returned object can be - a string, number, boolean, null, array or dictionary. - - @param repr the json string to parse - */ -- (id)objectWithString:(NSString *)repr; - -/** - @brief Return the object represented by the given string - - Returns the object represented by the passed-in string or nil on error. The returned object can be - a string, number, boolean, null, array or dictionary. - - @param jsonText the json string to parse - @param error pointer to an NSError object to populate on error - */ - -- (id)objectWithString:(NSString*)jsonText - error:(NSError**)error; - - -@end - - diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonParser.m b/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonParser.m deleted file mode 100644 index 222ef7038..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonParser.m +++ /dev/null @@ -1,516 +0,0 @@ -/* - Copyright (C) 2009,2010 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "SBJsonParser.h" - -@interface SBJsonParser () - -- (BOOL)scanValue:(NSObject **)o; - -- (BOOL)scanRestOfArray:(NSMutableArray **)o; -- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o; -- (BOOL)scanRestOfNull:(NSNull **)o; -- (BOOL)scanRestOfFalse:(NSNumber **)o; -- (BOOL)scanRestOfTrue:(NSNumber **)o; -- (BOOL)scanRestOfString:(NSMutableString **)o; - -// Cannot manage without looking at the first digit -- (BOOL)scanNumber:(NSNumber **)o; - -- (BOOL)scanHexQuad:(unichar *)x; -- (BOOL)scanUnicodeChar:(unichar *)x; - -- (BOOL)scanIsAtEnd; - -@end - -#define skipWhitespace(c) while (isspace(*c)) c++ -#define skipDigits(c) while (isdigit(*c)) c++ - - -@implementation SBJsonParser - -static char ctrl[0x22]; - - -+ (void)initialize { - ctrl[0] = '\"'; - ctrl[1] = '\\'; - for (int i = 1; i < 0x20; i++) - ctrl[i+1] = i; - ctrl[0x21] = 0; -} - -- (id)objectWithString:(NSString *)repr { - [self clearErrorTrace]; - - if (!repr) { - [self addErrorWithCode:EINPUT description:@"Input was 'nil'"]; - return nil; - } - - depth = 0; - c = [repr UTF8String]; - - id o; - if (![self scanValue:&o]) { - return nil; - } - - // We found some valid JSON. But did it also contain something else? - if (![self scanIsAtEnd]) { - [self addErrorWithCode:ETRAILGARBAGE description:@"Garbage after JSON"]; - return nil; - } - - NSAssert1(o, @"Should have a valid object from %@", repr); - - // Check that the object we've found is a valid JSON container. - if (![o isKindOfClass:[NSDictionary class]] && ![o isKindOfClass:[NSArray class]]) { - [self addErrorWithCode:EFRAGMENT description:@"Valid fragment, but not JSON"]; - return nil; - } - - return o; -} - -- (id)objectWithString:(NSString*)repr error:(NSError**)error { - id tmp = [self objectWithString:repr]; - if (tmp) - return tmp; - - if (error) - *error = [self.errorTrace lastObject]; - return nil; -} - - -/* - In contrast to the public methods, it is an error to omit the error parameter here. - */ -- (BOOL)scanValue:(NSObject **)o -{ - skipWhitespace(c); - - switch (*c++) { - case '{': - return [self scanRestOfDictionary:(NSMutableDictionary **)o]; - break; - case '[': - return [self scanRestOfArray:(NSMutableArray **)o]; - break; - case '"': - return [self scanRestOfString:(NSMutableString **)o]; - break; - case 'f': - return [self scanRestOfFalse:(NSNumber **)o]; - break; - case 't': - return [self scanRestOfTrue:(NSNumber **)o]; - break; - case 'n': - return [self scanRestOfNull:(NSNull **)o]; - break; - case '-': - case '0'...'9': - c--; // cannot verify number correctly without the first character - return [self scanNumber:(NSNumber **)o]; - break; - case '+': - [self addErrorWithCode:EPARSENUM description: @"Leading + disallowed in number"]; - return NO; - break; - case 0x0: - [self addErrorWithCode:EEOF description:@"Unexpected end of string"]; - return NO; - break; - default: - [self addErrorWithCode:EPARSE description: @"Unrecognised leading character"]; - return NO; - break; - } - - NSAssert(0, @"Should never get here"); - return NO; -} - -- (BOOL)scanRestOfTrue:(NSNumber **)o -{ - if (!strncmp(c, "rue", 3)) { - c += 3; - *o = [NSNumber numberWithBool:YES]; - return YES; - } - [self addErrorWithCode:EPARSE description:@"Expected 'true'"]; - return NO; -} - -- (BOOL)scanRestOfFalse:(NSNumber **)o -{ - if (!strncmp(c, "alse", 4)) { - c += 4; - *o = [NSNumber numberWithBool:NO]; - return YES; - } - [self addErrorWithCode:EPARSE description: @"Expected 'false'"]; - return NO; -} - -- (BOOL)scanRestOfNull:(NSNull **)o { - if (!strncmp(c, "ull", 3)) { - c += 3; - *o = [NSNull null]; - return YES; - } - [self addErrorWithCode:EPARSE description: @"Expected 'null'"]; - return NO; -} - -- (BOOL)scanRestOfArray:(NSMutableArray **)o { - if (maxDepth && ++depth > maxDepth) { - [self addErrorWithCode:EDEPTH description: @"Nested too deep"]; - return NO; - } - - *o = [NSMutableArray arrayWithCapacity:8]; - - for (; *c ;) { - id v; - - skipWhitespace(c); - if (*c == ']' && c++) { - depth--; - return YES; - } - - if (![self scanValue:&v]) { - [self addErrorWithCode:EPARSE description:@"Expected value while parsing array"]; - return NO; - } - - [*o addObject:v]; - - skipWhitespace(c); - if (*c == ',' && c++) { - skipWhitespace(c); - if (*c == ']') { - [self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in array"]; - return NO; - } - } - } - - [self addErrorWithCode:EEOF description: @"End of input while parsing array"]; - return NO; -} - -- (BOOL)scanRestOfDictionary:(NSMutableDictionary **)o -{ - if (maxDepth && ++depth > maxDepth) { - [self addErrorWithCode:EDEPTH description: @"Nested too deep"]; - return NO; - } - - *o = [NSMutableDictionary dictionaryWithCapacity:7]; - - for (; *c ;) { - id k, v; - - skipWhitespace(c); - if (*c == '}' && c++) { - depth--; - return YES; - } - - if (!(*c == '\"' && c++ && [self scanRestOfString:&k])) { - [self addErrorWithCode:EPARSE description: @"Object key string expected"]; - return NO; - } - - skipWhitespace(c); - if (*c != ':') { - [self addErrorWithCode:EPARSE description: @"Expected ':' separating key and value"]; - return NO; - } - - c++; - if (![self scanValue:&v]) { - NSString *string = [NSString stringWithFormat:@"Object value expected for key: %@", k]; - [self addErrorWithCode:EPARSE description: string]; - return NO; - } - - [*o setObject:v forKey:k]; - - skipWhitespace(c); - if (*c == ',' && c++) { - skipWhitespace(c); - if (*c == '}') { - [self addErrorWithCode:ETRAILCOMMA description: @"Trailing comma disallowed in object"]; - return NO; - } - } - } - - [self addErrorWithCode:EEOF description: @"End of input while parsing object"]; - return NO; -} - -- (BOOL)scanRestOfString:(NSMutableString **)o -{ - // if the string has no control characters in it, return it in one go, without any temporary allocations. - size_t len = strcspn(c, ctrl); - if (len && *(c + len) == '\"') - { - *o = [[[NSMutableString alloc] initWithBytes:(char*)c length:len encoding:NSUTF8StringEncoding] autorelease]; - c += len + 1; - return YES; - } - - *o = [NSMutableString stringWithCapacity:16]; - do { - // First see if there's a portion we can grab in one go. - // Doing this caused a massive speedup on the long string. - len = strcspn(c, ctrl); - if (len) { - // check for - id t = [[NSString alloc] initWithBytesNoCopy:(char*)c - length:len - encoding:NSUTF8StringEncoding - freeWhenDone:NO]; - if (t) { - [*o appendString:t]; - [t release]; - c += len; - } - } - - if (*c == '"') { - c++; - return YES; - - } else if (*c == '\\') { - unichar uc = *++c; - switch (uc) { - case '\\': - case '/': - case '"': - break; - - case 'b': uc = '\b'; break; - case 'n': uc = '\n'; break; - case 'r': uc = '\r'; break; - case 't': uc = '\t'; break; - case 'f': uc = '\f'; break; - - case 'u': - c++; - if (![self scanUnicodeChar:&uc]) { - [self addErrorWithCode:EUNICODE description: @"Broken unicode character"]; - return NO; - } - c--; // hack. - break; - default: - [self addErrorWithCode:EESCAPE description: [NSString stringWithFormat:@"Illegal escape sequence '0x%x'", uc]]; - return NO; - break; - } - CFStringAppendCharacters((CFMutableStringRef)*o, &uc, 1); - c++; - - } else if (*c < 0x20) { - [self addErrorWithCode:ECTRL description: [NSString stringWithFormat:@"Unescaped control character '0x%x'", *c]]; - return NO; - - } else { - NSLog(@"should not be able to get here"); - } - } while (*c); - - [self addErrorWithCode:EEOF description:@"Unexpected EOF while parsing string"]; - return NO; -} - -- (BOOL)scanUnicodeChar:(unichar *)x -{ - unichar hi, lo; - - if (![self scanHexQuad:&hi]) { - [self addErrorWithCode:EUNICODE description: @"Missing hex quad"]; - return NO; - } - - if (hi >= 0xd800) { // high surrogate char? - if (hi < 0xdc00) { // yes - expect a low char - - if (!(*c == '\\' && ++c && *c == 'u' && ++c && [self scanHexQuad:&lo])) { - [self addErrorWithCode:EUNICODE description: @"Missing low character in surrogate pair"]; - return NO; - } - - if (lo < 0xdc00 || lo >= 0xdfff) { - [self addErrorWithCode:EUNICODE description:@"Invalid low surrogate char"]; - return NO; - } - - hi = (hi - 0xd800) * 0x400 + (lo - 0xdc00) + 0x10000; - - } else if (hi < 0xe000) { - [self addErrorWithCode:EUNICODE description:@"Invalid high character in surrogate pair"]; - return NO; - } - } - - *x = hi; - return YES; -} - -- (BOOL)scanHexQuad:(unichar *)x -{ - *x = 0; - for (int i = 0; i < 4; i++) { - unichar uc = *c; - c++; - int d = (uc >= '0' && uc <= '9') - ? uc - '0' : (uc >= 'a' && uc <= 'f') - ? (uc - 'a' + 10) : (uc >= 'A' && uc <= 'F') - ? (uc - 'A' + 10) : -1; - if (d == -1) { - [self addErrorWithCode:EUNICODE description:@"Missing hex digit in quad"]; - return NO; - } - *x *= 16; - *x += d; - } - return YES; -} - -- (BOOL)scanNumber:(NSNumber **)o -{ - BOOL simple = YES; - - const char *ns = c; - - // The logic to test for validity of the number formatting is relicensed - // from JSON::XS with permission from its author Marc Lehmann. - // (Available at the CPAN: http://search.cpan.org/dist/JSON-XS/ .) - - if ('-' == *c) - c++; - - if ('0' == *c && c++) { - if (isdigit(*c)) { - [self addErrorWithCode:EPARSENUM description: @"Leading 0 disallowed in number"]; - return NO; - } - - } else if (!isdigit(*c) && c != ns) { - [self addErrorWithCode:EPARSENUM description: @"No digits after initial minus"]; - return NO; - - } else { - skipDigits(c); - } - - // Fractional part - if ('.' == *c && c++) { - simple = NO; - if (!isdigit(*c)) { - [self addErrorWithCode:EPARSENUM description: @"No digits after decimal point"]; - return NO; - } - skipDigits(c); - } - - // Exponential part - if ('e' == *c || 'E' == *c) { - simple = NO; - c++; - - if ('-' == *c || '+' == *c) - c++; - - if (!isdigit(*c)) { - [self addErrorWithCode:EPARSENUM description: @"No digits after exponent"]; - return NO; - } - skipDigits(c); - } - - // If we are only reading integers, don't go through the expense of creating an NSDecimal. - // This ends up being a very large perf win. - if (simple) { - BOOL negate = NO; - long long val = 0; - const char *d = ns; - - if (*d == '-') { - negate = YES; - d++; - } - - while (isdigit(*d)) { - val *= 10; - if (val < 0) - goto longlong_overflow; - val += *d - '0'; - if (val < 0) - goto longlong_overflow; - d++; - } - - *o = [NSNumber numberWithLongLong:negate ? -val : val]; - return YES; - - } else { - // jumped to by simple branch, if an overflow occured - longlong_overflow:; - - id str = [[NSString alloc] initWithBytesNoCopy:(char*)ns - length:c - ns - encoding:NSUTF8StringEncoding - freeWhenDone:NO]; - [str autorelease]; - if (str && (*o = [NSDecimalNumber decimalNumberWithString:str])) - return YES; - - [self addErrorWithCode:EPARSENUM description: @"Failed creating decimal instance"]; - return NO; - } -} - -- (BOOL)scanIsAtEnd -{ - skipWhitespace(c); - return !*c; -} - - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonWriter.h b/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonWriter.h deleted file mode 100644 index ae1a597bb..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonWriter.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import -#import "SBJsonBase.h" - -/** - @brief The JSON writer class. - - Objective-C types are mapped to JSON types in the following way: - - @li NSNull -> Null - @li NSString -> String - @li NSArray -> Array - @li NSDictionary -> Object - @li NSNumber (-initWithBool:) -> Boolean - @li NSNumber -> Number - - In JSON the keys of an object must be strings. NSDictionary keys need - not be, but attempting to convert an NSDictionary with non-string keys - into JSON will throw an exception. - - NSNumber instances created with the +initWithBool: method are - converted into the JSON boolean "true" and "false" values, and vice - versa. Any other NSNumber instances are converted to a JSON number the - way you would expect. - - */ -@interface SBJsonWriter : SBJsonBase { - -@private - BOOL sortKeys, humanReadable; -} - -/** - @brief Whether we are generating human-readable (multiline) JSON. - - Set whether or not to generate human-readable JSON. The default is NO, which produces - JSON without any whitespace. (Except inside strings.) If set to YES, generates human-readable - JSON with linebreaks after each array value and dictionary key/value pair, indented two - spaces per nesting level. - */ -@property BOOL humanReadable; - -/** - @brief Whether or not to sort the dictionary keys in the output. - - If this is set to YES, the dictionary keys in the JSON output will be in sorted order. - (This is useful if you need to compare two structures, for example.) The default is NO. - */ -@property BOOL sortKeys; - -/** - @brief Return JSON representation (or fragment) for the given object. - - Returns a string containing JSON representation of the passed in value, or nil on error. - If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error. - - @param value any instance that can be represented as a JSON fragment - - */ -- (NSString*)stringWithObject:(id)value; - -/** - @brief Return JSON representation (or fragment) for the given object. - - Returns a string containing JSON representation of the passed in value, or nil on error. - If nil is returned and @p error is not NULL, @p *error can be interrogated to find the cause of the error. - - @param value any instance that can be represented as a JSON fragment - @param error pointer to object to be populated with NSError on failure - - */- (NSString*)stringWithObject:(id)value - error:(NSError**)error; - - -@end - -/** - @brief Allows generation of JSON for otherwise unsupported classes. - - If you have a custom class that you want to create a JSON representation for you can implement - this method in your class. It should return a representation of your object defined - in terms of objects that can be translated into JSON. For example, a Person - object might implement it like this: - - @code - - (id)proxyForJson { - return [NSDictionary dictionaryWithObjectsAndKeys: - name, @"name", - phone, @"phone", - email, @"email", - nil]; - } - @endcode - - */ -@interface NSObject (SBProxyForJson) -- (id)proxyForJson; -@end - diff --git a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonWriter.m b/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonWriter.m deleted file mode 100644 index 83e8a202b..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/JSON/SBJsonWriter.m +++ /dev/null @@ -1,239 +0,0 @@ -/* - Copyright (C) 2009 Stig Brautaset. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - * Neither the name of the author nor the names of its contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#import "SBJsonWriter.h" - -@interface SBJsonWriter () - -- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json; -- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json; -- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json; -- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json; - -- (NSString*)indent; - -@end - -@implementation SBJsonWriter - -@synthesize sortKeys; -@synthesize humanReadable; - -static NSMutableCharacterSet *kEscapeChars; - -+ (void)initialize { - kEscapeChars = [[NSMutableCharacterSet characterSetWithRange: NSMakeRange(0,32)] retain]; - [kEscapeChars addCharactersInString: @"\"\\"]; -} - -- (NSString*)stringWithObject:(id)value { - [self clearErrorTrace]; - - if ([value isKindOfClass:[NSDictionary class]] || [value isKindOfClass:[NSArray class]]) { - depth = 0; - NSMutableString *json = [NSMutableString stringWithCapacity:128]; - if ([self appendValue:value into:json]) - return json; - } - - if ([value respondsToSelector:@selector(proxyForJson)]) { - NSString *tmp = [self stringWithObject:[value proxyForJson]]; - if (tmp) - return tmp; - } - - [self addErrorWithCode:EFRAGMENT description:@"Not valid type for JSON"]; - return nil; -} - -- (NSString*)stringWithObject:(id)value error:(NSError**)error { - NSString *tmp = [self stringWithObject:value]; - if (tmp) - return tmp; - - if (error) - *error = [self.errorTrace lastObject]; - return nil; -} - -- (NSString*)indent { - return [@"\n" stringByPaddingToLength:1 + 2 * depth withString:@" " startingAtIndex:0]; -} - -- (BOOL)appendValue:(id)fragment into:(NSMutableString*)json { - if ([fragment isKindOfClass:[NSDictionary class]]) { - if (![self appendDictionary:fragment into:json]) - return NO; - - } else if ([fragment isKindOfClass:[NSArray class]]) { - if (![self appendArray:fragment into:json]) - return NO; - - } else if ([fragment isKindOfClass:[NSString class]]) { - if (![self appendString:fragment into:json]) - return NO; - - } else if ([fragment isKindOfClass:[NSNumber class]]) { - if ('c' == *[fragment objCType]) { - [json appendString:[fragment boolValue] ? @"true" : @"false"]; - } else if ([fragment isEqualToNumber:(NSNumber*)kCFNumberNaN]) { - [self addErrorWithCode:EUNSUPPORTED description:@"NaN is not a valid number in JSON"]; - return NO; - - } else if (isinf([fragment doubleValue])) { - [self addErrorWithCode:EUNSUPPORTED description:@"Infinity is not a valid number in JSON"]; - return NO; - - } else { - [json appendString:[fragment stringValue]]; - } - } else if ([fragment isKindOfClass:[NSNull class]]) { - [json appendString:@"null"]; - } else if ([fragment respondsToSelector:@selector(proxyForJson)]) { - [self appendValue:[fragment proxyForJson] into:json]; - - } else { - [self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"JSON serialisation not supported for %@", [fragment class]]]; - return NO; - } - return YES; -} - -- (BOOL)appendArray:(NSArray*)fragment into:(NSMutableString*)json { - if (maxDepth && ++depth > maxDepth) { - [self addErrorWithCode:EDEPTH description: @"Nested too deep"]; - return NO; - } - [json appendString:@"["]; - - BOOL addComma = NO; - for (id value in fragment) { - if (addComma) - [json appendString:@","]; - else - addComma = YES; - - if ([self humanReadable]) - [json appendString:[self indent]]; - - if (![self appendValue:value into:json]) { - return NO; - } - } - - depth--; - if ([self humanReadable] && [fragment count]) - [json appendString:[self indent]]; - [json appendString:@"]"]; - return YES; -} - -- (BOOL)appendDictionary:(NSDictionary*)fragment into:(NSMutableString*)json { - if (maxDepth && ++depth > maxDepth) { - [self addErrorWithCode:EDEPTH description: @"Nested too deep"]; - return NO; - } - [json appendString:@"{"]; - - NSString *colon = [self humanReadable] ? @" : " : @":"; - BOOL addComma = NO; - NSArray *keys = [fragment allKeys]; - if (self.sortKeys) - keys = [keys sortedArrayUsingSelector:@selector(compare:)]; - - for (id value in keys) { - if (addComma) - [json appendString:@","]; - else - addComma = YES; - - if ([self humanReadable]) - [json appendString:[self indent]]; - - if (![value isKindOfClass:[NSString class]]) { - [self addErrorWithCode:EUNSUPPORTED description: @"JSON object key must be string"]; - return NO; - } - - if (![self appendString:value into:json]) - return NO; - - [json appendString:colon]; - if (![self appendValue:[fragment objectForKey:value] into:json]) { - [self addErrorWithCode:EUNSUPPORTED description:[NSString stringWithFormat:@"Unsupported value for key %@ in object", value]]; - return NO; - } - } - - depth--; - if ([self humanReadable] && [fragment count]) - [json appendString:[self indent]]; - [json appendString:@"}"]; - return YES; -} - -- (BOOL)appendString:(NSString*)fragment into:(NSMutableString*)json { - - [json appendString:@"\""]; - - NSRange esc = [fragment rangeOfCharacterFromSet:kEscapeChars]; - if ( !esc.length ) { - // No special chars -- can just add the raw string: - [json appendString:fragment]; - - } else { - NSUInteger length = [fragment length]; - for (NSUInteger i = 0; i < length; i++) { - unichar uc = [fragment characterAtIndex:i]; - switch (uc) { - case '"': [json appendString:@"\\\""]; break; - case '\\': [json appendString:@"\\\\"]; break; - case '\t': [json appendString:@"\\t"]; break; - case '\n': [json appendString:@"\\n"]; break; - case '\r': [json appendString:@"\\r"]; break; - case '\b': [json appendString:@"\\b"]; break; - case '\f': [json appendString:@"\\f"]; break; - default: - if (uc < 0x20) { - [json appendFormat:@"\\u%04x", uc]; - } else { - CFStringAppendCharacters((CFMutableStringRef)json, &uc, 1); - } - break; - - } - } - } - - [json appendString:@"\""]; - return YES; -} - - -@end diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2.xcodeproj/project.pbxproj b/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2.xcodeproj/project.pbxproj deleted file mode 100644 index 8ee3f1f7a..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2.xcodeproj/project.pbxproj +++ /dev/null @@ -1,686 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - 4F24484B121F2E5C00FEE1DA /* GTMOAuth2Authentication.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244848121F2E5C00FEE1DA /* GTMOAuth2Authentication.m */; }; - 4F24484C121F2E5C00FEE1DA /* GTMOAuth2SignIn.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F24484A121F2E5C00FEE1DA /* GTMOAuth2SignIn.m */; }; - 4F24491A121F370000FEE1DA /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244919121F370000FEE1DA /* GTMHTTPFetcher.m */; }; - 4F724A9012248CF5001A4AD0 /* GTMOAuth2Authentication.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244848121F2E5C00FEE1DA /* GTMOAuth2Authentication.m */; }; - 4F724A9212248CF5001A4AD0 /* GTMOAuth2SignIn.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F24484A121F2E5C00FEE1DA /* GTMOAuth2SignIn.m */; }; - 4F724A9412248CF5001A4AD0 /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244919121F370000FEE1DA /* GTMHTTPFetcher.m */; }; - 4F724AB812248D6B001A4AD0 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F724AB512248D6B001A4AD0 /* Security.framework */; }; - 4F724ABA12248D6B001A4AD0 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F724AB712248D6B001A4AD0 /* SystemConfiguration.framework */; }; - 4F724BAB12248F75001A4AD0 /* GTMHTTPFetchHistory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F724BA912248F75001A4AD0 /* GTMHTTPFetchHistory.m */; }; - 4F724BB012248F81001A4AD0 /* GTMHTTPFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F724BAE12248F81001A4AD0 /* GTMHTTPFetcherLogging.m */; }; - 4F8D436B133972F5000B4396 /* GTMOAuth2Window.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4F8D436A133972F5000B4396 /* GTMOAuth2Window.xib */; }; - 4F8D437E1339735D000B4396 /* GTMOAuth2ViewControllerTouch.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F8D437C1339735D000B4396 /* GTMOAuth2ViewControllerTouch.m */; }; - 4F94D2D012288B8A00BC78AA /* GTMHTTPFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F244918121F370000FEE1DA /* GTMHTTPFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4F94D2D112288B8A00BC78AA /* GTMHTTPFetcherLogging.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F724BAD12248F81001A4AD0 /* GTMHTTPFetcherLogging.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4F94D2D212288B8A00BC78AA /* GTMHTTPFetchHistory.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F724BA812248F75001A4AD0 /* GTMHTTPFetchHistory.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4F94D2D312288B8A00BC78AA /* GTMOAuth2Authentication.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F244847121F2E5C00FEE1DA /* GTMOAuth2Authentication.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4F94D2D812288B8A00BC78AA /* GTMOAuth2SignIn.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F244849121F2E5C00FEE1DA /* GTMOAuth2SignIn.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4F94D2D912288B8A00BC78AA /* GTMOAuth2WindowController.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F7249FA122485EE001A4AD0 /* GTMOAuth2WindowController.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4F94D33E1228944800BC78AA /* GTMOAuth2WindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F7249FB122485EE001A4AD0 /* GTMOAuth2WindowController.m */; }; - 4FC754F113E77E25006A0C26 /* GTMOAuth2Authentication.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244848121F2E5C00FEE1DA /* GTMOAuth2Authentication.m */; }; - 4FC754F213E77E25006A0C26 /* GTMOAuth2SignIn.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F24484A121F2E5C00FEE1DA /* GTMOAuth2SignIn.m */; }; - 4FC754F313E77E25006A0C26 /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244919121F370000FEE1DA /* GTMHTTPFetcher.m */; }; - 4FC754F413E77E25006A0C26 /* GTMOAuth2ViewControllerTouch.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F8D437C1339735D000B4396 /* GTMOAuth2ViewControllerTouch.m */; }; - 4FC754FD13E77E2B006A0C26 /* GTMHTTPFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F244918121F370000FEE1DA /* GTMHTTPFetcher.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4FC754FE13E77E2B006A0C26 /* GTMHTTPFetcherLogging.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F724BAD12248F81001A4AD0 /* GTMHTTPFetcherLogging.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4FC754FF13E77E2B006A0C26 /* GTMHTTPFetchHistory.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F724BA812248F75001A4AD0 /* GTMHTTPFetchHistory.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4FC7550013E77E2B006A0C26 /* GTMOAuth2Authentication.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F244847121F2E5C00FEE1DA /* GTMOAuth2Authentication.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4FC7550113E77E2B006A0C26 /* GTMOAuth2SignIn.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F244849121F2E5C00FEE1DA /* GTMOAuth2SignIn.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4FC7550213E77E2B006A0C26 /* GTMOAuth2WindowController.h in Headers */ = {isa = PBXBuildFile; fileRef = 4F7249FA122485EE001A4AD0 /* GTMOAuth2WindowController.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 4FC7550513E77E2B006A0C26 /* GTMOAuth2Window.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4F8D436A133972F5000B4396 /* GTMOAuth2Window.xib */; }; - 4FC7550713E77E2B006A0C26 /* GTMOAuth2Authentication.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244848121F2E5C00FEE1DA /* GTMOAuth2Authentication.m */; }; - 4FC7550813E77E2B006A0C26 /* GTMOAuth2SignIn.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F24484A121F2E5C00FEE1DA /* GTMOAuth2SignIn.m */; }; - 4FC7550913E77E2B006A0C26 /* GTMHTTPFetcher.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F244919121F370000FEE1DA /* GTMHTTPFetcher.m */; }; - 4FC7550A13E77E2B006A0C26 /* GTMHTTPFetchHistory.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F724BA912248F75001A4AD0 /* GTMHTTPFetchHistory.m */; }; - 4FC7550B13E77E2B006A0C26 /* GTMHTTPFetcherLogging.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F724BAE12248F81001A4AD0 /* GTMHTTPFetcherLogging.m */; }; - 4FC7550C13E77E2B006A0C26 /* GTMOAuth2WindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = 4F7249FB122485EE001A4AD0 /* GTMOAuth2WindowController.m */; }; - 4FC7550F13E77E2B006A0C26 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F724AB512248D6B001A4AD0 /* Security.framework */; }; - 4FC7551013E77E2B006A0C26 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4F724AB712248D6B001A4AD0 /* SystemConfiguration.framework */; }; -/* End PBXBuildFile section */ - -/* Begin PBXFileReference section */ - 4F244847121F2E5C00FEE1DA /* GTMOAuth2Authentication.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMOAuth2Authentication.h; sourceTree = ""; }; - 4F244848121F2E5C00FEE1DA /* GTMOAuth2Authentication.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMOAuth2Authentication.m; sourceTree = ""; }; - 4F244849121F2E5C00FEE1DA /* GTMOAuth2SignIn.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = GTMOAuth2SignIn.h; sourceTree = ""; }; - 4F24484A121F2E5C00FEE1DA /* GTMOAuth2SignIn.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GTMOAuth2SignIn.m; sourceTree = ""; }; - 4F244918121F370000FEE1DA /* GTMHTTPFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GTMHTTPFetcher.h; path = ../HTTPFetcher/GTMHTTPFetcher.h; sourceTree = SOURCE_ROOT; }; - 4F244919121F370000FEE1DA /* GTMHTTPFetcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcher.m; path = ../HTTPFetcher/GTMHTTPFetcher.m; sourceTree = SOURCE_ROOT; }; - 4F3A8DBE125A61910080EB6C /* ReleaseNotes.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = ReleaseNotes.txt; sourceTree = ""; }; - 4F7249FA122485EE001A4AD0 /* GTMOAuth2WindowController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GTMOAuth2WindowController.h; path = Mac/GTMOAuth2WindowController.h; sourceTree = ""; }; - 4F7249FB122485EE001A4AD0 /* GTMOAuth2WindowController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMOAuth2WindowController.m; path = Mac/GTMOAuth2WindowController.m; sourceTree = ""; }; - 4F724AB512248D6B001A4AD0 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = /System/Library/Frameworks/Security.framework; sourceTree = ""; }; - 4F724AB612248D6B001A4AD0 /* SenTestingKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SenTestingKit.framework; path = Library/Frameworks/SenTestingKit.framework; sourceTree = DEVELOPER_DIR; }; - 4F724AB712248D6B001A4AD0 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = /System/Library/Frameworks/SystemConfiguration.framework; sourceTree = ""; }; - 4F724BA812248F75001A4AD0 /* GTMHTTPFetchHistory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GTMHTTPFetchHistory.h; path = ../HTTPFetcher/GTMHTTPFetchHistory.h; sourceTree = SOURCE_ROOT; }; - 4F724BA912248F75001A4AD0 /* GTMHTTPFetchHistory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetchHistory.m; path = ../HTTPFetcher/GTMHTTPFetchHistory.m; sourceTree = SOURCE_ROOT; }; - 4F724BAD12248F81001A4AD0 /* GTMHTTPFetcherLogging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GTMHTTPFetcherLogging.h; path = ../HTTPFetcher/GTMHTTPFetcherLogging.h; sourceTree = SOURCE_ROOT; }; - 4F724BAE12248F81001A4AD0 /* GTMHTTPFetcherLogging.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMHTTPFetcherLogging.m; path = ../HTTPFetcher/GTMHTTPFetcherLogging.m; sourceTree = SOURCE_ROOT; }; - 4F8D436A133972F5000B4396 /* GTMOAuth2Window.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = GTMOAuth2Window.xib; path = Mac/GTMOAuth2Window.xib; sourceTree = ""; }; - 4F8D437B1339735D000B4396 /* GTMOAuth2ViewControllerTouch.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = GTMOAuth2ViewControllerTouch.h; path = Touch/GTMOAuth2ViewControllerTouch.h; sourceTree = ""; }; - 4F8D437C1339735D000B4396 /* GTMOAuth2ViewControllerTouch.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = GTMOAuth2ViewControllerTouch.m; path = Touch/GTMOAuth2ViewControllerTouch.m; sourceTree = ""; }; - 4F8D437D1339735D000B4396 /* GTMOAuth2ViewTouch.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = GTMOAuth2ViewTouch.xib; path = Touch/GTMOAuth2ViewTouch.xib; sourceTree = ""; }; - 4FC754FA13E77E25006A0C26 /* libOAuthTouch2NG.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libOAuthTouch2NG.a; sourceTree = BUILT_PRODUCTS_DIR; }; - 4FF2B2F9133BC54600D75613 /* GTMOAuth2Framework-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = "GTMOAuth2Framework-Info.plist"; path = "Mac/GTMOAuth2Framework-Info.plist"; sourceTree = ""; }; - D2AAC07E0554694100DB518D /* libOAuthTouch2.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libOAuthTouch2.a; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 4F724A6F12248B19001A4AD0 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F724AB812248D6B001A4AD0 /* Security.framework in Frameworks */, - 4F724ABA12248D6B001A4AD0 /* SystemConfiguration.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4FC754F613E77E25006A0C26 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4FC7550E13E77E2B006A0C26 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 4FC7550F13E77E2B006A0C26 /* Security.framework in Frameworks */, - 4FC7551013E77E2B006A0C26 /* SystemConfiguration.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D2AAC07C0554694100DB518D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 034768DFFF38A50411DB9C8B /* Products */ = { - isa = PBXGroup; - children = ( - D2AAC07E0554694100DB518D /* libOAuthTouch2.a */, - 4FC754FA13E77E25006A0C26 /* libOAuthTouch2NG.a */, - ); - name = Products; - sourceTree = ""; - }; - 0867D691FE84028FC02AAC07 /* OAuthTouchStaticLibrary */ = { - isa = PBXGroup; - children = ( - 4F7249C012248423001A4AD0 /* Sources */, - 034768DFFF38A50411DB9C8B /* Products */, - 4F724AA112248D35001A4AD0 /* Libraries */, - 4F3A8DBE125A61910080EB6C /* ReleaseNotes.txt */, - ); - name = OAuthTouchStaticLibrary; - sourceTree = ""; - }; - 4F7249C012248423001A4AD0 /* Sources */ = { - isa = PBXGroup; - children = ( - 4F244847121F2E5C00FEE1DA /* GTMOAuth2Authentication.h */, - 4F244848121F2E5C00FEE1DA /* GTMOAuth2Authentication.m */, - 4F244849121F2E5C00FEE1DA /* GTMOAuth2SignIn.h */, - 4F24484A121F2E5C00FEE1DA /* GTMOAuth2SignIn.m */, - 4F7249F2122485AC001A4AD0 /* Touch */, - 4F7249F3122485B2001A4AD0 /* Mac */, - 4F724BA712248F62001A4AD0 /* HTTPFetcher */, - ); - name = Sources; - sourceTree = ""; - }; - 4F7249F2122485AC001A4AD0 /* Touch */ = { - isa = PBXGroup; - children = ( - 4F8D437B1339735D000B4396 /* GTMOAuth2ViewControllerTouch.h */, - 4F8D437C1339735D000B4396 /* GTMOAuth2ViewControllerTouch.m */, - 4F8D437D1339735D000B4396 /* GTMOAuth2ViewTouch.xib */, - ); - name = Touch; - sourceTree = ""; - }; - 4F7249F3122485B2001A4AD0 /* Mac */ = { - isa = PBXGroup; - children = ( - 4F8D436A133972F5000B4396 /* GTMOAuth2Window.xib */, - 4F7249FA122485EE001A4AD0 /* GTMOAuth2WindowController.h */, - 4F7249FB122485EE001A4AD0 /* GTMOAuth2WindowController.m */, - 4FF2B2F9133BC54600D75613 /* GTMOAuth2Framework-Info.plist */, - ); - name = Mac; - sourceTree = ""; - }; - 4F724AA112248D35001A4AD0 /* Libraries */ = { - isa = PBXGroup; - children = ( - 4F724AB612248D6B001A4AD0 /* SenTestingKit.framework */, - 4F724AB512248D6B001A4AD0 /* Security.framework */, - 4F724AB712248D6B001A4AD0 /* SystemConfiguration.framework */, - ); - name = Libraries; - sourceTree = ""; - }; - 4F724BA712248F62001A4AD0 /* HTTPFetcher */ = { - isa = PBXGroup; - children = ( - 4F244918121F370000FEE1DA /* GTMHTTPFetcher.h */, - 4F244919121F370000FEE1DA /* GTMHTTPFetcher.m */, - 4F724BA812248F75001A4AD0 /* GTMHTTPFetchHistory.h */, - 4F724BA912248F75001A4AD0 /* GTMHTTPFetchHistory.m */, - 4F724BAD12248F81001A4AD0 /* GTMHTTPFetcherLogging.h */, - 4F724BAE12248F81001A4AD0 /* GTMHTTPFetcherLogging.m */, - ); - name = HTTPFetcher; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 4F724A6C12248B19001A4AD0 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F94D2D012288B8A00BC78AA /* GTMHTTPFetcher.h in Headers */, - 4F94D2D112288B8A00BC78AA /* GTMHTTPFetcherLogging.h in Headers */, - 4F94D2D212288B8A00BC78AA /* GTMHTTPFetchHistory.h in Headers */, - 4F94D2D312288B8A00BC78AA /* GTMOAuth2Authentication.h in Headers */, - 4F94D2D812288B8A00BC78AA /* GTMOAuth2SignIn.h in Headers */, - 4F94D2D912288B8A00BC78AA /* GTMOAuth2WindowController.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4FC754FC13E77E2B006A0C26 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 4FC754FD13E77E2B006A0C26 /* GTMHTTPFetcher.h in Headers */, - 4FC754FE13E77E2B006A0C26 /* GTMHTTPFetcherLogging.h in Headers */, - 4FC754FF13E77E2B006A0C26 /* GTMHTTPFetchHistory.h in Headers */, - 4FC7550013E77E2B006A0C26 /* GTMOAuth2Authentication.h in Headers */, - 4FC7550113E77E2B006A0C26 /* GTMOAuth2SignIn.h in Headers */, - 4FC7550213E77E2B006A0C26 /* GTMOAuth2WindowController.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 4F724A7012248B19001A4AD0 /* GTMOAuth2.framework */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4F724A7412248B19001A4AD0 /* Build configuration list for PBXNativeTarget "GTMOAuth2.framework" */; - buildPhases = ( - 4F724A6C12248B19001A4AD0 /* Headers */, - 4F724A6D12248B19001A4AD0 /* Resources */, - 4F724A6E12248B19001A4AD0 /* Sources */, - 4F724A6F12248B19001A4AD0 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = GTMOAuth2.framework; - productName = OAuth.framework; - productType = "com.apple.product-type.framework"; - }; - 4FC754EF13E77E25006A0C26 /* OAuthTouchNonGoogleStaticLib */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4FC754F713E77E25006A0C26 /* Build configuration list for PBXNativeTarget "OAuthTouchNonGoogleStaticLib" */; - buildPhases = ( - 4FC754F013E77E25006A0C26 /* Sources */, - 4FC754F613E77E25006A0C26 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = OAuthTouchNonGoogleStaticLib; - productName = OAuthTouchStaticLibrary; - productReference = 4FC754FA13E77E25006A0C26 /* libOAuthTouch2NG.a */; - productType = "com.apple.product-type.library.static"; - }; - 4FC754FB13E77E2B006A0C26 /* GTMOAuth2NonGoogle.framework */ = { - isa = PBXNativeTarget; - buildConfigurationList = 4FC7551113E77E2B006A0C26 /* Build configuration list for PBXNativeTarget "GTMOAuth2NonGoogle.framework" */; - buildPhases = ( - 4FC754FC13E77E2B006A0C26 /* Headers */, - 4FC7550413E77E2B006A0C26 /* Resources */, - 4FC7550613E77E2B006A0C26 /* Sources */, - 4FC7550E13E77E2B006A0C26 /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = GTMOAuth2NonGoogle.framework; - productName = OAuth.framework; - productType = "com.apple.product-type.framework"; - }; - D2AAC07D0554694100DB518D /* OAuthTouchStaticLib */ = { - isa = PBXNativeTarget; - buildConfigurationList = 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "OAuthTouchStaticLib" */; - buildPhases = ( - D2AAC07B0554694100DB518D /* Sources */, - D2AAC07C0554694100DB518D /* Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = OAuthTouchStaticLib; - productName = OAuthTouchStaticLibrary; - productReference = D2AAC07E0554694100DB518D /* libOAuthTouch2.a */; - productType = "com.apple.product-type.library.static"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 0867D690FE84028FC02AAC07 /* Project object */ = { - isa = PBXProject; - buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "GTMOAuth2" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 1; - knownRegions = ( - English, - Japanese, - French, - German, - ); - mainGroup = 0867D691FE84028FC02AAC07 /* OAuthTouchStaticLibrary */; - productRefGroup = 034768DFFF38A50411DB9C8B /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - D2AAC07D0554694100DB518D /* OAuthTouchStaticLib */, - 4FC754EF13E77E25006A0C26 /* OAuthTouchNonGoogleStaticLib */, - 4F724A7012248B19001A4AD0 /* GTMOAuth2.framework */, - 4FC754FB13E77E2B006A0C26 /* GTMOAuth2NonGoogle.framework */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 4F724A6D12248B19001A4AD0 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F8D436B133972F5000B4396 /* GTMOAuth2Window.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4FC7550413E77E2B006A0C26 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4FC7550513E77E2B006A0C26 /* GTMOAuth2Window.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 4F724A6E12248B19001A4AD0 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F724A9012248CF5001A4AD0 /* GTMOAuth2Authentication.m in Sources */, - 4F724A9212248CF5001A4AD0 /* GTMOAuth2SignIn.m in Sources */, - 4F724A9412248CF5001A4AD0 /* GTMHTTPFetcher.m in Sources */, - 4F724BAB12248F75001A4AD0 /* GTMHTTPFetchHistory.m in Sources */, - 4F724BB012248F81001A4AD0 /* GTMHTTPFetcherLogging.m in Sources */, - 4F94D33E1228944800BC78AA /* GTMOAuth2WindowController.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4FC754F013E77E25006A0C26 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4FC754F113E77E25006A0C26 /* GTMOAuth2Authentication.m in Sources */, - 4FC754F213E77E25006A0C26 /* GTMOAuth2SignIn.m in Sources */, - 4FC754F313E77E25006A0C26 /* GTMHTTPFetcher.m in Sources */, - 4FC754F413E77E25006A0C26 /* GTMOAuth2ViewControllerTouch.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 4FC7550613E77E2B006A0C26 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4FC7550713E77E2B006A0C26 /* GTMOAuth2Authentication.m in Sources */, - 4FC7550813E77E2B006A0C26 /* GTMOAuth2SignIn.m in Sources */, - 4FC7550913E77E2B006A0C26 /* GTMHTTPFetcher.m in Sources */, - 4FC7550A13E77E2B006A0C26 /* GTMHTTPFetchHistory.m in Sources */, - 4FC7550B13E77E2B006A0C26 /* GTMHTTPFetcherLogging.m in Sources */, - 4FC7550C13E77E2B006A0C26 /* GTMOAuth2WindowController.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - D2AAC07B0554694100DB518D /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4F24484B121F2E5C00FEE1DA /* GTMOAuth2Authentication.m in Sources */, - 4F24484C121F2E5C00FEE1DA /* GTMOAuth2SignIn.m in Sources */, - 4F24491A121F370000FEE1DA /* GTMHTTPFetcher.m in Sources */, - 4F8D437E1339735D000B4396 /* GTMOAuth2ViewControllerTouch.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - 1DEB921F08733DC00010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD)"; - "ARCHS[sdk=iphoneos*]" = ( - armv6, - armv7, - ); - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - INSTALL_PATH = /usr/local/lib; - PRODUCT_NAME = OAuthTouch2; - SDKROOT = iphoneos; - }; - name = Debug; - }; - 1DEB922008733DC00010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD)"; - "ARCHS[sdk=iphoneos*]" = ( - armv6, - armv7, - ); - GCC_MODEL_TUNING = G5; - INSTALL_PATH = /usr/local/lib; - PRODUCT_NAME = OAuthTouch2; - SDKROOT = iphoneos; - }; - name = Release; - }; - 1DEB922308733DC00010E9CD /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = YES; - GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_CHECK_SWITCH_STATEMENTS = YES; - GCC_WARN_MISSING_PARENTHESES = YES; - GCC_WARN_SHADOW = YES; - GCC_WARN_SIGN_COMPARE = YES; - GCC_WARN_STRICT_SELECTOR_MATCH = YES; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNKNOWN_PRAGMAS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_LABEL = YES; - GCC_WARN_UNUSED_VALUE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - OTHER_CFLAGS = "-DDEBUG=1"; - OTHER_LDFLAGS = "-ObjC"; - SDKROOT = macosx; - }; - name = Debug; - }; - 1DEB922408733DC00010E9CD /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - GCC_C_LANGUAGE_STANDARD = c99; - GCC_TREAT_IMPLICIT_FUNCTION_DECLARATIONS_AS_ERRORS = YES; - GCC_TREAT_WARNINGS_AS_ERRORS = YES; - GCC_WARN_ABOUT_MISSING_FIELD_INITIALIZERS = YES; - GCC_WARN_ABOUT_MISSING_NEWLINE = YES; - GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; - GCC_WARN_CHECK_SWITCH_STATEMENTS = YES; - GCC_WARN_MISSING_PARENTHESES = YES; - GCC_WARN_SHADOW = YES; - GCC_WARN_SIGN_COMPARE = YES; - GCC_WARN_STRICT_SELECTOR_MATCH = YES; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNKNOWN_PRAGMAS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_LABEL = YES; - GCC_WARN_UNUSED_VALUE = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - OTHER_LDFLAGS = "-ObjC"; - SDKROOT = macosx; - }; - name = Release; - }; - 4F724A7212248B19001A4AD0 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COPY_PHASE_STRIP = NO; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "\"$(DEVELOPER_FRAMEWORKS_DIR)\"", - ); - FRAMEWORK_VERSION = A; - GCC_DYNAMIC_NO_PIC = NO; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; - INFOPLIST_FILE = "Mac/GTMOAuth2Framework-Info.plist"; - INSTALL_PATH = "$(HOME)/Library/Frameworks"; - OTHER_LDFLAGS = ( - "-framework", - Foundation, - "-framework", - AppKit, - ); - PREBINDING = NO; - PRODUCT_NAME = GTMOAuth2; - SDKROOT = macosx; - }; - name = Debug; - }; - 4F724A7312248B19001A4AD0 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "\"$(DEVELOPER_FRAMEWORKS_DIR)\"", - ); - FRAMEWORK_VERSION = A; - GCC_MODEL_TUNING = G5; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; - INFOPLIST_FILE = "Mac/GTMOAuth2Framework-Info.plist"; - INSTALL_PATH = "$(HOME)/Library/Frameworks"; - OTHER_LDFLAGS = ( - "-framework", - Foundation, - "-framework", - AppKit, - ); - PREBINDING = NO; - PRODUCT_NAME = GTMOAuth2; - SDKROOT = macosx; - ZERO_LINK = NO; - }; - name = Release; - }; - 4FC754F813E77E25006A0C26 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - COPY_PHASE_STRIP = NO; - GCC_DYNAMIC_NO_PIC = NO; - INSTALL_PATH = /usr/local/lib; - OTHER_CFLAGS = ( - "-DGTM_OAUTH2_SKIP_GOOGLE_SUPPORT=1", - "$(inherited)", - ); - PRODUCT_NAME = OAuthTouch2NG; - SDKROOT = iphoneos; - }; - name = Debug; - }; - 4FC754F913E77E25006A0C26 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_32_BIT)"; - GCC_MODEL_TUNING = G5; - INSTALL_PATH = /usr/local/lib; - OTHER_CFLAGS = "-DGTM_OAUTH2_SKIP_GOOGLE_SUPPORT=1"; - PRODUCT_NAME = OAuthTouch2NG; - SDKROOT = iphoneos; - }; - name = Release; - }; - 4FC7551213E77E2B006A0C26 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COPY_PHASE_STRIP = NO; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "\"$(DEVELOPER_FRAMEWORKS_DIR)\"", - ); - FRAMEWORK_VERSION = A; - GCC_DYNAMIC_NO_PIC = NO; - GCC_MODEL_TUNING = G5; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; - INFOPLIST_FILE = "Mac/GTMOAuth2Framework-Info.plist"; - INSTALL_PATH = "$(HOME)/Library/Frameworks"; - OTHER_CFLAGS = ( - "-DGTM_OAUTH2_SKIP_GOOGLE_SUPPORT=1", - "$(inherited)", - ); - OTHER_LDFLAGS = ( - "-framework", - Foundation, - "-framework", - AppKit, - ); - PREBINDING = NO; - PRODUCT_NAME = GTMOAuth2; - SDKROOT = macosx; - }; - name = Debug; - }; - 4FC7551313E77E2B006A0C26 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - FRAMEWORK_SEARCH_PATHS = ( - "$(inherited)", - "\"$(DEVELOPER_FRAMEWORKS_DIR)\"", - ); - FRAMEWORK_VERSION = A; - GCC_MODEL_TUNING = G5; - GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/AppKit.framework/Headers/AppKit.h"; - INFOPLIST_FILE = "Mac/GTMOAuth2Framework-Info.plist"; - INSTALL_PATH = "$(HOME)/Library/Frameworks"; - OTHER_CFLAGS = "-DGTM_OAUTH2_SKIP_GOOGLE_SUPPORT=1"; - OTHER_LDFLAGS = ( - "-framework", - Foundation, - "-framework", - AppKit, - ); - PREBINDING = NO; - PRODUCT_NAME = GTMOAuth2; - SDKROOT = macosx; - ZERO_LINK = NO; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "OAuthTouchStaticLib" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB921F08733DC00010E9CD /* Debug */, - 1DEB922008733DC00010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "GTMOAuth2" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 1DEB922308733DC00010E9CD /* Debug */, - 1DEB922408733DC00010E9CD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4F724A7412248B19001A4AD0 /* Build configuration list for PBXNativeTarget "GTMOAuth2.framework" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4F724A7212248B19001A4AD0 /* Debug */, - 4F724A7312248B19001A4AD0 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4FC754F713E77E25006A0C26 /* Build configuration list for PBXNativeTarget "OAuthTouchNonGoogleStaticLib" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4FC754F813E77E25006A0C26 /* Debug */, - 4FC754F913E77E25006A0C26 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4FC7551113E77E2B006A0C26 /* Build configuration list for PBXNativeTarget "GTMOAuth2NonGoogle.framework" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 4FC7551213E77E2B006A0C26 /* Debug */, - 4FC7551313E77E2B006A0C26 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 0867D690FE84028FC02AAC07 /* Project object */; -} diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2Authentication.h b/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2Authentication.h deleted file mode 100644 index 02b9ce2e8..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2Authentication.h +++ /dev/null @@ -1,362 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -// This class implements the OAuth 2 protocol for authorizing requests. -// http://tools.ietf.org/html/draft-ietf-oauth-v2 - -#import - -#if GTM_USE_SESSION_FETCHER - #import "GTMSessionFetcher.h" -#else - #import "GTMHTTPFetcher.h" -#endif // GTM_USE_SESSION_FETCHER - -#define GTMOAuth2Fetcher GTMBridgeFetcher -#define GTMOAuth2FetcherService GTMBridgeFetcherService -#define GTMOAuth2FetcherServiceProtocol GTMBridgeFetcherServiceProtocol -#define GTMOAuth2AssertValidSelector GTMBridgeAssertValidSelector -#define GTMOAuth2CookieStorage GTMBridgeCookieStorage -#define kGTMOAuth2FetcherStatusDomain kGTMBridgeFetcherStatusDomain -#define kGTMOAuth2StatusBadRequest kGTMBridgeFetcherStatusBadRequest - - -// Until all OAuth 2 providers are up to the same spec, we'll provide a crude -// way here to override the "Bearer" string in the Authorization header -#ifndef GTM_OAUTH2_BEARER -#define GTM_OAUTH2_BEARER "Bearer" -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -// Service provider name allows stored authorization to be associated with -// the authorizing service -extern NSString *const kGTMOAuth2ServiceProviderGoogle; - -// -// GTMOAuth2SignIn constants, included here for use by clients -// -extern NSString *const kGTMOAuth2ErrorDomain; - -// Error userInfo keys -extern NSString *const kGTMOAuth2ErrorMessageKey; -extern NSString *const kGTMOAuth2ErrorRequestKey; -extern NSString *const kGTMOAuth2ErrorJSONKey; - -enum { - // Error code indicating that the window was prematurely closed - kGTMOAuth2ErrorWindowClosed = -1000, - kGTMOAuth2ErrorAuthorizationFailed = -1001, - kGTMOAuth2ErrorTokenExpired = -1002, - kGTMOAuth2ErrorTokenUnavailable = -1003, - kGTMOAuth2ErrorUnauthorizableRequest = -1004 -}; - - -// Notifications for token fetches -extern NSString *const kGTMOAuth2FetchStarted; -extern NSString *const kGTMOAuth2FetchStopped; - -extern NSString *const kGTMOAuth2FetcherKey; -extern NSString *const kGTMOAuth2FetchTypeKey; -extern NSString *const kGTMOAuth2FetchTypeToken; -extern NSString *const kGTMOAuth2FetchTypeRefresh; -extern NSString *const kGTMOAuth2FetchTypeAssertion; -extern NSString *const kGTMOAuth2FetchTypeUserInfo; - -// Token-issuance errors -extern NSString *const kGTMOAuth2ErrorKey; -extern NSString *const kGTMOAuth2ErrorObjectKey; - -extern NSString *const kGTMOAuth2ErrorInvalidRequest; -extern NSString *const kGTMOAuth2ErrorInvalidClient; -extern NSString *const kGTMOAuth2ErrorInvalidGrant; -extern NSString *const kGTMOAuth2ErrorUnauthorizedClient; -extern NSString *const kGTMOAuth2ErrorUnsupportedGrantType; -extern NSString *const kGTMOAuth2ErrorInvalidScope; - -// Notification that sign-in has completed, and token fetches will begin (useful -// for displaying interstitial messages after the window has closed) -extern NSString *const kGTMOAuth2UserSignedIn; - -// Notification for token changes -extern NSString *const kGTMOAuth2AccessTokenRefreshed; -extern NSString *const kGTMOAuth2RefreshTokenChanged; -extern NSString *const kGTMOAuth2AccessTokenRefreshFailed; - -// Notification for WebView loading -extern NSString *const kGTMOAuth2WebViewStartedLoading; -extern NSString *const kGTMOAuth2WebViewStoppedLoading; -extern NSString *const kGTMOAuth2WebViewKey; -extern NSString *const kGTMOAuth2WebViewStopKindKey; -extern NSString *const kGTMOAuth2WebViewFinished; -extern NSString *const kGTMOAuth2WebViewFailed; -extern NSString *const kGTMOAuth2WebViewCancelled; - -// Notification for network loss during html sign-in display -extern NSString *const kGTMOAuth2NetworkLost; -extern NSString *const kGTMOAuth2NetworkFound; - -#ifdef __cplusplus -} -#endif - -@interface GTMOAuth2Authentication : NSObject { - @private - NSString *clientID_; - NSString *clientSecret_; - NSString *redirectURI_; - NSMutableDictionary *parameters_; - - // authorization parameters - NSURL *tokenURL_; - NSDate *expirationDate_; - - NSString *authorizationTokenKey_; - - NSDictionary *additionalTokenRequestParameters_; - NSDictionary *additionalGrantTypeRequestParameters_; - - // queue of requests for authorization waiting for a valid access token - GTMOAuth2Fetcher *refreshFetcher_; - NSMutableArray *authorizationQueue_; - - id fetcherService_; // WEAK - - Class parserClass_; - - BOOL shouldAuthorizeAllRequests_; - - // arbitrary data retained for the user - id userData_; - NSMutableDictionary *properties_; -} - -// OAuth2 standard protocol parameters -// -// These should be the plain strings; any needed escaping will be provided by -// the library. - -// Request properties -@property (copy) NSString *clientID; -@property (copy) NSString *clientSecret; -@property (copy) NSString *redirectURI; -@property (retain) NSString *scope; -@property (retain) NSString *tokenType; -@property (retain) NSString *assertion; -@property (retain) NSString *refreshScope; - -// Apps may optionally add parameters here to be provided to the token -// endpoint on token requests and refreshes. -@property (retain) NSDictionary *additionalTokenRequestParameters; - -// Apps may optionally add parameters here to be provided to the token -// endpoint on specific token requests and refreshes, keyed by the grant_type. -// For example, if a different "type" parameter is required for obtaining -// the auth code and on refresh, this might be: -// -// viewController.authentication.additionalGrantTypeRequestParameters = @{ -// @"authorization_code" : @{ @"type" : @"code" }, -// @"refresh_token" : @{ @"type" : @"refresh" } -// }; -@property (retain) NSDictionary *additionalGrantTypeRequestParameters; - -// Response properties -@property (retain) NSMutableDictionary *parameters; - -@property (retain) NSString *accessToken; -@property (retain) NSString *refreshToken; -@property (retain) NSNumber *expiresIn; -@property (retain) NSString *code; -@property (retain) NSString *errorString; - -// URL for obtaining access tokens -@property (copy) NSURL *tokenURL; - -// Calculated expiration date (expiresIn seconds added to the -// time the access token was received.) -@property (copy) NSDate *expirationDate; - -// Service identifier, like "Google"; not used for authentication -// -// The provider name is just for allowing stored authorization to be associated -// with the authorizing service. -@property (copy) NSString *serviceProvider; - -// User ID; not used for authentication -@property (retain) NSString *userID; - -// User email and verified status; not used for authentication -// -// The verified string can be checked with -boolValue. If the result is false, -// then the email address is listed with the account on the server, but the -// address has not been confirmed as belonging to the owner of the account. -@property (retain) NSString *userEmail; -@property (retain) NSString *userEmailIsVerified; - -// Property indicating if this auth has a refresh or access token so is suitable -// for authorizing a request. This does not guarantee that the token is valid. -@property (readonly) BOOL canAuthorize; - -// Property indicating if this object will authorize plain http request -// (as well as any non-https requests.) Default is NO, only requests with the -// scheme https are authorized, since security may be compromised if tokens -// are sent over the wire using an unencrypted protocol like http. -@property (assign) BOOL shouldAuthorizeAllRequests; - -// userData is retained for the convenience of the caller -@property (retain) id userData; - -// Stored property values are retained for the convenience of the caller -@property (retain) NSDictionary *properties; - -// Property for the optional fetcher service instance to be used to create -// fetchers -// -// Fetcher service objects retain authorizations, so this is weak to avoid -// circular retains. -@property (assign) id fetcherService; // WEAK - -// Alternative JSON parsing class; this should implement the -// GTMOAuth2ParserClass informal protocol. If this property is -// not set, the class SBJSON must be available in the runtime. -@property (assign) Class parserClass; - -// Key for the response parameter used for the authorization header; by default, -// "access_token" is used, but some servers may expect alternatives, like -// "id_token". -@property (copy) NSString *authorizationTokenKey; - -// Convenience method for creating an authentication object -+ (id)authenticationWithServiceProvider:(NSString *)serviceProvider - tokenURL:(NSURL *)tokenURL - redirectURI:(NSString *)redirectURI - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret; - -// Clear out any authentication values, prepare for a new request fetch -- (void)reset; - -// Main authorization entry points -// -// These will refresh the access token, if necessary, add the access token to -// the request, then invoke the callback. -// -// The request argument may be nil to just force a refresh of the access token, -// if needed. -// -// NOTE: To avoid accidental leaks of bearer tokens, the request must -// be for a URL with the scheme https unless the shouldAuthorizeAllRequests -// property is set. - -// The finish selector should have a signature matching -// - (void)authentication:(GTMOAuth2Authentication *)auth -// request:(NSMutableURLRequest *)request -// finishedWithError:(NSError *)error; - -- (void)authorizeRequest:(NSMutableURLRequest *)request - delegate:(id)delegate - didFinishSelector:(SEL)sel; - -#if NS_BLOCKS_AVAILABLE -- (void)authorizeRequest:(NSMutableURLRequest *)request - completionHandler:(void (^)(NSError *error))handler; -#endif - -// Synchronous entry point; authorizing this way cannot refresh an expired -// access token -- (BOOL)authorizeRequest:(NSMutableURLRequest *)request; - -// If the authentication is waiting for a refresh to complete, spin the run -// loop, discarding events, until the fetch has completed -// -// This is only for use in testing or in tools without a user interface. -- (void)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds; - - -////////////////////////////////////////////////////////////////////////////// -// -// Internal properties and methods for use by GTMOAuth2SignIn -// - -// Pending fetcher to get a new access token, if any -@property (retain) GTMOAuth2Fetcher *refreshFetcher; - -// Check if a request is queued up to be authorized -- (BOOL)isAuthorizingRequest:(NSURLRequest *)request; - -// Check if a request appears to be authorized -- (BOOL)isAuthorizedRequest:(NSURLRequest *)request; - -// Stop any pending refresh fetch. This will also cancel the authorization -// for all fetch requests pending authorization. -- (void)stopAuthorization; - -// Prevents authorization callback for a given request. -- (void)stopAuthorizationForRequest:(NSURLRequest *)request; - -// OAuth fetch user-agent header value -- (NSString *)userAgent; - -// Parse and set token and token secret from response data -- (void)setKeysForResponseString:(NSString *)str; -- (void)setKeysForResponseDictionary:(NSDictionary *)dict; - -// Persistent token string for keychain storage -// -// We'll use the format "refresh_token=foo&serviceProvider=bar" so we can -// easily alter what portions of the auth data are stored -// -// Use these methods for serialization -- (NSString *)persistenceResponseString; -- (void)setKeysForPersistenceResponseString:(NSString *)str; - -// method to begin fetching an access token, used by the sign-in object -- (GTMOAuth2Fetcher *)beginTokenFetchWithDelegate:(id)delegate - didFinishSelector:(SEL)finishedSel; - -// Entry point to post a notification about a fetcher currently used for -// obtaining or refreshing a token; the sign-in object will also use this -// to indicate when the user's email address is being fetched. -// -// Fetch type constants are above under "notifications for token fetches" -- (void)notifyFetchIsRunning:(BOOL)isStarting - fetcher:(GTMOAuth2Fetcher *)fetcher - type:(NSString *)fetchType; - -// Arbitrary key-value properties retained for the user -- (void)setProperty:(id)obj forKey:(NSString *)key; -- (id)propertyForKey:(NSString *)key; - -// -// Utilities -// - -+ (NSString *)encodedOAuthValueForString:(NSString *)str; - -+ (NSString *)encodedQueryParametersForDictionary:(NSDictionary *)dict; - -+ (NSDictionary *)dictionaryWithResponseString:(NSString *)responseStr; - -+ (NSDictionary *)dictionaryWithJSONData:(NSData *)data; - -+ (NSString *)scopeWithStrings:(NSString *)firstStr, ... NS_REQUIRES_NIL_TERMINATION; -@end - -#endif // GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2Authentication.m b/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2Authentication.m deleted file mode 100644 index 8dcae26c6..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2Authentication.m +++ /dev/null @@ -1,1321 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#import "GTMOAuth2Authentication.h" - -// Extern strings - -NSString *const kGTMOAuth2ServiceProviderGoogle = @"Google"; - -NSString *const kGTMOAuth2ErrorDomain = @"com.google.GTMOAuth2"; - -NSString *const kGTMOAuth2ErrorMessageKey = @"error"; -NSString *const kGTMOAuth2ErrorRequestKey = @"request"; -NSString *const kGTMOAuth2ErrorJSONKey = @"json"; - -// Notifications -NSString *const kGTMOAuth2FetchStarted = @"kGTMOAuth2FetchStarted"; -NSString *const kGTMOAuth2FetchStopped = @"kGTMOAuth2FetchStopped"; - -NSString *const kGTMOAuth2FetcherKey = @"fetcher"; -NSString *const kGTMOAuth2FetchTypeKey = @"FetchType"; -NSString *const kGTMOAuth2FetchTypeToken = @"token"; -NSString *const kGTMOAuth2FetchTypeRefresh = @"refresh"; -NSString *const kGTMOAuth2FetchTypeAssertion = @"assertion"; -NSString *const kGTMOAuth2FetchTypeUserInfo = @"userInfo"; - -NSString *const kGTMOAuth2ErrorKey = @"error"; -NSString *const kGTMOAuth2ErrorObjectKey = @"kGTMOAuth2ErrorObjectKey"; - -NSString *const kGTMOAuth2ErrorInvalidRequest = @"invalid_request"; -NSString *const kGTMOAuth2ErrorInvalidClient = @"invalid_client"; -NSString *const kGTMOAuth2ErrorInvalidGrant = @"invalid_grant"; -NSString *const kGTMOAuth2ErrorUnauthorizedClient = @"unauthorized_client"; -NSString *const kGTMOAuth2ErrorUnsupportedGrantType = @"unsupported_grant_type"; -NSString *const kGTMOAuth2ErrorInvalidScope = @"invalid_scope"; - -NSString *const kGTMOAuth2UserSignedIn = @"kGTMOAuth2UserSignedIn"; - -NSString *const kGTMOAuth2AccessTokenRefreshed = @"kGTMOAuth2AccessTokenRefreshed"; -NSString *const kGTMOAuth2RefreshTokenChanged = @"kGTMOAuth2RefreshTokenChanged"; -NSString *const kGTMOAuth2AccessTokenRefreshFailed = @"kGTMOAuth2AccessTokenRefreshFailed"; - -NSString *const kGTMOAuth2WebViewStartedLoading = @"kGTMOAuth2WebViewStartedLoading"; -NSString *const kGTMOAuth2WebViewStoppedLoading = @"kGTMOAuth2WebViewStoppedLoading"; -NSString *const kGTMOAuth2WebViewKey = @"kGTMOAuth2WebViewKey"; -NSString *const kGTMOAuth2WebViewStopKindKey = @"kGTMOAuth2WebViewStopKindKey"; -NSString *const kGTMOAuth2WebViewFinished = @"finished"; -NSString *const kGTMOAuth2WebViewFailed = @"failed"; -NSString *const kGTMOAuth2WebViewCancelled = @"cancelled"; - -NSString *const kGTMOAuth2NetworkLost = @"kGTMOAuthNetworkLost"; -NSString *const kGTMOAuth2NetworkFound = @"kGTMOAuthNetworkFound"; - -// standard OAuth keys -static NSString *const kOAuth2AccessTokenKey = @"access_token"; -static NSString *const kOAuth2RefreshTokenKey = @"refresh_token"; -static NSString *const kOAuth2ScopeKey = @"scope"; -static NSString *const kOAuth2ErrorKey = @"error"; -static NSString *const kOAuth2TokenTypeKey = @"token_type"; -static NSString *const kOAuth2ExpiresInKey = @"expires_in"; -static NSString *const kOAuth2CodeKey = @"code"; -static NSString *const kOAuth2AssertionKey = @"assertion"; -static NSString *const kOAuth2RefreshScopeKey = @"refreshScope"; - -// additional persistent keys -static NSString *const kServiceProviderKey = @"serviceProvider"; -static NSString *const kUserIDKey = @"userID"; -static NSString *const kUserEmailKey = @"email"; -static NSString *const kUserEmailIsVerifiedKey = @"isVerified"; - -// fetcher keys -static NSString *const kTokenFetchDelegateKey = @"delegate"; -static NSString *const kTokenFetchSelectorKey = @"sel"; - -// If GTMNSJSONSerialization is available, it is used for formatting JSON -#if (TARGET_OS_MAC && !TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MAX_ALLOWED < 1070)) || \ - (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED < 50000)) -@interface GTMNSJSONSerialization : NSObject -+ (id)JSONObjectWithData:(NSData *)data options:(NSUInteger)opt error:(NSError **)error; -@end -#endif - -@interface GTMOAuth2ParserClass : NSObject -// just enough of SBJSON to be able to parse -- (id)objectWithString:(NSString*)repr error:(NSError**)error; -@end - -// wrapper class for requests needing authorization and their callbacks -@interface GTMOAuth2AuthorizationArgs : NSObject { - @private - NSMutableURLRequest *request_; - id delegate_; - SEL sel_; - id completionHandler_; - NSThread *thread_; - NSError *error_; -} - -@property (retain) NSMutableURLRequest *request; -@property (retain) id delegate; -@property (assign) SEL selector; -@property (copy) id completionHandler; -@property (retain) NSThread *thread; -@property (retain) NSError *error; - -+ (GTMOAuth2AuthorizationArgs *)argsWithRequest:(NSMutableURLRequest *)req - delegate:(id)delegate - selector:(SEL)sel - completionHandler:(id)completionHandler - thread:(NSThread *)thread; -@end - -@implementation GTMOAuth2AuthorizationArgs - -@synthesize request = request_, - delegate = delegate_, - selector = sel_, - completionHandler = completionHandler_, - thread = thread_, - error = error_; - -+ (GTMOAuth2AuthorizationArgs *)argsWithRequest:(NSMutableURLRequest *)req - delegate:(id)delegate - selector:(SEL)sel - completionHandler:(id)completionHandler - thread:(NSThread *)thread { - GTMOAuth2AuthorizationArgs *obj; - obj = [[[GTMOAuth2AuthorizationArgs alloc] init] autorelease]; - obj.request = req; - obj.delegate = delegate; - obj.selector = sel; - obj.completionHandler = completionHandler; - obj.thread = thread; - return obj; -} - -- (void)dealloc { - [request_ release]; - [delegate_ release]; - [completionHandler_ release]; - [thread_ release]; - [error_ release]; - - [super dealloc]; -} -@end - - -@interface GTMOAuth2Authentication () - -@property (retain) NSMutableArray *authorizationQueue; -@property (readonly) NSString *authorizationToken; - -- (void)setKeysForResponseJSONData:(NSData *)data; - -- (BOOL)authorizeRequestArgs:(GTMOAuth2AuthorizationArgs *)args; - -- (BOOL)authorizeRequestImmediateArgs:(GTMOAuth2AuthorizationArgs *)args; - -- (BOOL)shouldRefreshAccessToken; - -- (void)updateExpirationDate; - -- (void)tokenFetcher:(GTMOAuth2Fetcher *)fetcher - finishedWithData:(NSData *)data - error:(NSError *)error; - -- (void)auth:(GTMOAuth2Authentication *)auth -finishedRefreshWithFetcher:(GTMOAuth2Fetcher *)fetcher - error:(NSError *)error; - -- (void)invokeCallbackArgs:(GTMOAuth2AuthorizationArgs *)args; - -+ (void)invokeDelegate:(id)delegate - selector:(SEL)sel - object:(id)obj1 - object:(id)obj2 - object:(id)obj3; - -+ (NSString *)unencodedOAuthParameterForString:(NSString *)str; -+ (NSString *)encodedQueryParametersForDictionary:(NSDictionary *)dict; - -+ (NSDictionary *)dictionaryWithResponseData:(NSData *)data; - -@end - -@implementation GTMOAuth2Authentication - -@synthesize clientID = clientID_, - clientSecret = clientSecret_, - redirectURI = redirectURI_, - parameters = parameters_, - authorizationTokenKey = authorizationTokenKey_, - tokenURL = tokenURL_, - expirationDate = expirationDate_, - additionalTokenRequestParameters = additionalTokenRequestParameters_, - additionalGrantTypeRequestParameters = additionalGrantTypeRequestParameters_, - refreshFetcher = refreshFetcher_, - fetcherService = fetcherService_, - parserClass = parserClass_, - shouldAuthorizeAllRequests = shouldAuthorizeAllRequests_, - userData = userData_, - properties = properties_, - authorizationQueue = authorizationQueue_; - -// Response parameters -@dynamic accessToken, - refreshToken, - code, - assertion, - refreshScope, - errorString, - tokenType, - scope, - expiresIn, - serviceProvider, - userEmail, - userEmailIsVerified; - -@dynamic canAuthorize; - -+ (id)authenticationWithServiceProvider:(NSString *)serviceProvider - tokenURL:(NSURL *)tokenURL - redirectURI:(NSString *)redirectURI - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret { - GTMOAuth2Authentication *obj = [[[self alloc] init] autorelease]; - obj.serviceProvider = serviceProvider; - obj.tokenURL = tokenURL; - obj.redirectURI = redirectURI; - obj.clientID = clientID; - obj.clientSecret = clientSecret; - return obj; -} - -- (id)init { - self = [super init]; - if (self) { - authorizationQueue_ = [[NSMutableArray alloc] init]; - parameters_ = [[NSMutableDictionary alloc] init]; - } - return self; -} - -- (NSString *)description { - NSArray *props = [NSArray arrayWithObjects:@"accessToken", @"refreshToken", - @"code", @"assertion", @"expirationDate", @"errorString", - nil]; - NSMutableString *valuesStr = [NSMutableString string]; - NSString *separator = @""; - for (NSString *prop in props) { - id result = [self valueForKey:prop]; - if (result) { - [valuesStr appendFormat:@"%@%@=\"%@\"", separator, prop, result]; - separator = @", "; - } - } - - return [NSString stringWithFormat:@"%@ %p: {%@}", - [self class], self, valuesStr]; -} - -- (void)dealloc { - [clientID_ release]; - [clientSecret_ release]; - [redirectURI_ release]; - [parameters_ release]; - [authorizationTokenKey_ release]; - [tokenURL_ release]; - [expirationDate_ release]; - [additionalTokenRequestParameters_ release]; - [additionalGrantTypeRequestParameters_ release]; - [refreshFetcher_ release]; - [authorizationQueue_ release]; - [userData_ release]; - [properties_ release]; - - [super dealloc]; -} - -#pragma mark - - -- (void)setKeysForResponseDictionary:(NSDictionary *)dict { - if (dict == nil) return; - - // If a new code or access token is being set, remove the old expiration - NSString *newCode = [dict objectForKey:kOAuth2CodeKey]; - NSString *newAccessToken = [dict objectForKey:kOAuth2AccessTokenKey]; - if (newCode || newAccessToken) { - self.expiresIn = nil; - } - - BOOL didRefreshTokenChange = NO; - NSString *refreshToken = [dict objectForKey:kOAuth2RefreshTokenKey]; - if (refreshToken) { - NSString *priorRefreshToken = self.refreshToken; - - if (priorRefreshToken != refreshToken - && (priorRefreshToken == nil - || ![priorRefreshToken isEqual:refreshToken])) { - didRefreshTokenChange = YES; - } - } - - [self.parameters addEntriesFromDictionary:dict]; - [self updateExpirationDate]; - - if (didRefreshTokenChange) { - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:kGTMOAuth2RefreshTokenChanged - object:self - userInfo:nil]; - } - // NSLog(@"keys set ----------------------------\n%@", dict); -} - -- (void)setKeysForResponseString:(NSString *)str { - NSDictionary *dict = [[self class] dictionaryWithResponseString:str]; - [self setKeysForResponseDictionary:dict]; -} - -- (void)setKeysForResponseJSONData:(NSData *)data { - NSDictionary *dict = [[self class] dictionaryWithJSONData:data]; - [self setKeysForResponseDictionary:dict]; -} - -+ (NSDictionary *)dictionaryWithJSONData:(NSData *)data { - NSMutableDictionary *obj = nil; - NSError *error = nil; - - Class serializer = NSClassFromString(@"NSJSONSerialization"); - if (serializer) { - const NSUInteger kOpts = (1UL << 0); // NSJSONReadingMutableContainers - obj = [serializer JSONObjectWithData:data - options:kOpts - error:&error]; -#if DEBUG - if (error) { - NSString *str = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - NSLog(@"NSJSONSerialization error %@ parsing %@", - error, str); - } -#endif - return obj; - } else { - // try SBJsonParser or SBJSON - Class jsonParseClass = NSClassFromString(@"SBJsonParser"); - if (!jsonParseClass) { - jsonParseClass = NSClassFromString(@"SBJSON"); - } - if (jsonParseClass) { - GTMOAuth2ParserClass *parser = [[[jsonParseClass alloc] init] autorelease]; - NSString *jsonStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - if (jsonStr) { - obj = [parser objectWithString:jsonStr error:&error]; -#if DEBUG - if (error) { - NSLog(@"%@ error %@ parsing %@", NSStringFromClass(jsonParseClass), - error, jsonStr); - } -#endif - return obj; - } - } else { -#if DEBUG - NSAssert(0, @"GTMOAuth2Authentication: No parser available"); -#endif - } - } - return nil; -} - -#pragma mark Authorizing Requests - -// General entry point for authorizing requests - -#if NS_BLOCKS_AVAILABLE -// Authorizing with a completion block -- (void)authorizeRequest:(NSMutableURLRequest *)request - completionHandler:(void (^)(NSError *error))handler { - - GTMOAuth2AuthorizationArgs *args; - args = [GTMOAuth2AuthorizationArgs argsWithRequest:request - delegate:nil - selector:NULL - completionHandler:handler - thread:[NSThread currentThread]]; - [self authorizeRequestArgs:args]; -} -#endif - -// Authorizing with a callback selector -// -// Selector has the signature -// - (void)authentication:(GTMOAuth2Authentication *)auth -// request:(NSMutableURLRequest *)request -// finishedWithError:(NSError *)error; -- (void)authorizeRequest:(NSMutableURLRequest *)request - delegate:(id)delegate - didFinishSelector:(SEL)sel { - GTMOAuth2AssertValidSelector(delegate, sel, - @encode(GTMOAuth2Authentication *), - @encode(NSMutableURLRequest *), - @encode(NSError *), 0); - - GTMOAuth2AuthorizationArgs *args; - args = [GTMOAuth2AuthorizationArgs argsWithRequest:request - delegate:delegate - selector:sel - completionHandler:nil - thread:[NSThread currentThread]]; - [self authorizeRequestArgs:args]; -} - -// Internal routine common to delegate and block invocations -- (BOOL)authorizeRequestArgs:(GTMOAuth2AuthorizationArgs *)args { - BOOL didAttempt = NO; - - @synchronized(authorizationQueue_) { - - BOOL shouldRefresh = [self shouldRefreshAccessToken]; - - if (shouldRefresh) { - NSLog(@"Should refresh. Thread: %@\n", [NSThread currentThread].description); - // attempt to refresh now; once we have a fresh access token, we will - // authorize the request and call back to the user - didAttempt = YES; - - if (self.refreshFetcher == nil) { - // there's not already a refresh pending - SEL finishedSel = @selector(auth:finishedRefreshWithFetcher:error:); - self.refreshFetcher = [self beginTokenFetchWithDelegate:self - didFinishSelector:finishedSel]; - if (self.refreshFetcher) { - [authorizationQueue_ addObject:args]; - } - } else { - // there's already a refresh pending - [authorizationQueue_ addObject:args]; - } - } - - if (!shouldRefresh || self.refreshFetcher == nil) { - // we're not fetching a new access token, so we can authorize the request - // now - didAttempt = [self authorizeRequestImmediateArgs:args]; - } - } - return didAttempt; -} - -- (void)auth:(GTMOAuth2Authentication *)auth -finishedRefreshWithFetcher:(GTMOAuth2Fetcher *)fetcher - error:(NSError *)error { - @synchronized(authorizationQueue_) { - NSLog(@"auth:FinishedRefreshWithFetcher:error done. Thread: %@\n", [NSThread currentThread].description); - - // If there's an error, we want to try using the old access token anyway, - // in case it's a backend problem preventing refresh, in which case - // access tokens past their expiration date may still work - - self.refreshFetcher = nil; - - // Swap in a new auth queue in case the callbacks try to immediately auth - // another request - NSArray *pendingAuthQueue = [NSArray arrayWithArray:authorizationQueue_]; - [authorizationQueue_ removeAllObjects]; - - BOOL hasAccessToken = ([self.accessToken length] > 0); - - NSString *noteName; - NSDictionary *userInfo = nil; - if (hasAccessToken && error == nil) { - // Successful refresh. - noteName = kGTMOAuth2AccessTokenRefreshed; - userInfo = nil; - } else { - // Google's OAuth 2 implementation returns a 400 with JSON body - // containing error key "invalid_grant" to indicate the refresh token - // is invalid or has been revoked by the user. We'll promote the - // JSON error key's value for easy inspection by the observer. - noteName = kGTMOAuth2AccessTokenRefreshFailed; - NSString *jsonErr = nil; - if ([error code] == kGTMOAuth2StatusBadRequest) { - NSDictionary *json = [[error userInfo] objectForKey:kGTMOAuth2ErrorJSONKey]; - jsonErr = [json objectForKey:kGTMOAuth2ErrorMessageKey]; - } - // error and jsonErr may be nil - userInfo = [NSMutableDictionary dictionary]; - [userInfo setValue:error forKey:kGTMOAuth2ErrorObjectKey]; - [userInfo setValue:jsonErr forKey:kGTMOAuth2ErrorMessageKey]; - } - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:noteName - object:self - userInfo:userInfo]; - - for (GTMOAuth2AuthorizationArgs *args in pendingAuthQueue) { - if (!hasAccessToken && args.error == nil) { - args.error = error; - } - - [self authorizeRequestImmediateArgs:args]; - } - } -} - -- (BOOL)isAuthorizingRequest:(NSURLRequest *)request { - BOOL wasFound = NO; - @synchronized(authorizationQueue_) { - for (GTMOAuth2AuthorizationArgs *args in authorizationQueue_) { - if ([args request] == request) { - wasFound = YES; - break; - } - } - } - return wasFound; -} - -- (BOOL)isAuthorizedRequest:(NSURLRequest *)request { - NSString *authStr = [request valueForHTTPHeaderField:@"Authorization"]; - return ([authStr length] > 0); -} - -- (void)stopAuthorization { - @synchronized(authorizationQueue_) { - [authorizationQueue_ removeAllObjects]; - - [self.refreshFetcher stopFetching]; - self.refreshFetcher = nil; - } -} - -- (void)stopAuthorizationForRequest:(NSURLRequest *)request { - @synchronized(authorizationQueue_) { - NSUInteger argIndex = 0; - BOOL found = NO; - for (GTMOAuth2AuthorizationArgs *args in authorizationQueue_) { - if ([args request] == request) { - found = YES; - break; - } - argIndex++; - } - - if (found) { - [authorizationQueue_ removeObjectAtIndex:argIndex]; - - // If the queue is now empty, go ahead and stop the fetcher. - if ([authorizationQueue_ count] == 0) { - [self stopAuthorization]; - } - } - } -} - -- (BOOL)authorizeRequestImmediateArgs:(GTMOAuth2AuthorizationArgs *)args { - // This authorization entry point never attempts to refresh the access token, - // but does call the completion routine - - NSMutableURLRequest *request = args.request; - - NSURL *requestURL = [request URL]; - NSString *scheme = [requestURL scheme]; - BOOL isAuthorizableRequest = self.shouldAuthorizeAllRequests - || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame - || [requestURL isFileURL]; - if (!isAuthorizableRequest) { - // Request is not https, so may be insecure - // - // The NSError will be created below -#if DEBUG - NSLog(@"Cannot authorize request with scheme %@ (%@)", scheme, request); -#endif - } - - // Get the access token. - NSString *accessToken = self.authorizationToken; - if (isAuthorizableRequest && [accessToken length] > 0) { - if (request) { - // we have a likely valid access token - NSString *value = [NSString stringWithFormat:@"%s %@", - GTM_OAUTH2_BEARER, accessToken]; - [request setValue:value forHTTPHeaderField:@"Authorization"]; - } - - // We've authorized the request, even if the previous refresh - // failed with an error - args.error = nil; - } else if (args.error == nil) { - NSDictionary *userInfo = nil; - if (request) { - userInfo = [NSDictionary dictionaryWithObject:request - forKey:kGTMOAuth2ErrorRequestKey]; - } - NSInteger code = (isAuthorizableRequest ? - kGTMOAuth2ErrorAuthorizationFailed : - kGTMOAuth2ErrorUnauthorizableRequest); - args.error = [NSError errorWithDomain:kGTMOAuth2ErrorDomain - code:code - userInfo:userInfo]; - } - - // Invoke any callbacks on the proper thread - if (args.delegate || args.completionHandler) { - NSThread *targetThread = args.thread; - NSThread *currentThread = [NSThread currentThread]; - BOOL isSameThread = [targetThread isEqual:currentThread]; - - if (isSameThread) { - [self invokeCallbackArgs:args]; - } else { - SEL sel = @selector(invokeCallbackArgs:); - NSOperationQueue *delegateQueue = self.fetcherService.delegateQueue; - if (delegateQueue) { - NSInvocationOperation *op; - op = [[[NSInvocationOperation alloc] initWithTarget:self - selector:sel - object:args] autorelease]; - [delegateQueue addOperation:op]; - } else { - NSLog(@"sel: %@\n thread: %@\n error: %@\n request:%@\n args.selector:%@\n args.delegate:%d\n ", NSStringFromSelector(sel), targetThread, args.error, args.request.description, - NSStringFromSelector(args.selector), (args.delegate == nil)); - [self performSelector:sel - onThread:targetThread - withObject:args - waitUntilDone:NO]; - } - } - } - - BOOL didAuth = (args.error == nil); - return didAuth; -} - -- (void)invokeCallbackArgs:(GTMOAuth2AuthorizationArgs *)args { - // Invoke the callbacks - NSError *error = args.error; - - id delegate = args.delegate; - SEL sel = args.selector; - if (delegate && sel) { - NSMutableURLRequest *request = args.request; - - NSMethodSignature *sig = [delegate methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:delegate]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&request atIndex:3]; - [invocation setArgument:&error atIndex:4]; - [invocation invoke]; - } - -#if NS_BLOCKS_AVAILABLE - id handler = args.completionHandler; - if (handler) { - void (^authCompletionBlock)(NSError *) = handler; - authCompletionBlock(error); - } -#endif -} - -- (BOOL)authorizeRequest:(NSMutableURLRequest *)request { - // Entry point for synchronous authorization mechanisms - GTMOAuth2AuthorizationArgs *args; - args = [GTMOAuth2AuthorizationArgs argsWithRequest:request - delegate:nil - selector:NULL - completionHandler:nil - thread:[NSThread currentThread]]; - return [self authorizeRequestImmediateArgs:args]; -} - -- (BOOL)canAuthorize { - NSString *token = self.refreshToken; - if (token == nil) { - // For services which do not support refresh tokens, we'll just check - // the access token. - token = self.authorizationToken; - } - BOOL canAuth = [token length] > 0; - return canAuth; -} - -- (BOOL)shouldRefreshAccessToken { - // We should refresh the access token when it's missing or nearly expired - // and we have a refresh token - BOOL shouldRefresh = NO; - NSString *accessToken = self.accessToken; - NSString *refreshToken = self.refreshToken; - NSString *assertion = self.assertion; - NSString *code = self.code; - - BOOL hasRefreshToken = ([refreshToken length] > 0); - BOOL hasAccessToken = ([accessToken length] > 0); - BOOL hasAssertion = ([assertion length] > 0); - BOOL hasCode = ([code length] > 0); - - // Determine if we need to refresh the access token - if (hasRefreshToken || hasAssertion || hasCode) { - if (!hasAccessToken) { - shouldRefresh = YES; - } else { - // We'll consider the token expired if it expires 60 seconds from now - // or earlier - NSDate *expirationDate = self.expirationDate; - NSTimeInterval timeToExpire = [expirationDate timeIntervalSinceNow]; - if (expirationDate == nil || timeToExpire < 60.0) { - // access token has expired, or will in a few seconds - shouldRefresh = YES; - } - } - } - return shouldRefresh; -} - -- (void)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds { - // If there is a refresh fetcher pending, wait for it. - // - // This is only intended for unit test or for use in command-line tools. - GTMOAuth2Fetcher *fetcher = self.refreshFetcher; - [fetcher waitForCompletionWithTimeout:timeoutInSeconds]; -} - -#pragma mark Token Fetch - -- (NSString *)userAgent { - NSBundle *bundle = [NSBundle mainBundle]; - NSString *appID = [bundle bundleIdentifier]; - - NSString *version = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - if (version == nil) { - version = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"]; - } - - if (appID && version) { - appID = [appID stringByAppendingFormat:@"/%@", version]; - } - - NSString *userAgent = @"gtm-oauth2"; - if (appID) { - userAgent = [userAgent stringByAppendingFormat:@" %@", appID]; - } - return userAgent; -} - -- (GTMOAuth2Fetcher *)beginTokenFetchWithDelegate:(id)delegate - didFinishSelector:(SEL)finishedSel { - - NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary]; - - NSString *fetchType; - - NSString *refreshToken = self.refreshToken; - NSString *code = self.code; - NSString *assertion = self.assertion; - NSString *grantType = nil; - - if (refreshToken) { - // We have a refresh token - grantType = @"refresh_token"; - [paramsDict setObject:refreshToken forKey:@"refresh_token"]; - - NSString *refreshScope = self.refreshScope; - if ([refreshScope length] > 0) { - [paramsDict setObject:refreshScope forKey:@"scope"]; - } - - fetchType = kGTMOAuth2FetchTypeRefresh; - } else if (code) { - // We have a code string - grantType = @"authorization_code"; - [paramsDict setObject:code forKey:@"code"]; - - NSString *redirectURI = self.redirectURI; - if ([redirectURI length] > 0) { - [paramsDict setObject:redirectURI forKey:@"redirect_uri"]; - } - - NSString *scope = self.scope; - if ([scope length] > 0) { - [paramsDict setObject:scope forKey:@"scope"]; - } - - fetchType = kGTMOAuth2FetchTypeToken; - } else if (assertion) { - // We have an assertion string - grantType = @"http://oauth.net/grant_type/jwt/1.0/bearer"; - [paramsDict setObject:assertion forKey:@"assertion"]; - fetchType = kGTMOAuth2FetchTypeAssertion; - } else { -#if DEBUG - NSAssert(0, @"unexpected lack of code or refresh token for fetching"); -#endif - return nil; - } - [paramsDict setObject:grantType forKey:@"grant_type"]; - - NSString *clientID = self.clientID; - if ([clientID length] > 0) { - [paramsDict setObject:clientID forKey:@"client_id"]; - } - - NSString *clientSecret = self.clientSecret; - if ([clientSecret length] > 0) { - [paramsDict setObject:clientSecret forKey:@"client_secret"]; - } - - NSDictionary *additionalParams = self.additionalTokenRequestParameters; - if (additionalParams) { - [paramsDict addEntriesFromDictionary:additionalParams]; - } - NSDictionary *grantTypeParams = - [self.additionalGrantTypeRequestParameters objectForKey:grantType]; - if (grantTypeParams) { - [paramsDict addEntriesFromDictionary:grantTypeParams]; - } - - NSString *paramStr = [[self class] encodedQueryParametersForDictionary:paramsDict]; - NSData *paramData = [paramStr dataUsingEncoding:NSUTF8StringEncoding]; - - NSURL *tokenURL = self.tokenURL; - - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:tokenURL]; - [request setValue:@"application/x-www-form-urlencoded" - forHTTPHeaderField:@"Content-Type"]; - - NSString *userAgent = [self userAgent]; - [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - - GTMOAuth2Fetcher *fetcher; - id fetcherService = self.fetcherService; - if (fetcherService) { - fetcher = (GTMOAuth2Fetcher *)[fetcherService fetcherWithRequest:request]; - - // Don't use an authorizer for an auth token fetch - fetcher.authorizer = nil; - } else { - fetcher = [GTMOAuth2Fetcher fetcherWithRequest:request]; - } - -#if !STRIP_GTM_FETCH_LOGGING - // The user email address is known at token refresh time, not during the initial code exchange. - NSString *userEmail = [self userEmail]; - NSString *forStr = userEmail ? [NSString stringWithFormat:@"for \"%@\"", userEmail] : @""; - [fetcher setCommentWithFormat:@"GTMOAuth2 %@ fetch to %@ %@", fetchType, [tokenURL host], forStr]; -#endif - - fetcher.bodyData = paramData; - fetcher.retryEnabled = YES; - fetcher.maxRetryInterval = 15.0; - - // Fetcher properties will retain the delegate - [fetcher setProperty:delegate forKey:kTokenFetchDelegateKey]; - if (finishedSel) { - NSString *selStr = NSStringFromSelector(finishedSel); - [fetcher setProperty:selStr forKey:kTokenFetchSelectorKey]; - } - - [fetcher beginFetchWithDelegate:self - didFinishSelector:@selector(tokenFetcher:finishedWithData:error:)]; - - [self notifyFetchIsRunning:YES fetcher:fetcher type:fetchType]; - return fetcher; -} - -- (void)tokenFetcher:(GTMOAuth2Fetcher *)fetcher - finishedWithData:(NSData *)data - error:(NSError *)error { - [self notifyFetchIsRunning:NO fetcher:fetcher type:nil]; - - NSDictionary *responseHeaders = [fetcher responseHeaders]; - NSString *responseType = [responseHeaders valueForKey:@"Content-Type"]; - BOOL isResponseJSON = [responseType hasPrefix:@"application/json"]; - BOOL hasData = ([data length] > 0); - - if (error) { - // Failed. If the error body is JSON, parse it and add it to the error's - // userInfo dictionary. - if (hasData) { - if (isResponseJSON) { - NSDictionary *errorJson = [[self class] dictionaryWithJSONData:data]; - if ([errorJson count] > 0) { -#if DEBUG - NSLog(@"Error %@\nError data:\n%@", error, errorJson); -#endif - // Add the JSON error body to the userInfo of the error - NSMutableDictionary *userInfo; - userInfo = [NSMutableDictionary dictionaryWithObject:errorJson - forKey:kGTMOAuth2ErrorJSONKey]; - NSDictionary *prevUserInfo = [error userInfo]; - if (prevUserInfo) { - [userInfo addEntriesFromDictionary:prevUserInfo]; - } - error = [NSError errorWithDomain:[error domain] - code:[error code] - userInfo:userInfo]; - } - } - } - } else { - // Succeeded; we have the requested token. -#if DEBUG - NSAssert(hasData, @"data missing in token response"); -#endif - - if (hasData) { - if (isResponseJSON) { - [self setKeysForResponseJSONData:data]; - } else { - // Support for legacy token servers that return form-urlencoded data - NSString *dataStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - [self setKeysForResponseString:dataStr]; - } - -#if DEBUG - // Watch for token exchanges that return a non-bearer or unlabeled token - NSString *tokenType = [self tokenType]; - if (tokenType == nil - || [tokenType caseInsensitiveCompare:@"bearer"] != NSOrderedSame) { - NSLog(@"GTMOAuth2: Unexpected token type: %@", tokenType); - } -#endif - } - } - - id delegate = [fetcher propertyForKey:kTokenFetchDelegateKey]; - SEL sel = NULL; - NSString *selStr = [fetcher propertyForKey:kTokenFetchSelectorKey]; - if (selStr) sel = NSSelectorFromString(selStr); - - [[self class] invokeDelegate:delegate - selector:sel - object:self - object:fetcher - object:error]; - - // Prevent a circular reference from retaining the delegate - [fetcher setProperty:nil forKey:kTokenFetchDelegateKey]; -} - -#pragma mark Fetch Notifications - -- (void)notifyFetchIsRunning:(BOOL)isStarting - fetcher:(GTMOAuth2Fetcher *)fetcher - type:(NSString *)fetchType { - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - - NSString *name = (isStarting ? kGTMOAuth2FetchStarted : kGTMOAuth2FetchStopped); - NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: - fetcher, kGTMOAuth2FetcherKey, - fetchType, kGTMOAuth2FetchTypeKey, // fetchType may be nil - nil]; - [nc postNotificationName:name - object:self - userInfo:dict]; -} - -#pragma mark Persistent Response Strings - -- (void)setKeysForPersistenceResponseString:(NSString *)str { - // All persistence keys can be set directly as if returned by a server - [self setKeysForResponseString:str]; -} - -// This returns a "response string" that can be passed later to -// setKeysForResponseString: to reuse an old access token in a new auth object -- (NSString *)persistenceResponseString { - NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:4]; - - NSString *refreshToken = self.refreshToken; - NSString *accessToken = nil; - if (refreshToken == nil) { - // We store the access token only for services that do not support refresh - // tokens; otherwise, we assume the access token is too perishable to - // be worth storing - accessToken = self.accessToken; - } - - // Any nil values will not set a dictionary entry - [dict setValue:refreshToken forKey:kOAuth2RefreshTokenKey]; - [dict setValue:accessToken forKey:kOAuth2AccessTokenKey]; - [dict setValue:self.serviceProvider forKey:kServiceProviderKey]; - [dict setValue:self.userID forKey:kUserIDKey]; - [dict setValue:self.userEmail forKey:kUserEmailKey]; - [dict setValue:self.userEmailIsVerified forKey:kUserEmailIsVerifiedKey]; - [dict setValue:self.scope forKey:kOAuth2ScopeKey]; - - NSString *result = [[self class] encodedQueryParametersForDictionary:dict]; - return result; -} - -- (BOOL)primeForRefresh { - if (self.refreshToken == nil) { - // Cannot refresh without a refresh token - return NO; - } - self.accessToken = nil; - self.expiresIn = nil; - self.expirationDate = nil; - self.errorString = nil; - return YES; -} - -- (void)reset { - // Reset all per-authorization values - self.code = nil; - self.accessToken = nil; - self.refreshToken = nil; - self.assertion = nil; - self.expiresIn = nil; - self.errorString = nil; - self.expirationDate = nil; - self.userEmail = nil; - self.userEmailIsVerified = nil; - self.authorizationTokenKey = nil; -} - -#pragma mark Accessors for Response Parameters - -- (NSString *)authorizationToken { - // The token used for authorization is typically the access token unless - // the user has specified that an alternative parameter be used. - NSString *authorizationToken; - NSString *authTokenKey = self.authorizationTokenKey; - if (authTokenKey != nil) { - authorizationToken = [self.parameters objectForKey:authTokenKey]; - } else { - authorizationToken = self.accessToken; - } - return authorizationToken; -} - -- (NSString *)accessToken { - return [self.parameters objectForKey:kOAuth2AccessTokenKey]; -} - -- (void)setAccessToken:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2AccessTokenKey]; -} - -- (NSString *)refreshToken { - return [self.parameters objectForKey:kOAuth2RefreshTokenKey]; -} - -- (void)setRefreshToken:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2RefreshTokenKey]; -} - -- (NSString *)code { - return [self.parameters objectForKey:kOAuth2CodeKey]; -} - -- (void)setCode:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2CodeKey]; -} - -- (NSString *)assertion { - return [self.parameters objectForKey:kOAuth2AssertionKey]; -} - -- (void)setAssertion:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2AssertionKey]; -} - -- (NSString *)refreshScope { - return [self.parameters objectForKey:kOAuth2RefreshScopeKey]; -} - -- (void)setRefreshScope:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2RefreshScopeKey]; -} - -- (NSString *)errorString { - return [self.parameters objectForKey:kOAuth2ErrorKey]; -} - -- (void)setErrorString:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2ErrorKey]; -} - -- (NSString *)tokenType { - return [self.parameters objectForKey:kOAuth2TokenTypeKey]; -} - -- (void)setTokenType:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2TokenTypeKey]; -} - -- (NSString *)scope { - return [self.parameters objectForKey:kOAuth2ScopeKey]; -} - -- (void)setScope:(NSString *)str { - [self.parameters setValue:str forKey:kOAuth2ScopeKey]; -} - -- (NSNumber *)expiresIn { - id value = [self.parameters objectForKey:kOAuth2ExpiresInKey]; - if ([value isKindOfClass:[NSString class]]) { - value = [NSNumber numberWithInteger:[value integerValue]]; - } - return value; -} - -- (void)setExpiresIn:(NSNumber *)num { - [self.parameters setValue:num forKey:kOAuth2ExpiresInKey]; - [self updateExpirationDate]; -} - -- (void)updateExpirationDate { - // Update our absolute expiration time to something close to when - // the server expects the expiration - NSDate *date = nil; - NSNumber *expiresIn = self.expiresIn; - if (expiresIn) { - unsigned long deltaSeconds = [expiresIn unsignedLongValue]; - if (deltaSeconds > 0) { - date = [NSDate dateWithTimeIntervalSinceNow:deltaSeconds]; - } - } - self.expirationDate = date; -} - -// -// Keys custom to this class, not part of OAuth 2 -// - -- (NSString *)serviceProvider { - return [self.parameters objectForKey:kServiceProviderKey]; -} - -- (void)setServiceProvider:(NSString *)str { - [self.parameters setValue:str forKey:kServiceProviderKey]; -} - -- (NSString *)userID { - return [self.parameters objectForKey:kUserIDKey]; -} - -- (void)setUserID:(NSString *)str { - [self.parameters setValue:str forKey:kUserIDKey]; -} - -- (NSString *)userEmail { - return [self.parameters objectForKey:kUserEmailKey]; -} - -- (void)setUserEmail:(NSString *)str { - [self.parameters setValue:str forKey:kUserEmailKey]; -} - -- (NSString *)userEmailIsVerified { - return [self.parameters objectForKey:kUserEmailIsVerifiedKey]; -} - -- (void)setUserEmailIsVerified:(NSString *)str { - [self.parameters setValue:str forKey:kUserEmailIsVerifiedKey]; -} - -#pragma mark User Properties - -- (void)setProperty:(id)obj forKey:(NSString *)key { - if (obj == nil) { - // User passed in nil, so delete the property - [properties_ removeObjectForKey:key]; - } else { - // Be sure the property dictionary exists - if (properties_ == nil) { - [self setProperties:[NSMutableDictionary dictionary]]; - } - [properties_ setObject:obj forKey:key]; - } -} - -- (id)propertyForKey:(NSString *)key { - id obj = [properties_ objectForKey:key]; - - // Be sure the returned pointer has the life of the autorelease pool, - // in case self is released immediately - return [[obj retain] autorelease]; -} - -#pragma mark Utility Routines - -+ (NSString *)encodedOAuthValueForString:(NSString *)str { - CFStringRef originalString = (CFStringRef) str; - CFStringRef leaveUnescaped = NULL; - CFStringRef forceEscaped = CFSTR("!*'();:@&=+$,/?%#[]"); - - CFStringRef escapedStr = NULL; - if (str) { - escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, - originalString, - leaveUnescaped, - forceEscaped, - kCFStringEncodingUTF8); - [(id)CFMakeCollectable(escapedStr) autorelease]; - } - - return (NSString *)escapedStr; -} - -+ (NSString *)encodedQueryParametersForDictionary:(NSDictionary *)dict { - // Make a string like "cat=fluffy@dog=spot" - NSMutableString *result = [NSMutableString string]; - NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; - NSString *joiner = @""; - for (NSString *key in sortedKeys) { - NSString *value = [dict objectForKey:key]; - NSString *encodedValue = [self encodedOAuthValueForString:value]; - NSString *encodedKey = [self encodedOAuthValueForString:key]; - [result appendFormat:@"%@%@=%@", joiner, encodedKey, encodedValue]; - joiner = @"&"; - } - return result; -} - -+ (void)invokeDelegate:(id)delegate - selector:(SEL)sel - object:(id)obj1 - object:(id)obj2 - object:(id)obj3 { - if (delegate && sel) { - NSMethodSignature *sig = [delegate methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:delegate]; - [invocation setArgument:&obj1 atIndex:2]; - [invocation setArgument:&obj2 atIndex:3]; - [invocation setArgument:&obj3 atIndex:4]; - [invocation invoke]; - } -} - -+ (NSString *)unencodedOAuthParameterForString:(NSString *)str { - NSString *plainStr = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - return plainStr; -} - -+ (NSDictionary *)dictionaryWithResponseString:(NSString *)responseStr { - // Build a dictionary from a response string of the form - // "cat=fluffy&dog=spot". Missing or empty values are considered - // empty strings; keys and values are percent-decoded. - if (responseStr == nil) return nil; - - NSArray *items = [responseStr componentsSeparatedByString:@"&"]; - - NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithCapacity:[items count]]; - - for (NSString *item in items) { - NSString *key = nil; - NSString *value = @""; - - NSRange equalsRange = [item rangeOfString:@"="]; - if (equalsRange.location != NSNotFound) { - // The parameter has at least one '=' - key = [item substringToIndex:equalsRange.location]; - - // There are characters after the '=' - value = [item substringFromIndex:(equalsRange.location + 1)]; - } else { - // The parameter has no '=' - key = item; - } - - NSString *plainKey = [[self class] unencodedOAuthParameterForString:key]; - NSString *plainValue = [[self class] unencodedOAuthParameterForString:value]; - - [responseDict setObject:plainValue forKey:plainKey]; - } - - return responseDict; -} - -+ (NSDictionary *)dictionaryWithResponseData:(NSData *)data { - NSString *responseStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - NSDictionary *dict = [self dictionaryWithResponseString:responseStr]; - return dict; -} - -+ (NSString *)scopeWithStrings:(NSString *)str, ... { - // concatenate the strings, joined by a single space - NSString *result = @""; - NSString *joiner = @""; - if (str) { - va_list argList; - va_start(argList, str); - while (str) { - result = [result stringByAppendingFormat:@"%@%@", joiner, str]; - joiner = @" "; - str = va_arg(argList, id); - } - va_end(argList); - } - return result; -} - -@end - -#endif // GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2SignIn.h b/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2SignIn.h deleted file mode 100644 index f9accbfd2..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2SignIn.h +++ /dev/null @@ -1,191 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// This sign-in object opens and closes the web view window as needed for -// users to sign in. For signing in to Google, it also obtains -// the authenticated user's email address. -// -// Typically, this will be managed for the application by -// GTMOAuth2ViewControllerTouch or GTMOAuth2WindowController, so this -// class's interface is interesting only if -// you are creating your own window controller for sign-in. -// -// -// Delegate methods implemented by the window controller -// -// The window controller implements two methods for use by the sign-in object, -// the webRequestSelector and the finishedSelector: -// -// webRequestSelector has a signature matching -// - (void)signIn:(GTMOAuth2SignIn *)signIn displayRequest:(NSURLRequest *)request -// -// The web request selector will be invoked with a request to be displayed, or -// nil to close the window when the final callback request has been encountered. -// -// -// finishedSelector has a signature matching -// - (void)signin:(GTMOAuth2SignIn *)signin finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error -// -// The finished selector will be invoked when sign-in has completed, except -// when explicitly canceled by calling cancelSigningIn -// - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#import -#import - -// GTMHTTPFetcher brings in GTLDefines/GDataDefines -#if GTM_USE_SESSION_FETCHER -#import "GTMSessionFetcher.h" -#else -#import "GTMHTTPFetcher.h" -#endif - -#import "GTMOAuth2Authentication.h" - -@interface GTMOAuth2SignIn : NSObject { - @private - GTMOAuth2Authentication *auth_; - - // the endpoint for displaying the sign-in page - NSURL *authorizationURL_; - NSDictionary *additionalAuthorizationParameters_; - - id delegate_; - SEL webRequestSelector_; - SEL finishedSelector_; - - BOOL hasHandledCallback_; - - GTMOAuth2Fetcher *pendingFetcher_; - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - BOOL shouldFetchGoogleUserEmail_; - BOOL shouldFetchGoogleUserProfile_; - NSDictionary *userProfile_; -#endif - - SCNetworkReachabilityRef reachabilityRef_; - NSTimer *networkLossTimer_; - NSTimeInterval networkLossTimeoutInterval_; - BOOL hasNotifiedNetworkLoss_; - - id userData_; -} - -@property (nonatomic, retain) GTMOAuth2Authentication *authentication; - -@property (nonatomic, retain) NSURL *authorizationURL; -@property (nonatomic, retain) NSDictionary *additionalAuthorizationParameters; - -// The delegate is released when signing in finishes or is cancelled -@property (nonatomic, retain) id delegate; -@property (nonatomic, assign) SEL webRequestSelector; -@property (nonatomic, assign) SEL finishedSelector; - -@property (nonatomic, retain) id userData; - -// By default, signing in to Google will fetch the user's email, but will not -// fetch the user's profile. -// -// The email is saved in the auth object. -// The profile is available immediately after sign-in. -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -@property (nonatomic, assign) BOOL shouldFetchGoogleUserEmail; -@property (nonatomic, assign) BOOL shouldFetchGoogleUserProfile; -@property (nonatomic, retain, readonly) NSDictionary *userProfile; -#endif - -// The default timeout for an unreachable network during display of the -// sign-in page is 30 seconds; set this to 0 to have no timeout -@property (nonatomic, assign) NSTimeInterval networkLossTimeoutInterval; - -// The delegate is retained until sign-in has completed or been canceled -// -// designated initializer -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - delegate:(id)delegate - webRequestSelector:(SEL)webRequestSelector - finishedSelector:(SEL)finishedSelector; - -// A default authentication object for signing in to Google services -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Authentication *)standardGoogleAuthenticationForScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret; -#endif - -#pragma mark Methods used by the Window Controller - -// Start the sequence of fetches and sign-in window display for sign-in -- (BOOL)startSigningIn; - -// Stop any pending fetches, and close the window (but don't call the -// delegate's finishedSelector) -- (void)cancelSigningIn; - -// Window controllers must tell the sign-in object about any redirect -// requested by the web view, and any changes in the webview window title -// -// If these return YES then the event was handled by the -// sign-in object (typically by closing the window) and should be ignored by -// the window controller's web view - -- (BOOL)requestRedirectedToRequest:(NSURLRequest *)redirectedRequest; -- (BOOL)titleChanged:(NSString *)title; -- (BOOL)cookiesChanged:(NSHTTPCookieStorage *)cookieStorage; -- (BOOL)loadFailedWithError:(NSError *)error; - -// Window controllers must tell the sign-in object if the window was closed -// prematurely by the user (but not by the sign-in object); this calls the -// delegate's finishedSelector -- (void)windowWasClosed; - -// Start the sequences for signing in with an authorization code. The -// authentication must contain an authorization code, otherwise the process -// will fail. -- (void)authCodeObtained; - -#pragma mark - - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -// Revocation of an authorized token from Google -+ (void)revokeTokenForGoogleAuthentication:(GTMOAuth2Authentication *)auth; - -// Create a fetcher for obtaining the user's Google email address or profile, -// according to the current auth scopes. -// -// The auth object must have been created with appropriate scopes. -// -// The fetcher's response data can be parsed with NSJSONSerialization. -+ (GTMOAuth2Fetcher *)userInfoFetcherWithAuth:(GTMOAuth2Authentication *)auth; -#endif - -#pragma mark - - -// Standard authentication values -+ (NSString *)nativeClientRedirectURI; -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (NSURL *)googleAuthorizationURL; -+ (NSURL *)googleTokenURL; -+ (NSURL *)googleUserInfoURL; -#endif - -@end - -#endif // #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2SignIn.m b/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2SignIn.m deleted file mode 100644 index 472b0b0d0..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/GTMOAuth2SignIn.m +++ /dev/null @@ -1,971 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#import "GTMOAuth2SignIn.h" - -// we'll default to timing out if the network becomes unreachable for more -// than 30 seconds when the sign-in page is displayed -static const NSTimeInterval kDefaultNetworkLossTimeoutInterval = 30.0; - -// URI indicating an installed app is signing in. This is described at -// -// http://code.google.com/apis/accounts/docs/OAuth2.html#IA -// -NSString *const kOOBString = @"urn:ietf:wg:oauth:2.0:oob"; - - -@interface GTMOAuth2SignIn () -@property (assign) BOOL hasHandledCallback; -@property (retain) GTMOAuth2Fetcher *pendingFetcher; -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -@property (nonatomic, retain, readwrite) NSDictionary *userProfile; -#endif - -- (void)invokeFinalCallbackWithError:(NSError *)error; - -- (BOOL)startWebRequest; -+ (NSMutableURLRequest *)mutableURLRequestWithURL:(NSURL *)oldURL - paramString:(NSString *)paramStr; -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -- (void)addScopeForGoogleUserInfo; -- (void)fetchGoogleUserInfo; -#endif -- (void)finishSignInWithError:(NSError *)error; - -- (void)auth:(GTMOAuth2Authentication *)auth -finishedWithFetcher:(GTMOAuth2Fetcher *)fetcher - error:(NSError *)error; - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -- (void)infoFetcher:(GTMOAuth2Fetcher *)fetcher - finishedWithData:(NSData *)data - error:(NSError *)error; -+ (NSData *)decodeWebSafeBase64:(NSString *)base64Str; -- (void)updateGoogleUserInfoWithData:(NSData *)data; -#endif - -- (void)closeTheWindow; - -- (void)startReachabilityCheck; -- (void)stopReachabilityCheck; -- (void)reachabilityTarget:(SCNetworkReachabilityRef)reachabilityRef - changedFlags:(SCNetworkConnectionFlags)flags; -- (void)reachabilityTimerFired:(NSTimer *)timer; -@end - -@implementation GTMOAuth2SignIn - -@synthesize authentication = auth_; - -@synthesize authorizationURL = authorizationURL_; -@synthesize additionalAuthorizationParameters = additionalAuthorizationParameters_; - -@synthesize delegate = delegate_; -@synthesize webRequestSelector = webRequestSelector_; -@synthesize finishedSelector = finishedSelector_; -@synthesize hasHandledCallback = hasHandledCallback_; -@synthesize pendingFetcher = pendingFetcher_; -@synthesize userData = userData_; - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -@synthesize shouldFetchGoogleUserEmail = shouldFetchGoogleUserEmail_; -@synthesize shouldFetchGoogleUserProfile = shouldFetchGoogleUserProfile_; -@synthesize userProfile = userProfile_; -#endif - -@synthesize networkLossTimeoutInterval = networkLossTimeoutInterval_; - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (NSURL *)googleAuthorizationURL { - NSString *str = @"https://accounts.google.com/o/oauth2/auth"; - return [NSURL URLWithString:str]; -} - -+ (NSURL *)googleTokenURL { - NSString *str = @"https://accounts.google.com/o/oauth2/token"; - return [NSURL URLWithString:str]; -} - -+ (NSURL *)googleRevocationURL { - NSString *urlStr = @"https://accounts.google.com/o/oauth2/revoke"; - return [NSURL URLWithString:urlStr]; -} - -+ (NSURL *)googleUserInfoURL { -#if GTM_OAUTH2_USES_OPENIDCONNECT - NSString *urlStr = @" https://www.googleapis.com/plus/v1/people/me/openIdConnect"; -#else - NSString *urlStr = @"https://www.googleapis.com/oauth2/v3/userinfo"; -#endif - return [NSURL URLWithString:urlStr]; -} -#endif - -+ (NSString *)nativeClientRedirectURI { - return kOOBString; -} - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Authentication *)standardGoogleAuthenticationForScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret { - NSString *redirectURI = [self nativeClientRedirectURI]; - NSURL *tokenURL = [self googleTokenURL]; - - GTMOAuth2Authentication *auth; - auth = [GTMOAuth2Authentication authenticationWithServiceProvider:kGTMOAuth2ServiceProviderGoogle - tokenURL:tokenURL - redirectURI:redirectURI - clientID:clientID - clientSecret:clientSecret]; - auth.scope = scope; - - return auth; -} - - -- (void)addScopeForGoogleUserInfo { -#if GTM_OAUTH2_USES_OPENIDCONNECT - NSString *const emailScope = @"email"; - NSString *const profileScope = @"profile"; - BOOL (^hasScope)(NSString *, NSString *) = ^(NSString *scopesString, NSString *scope) { - // For one-word scopes, we need an exact match rather than a substring match. - NSArray *words = [scopesString componentsSeparatedByString:@" "]; - return [words containsObject:scope]; - }; -#else - NSString *const emailScope = @"https://www.googleapis.com/auth/userinfo.email"; - NSString *const profileScope = @"https://www.googleapis.com/auth/userinfo.profile"; - BOOL (^hasScope)(NSString *, NSString *) = ^BOOL(NSString *scopesString, NSString *scope) { - return [scopesString rangeOfString:scope].location != NSNotFound; - }; -#endif // GTM_OAUTH2_USES_OPENIDCONNECT - - GTMOAuth2Authentication *auth = self.authentication; - if (self.shouldFetchGoogleUserEmail) { - NSString *scopeStrings = auth.scope; - if (!hasScope(scopeStrings, emailScope)) { - scopeStrings = [GTMOAuth2Authentication scopeWithStrings:scopeStrings, emailScope, nil]; - auth.scope = scopeStrings; - } - } - - if (self.shouldFetchGoogleUserProfile) { - NSString *scopeStrings = auth.scope; - if (!hasScope(scopeStrings, profileScope)) { - scopeStrings = [GTMOAuth2Authentication scopeWithStrings:scopeStrings, profileScope, nil]; - auth.scope = scopeStrings; - } - } -} -#endif - -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - delegate:(id)delegate - webRequestSelector:(SEL)webRequestSelector - finishedSelector:(SEL)finishedSelector { - // check the selectors on debug builds - GTMOAuth2AssertValidSelector(delegate, webRequestSelector, - @encode(GTMOAuth2SignIn *), @encode(NSURLRequest *), 0); - GTMOAuth2AssertValidSelector(delegate, finishedSelector, - @encode(GTMOAuth2SignIn *), @encode(GTMOAuth2Authentication *), - @encode(NSError *), 0); - - // designated initializer - self = [super init]; - if (self) { - auth_ = [auth retain]; - authorizationURL_ = [authorizationURL retain]; - delegate_ = [delegate retain]; - webRequestSelector_ = webRequestSelector; - finishedSelector_ = finishedSelector; - - // for Google authentication, we want to automatically fetch user info -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - NSString *host = [authorizationURL host]; - if ([host hasSuffix:@".google.com"]) { - shouldFetchGoogleUserEmail_ = YES; - } -#endif - - // default timeout for a lost internet connection while the server - // UI is displayed is 30 seconds - networkLossTimeoutInterval_ = kDefaultNetworkLossTimeoutInterval; - } - return self; -} - -- (void)dealloc { - [self stopReachabilityCheck]; - - [auth_ release]; - [authorizationURL_ release]; - [additionalAuthorizationParameters_ release]; - [delegate_ release]; - [pendingFetcher_ release]; -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - [userProfile_ release]; -#endif - [userData_ release]; - - [super dealloc]; -} - -#pragma mark Sign-in Sequence Methods - -// stop any pending fetches, and close the window (but don't call the -// delegate's finishedSelector) -- (void)cancelSigningIn { - [self.pendingFetcher stopFetching]; - self.pendingFetcher = nil; - - [self.authentication stopAuthorization]; - - [self closeTheWindow]; - - [delegate_ autorelease]; - delegate_ = nil; -} - -// -// This is the entry point to begin the sequence -// - display the authentication web page, and monitor redirects -// - exchange the code for an access token and a refresh token -// - for Google sign-in, fetch the user's email address -// - tell the delegate we're finished -// -- (BOOL)startSigningIn { - // For signing in to Google, append the scope for obtaining the authenticated - // user email and profile, as appropriate -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - [self addScopeForGoogleUserInfo]; -#endif - - // start the authorization - return [self startWebRequest]; -} - -- (NSMutableDictionary *)parametersForWebRequest { - GTMOAuth2Authentication *auth = self.authentication; - NSString *clientID = auth.clientID; - NSString *redirectURI = auth.redirectURI; - - BOOL hasClientID = ([clientID length] > 0); - BOOL hasRedirect = ([redirectURI length] > 0 - || redirectURI == [[self class] nativeClientRedirectURI]); - if (!hasClientID || !hasRedirect) { -#if DEBUG - NSAssert(hasClientID, @"GTMOAuth2SignIn: clientID needed"); - NSAssert(hasRedirect, @"GTMOAuth2SignIn: redirectURI needed"); -#endif - return nil; - } - - // invoke the UI controller's web request selector to display - // the authorization page - - // add params to the authorization URL - NSString *scope = auth.scope; - if ([scope length] == 0) scope = nil; - - NSMutableDictionary *paramsDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: - @"code", @"response_type", - clientID, @"client_id", - scope, @"scope", // scope may be nil - nil]; - if (redirectURI) { - [paramsDict setObject:redirectURI forKey:@"redirect_uri"]; - } - return paramsDict; -} - -- (BOOL)startWebRequest { - NSMutableDictionary *paramsDict = [self parametersForWebRequest]; - - NSDictionary *additionalParams = self.additionalAuthorizationParameters; - if (additionalParams) { - [paramsDict addEntriesFromDictionary:additionalParams]; - } - - NSString *paramStr = [GTMOAuth2Authentication encodedQueryParametersForDictionary:paramsDict]; - - NSURL *authorizationURL = self.authorizationURL; - NSMutableURLRequest *request; - request = [[self class] mutableURLRequestWithURL:authorizationURL - paramString:paramStr]; - - [delegate_ performSelector:self.webRequestSelector - withObject:self - withObject:request]; - - // at this point, we're waiting on the server-driven html UI, so - // we want notification if we lose connectivity to the web server - [self startReachabilityCheck]; - return YES; -} - -// utility for making a request from an old URL with some additional parameters -+ (NSMutableURLRequest *)mutableURLRequestWithURL:(NSURL *)oldURL - paramString:(NSString *)paramStr { - if ([paramStr length] == 0) { - return [NSMutableURLRequest requestWithURL:oldURL]; - } - - NSString *query = [oldURL query]; - if ([query length] > 0) { - query = [query stringByAppendingFormat:@"&%@", paramStr]; - } else { - query = paramStr; - } - - NSString *portStr = @""; - NSString *oldPort = [[oldURL port] stringValue]; - if ([oldPort length] > 0) { - portStr = [@":" stringByAppendingString:oldPort]; - } - - NSString *qMark = [query length] > 0 ? @"?" : @""; - NSString *newURLStr = [NSString stringWithFormat:@"%@://%@%@%@%@%@", - [oldURL scheme], [oldURL host], portStr, - [oldURL path], qMark, query]; - NSURL *newURL = [NSURL URLWithString:newURLStr]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:newURL]; - return request; -} - -// entry point for the window controller to tell us that the window -// prematurely closed -- (void)windowWasClosed { - [self stopReachabilityCheck]; - - NSError *error = [NSError errorWithDomain:kGTMOAuth2ErrorDomain - code:kGTMOAuth2ErrorWindowClosed - userInfo:nil]; - [self invokeFinalCallbackWithError:error]; -} - -// internal method to tell the window controller to close the window -- (void)closeTheWindow { - [self stopReachabilityCheck]; - - // a nil request means the window should be closed - [delegate_ performSelector:self.webRequestSelector - withObject:self - withObject:nil]; -} - -// entry point for the window controller to tell us what web page has been -// requested -// -// When the request is for the callback URL, this method invokes -// authCodeObtained and returns YES -- (BOOL)requestRedirectedToRequest:(NSURLRequest *)redirectedRequest { - // for Google's installed app sign-in protocol, we'll look for the - // end-of-sign-in indicator in the titleChanged: method below - NSString *redirectURI = self.authentication.redirectURI; - if (redirectURI == nil) return NO; - - // when we're searching for the window title string, then we can ignore - // redirects - NSString *standardURI = [[self class] nativeClientRedirectURI]; - if (standardURI != nil && [redirectURI isEqual:standardURI]) return NO; - - // compare the redirectURI, which tells us when the web sign-in is done, - // to the actual redirection - NSURL *redirectURL = [NSURL URLWithString:redirectURI]; - NSURL *requestURL = [redirectedRequest URL]; - - // avoid comparing to nil host and path values (such as when redirected to - // "about:blank") - NSString *requestHost = [requestURL host]; - NSString *requestPath = [requestURL path]; - BOOL isCallback; - if (requestHost && requestPath) { - isCallback = [[redirectURL host] isEqual:[requestURL host]] - && [[redirectURL path] isEqual:[requestURL path]]; - } else if (requestURL) { - // handle "about:blank" - isCallback = [redirectURL isEqual:requestURL]; - } else { - isCallback = NO; - } - - if (!isCallback) { - // tell the caller that this request is nothing interesting - return NO; - } - - // we've reached the callback URL - - // try to get the access code - if (!self.hasHandledCallback) { - NSString *responseStr = [[redirectedRequest URL] query]; - [self.authentication setKeysForResponseString:responseStr]; - -#if DEBUG - NSAssert([self.authentication.code length] > 0 - || [self.authentication.errorString length] > 0, - @"response lacks auth code or error"); -#endif - - [self authCodeObtained]; - } - // tell the delegate that we did handle this request - return YES; -} - -// entry point for the window controller to tell us when a new page title has -// been loadded -// -// When the title indicates sign-in has completed, this method invokes -// authCodeObtained and returns YES -- (BOOL)titleChanged:(NSString *)title { - // return YES if the OAuth flow ending title was detected - - // right now we're just looking for a parameter list following the last space - // in the title string, but hopefully we'll eventually get something better - // from the server to search for - NSRange paramsRange = [title rangeOfString:@" " - options:NSBackwardsSearch]; - NSUInteger spaceIndex = paramsRange.location; - if (spaceIndex != NSNotFound) { - NSString *responseStr = [title substringFromIndex:(spaceIndex + 1)]; - - NSDictionary *dict = [GTMOAuth2Authentication dictionaryWithResponseString:responseStr]; - - NSString *code = [dict objectForKey:@"code"]; - NSString *error = [dict objectForKey:@"error"]; - if ([code length] > 0 || [error length] > 0) { - - if (!self.hasHandledCallback) { - [self.authentication setKeysForResponseDictionary:dict]; - - [self authCodeObtained]; - } - return YES; - } - } - return NO; -} - -- (BOOL)cookiesChanged:(NSHTTPCookieStorage *)cookieStorage { - // We're ignoring these. - return NO; -}; - -// entry point for the window controller to tell us when a load has failed -// in the webview -// -// if the initial authorization URL fails, bail out so the user doesn't -// see an empty webview -- (BOOL)loadFailedWithError:(NSError *)error { - NSURL *authorizationURL = self.authorizationURL; - NSURL *failedURL = [[error userInfo] valueForKey:@"NSErrorFailingURLKey"]; // NSURLErrorFailingURLErrorKey defined in 10.6 - - BOOL isAuthURL = [[failedURL host] isEqual:[authorizationURL host]] - && [[failedURL path] isEqual:[authorizationURL path]]; - - if (isAuthURL) { - // We can assume that we have no pending fetchers, since we only - // handle failure to load the initial authorization URL - [self closeTheWindow]; - [self invokeFinalCallbackWithError:error]; - return YES; - } - return NO; -} - -- (void)authCodeObtained { - // the callback page was requested, or the authenticate code was loaded - // into a page's title, so exchange the auth code for access & refresh tokens - // and tell the window to close - - // avoid duplicate signals that the callback point has been reached - self.hasHandledCallback = YES; - - // If the signin was request for exchanging an authentication token to a - // refresh token, there is no window to close. - if (self.webRequestSelector) { - [self closeTheWindow]; - } else { - // For signing in to Google, append the scope for obtaining the - // authenticated user email and profile, as appropriate. This is usually - // done by the startSigningIn method, but this method is not called when - // exchanging an authentication token for a refresh token. -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - [self addScopeForGoogleUserInfo]; -#endif - } - - NSError *error = nil; - - GTMOAuth2Authentication *auth = self.authentication; - NSString *code = auth.code; - if ([code length] > 0) { - // exchange the code for a token - SEL sel = @selector(auth:finishedWithFetcher:error:); - GTMOAuth2Fetcher *fetcher = [auth beginTokenFetchWithDelegate:self - didFinishSelector:sel]; - if (fetcher == nil) { - error = [NSError errorWithDomain:kGTMOAuth2FetcherStatusDomain - code:-1 - userInfo:nil]; - } else { - self.pendingFetcher = fetcher; - } - - // notify the app so it can put up a post-sign in, pre-token exchange UI - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:kGTMOAuth2UserSignedIn - object:self - userInfo:nil]; - } else { - // the callback lacked an auth code - NSString *errStr = auth.errorString; - NSDictionary *userInfo = nil; - if ([errStr length] > 0) { - userInfo = [NSDictionary dictionaryWithObject:errStr - forKey:kGTMOAuth2ErrorMessageKey]; - } - - error = [NSError errorWithDomain:kGTMOAuth2ErrorDomain - code:kGTMOAuth2ErrorAuthorizationFailed - userInfo:userInfo]; - } - - if (error) { - [self finishSignInWithError:error]; - } -} - -- (void)auth:(GTMOAuth2Authentication *)auth -finishedWithFetcher:(GTMOAuth2Fetcher *)fetcher - error:(NSError *)error { - self.pendingFetcher = nil; - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - if (error == nil - && (self.shouldFetchGoogleUserEmail || self.shouldFetchGoogleUserProfile) - && [self.authentication.serviceProvider isEqual:kGTMOAuth2ServiceProviderGoogle]) { - // fetch the user's information from the Google server - [self fetchGoogleUserInfo]; - } else { - // we're not authorizing with Google, so we're done - [self finishSignInWithError:error]; - } -#else - [self finishSignInWithError:error]; -#endif -} - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Fetcher *)userInfoFetcherWithAuth:(GTMOAuth2Authentication *)auth { - // create a fetcher for obtaining the user's email or profile - NSURL *infoURL = [[self class] googleUserInfoURL]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:infoURL]; - - if ([auth respondsToSelector:@selector(userAgent)]) { - NSString *userAgent = [auth userAgent]; - [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - } - [request setValue:@"no-cache" forHTTPHeaderField:@"Cache-Control"]; - - GTMOAuth2Fetcher *fetcher; - id fetcherService = nil; - if ([auth respondsToSelector:@selector(fetcherService)]) { - fetcherService = auth.fetcherService; - }; - if (fetcherService) { - fetcher = (GTMOAuth2Fetcher *)[fetcherService fetcherWithRequest:request]; - } else { - fetcher = [GTMOAuth2Fetcher fetcherWithRequest:request]; - } - fetcher.authorizer = auth; - fetcher.retryEnabled = YES; - fetcher.maxRetryInterval = 15.0; -#if !STRIP_GTM_FETCH_LOGGING - // The user email address is known at token refresh time, not during the initial code exchange. - NSString *userEmail = auth.userEmail; - NSString *forStr = userEmail ? [NSString stringWithFormat:@"for \"%@\"", userEmail] : @""; - [fetcher setCommentWithFormat:@"GTMOAuth2 user info %@", forStr]; -#endif - return fetcher; -} - -- (void)fetchGoogleUserInfo { - if (!self.shouldFetchGoogleUserProfile) { - // If we only need email and user ID, not the full profile, and we have an - // id_token, it may have the email and user ID so we won't need to fetch - // them. - GTMOAuth2Authentication *auth = self.authentication; - NSString *idToken = [auth.parameters objectForKey:@"id_token"]; - if ([idToken length] > 0) { - // The id_token has three dot-delimited parts. The second is the - // JSON profile. - // - // http://www.tbray.org/ongoing/When/201x/2013/04/04/ID-Tokens - NSArray *parts = [idToken componentsSeparatedByString:@"."]; - if ([parts count] == 3) { - NSString *part2 = [parts objectAtIndex:1]; - if ([part2 length] > 0) { - NSData *data = [[self class] decodeWebSafeBase64:part2]; - if ([data length] > 0) { - [self updateGoogleUserInfoWithData:data]; - if ([[auth userID] length] > 0 && [[auth userEmail] length] > 0) { - // We obtained user ID and email from the ID token. - [self finishSignInWithError:nil]; - return; - } - } - } - } - } - } - - // Fetch the email and profile from the userinfo endpoint. - GTMOAuth2Authentication *auth = self.authentication; - GTMOAuth2Fetcher *fetcher = [[self class] userInfoFetcherWithAuth:auth]; - [fetcher beginFetchWithDelegate:self - didFinishSelector:@selector(infoFetcher:finishedWithData:error:)]; - - self.pendingFetcher = fetcher; - - [auth notifyFetchIsRunning:YES - fetcher:fetcher - type:kGTMOAuth2FetchTypeUserInfo]; -} - -- (void)infoFetcher:(GTMOAuth2Fetcher *)fetcher - finishedWithData:(NSData *)data - error:(NSError *)error { - GTMOAuth2Authentication *auth = self.authentication; - [auth notifyFetchIsRunning:NO - fetcher:fetcher - type:nil]; - - self.pendingFetcher = nil; - - if (error) { -#if DEBUG - if (data) { - NSString *dataStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - NSLog(@"infoFetcher error: %@\n%@", error, dataStr); - } -#endif - } else { - // We have the authenticated user's info - [self updateGoogleUserInfoWithData:data]; - } - [self finishSignInWithError:error]; -} - -- (void)updateGoogleUserInfoWithData:(NSData *)data { - if (!data) return; - - GTMOAuth2Authentication *auth = self.authentication; - NSDictionary *profileDict = [[auth class] dictionaryWithJSONData:data]; - if (profileDict) { - // Profile dictionary keys mostly conform to - // http://openid.net/specs/openid-connect-messages-1_0.html#StandardClaims - - self.userProfile = profileDict; - - // Save the ID into the auth object - NSString *subjectID = [profileDict objectForKey:@"sub"]; - [auth setUserID:subjectID]; - - // Save the email into the auth object - NSString *email = [profileDict objectForKey:@"email"]; - [auth setUserEmail:email]; - -#if DEBUG - NSAssert([subjectID length] > 0 && [email length] > 0, - @"profile lacks userID or userEmail: %@", profileDict); -#endif - - // The email_verified key is a boolean NSNumber in the userinfo - // endpoint response, but it is a string like "true" in the id_token. - // We want to consistently save it as a string of the boolean value, - // like @"1". - id verified = [profileDict objectForKey:@"email_verified"]; - if ([verified isKindOfClass:[NSString class]]) { - verified = [NSNumber numberWithBool:[verified boolValue]]; - } - - [auth setUserEmailIsVerified:[verified stringValue]]; - } -} - -#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - -- (void)finishSignInWithError:(NSError *)error { - [self invokeFinalCallbackWithError:error]; -} - -// convenience method for making the final call to our delegate -- (void)invokeFinalCallbackWithError:(NSError *)error { - if (delegate_ && finishedSelector_) { - GTMOAuth2Authentication *auth = self.authentication; - - NSMethodSignature *sig = [delegate_ methodSignatureForSelector:finishedSelector_]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:finishedSelector_]; - [invocation setTarget:delegate_]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&auth atIndex:3]; - [invocation setArgument:&error atIndex:4]; - [invocation invoke]; - } - - // we'll no longer send messages to the delegate - // - // we want to autorelease it rather than assign to the property in case - // the delegate is below us in the call stack - [delegate_ autorelease]; - delegate_ = nil; -} - -#pragma mark Reachability monitoring - -static void ReachabilityCallBack(SCNetworkReachabilityRef target, - SCNetworkConnectionFlags flags, - void *info) { - // pass the flags to the signIn object - GTMOAuth2SignIn *signIn = (GTMOAuth2SignIn *)info; - - [signIn reachabilityTarget:target - changedFlags:flags]; -} - -- (void)startReachabilityCheck { - // the user may set the timeout to 0 to skip the reachability checking - // during display of the sign-in page - if (networkLossTimeoutInterval_ <= 0.0 || reachabilityRef_ != NULL) { - return; - } - - // create a reachability target from the authorization URL, add our callback, - // and schedule it on the run loop so we'll be notified if the network drops - NSURL *url = self.authorizationURL; - const char* host = [[url host] UTF8String]; - reachabilityRef_ = SCNetworkReachabilityCreateWithName(kCFAllocatorSystemDefault, - host); - if (reachabilityRef_) { - BOOL isScheduled = NO; - SCNetworkReachabilityContext ctx = { 0, self, NULL, NULL, NULL }; - - if (SCNetworkReachabilitySetCallback(reachabilityRef_, - ReachabilityCallBack, &ctx)) { - if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef_, - CFRunLoopGetCurrent(), - kCFRunLoopDefaultMode)) { - isScheduled = YES; - } - } - - if (!isScheduled) { - CFRelease(reachabilityRef_); - reachabilityRef_ = NULL; - } - } -} - -- (void)destroyUnreachabilityTimer { - [networkLossTimer_ invalidate]; - [networkLossTimer_ autorelease]; - networkLossTimer_ = nil; -} - -- (void)reachabilityTarget:(SCNetworkReachabilityRef)reachabilityRef - changedFlags:(SCNetworkConnectionFlags)flags { - BOOL isConnected = (flags & kSCNetworkFlagsReachable) != 0 - && (flags & kSCNetworkFlagsConnectionRequired) == 0; - - if (isConnected) { - // server is again reachable - [self destroyUnreachabilityTimer]; - - if (hasNotifiedNetworkLoss_) { - // tell the user that the network has been found - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:kGTMOAuth2NetworkFound - object:self - userInfo:nil]; - hasNotifiedNetworkLoss_ = NO; - } - } else { - // the server has become unreachable; start the timer, if necessary - if (networkLossTimer_ == nil - && networkLossTimeoutInterval_ > 0 - && !hasNotifiedNetworkLoss_) { - SEL sel = @selector(reachabilityTimerFired:); - networkLossTimer_ = [[NSTimer scheduledTimerWithTimeInterval:networkLossTimeoutInterval_ - target:self - selector:sel - userInfo:nil - repeats:NO] retain]; - } - } -} - -- (void)reachabilityTimerFired:(NSTimer *)timer { - // the user may call [[notification object] cancelSigningIn] to - // dismiss the sign-in - if (!hasNotifiedNetworkLoss_) { - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:kGTMOAuth2NetworkLost - object:self - userInfo:nil]; - hasNotifiedNetworkLoss_ = YES; - } - - [self destroyUnreachabilityTimer]; -} - -- (void)stopReachabilityCheck { - [self destroyUnreachabilityTimer]; - - if (reachabilityRef_) { - SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef_, - CFRunLoopGetCurrent(), - kCFRunLoopDefaultMode); - SCNetworkReachabilitySetCallback(reachabilityRef_, NULL, NULL); - - CFRelease(reachabilityRef_); - reachabilityRef_ = NULL; - } -} - -#pragma mark Token Revocation - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (void)revokeTokenForGoogleAuthentication:(GTMOAuth2Authentication *)auth { - if (auth.refreshToken != nil - && auth.canAuthorize - && [auth.serviceProvider isEqual:kGTMOAuth2ServiceProviderGoogle]) { - - // create a signed revocation request for this authentication object - NSURL *url = [self googleRevocationURL]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; - - NSString *token = auth.refreshToken; - NSString *encoded = [GTMOAuth2Authentication encodedOAuthValueForString:token]; - if (encoded != nil) { - NSString *body = [@"token=" stringByAppendingString:encoded]; - - [request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]]; - [request setHTTPMethod:@"POST"]; - - NSString *userAgent = [auth userAgent]; - [request setValue:userAgent forHTTPHeaderField:@"User-Agent"]; - - // there's nothing to be done if revocation succeeds or fails - GTMOAuth2Fetcher *fetcher; - id fetcherService = auth.fetcherService; - if (fetcherService) { - fetcher = (GTMOAuth2Fetcher *)[fetcherService fetcherWithRequest:request]; - } else { - fetcher = [GTMOAuth2Fetcher fetcherWithRequest:request]; - } - [fetcher setCommentWithFormat:@"GTMOAuth2 revoke token for %@", auth.userEmail]; - - // Use a completion handler fetch for better debugging, but only if we're - // guaranteed that blocks are available in the runtime -#if (!TARGET_OS_IPHONE && (MAC_OS_X_VERSION_MIN_REQUIRED >= 1060)) || \ - (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MIN_REQUIRED >= 40000)) - // Blocks are available - [fetcher beginFetchWithCompletionHandler:^(NSData *data, NSError *error) { - #if DEBUG - if (error) { - NSString *errStr = [[[NSString alloc] initWithData:data - encoding:NSUTF8StringEncoding] autorelease]; - NSLog(@"revoke error: %@", errStr); - } - #endif // DEBUG - }]; -#else - // Blocks may not be available - [fetcher beginFetchWithDelegate:nil didFinishSelector:NULL]; -#endif - } - } - [auth reset]; -} - - -// Based on Cyrus Najmabadi's elegent little encoder and decoder from -// http://www.cocoadev.com/index.pl?BaseSixtyFour and on GTLBase64 - -+ (NSData *)decodeWebSafeBase64:(NSString *)base64Str { - static char decodingTable[128]; - static BOOL hasInited = NO; - - if (!hasInited) { - char webSafeEncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - memset(decodingTable, 0, 128); - for (unsigned int i = 0; i < sizeof(webSafeEncodingTable); i++) { - decodingTable[(unsigned int) webSafeEncodingTable[i]] = (char)i; - } - hasInited = YES; - } - - // The input string should be plain ASCII. - const char *cString = [base64Str cStringUsingEncoding:NSASCIIStringEncoding]; - if (cString == nil) return nil; - - NSInteger inputLength = (NSInteger)strlen(cString); - // Input length is not being restricted to multiples of 4. - if (inputLength == 0) return [NSData data]; - - while (inputLength > 0 && cString[inputLength - 1] == '=') { - inputLength--; - } - - NSInteger outputLength = inputLength * 3 / 4; - NSMutableData* data = [NSMutableData dataWithLength:(NSUInteger)outputLength]; - uint8_t *output = [data mutableBytes]; - - NSInteger inputPoint = 0; - NSInteger outputPoint = 0; - char *table = decodingTable; - - while (inputPoint < inputLength - 1) { - int i0 = cString[inputPoint++]; - int i1 = cString[inputPoint++]; - int i2 = inputPoint < inputLength ? cString[inputPoint++] : 'A'; // 'A' will decode to \0 - int i3 = inputPoint < inputLength ? cString[inputPoint++] : 'A'; - - output[outputPoint++] = (uint8_t)((table[i0] << 2) | (table[i1] >> 4)); - if (outputPoint < outputLength) { - output[outputPoint++] = (uint8_t)(((table[i1] & 0xF) << 4) | (table[i2] >> 2)); - } - if (outputPoint < outputLength) { - output[outputPoint++] = (uint8_t)(((table[i2] & 0x3) << 6) | table[i3]); - } - } - - return data; -} - -#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - -@end - -#endif // #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2Framework-Info.plist b/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2Framework-Info.plist deleted file mode 100644 index 4433570ee..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2Framework-Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - com.google.${PRODUCT_NAME:rfc1034identifier} - CFBundleInfoDictionaryVersion - 6.0 - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0 - CFBundleSignature - ???? - CFBundleVersion - 1 - - diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2WindowController.h b/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2WindowController.h deleted file mode 100644 index fb28d1350..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2WindowController.h +++ /dev/null @@ -1,336 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// GTMOAuth2WindowController -// -// This window controller for Mac handles sign-in via OAuth2 to Google or -// other services. -// -// This controller is not reusable; create a new instance of this controller -// every time the user will sign in. -// -// Sample usage for signing in to a Google service: -// -// static NSString *const kKeychainItemName = @”My App: Google Plus”; -// NSString *scope = @"https://www.googleapis.com/auth/plus.me"; -// -// -// GTMOAuth2WindowController *windowController; -// windowController = [[[GTMOAuth2WindowController alloc] initWithScope:scope -// clientID:clientID -// clientSecret:clientSecret -// keychainItemName:kKeychainItemName -// resourceBundle:nil] autorelease]; -// -// [windowController signInSheetModalForWindow:mMainWindow -// delegate:self -// finishedSelector:@selector(windowController:finishedWithAuth:error:)]; -// -// The finished selector should have a signature matching this: -// -// - (void)windowController:(GTMOAuth2WindowController *)windowController -// finishedWithAuth:(GTMOAuth2Authentication *)auth -// error:(NSError *)error { -// if (error != nil) { -// // sign in failed -// } else { -// // sign in succeeded -// // -// // with the GTL library, pass the authentication to the service object, -// // like -// // [[self contactService] setAuthorizer:auth]; -// // -// // or use it to sign a request directly, like -// // BOOL isAuthorizing = [self authorizeRequest:request -// // delegate:self -// // didFinishSelector:@selector(auth:finishedWithError:)]; -// } -// } -// -// To sign in to services other than Google, use the longer init method, -// as shown in the sample application -// -// If the network connection is lost for more than 30 seconds while the sign-in -// html is displayed, the notification kGTLOAuthNetworkLost will be sent. - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#include - -#if !TARGET_OS_IPHONE - -#import -#import - -// GTMHTTPFetcher.h brings in GTLDefines/GDataDefines -#if GTM_USE_SESSION_FETCHER -#import "GTMSessionFetcher.h" -#else -#import "GTMHTTPFetcher.h" -#import "GTMHTTPFetchHistory.h" // for GTMCookieStorage -#endif - -#import "GTMOAuth2SignIn.h" -#import "GTMOAuth2Authentication.h" - -@class GTMOAuth2SignIn; - -@interface GTMOAuth2WindowController : NSWindowController { - @private - // IBOutlets - NSButton *keychainCheckbox_; - WebView *webView_; - NSButton *webCloseButton_; - NSButton *webBackButton_; - - // the object responsible for the sign-in networking sequence; it holds - // onto the authentication object as well - GTMOAuth2SignIn *signIn_; - - // the page request to load when awakeFromNib occurs - NSURLRequest *initialRequest_; - - // local storage for WebKit cookies so they're not shared with Safari - GTMOAuth2CookieStorage *cookieStorage_; - - // the user we're calling back - // - // the delegate is retained only until the callback is invoked - // or the sign-in is canceled - id delegate_; - SEL finishedSelector_; - -#if NS_BLOCKS_AVAILABLE - void (^completionBlock_)(GTMOAuth2Authentication *, NSError *); -#elif !__LP64__ - // placeholders: for 32-bit builds, keep the size of the object's ivar section - // the same with and without blocks -#ifndef __clang_analyzer__ - id completionPlaceholder_; -#endif -#endif - - // flag allowing application to quit during display of sign-in sheet on 10.6 - // and later - BOOL shouldAllowApplicationTermination_; - - // delegate method for handling URLs to be opened in external windows - SEL externalRequestSelector_; - - BOOL isWindowShown_; - - // paranoid flag to ensure we only close once during the sign-in sequence - BOOL hasDoneFinalRedirect_; - - // paranoid flag to ensure we only call the user back once - BOOL hasCalledFinished_; - - // if non-nil, we display as a sheet on the specified window - NSWindow *sheetModalForWindow_; - - // if non-empty, the name of the application and service used for the - // keychain item - NSString *keychainItemName_; - - // if non-nil, the html string to be displayed immediately upon opening - // of the web view - NSString *initialHTMLString_; - - // if true, we allow default WebView handling of cookies, so the - // same user remains signed in each time the dialog is displayed - BOOL shouldPersistUser_; - - // user-defined data - id userData_; - NSMutableDictionary *properties_; -} - -// User interface elements -@property (nonatomic, assign) IBOutlet NSButton *keychainCheckbox; -@property (nonatomic, assign) IBOutlet WebView *webView; -@property (nonatomic, assign) IBOutlet NSButton *webCloseButton; -@property (nonatomic, assign) IBOutlet NSButton *webBackButton; - -// The application and service name to use for saving the auth tokens -// to the keychain -@property (nonatomic, copy) NSString *keychainItemName; - -// If true, the sign-in will remember which user was last signed in -// -// Defaults to false, so showing the sign-in window will always ask for -// the username and password, rather than skip to the grant authorization -// page. During development, it may be convenient to set this to true -// to speed up signing in. -@property (nonatomic, assign) BOOL shouldPersistUser; - -// Optional html string displayed immediately upon opening the web view -// -// This string is visible just until the sign-in web page loads, and -// may be used for a "Loading..." type of message -@property (nonatomic, copy) NSString *initialHTMLString; - -// The default timeout for an unreachable network during display of the -// sign-in page is 30 seconds, after which the notification -// kGTLOAuthNetworkLost is sent; set this to 0 to have no timeout -@property (nonatomic, assign) NSTimeInterval networkLossTimeoutInterval; - -// On 10.6 and later, the sheet can allow application termination by calling -// NSWindow's setPreventsApplicationTerminationWhenModal: -@property (nonatomic, assign) BOOL shouldAllowApplicationTermination; - -// Selector for a delegate method to handle requests sent to an external -// browser. -// -// Selector should have a signature matching -// - (void)windowController:(GTMOAuth2WindowController *)controller -// opensRequest:(NSURLRequest *)request; -// -// The controller's default behavior is to use NSWorkspace's openURL: -@property (nonatomic, assign) SEL externalRequestSelector; - -// The underlying object to hold authentication tokens and authorize http -// requests -@property (nonatomic, retain, readonly) GTMOAuth2Authentication *authentication; - -// The underlying object which performs the sign-in networking sequence -@property (nonatomic, retain, readonly) GTMOAuth2SignIn *signIn; - -// Any arbitrary data object the user would like the controller to retain -@property (nonatomic, retain) id userData; - -// Stored property values are retained for the convenience of the caller -- (void)setProperty:(id)obj forKey:(NSString *)key; -- (id)propertyForKey:(NSString *)key; - -@property (nonatomic, retain) NSDictionary *properties; - -- (IBAction)closeWindow:(id)sender; - -// Create a controller for authenticating to Google services -// -// scope is the requested scope of authorization -// (like "http://www.google.com/m8/feeds") -// -// keychainItemName is used for storing the token on the keychain, -// and is required for the "remember for later" checkbox to be shown; -// keychainItemName should be like "My Application: Google Contacts" -// (or set to nil if no persistent keychain storage is desired) -// -// resourceBundle may be nil if the window is in the main bundle's nib -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (id)controllerWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName // may be nil - resourceBundle:(NSBundle *)bundle; // may be nil - -- (id)initWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - resourceBundle:(NSBundle *)bundle; -#endif - -// Create a controller for authenticating to non-Google services, taking -// explicit endpoint URLs and an authentication object -+ (id)controllerWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName // may be nil - resourceBundle:(NSBundle *)bundle; // may be nil - -// This is the designated initializer -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - resourceBundle:(NSBundle *)bundle; - -// Entry point to begin displaying the sign-in window -// -// the finished selector should have a signature matching -// - (void)windowController:(GTMOAuth2WindowController *)windowController -// finishedWithAuth:(GTMOAuth2Authentication *)auth -// error:(NSError *)error { -// -// Once the finished method has been invoked with no error, the auth object -// may be used to authorize requests (refreshing the access token, if necessary, -// and adding the auth header) like: -// -// [authorizer authorizeRequest:myNSMutableURLRequest] -// delegate:self -// didFinishSelector:@selector(auth:finishedWithError:)]; -// -// or can be stored in a GTL service object like -// GTLServiceGoogleContact *service = [self contactService]; -// [service setAuthorizer:auth]; -// -// The delegate is retained only until the finished selector is invoked or -// the sign-in is canceled -- (void)signInSheetModalForWindow:(NSWindow *)parentWindowOrNil - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector; - -#if NS_BLOCKS_AVAILABLE -- (void)signInSheetModalForWindow:(NSWindow *)parentWindowOrNil - completionHandler:(void (^)(GTMOAuth2Authentication *auth, NSError *error))handler; -#endif - -- (void)cancelSigningIn; - -// Subclasses may override authNibName to specify a custom name -+ (NSString *)authNibName; - -// apps may replace the sign-in class with their own subclass of it -+ (Class)signInClass; -+ (void)setSignInClass:(Class)theClass; - -// Revocation of an authorized token from Google -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (void)revokeTokenForGoogleAuthentication:(GTMOAuth2Authentication *)auth; -#endif - -// Keychain -// -// The keychain checkbox is shown if the keychain application service -// name (typically set in the initWithScope: method) is non-empty -// - -// Create an authentication object for Google services from the access -// token and secret stored in the keychain; if no token is available, return -// an unauthorized auth object -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Authentication *)authForGoogleFromKeychainForName:(NSString *)keychainItemName - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret; -#endif - -// Add tokens from the keychain, if available, to the authentication object -// -// returns YES if the authentication object was authorized from the keychain -+ (BOOL)authorizeFromKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)auth; - -// Method for deleting the stored access token and secret, useful for "signing -// out" -+ (BOOL)removeAuthFromKeychainForName:(NSString *)keychainItemName; - -// Method for saving the stored access token and secret; typically, this method -// is used only by the window controller -+ (BOOL)saveAuthToKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)auth; -@end - -#endif // #if !TARGET_OS_IPHONE - -#endif // #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2WindowController.m b/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2WindowController.m deleted file mode 100644 index 02ae99b24..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/Mac/GTMOAuth2WindowController.m +++ /dev/null @@ -1,728 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#import - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#if !TARGET_OS_IPHONE - -#import "GTMOAuth2WindowController.h" - -@interface GTMOAuth2WindowController () -@property (nonatomic, retain) GTMOAuth2SignIn *signIn; -@property (nonatomic, copy) NSURLRequest *initialRequest; -@property (nonatomic, retain) GTMOAuth2CookieStorage *cookieStorage; -@property (nonatomic, retain) NSWindow *sheetModalForWindow; - -- (void)signInCommonForWindow:(NSWindow *)parentWindowOrNil; -- (void)setupSheetTerminationHandling; -- (void)destroyWindow; -- (void)handlePrematureWindowClose; -- (BOOL)shouldUseKeychain; -- (void)signIn:(GTMOAuth2SignIn *)signIn displayRequest:(NSURLRequest *)request; -- (void)signIn:(GTMOAuth2SignIn *)signIn finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error; -- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; - -- (void)handleCookiesForResponse:(NSURLResponse *)response; -- (NSURLRequest *)addCookiesToRequest:(NSURLRequest *)request; -@end - -const char *kKeychainAccountName = "OAuth"; - -@implementation GTMOAuth2WindowController - -// IBOutlets -@synthesize keychainCheckbox = keychainCheckbox_, - webView = webView_, - webCloseButton = webCloseButton_, - webBackButton = webBackButton_; - -// regular ivars -@synthesize signIn = signIn_, - initialRequest = initialRequest_, - cookieStorage = cookieStorage_, - sheetModalForWindow = sheetModalForWindow_, - keychainItemName = keychainItemName_, - initialHTMLString = initialHTMLString_, - shouldAllowApplicationTermination = shouldAllowApplicationTermination_, - externalRequestSelector = externalRequestSelector_, - shouldPersistUser = shouldPersistUser_, - userData = userData_, - properties = properties_; - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -// Create a controller for authenticating to Google services -+ (id)controllerWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - resourceBundle:(NSBundle *)bundle { - return [[[self alloc] initWithScope:scope - clientID:clientID - clientSecret:clientSecret - keychainItemName:keychainItemName - resourceBundle:bundle] autorelease]; -} - -- (id)initWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - resourceBundle:(NSBundle *)bundle { - Class signInClass = [[self class] signInClass]; - GTMOAuth2Authentication *auth; - auth = [signInClass standardGoogleAuthenticationForScope:scope - clientID:clientID - clientSecret:clientSecret]; - NSURL *authorizationURL = [signInClass googleAuthorizationURL]; - return [self initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - resourceBundle:bundle]; -} -#endif - -// Create a controller for authenticating to any service -+ (id)controllerWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - resourceBundle:(NSBundle *)bundle { - return [[[self alloc] initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - resourceBundle:bundle] autorelease]; -} - -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - resourceBundle:(NSBundle *)bundle { - if (bundle == nil) { - bundle = [NSBundle mainBundle]; - } - - NSString *nibName = [[self class] authNibName]; - NSString *nibPath = [bundle pathForResource:nibName - ofType:@"nib"]; - - self = [super initWithWindowNibPath:nibPath - owner:self]; - if (self != nil) { - // use the supplied auth and OAuth endpoint URLs - Class signInClass = [[self class] signInClass]; - signIn_ = [[signInClass alloc] initWithAuthentication:auth - authorizationURL:authorizationURL - delegate:self - webRequestSelector:@selector(signIn:displayRequest:) - finishedSelector:@selector(signIn:finishedWithAuth:error:)]; - keychainItemName_ = [keychainItemName copy]; - - // create local, temporary storage for WebKit cookies - cookieStorage_ = [[GTMOAuth2CookieStorage alloc] init]; - } - return self; -} - -- (void)dealloc { - [signIn_ release]; - [initialRequest_ release]; - [cookieStorage_ release]; - [delegate_ release]; -#if NS_BLOCKS_AVAILABLE - [completionBlock_ release]; -#endif - [sheetModalForWindow_ release]; - [keychainItemName_ release]; - [initialHTMLString_ release]; - [userData_ release]; - [properties_ release]; - - [super dealloc]; -} - -- (void)awakeFromNib { - // load the requested initial sign-in page - [self.webView setResourceLoadDelegate:self]; - [self.webView setPolicyDelegate:self]; - - // the app may prefer some html other than blank white to be displayed - // before the sign-in web page loads - NSString *html = self.initialHTMLString; - if ([html length] > 0) { - [[self.webView mainFrame] loadHTMLString:html baseURL:nil]; - } - - // hide the keychain checkbox if we're not supporting keychain - BOOL hideKeychainCheckbox = ![self shouldUseKeychain]; - - const NSTimeInterval kJanuary2011 = 1293840000; - BOOL isDateValid = ([[NSDate date] timeIntervalSince1970] > kJanuary2011); - if (isDateValid) { - // start the asynchronous load of the sign-in web page - [[self.webView mainFrame] performSelector:@selector(loadRequest:) - withObject:self.initialRequest - afterDelay:0.01 - inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; - } else { - // clock date is invalid, so signing in would fail with an unhelpful error - // from the server. Warn the user in an html string showing a watch icon, - // question mark, and the system date and time. Hopefully this will clue - // in brighter users, or at least let them make a useful screenshot to show - // to developers. - // - // Even better is for apps to check the system clock and show some more - // helpful, localized instructions for users; this is really a fallback. - NSString *const htmlTemplate = @"

" - @"⌚ ?
System Clock Incorrect
%@" - @"
"; - NSString *errHTML = [NSString stringWithFormat:htmlTemplate, [NSDate date]]; - - [[webView_ mainFrame] loadHTMLString:errHTML baseURL:nil]; - hideKeychainCheckbox = YES; - } - -#if DEBUG - // Verify that Javascript is enabled - BOOL hasJS = [[webView_ preferences] isJavaScriptEnabled]; - NSAssert(hasJS, @"GTMOAuth2: Javascript is required"); -#endif - - [keychainCheckbox_ setHidden:hideKeychainCheckbox]; -} - -+ (NSString *)authNibName { - // subclasses may override this to specify a custom nib name - return @"GTMOAuth2Window"; -} - -#pragma mark - - -- (void)signInSheetModalForWindow:(NSWindow *)parentWindowOrNil - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector { - // check the selector on debug builds - GTMOAuth2AssertValidSelector(delegate, finishedSelector, - @encode(GTMOAuth2WindowController *), @encode(GTMOAuth2Authentication *), - @encode(NSError *), 0); - - delegate_ = [delegate retain]; - finishedSelector_ = finishedSelector; - - [self signInCommonForWindow:parentWindowOrNil]; -} - -#if NS_BLOCKS_AVAILABLE -- (void)signInSheetModalForWindow:(NSWindow *)parentWindowOrNil - completionHandler:(void (^)(GTMOAuth2Authentication *, NSError *))handler { - completionBlock_ = [handler copy]; - - [self signInCommonForWindow:parentWindowOrNil]; -} -#endif - -- (void)signInCommonForWindow:(NSWindow *)parentWindowOrNil { - self.sheetModalForWindow = parentWindowOrNil; - hasDoneFinalRedirect_ = NO; - hasCalledFinished_ = NO; - - [self.signIn startSigningIn]; -} - -- (void)cancelSigningIn { - // The user has explicitly asked us to cancel signing in - // (so no further callback is required) - hasCalledFinished_ = YES; - - [delegate_ autorelease]; - delegate_ = nil; - -#if NS_BLOCKS_AVAILABLE - [completionBlock_ autorelease]; - completionBlock_ = nil; -#endif - - // The signIn object's cancel method will close the window - [self.signIn cancelSigningIn]; - hasDoneFinalRedirect_ = YES; -} - -- (IBAction)closeWindow:(id)sender { - // dismiss the window/sheet before we call back the client - [self destroyWindow]; - [self handlePrematureWindowClose]; -} - -#pragma mark SignIn callbacks - -- (void)signIn:(GTMOAuth2SignIn *)signIn displayRequest:(NSURLRequest *)request { - // this is the signIn object's webRequest method, telling the controller - // to either display the request in the webview, or close the window - // - // All web requests and all window closing goes through this routine - -#if DEBUG - if ((isWindowShown_ && request != nil) - || (!isWindowShown_ && request == nil)) { - NSLog(@"Window state unexpected for request %@", [request URL]); - return; - } -#endif - - if (request != nil) { - // display the request - self.initialRequest = request; - - NSWindow *parentWindow = self.sheetModalForWindow; - if (parentWindow) { - [self setupSheetTerminationHandling]; - - NSWindow *sheet = [self window]; - [NSApp beginSheet:sheet - modalForWindow:parentWindow - modalDelegate:self - didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:) - contextInfo:nil]; - } else { - // modeless - [self showWindow:self]; - } - isWindowShown_ = YES; - } else { - // request was nil - [self destroyWindow]; - } -} - -- (void)setupSheetTerminationHandling { - NSWindow *sheet = [self window]; - - SEL sel = @selector(setPreventsApplicationTerminationWhenModal:); - if ([sheet respondsToSelector:sel]) { - // setPreventsApplicationTerminationWhenModal is available in NSWindow - // on 10.6 and later - BOOL boolVal = !self.shouldAllowApplicationTermination; - NSMethodSignature *sig = [sheet methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:sheet]; - [invocation setArgument:&boolVal atIndex:2]; - [invocation invoke]; - } -} - -- (void)destroyWindow { - // no request; close the window - - // Avoid more callbacks after the close happens, as the window - // controller may be gone. - [self.webView stopLoading:nil]; - - NSWindow *parentWindow = self.sheetModalForWindow; - if (parentWindow) { - [NSApp endSheet:[self window]]; - } else { - // defer closing the window, in case we're responding to some window event - [[self window] performSelector:@selector(close) - withObject:nil - afterDelay:0.1 - inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; - - } - isWindowShown_ = NO; -} - -- (void)handlePrematureWindowClose { - if (!hasDoneFinalRedirect_) { - // tell the sign-in object to tell the user's finished method - // that we're done - [self.signIn windowWasClosed]; - hasDoneFinalRedirect_ = YES; - } -} - -- (void)sheetDidEnd:(NSWindow *)sheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo { - [sheet orderOut:self]; - - self.sheetModalForWindow = nil; -} - -- (void)signIn:(GTMOAuth2SignIn *)signIn finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error { - if (!hasCalledFinished_) { - hasCalledFinished_ = YES; - - if (error == nil) { - BOOL shouldUseKeychain = [self shouldUseKeychain]; - if (shouldUseKeychain) { - BOOL canAuthorize = auth.canAuthorize; - BOOL isKeychainChecked = ([keychainCheckbox_ state] == NSOnState); - - NSString *keychainItemName = self.keychainItemName; - - if (isKeychainChecked && canAuthorize) { - // save the auth params in the keychain - [[self class] saveAuthToKeychainForName:keychainItemName - authentication:auth]; - } else { - // remove the auth params from the keychain - [[self class] removeAuthFromKeychainForName:keychainItemName]; - } - } - } - - if (delegate_ && finishedSelector_) { - SEL sel = finishedSelector_; - NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:delegate_]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&auth atIndex:3]; - [invocation setArgument:&error atIndex:4]; - [invocation invoke]; - } - - [delegate_ autorelease]; - delegate_ = nil; - -#if NS_BLOCKS_AVAILABLE - if (completionBlock_) { - completionBlock_(auth, error); - - // release the block here to avoid a retain loop on the controller - [completionBlock_ autorelease]; - completionBlock_ = nil; - } -#endif - } -} - -static Class gSignInClass = Nil; - -+ (Class)signInClass { - if (gSignInClass == Nil) { - gSignInClass = [GTMOAuth2SignIn class]; - } - return gSignInClass; -} - -+ (void)setSignInClass:(Class)theClass { - gSignInClass = theClass; -} - -#pragma mark Token Revocation - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (void)revokeTokenForGoogleAuthentication:(GTMOAuth2Authentication *)auth { - [[self signInClass] revokeTokenForGoogleAuthentication:auth]; -} -#endif - -#pragma mark WebView methods - -- (NSURLRequest *)webView:(WebView *)sender resource:(id)identifier willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse fromDataSource:(WebDataSource *)dataSource { - // override WebKit's cookie storage with our own to avoid cookie persistence - // across sign-ins and interaction with the Safari browser's sign-in state - [self handleCookiesForResponse:redirectResponse]; - request = [self addCookiesToRequest:request]; - - if (!hasDoneFinalRedirect_) { - hasDoneFinalRedirect_ = [self.signIn requestRedirectedToRequest:request]; - if (hasDoneFinalRedirect_) { - // signIn has told the window to close - return nil; - } - } - return request; -} - -- (void)webView:(WebView *)sender resource:(id)identifier didReceiveResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)dataSource { - // override WebKit's cookie storage with our own - [self handleCookiesForResponse:response]; -} - -- (void)webView:(WebView *)sender resource:(id)identifier didFinishLoadingFromDataSource:(WebDataSource *)dataSource { - NSString *title = [sender stringByEvaluatingJavaScriptFromString:@"document.title"]; - if ([title length] > 0) { - [self.signIn titleChanged:title]; - } - - [signIn_ cookiesChanged:(NSHTTPCookieStorage *)cookieStorage_]; -} - -- (void)webView:(WebView *)sender resource:(id)identifier didFailLoadingWithError:(NSError *)error fromDataSource:(WebDataSource *)dataSource { - [self.signIn loadFailedWithError:error]; -} - -- (void)windowWillClose:(NSNotification *)note { - if (isWindowShown_) { - [self handlePrematureWindowClose]; - } - isWindowShown_ = NO; -} - -- (void)webView:(WebView *)webView -decidePolicyForNewWindowAction:(NSDictionary *)actionInformation - request:(NSURLRequest *)request - newFrameName:(NSString *)frameName -decisionListener:(id)listener { - SEL sel = self.externalRequestSelector; - if (sel) { - [delegate_ performSelector:sel - withObject:self - withObject:request]; - } else { - // default behavior is to open the URL in NSWorkspace's default browser - NSURL *url = [request URL]; - [[NSWorkspace sharedWorkspace] openURL:url]; - } - [listener ignore]; -} - -#pragma mark Cookie management - -// Rather than let the WebView use Safari's default cookie storage, we intercept -// requests and response to segregate and later discard cookies from signing in. -// -// This allows the application to actually sign out by discarding the auth token -// rather than the user being kept signed in by the cookies. - -- (void)handleCookiesForResponse:(NSURLResponse *)response { - if (self.shouldPersistUser) { - // we'll let WebKit handle the cookies; they'll persist across apps - // and across runs of this app - return; - } - - if ([response respondsToSelector:@selector(allHeaderFields)]) { - // grab the cookies from the header as NSHTTPCookies and store them locally - NSDictionary *headers = [(NSHTTPURLResponse *)response allHeaderFields]; - if (headers) { - NSURL *url = [response URL]; - NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headers - forURL:url]; - if ([cookies count] > 0) { - [cookieStorage_ setCookies:cookies]; - } - } - } -} - -- (NSURLRequest *)addCookiesToRequest:(NSURLRequest *)request { - if (self.shouldPersistUser) { - // we'll let WebKit handle the cookies; they'll persist across apps - // and across runs of this app - return request; - } - - // override WebKit's usual automatic storage of cookies - NSMutableURLRequest *mutableRequest = [[request mutableCopy] autorelease]; - [mutableRequest setHTTPShouldHandleCookies:NO]; - - // add our locally-stored cookies for this URL, if any - NSArray *cookies = [cookieStorage_ cookiesForURL:[request URL]]; - if ([cookies count] > 0) { - NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; - NSString *cookieHeader = [headers objectForKey:@"Cookie"]; - if (cookieHeader) { - [mutableRequest setValue:cookieHeader forHTTPHeaderField:@"Cookie"]; - } - } - return mutableRequest; -} - -#pragma mark Keychain support - -+ (NSString *)prefsKeyForName:(NSString *)keychainItemName { - NSString *result = [@"OAuth2: " stringByAppendingString:keychainItemName]; - return result; -} - -+ (BOOL)saveAuthToKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)auth { - - [self removeAuthFromKeychainForName:keychainItemName]; - - // don't save unless we have a token that can really authorize requests - if (!auth.canAuthorize) return NO; - - // make a response string containing the values we want to save - NSString *password = [auth persistenceResponseString]; - - SecKeychainRef defaultKeychain = NULL; - SecKeychainItemRef *dontWantItemRef= NULL; - const char *utf8ServiceName = [keychainItemName UTF8String]; - const char *utf8Password = [password UTF8String]; - - OSStatus err = SecKeychainAddGenericPassword(defaultKeychain, - (UInt32) strlen(utf8ServiceName), utf8ServiceName, - (UInt32) strlen(kKeychainAccountName), kKeychainAccountName, - (UInt32) strlen(utf8Password), utf8Password, - dontWantItemRef); - BOOL didSucceed = (err == noErr); - if (didSucceed) { - // write to preferences that we have a keychain item (so we know later - // that we can read from the keychain without raising a permissions dialog) - NSString *prefKey = [self prefsKeyForName:keychainItemName]; - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - [defaults setBool:YES forKey:prefKey]; - } - - return didSucceed; -} - -+ (BOOL)removeAuthFromKeychainForName:(NSString *)keychainItemName { - - SecKeychainRef defaultKeychain = NULL; - SecKeychainItemRef itemRef = NULL; - const char *utf8ServiceName = [keychainItemName UTF8String]; - - // we don't really care about the password here, we just want to - // get the SecKeychainItemRef so we can delete it. - OSStatus err = SecKeychainFindGenericPassword (defaultKeychain, - (UInt32) strlen(utf8ServiceName), utf8ServiceName, - (UInt32) strlen(kKeychainAccountName), kKeychainAccountName, - 0, NULL, // ignore password - &itemRef); - if (err != noErr) { - // failure to find is success - return YES; - } else { - // found something, so delete it - err = SecKeychainItemDelete(itemRef); - CFRelease(itemRef); - - // remove our preference key - NSString *prefKey = [self prefsKeyForName:keychainItemName]; - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - [defaults removeObjectForKey:prefKey]; - - return (err == noErr); - } -} - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Authentication *)authForGoogleFromKeychainForName:(NSString *)keychainItemName - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret { - Class signInClass = [self signInClass]; - NSURL *tokenURL = [signInClass googleTokenURL]; - NSString *redirectURI = [signInClass nativeClientRedirectURI]; - - GTMOAuth2Authentication *auth; - auth = [GTMOAuth2Authentication authenticationWithServiceProvider:kGTMOAuth2ServiceProviderGoogle - tokenURL:tokenURL - redirectURI:redirectURI - clientID:clientID - clientSecret:clientSecret]; - - [GTMOAuth2WindowController authorizeFromKeychainForName:keychainItemName - authentication:auth]; - return auth; -} -#endif - -+ (BOOL)authorizeFromKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)newAuth { - [newAuth setAccessToken:nil]; - - // before accessing the keychain, check preferences to verify that we've - // previously saved a token to the keychain (so we don't needlessly raise - // a keychain access permission dialog) - NSString *prefKey = [self prefsKeyForName:keychainItemName]; - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - BOOL flag = [defaults boolForKey:prefKey]; - if (!flag) { - return NO; - } - - BOOL didGetTokens = NO; - - SecKeychainRef defaultKeychain = NULL; - const char *utf8ServiceName = [keychainItemName UTF8String]; - SecKeychainItemRef *dontWantItemRef = NULL; - - void *passwordBuff = NULL; - UInt32 passwordBuffLength = 0; - - OSStatus err = SecKeychainFindGenericPassword(defaultKeychain, - (UInt32) strlen(utf8ServiceName), utf8ServiceName, - (UInt32) strlen(kKeychainAccountName), kKeychainAccountName, - &passwordBuffLength, &passwordBuff, - dontWantItemRef); - if (err == noErr && passwordBuff != NULL) { - - NSString *password = [[[NSString alloc] initWithBytes:passwordBuff - length:passwordBuffLength - encoding:NSUTF8StringEncoding] autorelease]; - - // free the password buffer that was allocated above - SecKeychainItemFreeContent(NULL, passwordBuff); - - if (password != nil) { - [newAuth setKeysForResponseString:password]; - didGetTokens = YES; - } - } - return didGetTokens; -} - -#pragma mark User Properties - -- (void)setProperty:(id)obj forKey:(NSString *)key { - if (obj == nil) { - // User passed in nil, so delete the property - [properties_ removeObjectForKey:key]; - } else { - // Be sure the property dictionary exists - if (properties_ == nil) { - [self setProperties:[NSMutableDictionary dictionary]]; - } - [properties_ setObject:obj forKey:key]; - } -} - -- (id)propertyForKey:(NSString *)key { - id obj = [properties_ objectForKey:key]; - - // Be sure the returned pointer has the life of the autorelease pool, - // in case self is released immediately - return [[obj retain] autorelease]; -} - -#pragma mark Accessors - -- (GTMOAuth2Authentication *)authentication { - return self.signIn.authentication; -} - -- (void)setNetworkLossTimeoutInterval:(NSTimeInterval)val { - self.signIn.networkLossTimeoutInterval = val; -} - -- (NSTimeInterval)networkLossTimeoutInterval { - return self.signIn.networkLossTimeoutInterval; -} - -- (BOOL)shouldUseKeychain { - NSString *name = self.keychainItemName; - return ([name length] > 0); -} - -@end - -#endif // #if !TARGET_OS_IPHONE - -#endif // #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/ReleaseNotes.txt b/Paco-iOS/vendor/gtm-oauth2/Source/ReleaseNotes.txt deleted file mode 100644 index d4816a8e6..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/ReleaseNotes.txt +++ /dev/null @@ -1,132 +0,0 @@ -GTM OAuth 2 Release Notes - -Project site: http://code.google.com/p/gtm-oauth2/ -Discussion group: http://groups.google.com/group/gtm-oauth2 - -7-August-2012 - -Replaced initial html delay fix with a pending request mechanism. - -26-July-2012 - -Added popViewBlock property to GTMOAuth2ViewControllerTouch to allow -dismissing the view when it lacks a navigation controller. - - -13-April-2012 - -Support setting keychain accessibility for iOS. - - -4-April-2012 - -Add scope to persistenceResponseString so applications can inspect -the prior scope after loading the token from the keychain. - - -3-April-2012 - -Now pulls version 2.3.2 of SBJSON sources from github. - - -14-March-2012 - -Added notification on access token refresh. - - -7-October-2011 - -Added notifications for starting and stopping loads of UIWebView. - - -30-September-2011 - -Add brief delay to view controller to allow initial html to load. - - -21-September-2011 - -Added additionalTokenRequestParameters property to the authorization object. - -Updated the domain for clearing cookies when signing into Google services. - - -7-September-2011 - -Add support for token servers providing url-encoded responses (thanks ivo) - - -25-August-2011 - -Added convenience methods for creating autoreleased controllers. - - -24-August-2011 - -Fixed sign-in when Mac window controller displays as a standalone -modal window (thanks mirko) - - -2-August-2011 - -Projects may now define GTM_OAUTH2_SKIP_GOOGLE_SUPPORT to exclude -Google-specific code. The GTMOAuth2 project file also now includes -"non-Google" targets for building without Google-specific code. - - -18-July-2011 - -The authorization header now uses the "Bearer" prefix. - - -12-July-2011 - -Added an additionalAuthorizationParameters property to the SignIn class, used -by the sample apps to specify a display language for the sign-in pages. - - -20-June-2011 - -To avoid accidental leakage of tokens, the authentication object now -returns kGTMOAuth2ErrorUnauthorizableRequest when attempting to authorize -requests with schemes other than https. The property -shouldAuthorizeAllRequests can be set to override this and allow any -request to be authorized. - - -1-June-2011 - -Added Mac window controller property shouldAllowApplicationTermination - -Added user properties to window & view controllers. - -Fetchers may now optionally be created by a GTMHTTPFetcherService instance. - - -24-May-2011 - -Mac window controller now opens pop-up window links in an external browser -by default, and provides an externalRequestSelector property to let -the client provide custom handling. - - -4-May-2011 - -Addded support for services which provide access tokens, but no -refresh tokens. - - -Release 1.0.0 -6-April-2011 - -Initial public release. - - -JSON notes: - -This library currently relies on version 2.1.1 of SBJSON: - -http://json-framework.googlecode.com/svn/tags/2.1.1/Source/ - -The latest version of SBJSON is avaiilable at http://stig.github.com/json-framework/ - diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewControllerTouch.h b/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewControllerTouch.h deleted file mode 100644 index 8670b03cb..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewControllerTouch.h +++ /dev/null @@ -1,398 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMOAuth2ViewControllerTouch.h -// -// This view controller for iPhone handles sign-in via OAuth to Google or -// other services. -// -// This controller is not reusable; create a new instance of this controller -// every time the user will sign in. -// - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#import - -#if TARGET_OS_IPHONE - -#import - -#import "GTMOAuth2Authentication.h" - -#ifdef __cplusplus -extern "C" { -#endif - -extern NSString *const kGTMOAuth2KeychainErrorDomain; - -// Notifications that the view controller is swapping out and back in cookies. -// Apps may use this to avoid relying on the cookie store while view controller -// has them swapped out. -extern NSString *const kGTMOAuth2CookiesWillSwapOut; -extern NSString *const kGTMOAuth2CookiesDidSwapIn; - -#ifdef __cplusplus -} -#endif - -@class GTMOAuth2SignIn; -@class GTMOAuth2ViewControllerTouch; - -typedef void (^GTMOAuth2ViewControllerCompletionHandler)(GTMOAuth2ViewControllerTouch *viewController, GTMOAuth2Authentication *auth, NSError *error); - -@interface GTMOAuth2ViewControllerTouch : UIViewController { - @private - UIButton *backButton_; - UIButton *forwardButton_; - UIActivityIndicatorView *initialActivityIndicator_; - UIView *navButtonsView_; - UIBarButtonItem *rightBarButtonItem_; - UIWebView *webView_; - - // The object responsible for the sign-in networking sequence; it holds - // onto the authentication object as well. - GTMOAuth2SignIn *signIn_; - - // the page request to load when awakeFromNib occurs - NSURLRequest *request_; - - // The user we're calling back - // - // The delegate is retained only until the callback is invoked - // or the sign-in is canceled - id delegate_; - SEL finishedSelector_; - -#if NS_BLOCKS_AVAILABLE - GTMOAuth2ViewControllerCompletionHandler completionBlock_; - - void (^popViewBlock_)(void); -#endif - - NSString *keychainItemName_; - CFTypeRef keychainItemAccessibility_; - - // if non-nil, the html string to be displayed immediately upon opening - // of the web view - NSString *initialHTMLString_; - - // set to 1 or -1 if the user sets the showsInitialActivityIndicator - // property - int mustShowActivityIndicator_; - - // if non-nil, the URL for which cookies will be deleted when the - // browser view is dismissed - NSURL *browserCookiesURL_; - - id userData_; - NSMutableDictionary *properties_; - -#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000 - // We delegate the decision to our owning NavigationController (if any). - // But, the NavigationController will call us back, and ask us. - // BOOL keeps us from infinite looping. - BOOL isInsideShouldAutorotateToInterfaceOrientation_; -#endif - - // YES, when view first shown in this signIn session. - BOOL isViewShown_; - - // YES, after the view has fully transitioned in. - BOOL didViewAppear_; - - // YES between sends of start and stop notifications - BOOL hasNotifiedWebViewStartedLoading_; - - // To prevent us from calling our delegate's selector more than once. - BOOL hasCalledFinished_; - - // Set in a webView callback. - BOOL hasDoneFinalRedirect_; - - // Set during the pop initiated by the sign-in object; otherwise, - // viewWillDisappear indicates that some external change of the view - // has stopped the sign-in. - BOOL didDismissSelf_; - - // Work around default cookie policy bug in iOS 7; see comments in viewWillAppear. - NSHTTPCookieAcceptPolicy savedCookiePolicy_; -} - -// the application and service name to use for saving the auth tokens -// to the keychain -@property (nonatomic, copy) NSString *keychainItemName; - -// the keychain item accessibility is a system constant for use -// with kSecAttrAccessible. -// -// Since it's a system constant, we do not need to retain it. -@property (nonatomic, assign) CFTypeRef keychainItemAccessibility; - -// optional html string displayed immediately upon opening the web view -// -// This string is visible just until the sign-in web page loads, and -// may be used for a "Loading..." type of message or to set the -// initial view color -@property (nonatomic, copy) NSString *initialHTMLString; - -// an activity indicator shows during initial webview load when no initial HTML -// string is specified, but the activity indicator can be forced to be shown -// with this property -@property (nonatomic, assign) BOOL showsInitialActivityIndicator; - -// the underlying object to hold authentication tokens and authorize http -// requests -@property (nonatomic, retain, readonly) GTMOAuth2Authentication *authentication; - -// the underlying object which performs the sign-in networking sequence -@property (nonatomic, retain, readonly) GTMOAuth2SignIn *signIn; - -// user interface elements -@property (nonatomic, retain) IBOutlet UIButton *backButton; -@property (nonatomic, retain) IBOutlet UIButton *forwardButton; -@property (nonatomic, retain) IBOutlet UIActivityIndicatorView *initialActivityIndicator; -@property (nonatomic, retain) IBOutlet UIView *navButtonsView; -@property (nonatomic, retain) IBOutlet UIBarButtonItem *rightBarButtonItem; -@property (nonatomic, retain) IBOutlet UIWebView *webView; - -#if NS_BLOCKS_AVAILABLE -// An optional block to be called when the view should be popped. If not set, -// the view controller will use its navigation controller to pop the view. -@property (nonatomic, copy) void (^popViewBlock)(void); -#endif - -// the default timeout for an unreachable network during display of the -// sign-in page is 30 seconds; set this to 0 to have no timeout -@property (nonatomic, assign) NSTimeInterval networkLossTimeoutInterval; - -// if set, cookies are deleted for this URL when the view is hidden -// -// This is now vestigial and ignored; all cookies are temporarily removed -// from cookie storage when sign-in begins. -@property (nonatomic, retain) NSURL *browserCookiesURL; - -// userData is retained for the convenience of the caller -@property (nonatomic, retain) id userData; - -// Stored property values are retained for the convenience of the caller -- (void)setProperty:(id)obj forKey:(NSString *)key; -- (id)propertyForKey:(NSString *)key; - -@property (nonatomic, retain) NSDictionary *properties; - -// Method for creating a controller to authenticate to Google services -// -// scope is the requested scope of authorization -// (like "http://www.google.com/m8/feeds") -// -// keychain item name is used for storing the token on the keychain, -// keychainItemName should be like "My Application: Google Latitude" -// (or set to nil if no persistent keychain storage is desired) -// -// the delegate is retained only until the finished selector is invoked -// or the sign-in is canceled -// -// If you don't like the default nibName and bundle, you can change them -// using the UIViewController properties once you've made one of these. -// -// finishedSelector is called after authentication completes. It should follow -// this signature. -// -// - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController -// finishedWithAuth:(GTMOAuth2Authentication *)auth -// error:(NSError *)error; -// -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (id)controllerWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector; - -- (id)initWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector; - -#if NS_BLOCKS_AVAILABLE -+ (id)controllerWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler; - -- (id)initWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler; -#endif -#endif - -// Create a controller for authenticating to non-Google services, taking -// explicit endpoint URLs and an authentication object -+ (id)controllerWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName // may be nil - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector; - -// This is the designated initializer -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector; - -#if NS_BLOCKS_AVAILABLE -+ (id)controllerWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName // may be nil - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler; - -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler; -#endif - -// subclasses may override authNibName to specify a custom name -+ (NSString *)authNibName; - -// subclasses may override authNibBundle to specify a custom bundle -+ (NSBundle *)authNibBundle; - -// subclasses may override setUpNavigation to provide their own navigation -// controls -- (void)setUpNavigation; - -// Swaps out the system cookies. The default implementation saves the system -// cookies and then switches to the cookies used for sign-in, initally empty. -// -// subclasses may override swapOutCookies to implement their own cookie -// management scheme. -- (void)swapOutCookies; - -// Swaps in the system cookies that were swapped out. The default implementation -// saves the cookies used for sign-in and then restores the system cookies -// that were saved in |swapOutCookies|. -// -// subclasses may override swapInCookies to implement their own cookie -// management scheme. -- (void)swapInCookies; - -// apps may replace the sign-in class with their own subclass of it -+ (Class)signInClass; -+ (void)setSignInClass:(Class)theClass; - -- (void)cancelSigningIn; - -// revocation of an authorized token from Google -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (void)revokeTokenForGoogleAuthentication:(GTMOAuth2Authentication *)auth; -#endif - -// -// Keychain -// - -// create an authentication object for Google services from the access -// token and secret stored in the keychain; if no token is available, return -// an unauthorized auth object. OK to pass NULL for the error parameter. -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Authentication *)authForGoogleFromKeychainForName:(NSString *)keychainItemName - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - error:(NSError **)error; -// Equivalent to calling the method above with a NULL error parameter. -+ (GTMOAuth2Authentication *)authForGoogleFromKeychainForName:(NSString *)keychainItemName - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret; -#endif - -// add tokens from the keychain, if available, to the authentication object -// -// returns YES if the authentication object was authorized from the keychain -+ (BOOL)authorizeFromKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)auth - error:(NSError **)error; - -// method for deleting the stored access token and secret, useful for "signing -// out" -+ (BOOL)removeAuthFromKeychainForName:(NSString *)keychainItemName; - -// method for saving the stored access token and secret -// -// returns YES if the save was successful. OK to pass NULL for the error -// parameter. -+ (BOOL)saveParamsToKeychainForName:(NSString *)keychainItemName - accessibility:(CFTypeRef)accessibility - authentication:(GTMOAuth2Authentication *)auth - error:(NSError **)error; - -// older version, defaults to kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly -+ (BOOL)saveParamsToKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)auth; - -@end - -// To function, GTMOAuth2ViewControllerTouch needs a certain amount of access -// to the iPhone's keychain. To keep things simple, its keychain access is -// broken out into a helper class. We declare it here in case you'd like to use -// it too, to store passwords. - -enum { - kGTMOAuth2KeychainErrorBadArguments = -1301, - kGTMOAuth2KeychainErrorNoPassword = -1302 -}; - - -@interface GTMOAuth2Keychain : NSObject - -+ (GTMOAuth2Keychain *)defaultKeychain; - -// OK to pass nil for the error parameter. -- (NSString *)passwordForService:(NSString *)service - account:(NSString *)account - error:(NSError **)error; - -// OK to pass nil for the error parameter. -- (BOOL)removePasswordForService:(NSString *)service - account:(NSString *)account - error:(NSError **)error; - -// OK to pass nil for the error parameter. -// -// accessibility should be one of the constants for kSecAttrAccessible -// such as kSecAttrAccessibleWhenUnlocked -- (BOOL)setPassword:(NSString *)password - forService:(NSString *)service - accessibility:(CFTypeRef)accessibility - account:(NSString *)account - error:(NSError **)error; - -// For unit tests: allow setting a mock object -+ (void)setDefaultKeychain:(GTMOAuth2Keychain *)keychain; - -@end - -#endif // TARGET_OS_IPHONE - -#endif // #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewControllerTouch.m b/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewControllerTouch.m deleted file mode 100644 index 976e6cf71..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewControllerTouch.m +++ /dev/null @@ -1,1104 +0,0 @@ -/* Copyright (c) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// -// GTMOAuth2ViewControllerTouch.m -// - -#import -#import - -#if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES - -#if TARGET_OS_IPHONE - -#import "GTMOAuth2ViewControllerTouch.h" - -#import "GTMOAuth2SignIn.h" -#import "GTMOAuth2Authentication.h" - -NSString *const kGTMOAuth2KeychainErrorDomain = @"com.google.GTMOAuthKeychain"; - -NSString *const kGTMOAuth2CookiesWillSwapOut = @"kGTMOAuth2CookiesWillSwapOut"; -NSString *const kGTMOAuth2CookiesDidSwapIn = @"kGTMOAuth2CookiesDidSwapIn"; - -static NSString * const kGTMOAuth2AccountName = @"OAuth"; -static GTMOAuth2Keychain* gGTMOAuth2DefaultKeychain = nil; - -@interface GTMOAuth2ViewControllerTouch() -@property (nonatomic, copy) NSURLRequest *request; -@property (nonatomic, copy) NSArray *systemCookies; -@property (nonatomic, copy) NSArray *signInCookies; -@end - -@implementation GTMOAuth2ViewControllerTouch - -// IBOutlets -@synthesize request = request_, - systemCookies = systemCookies_, - signInCookies = signInCookies_, - backButton = backButton_, - forwardButton = forwardButton_, - navButtonsView = navButtonsView_, - rightBarButtonItem = rightBarButtonItem_, - webView = webView_, - initialActivityIndicator = initialActivityIndicator_; - -@synthesize keychainItemName = keychainItemName_, - keychainItemAccessibility = keychainItemAccessibility_, - initialHTMLString = initialHTMLString_, - browserCookiesURL = browserCookiesURL_, - signIn = signIn_, - userData = userData_, - properties = properties_; - -#if NS_BLOCKS_AVAILABLE -@synthesize popViewBlock = popViewBlock_; -#endif - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (id)controllerWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector { - return [[[self alloc] initWithScope:scope - clientID:clientID - clientSecret:clientSecret - keychainItemName:keychainItemName - delegate:delegate - finishedSelector:finishedSelector] autorelease]; -} - -- (id)initWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector { - // convenient entry point for Google authentication - - Class signInClass = [[self class] signInClass]; - - GTMOAuth2Authentication *auth; - auth = [signInClass standardGoogleAuthenticationForScope:scope - clientID:clientID - clientSecret:clientSecret]; - NSURL *authorizationURL = [signInClass googleAuthorizationURL]; - return [self initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - delegate:delegate - finishedSelector:finishedSelector]; -} - -#if NS_BLOCKS_AVAILABLE - -+ (id)controllerWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler { - return [[[self alloc] initWithScope:scope - clientID:clientID - clientSecret:clientSecret - keychainItemName:keychainItemName - completionHandler:handler] autorelease]; -} - -- (id)initWithScope:(NSString *)scope - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler { - // convenient entry point for Google authentication - - Class signInClass = [[self class] signInClass]; - - GTMOAuth2Authentication *auth; - auth = [signInClass standardGoogleAuthenticationForScope:scope - clientID:clientID - clientSecret:clientSecret]; - NSURL *authorizationURL = [signInClass googleAuthorizationURL]; - self = [self initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - delegate:nil - finishedSelector:NULL]; - if (self) { - completionBlock_ = [handler copy]; - } - return self; -} - -#endif // NS_BLOCKS_AVAILABLE -#endif // !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT - -+ (id)controllerWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector { - return [[[self alloc] initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - delegate:delegate - finishedSelector:finishedSelector] autorelease]; -} - -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - delegate:(id)delegate - finishedSelector:(SEL)finishedSelector { - - NSString *nibName = [[self class] authNibName]; - NSBundle *nibBundle = [[self class] authNibBundle]; - - self = [super initWithNibName:nibName bundle:nibBundle]; - if (self != nil) { - delegate_ = [delegate retain]; - finishedSelector_ = finishedSelector; - - Class signInClass = [[self class] signInClass]; - - // use the supplied auth and OAuth endpoint URLs - signIn_ = [[signInClass alloc] initWithAuthentication:auth - authorizationURL:authorizationURL - delegate:self - webRequestSelector:@selector(signIn:displayRequest:) - finishedSelector:@selector(signIn:finishedWithAuth:error:)]; - - [self setKeychainItemName:keychainItemName]; - - savedCookiePolicy_ = (NSHTTPCookieAcceptPolicy)NSUIntegerMax; - } - return self; -} - -#if NS_BLOCKS_AVAILABLE -+ (id)controllerWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler { - return [[[self alloc] initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - completionHandler:handler] autorelease]; -} - -- (id)initWithAuthentication:(GTMOAuth2Authentication *)auth - authorizationURL:(NSURL *)authorizationURL - keychainItemName:(NSString *)keychainItemName - completionHandler:(GTMOAuth2ViewControllerCompletionHandler)handler { - // fall back to the non-blocks init - self = [self initWithAuthentication:auth - authorizationURL:authorizationURL - keychainItemName:keychainItemName - delegate:nil - finishedSelector:NULL]; - if (self) { - completionBlock_ = [handler copy]; - } - return self; -} -#endif - -- (void)dealloc { - [webView_ setDelegate:nil]; - - [backButton_ release]; - [forwardButton_ release]; - [initialActivityIndicator_ release]; - [navButtonsView_ release]; - [rightBarButtonItem_ release]; - [webView_ stopLoading]; - [webView_ release]; - [signIn_ release]; - [request_ release]; - [systemCookies_ release]; - [signInCookies_ release]; - [delegate_ release]; -#if NS_BLOCKS_AVAILABLE - [completionBlock_ release]; - [popViewBlock_ release]; -#endif - [keychainItemName_ release]; - [initialHTMLString_ release]; - [browserCookiesURL_ release]; - [userData_ release]; - [properties_ release]; - - [super dealloc]; -} - -+ (NSString *)authNibName { - // subclasses may override this to specify a custom nib name - return @"GTMOAuth2ViewTouch"; -} - -+ (NSBundle *)authNibBundle { - // subclasses may override this to specify a custom nib bundle - return nil; -} - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (GTMOAuth2Authentication *)authForGoogleFromKeychainForName:(NSString *)keychainItemName - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret { - return [self authForGoogleFromKeychainForName:keychainItemName - clientID:clientID - clientSecret:clientSecret - error:NULL]; -} - -+ (GTMOAuth2Authentication *)authForGoogleFromKeychainForName:(NSString *)keychainItemName - clientID:(NSString *)clientID - clientSecret:(NSString *)clientSecret - error:(NSError **)error { - Class signInClass = [self signInClass]; - NSURL *tokenURL = [signInClass googleTokenURL]; - NSString *redirectURI = [signInClass nativeClientRedirectURI]; - - GTMOAuth2Authentication *auth; - auth = [GTMOAuth2Authentication authenticationWithServiceProvider:kGTMOAuth2ServiceProviderGoogle - tokenURL:tokenURL - redirectURI:redirectURI - clientID:clientID - clientSecret:clientSecret]; - [[self class] authorizeFromKeychainForName:keychainItemName - authentication:auth - error:error]; - return auth; -} - -#endif - -+ (BOOL)authorizeFromKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)newAuth - error:(NSError **)error { - newAuth.accessToken = nil; - - BOOL didGetTokens = NO; - GTMOAuth2Keychain *keychain = [GTMOAuth2Keychain defaultKeychain]; - NSString *password = [keychain passwordForService:keychainItemName - account:kGTMOAuth2AccountName - error:error]; - if (password != nil) { - [newAuth setKeysForResponseString:password]; - didGetTokens = YES; - } - return didGetTokens; -} - -+ (BOOL)removeAuthFromKeychainForName:(NSString *)keychainItemName { - GTMOAuth2Keychain *keychain = [GTMOAuth2Keychain defaultKeychain]; - return [keychain removePasswordForService:keychainItemName - account:kGTMOAuth2AccountName - error:nil]; -} - -+ (BOOL)saveParamsToKeychainForName:(NSString *)keychainItemName - authentication:(GTMOAuth2Authentication *)auth { - return [self saveParamsToKeychainForName:keychainItemName - accessibility:NULL - authentication:auth - error:NULL]; -} - -+ (BOOL)saveParamsToKeychainForName:(NSString *)keychainItemName - accessibility:(CFTypeRef)accessibility - authentication:(GTMOAuth2Authentication *)auth - error:(NSError **)error { - [self removeAuthFromKeychainForName:keychainItemName]; - // don't save unless we have a token that can really authorize requests - if (![auth canAuthorize]) { - if (error) { - *error = [NSError errorWithDomain:kGTMOAuth2ErrorDomain - code:kGTMOAuth2ErrorTokenUnavailable - userInfo:nil]; - } - return NO; - } - - if (accessibility == NULL - && &kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly != NULL) { - accessibility = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly; - } - - // make a response string containing the values we want to save - NSString *password = [auth persistenceResponseString]; - GTMOAuth2Keychain *keychain = [GTMOAuth2Keychain defaultKeychain]; - return [keychain setPassword:password - forService:keychainItemName - accessibility:accessibility - account:kGTMOAuth2AccountName - error:error]; -} - -- (void)loadView { - NSString *nibPath = nil; - NSBundle *nibBundle = [self nibBundle]; - if (nibBundle == nil) { - nibBundle = [NSBundle mainBundle]; - } - NSString *nibName = self.nibName; - if (nibName != nil) { - nibPath = [nibBundle pathForResource:nibName ofType:@"nib"]; - } - if (nibPath != nil && [[NSFileManager defaultManager] fileExistsAtPath:nibPath]) { - [super loadView]; - } else { - // One of the requirements of loadView is that a valid view object is set to - // self.view upon completion. Otherwise, subclasses that attempt to - // access self.view after calling [super loadView] will enter an infinite - // loop due to the fact that UIViewController's -view accessor calls - // loadView when self.view is nil. - self.view = [[[UIView alloc] init] autorelease]; - -#if DEBUG - NSLog(@"missing %@.nib", nibName); -#endif - } -} - - -- (void)viewDidLoad { - [super viewDidLoad]; - [self setUpNavigation]; -} - -- (void)setUpNavigation { - rightBarButtonItem_.customView = navButtonsView_; - self.navigationItem.rightBarButtonItem = rightBarButtonItem_; -} - -- (void)popView { -#if NS_BLOCKS_AVAILABLE - void (^popViewBlock)() = self.popViewBlock; -#else - id popViewBlock = nil; -#endif - - if (popViewBlock || self.navigationController.topViewController == self) { - if (!self.view.hidden) { - // Set the flag to our viewWillDisappear method so it knows - // this is a disappearance initiated by the sign-in object, - // not the user cancelling via the navigation controller - didDismissSelf_ = YES; - - if (popViewBlock) { -#if NS_BLOCKS_AVAILABLE - popViewBlock(); - self.popViewBlock = nil; -#endif - } else { - [self.navigationController popViewControllerAnimated:YES]; - } - self.view.hidden = YES; - } - } -} - -- (void)notifyWithName:(NSString *)name - webView:(UIWebView *)webView - kind:(NSString *)kind { - BOOL isStarting = [name isEqual:kGTMOAuth2WebViewStartedLoading]; - if (hasNotifiedWebViewStartedLoading_ == isStarting) { - // Duplicate notification - // - // UIWebView's delegate methods are so unbalanced that there's little - // point trying to keep a count, as it could easily end up stuck greater - // than zero. - // - // We don't really have a way to track the starts and stops of - // subframe loads, too, as the webView in the notification is always - // for the topmost request. - return; - } - hasNotifiedWebViewStartedLoading_ = isStarting; - - // Notification for webview load starting and stopping - NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: - webView, kGTMOAuth2WebViewKey, - kind, kGTMOAuth2WebViewStopKindKey, // kind may be nil - nil]; - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - [nc postNotificationName:name - object:self - userInfo:dict]; -} - -- (void)cancelSigningIn { - // The application has explicitly asked us to cancel signing in - // (so no further callback is required) - hasCalledFinished_ = YES; - - [delegate_ autorelease]; - delegate_ = nil; - -#if NS_BLOCKS_AVAILABLE - [completionBlock_ autorelease]; - completionBlock_ = nil; -#endif - - // The sign-in object's cancel method will close the window - [signIn_ cancelSigningIn]; - hasDoneFinalRedirect_ = YES; -} - -static Class gSignInClass = Nil; - -+ (Class)signInClass { - if (gSignInClass == Nil) { - gSignInClass = [GTMOAuth2SignIn class]; - } - return gSignInClass; -} - -+ (void)setSignInClass:(Class)theClass { - gSignInClass = theClass; -} - -#pragma mark Token Revocation - -#if !GTM_OAUTH2_SKIP_GOOGLE_SUPPORT -+ (void)revokeTokenForGoogleAuthentication:(GTMOAuth2Authentication *)auth { - [[self signInClass] revokeTokenForGoogleAuthentication:auth]; -} -#endif - -#pragma mark Browser Cookies - -- (GTMOAuth2Authentication *)authentication { - return self.signIn.authentication; -} - -- (void)swapOutCookies { - // Switch to the cookie set used for sign-in, initially empty. - self.systemCookies = [self swapBrowserCookies:self.signInCookies]; -} - -- (void)swapInCookies { - // Switch back to the saved system cookies. - self.signInCookies = [self swapBrowserCookies:self.systemCookies]; -} - -- (NSArray *)swapBrowserCookies:(NSArray *)newCookies { - NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; - - NSHTTPCookieAcceptPolicy savedPolicy = [cookieStorage cookieAcceptPolicy]; - [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways]; - - NSArray *priorCookies = [[[cookieStorage cookies] copy] autorelease]; - for (NSHTTPCookie *cookie in priorCookies) { - [cookieStorage deleteCookie:cookie]; - } - for (NSHTTPCookie *cookie in newCookies) { - [cookieStorage setCookie:cookie]; - } - - [cookieStorage setCookieAcceptPolicy:savedPolicy]; - - return priorCookies; -} - -#pragma mark Accessors - -- (void)setNetworkLossTimeoutInterval:(NSTimeInterval)val { - signIn_.networkLossTimeoutInterval = val; -} - -- (NSTimeInterval)networkLossTimeoutInterval { - return signIn_.networkLossTimeoutInterval; -} - -- (BOOL)shouldUseKeychain { - NSString *name = self.keychainItemName; - return ([name length] > 0); -} - -- (BOOL)showsInitialActivityIndicator { - return (mustShowActivityIndicator_ == 1 || initialHTMLString_ == nil); -} - -- (void)setShowsInitialActivityIndicator:(BOOL)flag { - mustShowActivityIndicator_ = (flag ? 1 : -1); -} - -#pragma mark User Properties - -- (void)setProperty:(id)obj forKey:(NSString *)key { - if (obj == nil) { - // User passed in nil, so delete the property - [properties_ removeObjectForKey:key]; - } else { - // Be sure the property dictionary exists - if (properties_ == nil) { - [self setProperties:[NSMutableDictionary dictionary]]; - } - [properties_ setObject:obj forKey:key]; - } -} - -- (id)propertyForKey:(NSString *)key { - id obj = [properties_ objectForKey:key]; - - // Be sure the returned pointer has the life of the autorelease pool, - // in case self is released immediately - return [[obj retain] autorelease]; -} - -#pragma mark SignIn callbacks - -- (void)signIn:(GTMOAuth2SignIn *)signIn displayRequest:(NSURLRequest *)request { - // This is the signIn object's webRequest method, telling the controller - // to either display the request in the webview, or if the request is nil, - // to close the window. - // - // All web requests and all window closing goes through this routine - -#if DEBUG - if (self.navigationController) { - if (self.navigationController.topViewController != self && request != nil) { - NSLog(@"Unexpected: Request to show, when already on top. request %@", [request URL]); - } else if(self.navigationController.topViewController != self && request == nil) { - NSLog(@"Unexpected: Request to pop, when not on top. request nil"); - } - } -#endif - - if (request != nil) { - const NSTimeInterval kJanuary2011 = 1293840000; - BOOL isDateValid = ([[NSDate date] timeIntervalSince1970] > kJanuary2011); - if (isDateValid) { - // Display the request. - self.request = request; - // The app may prefer some html other than blank white to be displayed - // before the sign-in web page loads. - // The first fetch might be slow, so the client programmer may want - // to show a local "loading" message. - // On iOS 5+, UIWebView will ignore loadHTMLString: if it's followed by - // a loadRequest: call, so if there is a "loading" message we defer - // the loadRequest: until after after we've drawn the "loading" message. - // - // If there is no initial html string, we show the activity indicator - // unless the user set showsInitialActivityIndicator to NO; if there - // is an initial html string, we hide the indicator unless the user set - // showsInitialActivityIndicator to YES. - NSString *html = self.initialHTMLString; - if ([html length] > 0) { - [initialActivityIndicator_ setHidden:(mustShowActivityIndicator_ < 1)]; - [self.webView loadHTMLString:html baseURL:nil]; - } else { - [initialActivityIndicator_ setHidden:(mustShowActivityIndicator_ < 0)]; - [self.webView loadRequest:request]; - } - } else { - // clock date is invalid, so signing in would fail with an unhelpful error - // from the server. Warn the user in an html string showing a watch icon, - // question mark, and the system date and time. Hopefully this will clue - // in brighter users, or at least give them a clue when they report the - // problem to developers. - // - // Even better is for apps to check the system clock and show some more - // helpful, localized instructions for users; this is really a fallback. - NSString *const html = @"
" - @"⌚ ?
System Clock Incorrect
%@" - @"
"; - NSString *errHTML = [NSString stringWithFormat:html, [NSDate date]]; - - [[self webView] loadHTMLString:errHTML baseURL:nil]; - } - } else { - // request was nil. - [self popView]; - } -} - -- (void)signIn:(GTMOAuth2SignIn *)signIn - finishedWithAuth:(GTMOAuth2Authentication *)auth - error:(NSError *)error { - if (!hasCalledFinished_) { - hasCalledFinished_ = YES; - - if (error == nil) { - if (self.shouldUseKeychain) { - NSString *keychainItemName = self.keychainItemName; - if (auth.canAuthorize) { - // save the auth params in the keychain - CFTypeRef accessibility = self.keychainItemAccessibility; - [[self class] saveParamsToKeychainForName:keychainItemName - accessibility:accessibility - authentication:auth - error:NULL]; - } else { - // remove the auth params from the keychain - [[self class] removeAuthFromKeychainForName:keychainItemName]; - } - } - } - - if (delegate_ && finishedSelector_) { - SEL sel = finishedSelector_; - NSMethodSignature *sig = [delegate_ methodSignatureForSelector:sel]; - NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:sig]; - [invocation setSelector:sel]; - [invocation setTarget:delegate_]; - [invocation setArgument:&self atIndex:2]; - [invocation setArgument:&auth atIndex:3]; - [invocation setArgument:&error atIndex:4]; - [invocation invoke]; - } - - [delegate_ autorelease]; - delegate_ = nil; - -#if NS_BLOCKS_AVAILABLE - if (completionBlock_) { - completionBlock_(self, auth, error); - - // release the block here to avoid a retain loop on the controller - [completionBlock_ autorelease]; - completionBlock_ = nil; - } -#endif - } -} - -- (void)moveWebViewFromUnderNavigationBar { - CGRect dontCare; - CGRect webFrame = self.view.bounds; - UINavigationBar *navigationBar = self.navigationController.navigationBar; - CGRectDivide(webFrame, &dontCare, &webFrame, - navigationBar.frame.size.height, CGRectMinYEdge); - [self.webView setFrame:webFrame]; -} - -// isTranslucent is defined in iPhoneOS 3.0 on. -- (BOOL)isNavigationBarTranslucent { - UINavigationBar *navigationBar = [[self navigationController] navigationBar]; - BOOL isTranslucent = - ([navigationBar respondsToSelector:@selector(isTranslucent)] && - [navigationBar isTranslucent]); - return isTranslucent; -} - -#pragma mark - -#pragma mark Protocol implementations - -- (void)viewWillAppear:(BOOL)animated { - // See the comment on clearBrowserCookies in viewWillDisappear. - [[NSNotificationCenter defaultCenter] postNotificationName:kGTMOAuth2CookiesWillSwapOut - object:self - userInfo:nil]; - [self swapOutCookies]; - - if (!isViewShown_) { - isViewShown_ = YES; - if ([self isNavigationBarTranslucent]) { - [self moveWebViewFromUnderNavigationBar]; - } - if (![signIn_ startSigningIn]) { - // Can't start signing in. We must pop our view. - // UIWebview needs time to stabilize. Animations need time to complete. - // We remove ourself from the view stack after that. - [self performSelector:@selector(popView) - withObject:nil - afterDelay:0.5 - inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; - } - - // Work around iOS 7.0 bug described in https://devforums.apple.com/thread/207323 by temporarily - // setting our cookie storage policy to be permissive enough to keep the sign-in server - // satisfied, just in case the app inherited from Safari a policy that blocks all cookies. - NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; - NSHTTPCookieAcceptPolicy policy = [storage cookieAcceptPolicy]; - if (policy == NSHTTPCookieAcceptPolicyNever) { - savedCookiePolicy_ = policy; - [storage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyOnlyFromMainDocumentDomain]; - } - } - - [super viewWillAppear:animated]; -} - -- (void)viewDidAppear:(BOOL)animated { - didViewAppear_ = YES; - [super viewDidAppear:animated]; -} - -- (void)viewWillDisappear:(BOOL)animated { - if (![self isBeingObscured:self]) { - if (!didDismissSelf_) { - // We won't receive further webview delegate messages, so be sure the - // started loading notification is balanced, if necessary - [self notifyWithName:kGTMOAuth2WebViewStoppedLoading - webView:self.webView - kind:kGTMOAuth2WebViewCancelled]; - - // We are not popping ourselves, so presumably we are being popped by the - // navigation controller; tell the sign-in object to close up shop - // - // this will indirectly call our signIn:finishedWithAuth:error: method - // for us - [signIn_ windowWasClosed]; - -#if NS_BLOCKS_AVAILABLE - self.popViewBlock = nil; -#endif - } - - if (savedCookiePolicy_ != (NSHTTPCookieAcceptPolicy)NSUIntegerMax) { - NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; - [storage setCookieAcceptPolicy:savedCookiePolicy_]; - savedCookiePolicy_ = (NSHTTPCookieAcceptPolicy)NSUIntegerMax; - } - } - - [self swapInCookies]; - [[NSNotificationCenter defaultCenter] postNotificationName:kGTMOAuth2CookiesDidSwapIn - object:self - userInfo:nil]; - [super viewWillDisappear:animated]; -} - -- (BOOL)isBeingObscured:(UIViewController *)vc { - // Check if this view controller, or an ancestor, is being disappearing because - // of being obscured by another view. - if ([vc isBeingDismissed] || [vc isMovingFromParentViewController]) { - return NO; - } - UIViewController *parentVC = vc.parentViewController; - if (parentVC) { - return [self isBeingObscured:parentVC]; - } - return YES; -} - -- (void)viewDidLayoutSubviews { - // We don't call super's version of this method because - // -[UIViewController viewDidLayoutSubviews] is documented as a no-op, that - // didn't exist before iOS 5. - [initialActivityIndicator_ setCenter:[webView_ center]]; -} - -- (BOOL)webView:(UIWebView *)webView - shouldStartLoadWithRequest:(NSURLRequest *)request - navigationType:(UIWebViewNavigationType)navigationType { - - if (!hasDoneFinalRedirect_) { - hasDoneFinalRedirect_ = [signIn_ requestRedirectedToRequest:request]; - if (hasDoneFinalRedirect_) { - // signIn has told the view to close - return NO; - } - } - return YES; -} - -- (void)updateUI { - [backButton_ setEnabled:[[self webView] canGoBack]]; - [forwardButton_ setEnabled:[[self webView] canGoForward]]; -} - -- (void)webViewDidStartLoad:(UIWebView *)webView { - [self notifyWithName:kGTMOAuth2WebViewStartedLoading - webView:webView - kind:nil]; - [self updateUI]; -} - -- (void)webViewDidFinishLoad:(UIWebView *)webView { - [self notifyWithName:kGTMOAuth2WebViewStoppedLoading - webView:webView - kind:kGTMOAuth2WebViewFinished]; - - NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"]; - if ([title length] > 0) { - [signIn_ titleChanged:title]; - } else { -#if DEBUG && !defined(NS_BLOCK_ASSERTIONS) - // Verify that Javascript is enabled - NSString *result = [webView stringByEvaluatingJavaScriptFromString:@"1+1"]; - NSAssert([result integerValue] == 2, @"GTMOAuth2: Javascript is required"); -#endif // DEBUG && !defined(NS_BLOCK_ASSERTIONS) - } - - if (self.request && [self.initialHTMLString length] > 0) { - // The request was pending. - [self setInitialHTMLString:nil]; - [self.webView loadRequest:self.request]; - } else { - [initialActivityIndicator_ setHidden:YES]; - [signIn_ cookiesChanged:[NSHTTPCookieStorage sharedHTTPCookieStorage]]; - - [self updateUI]; - } -} - -- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { - [self notifyWithName:kGTMOAuth2WebViewStoppedLoading - webView:webView - kind:kGTMOAuth2WebViewFailed]; - - // Tell the sign-in object that a load failed; if it was the authorization - // URL, it will pop the view and return an error to the delegate. - if (didViewAppear_) { - BOOL isUserInterruption = ([error code] == NSURLErrorCancelled - && [[error domain] isEqual:NSURLErrorDomain]); - if (isUserInterruption) { - // Ignore this error: - // Users report that this error occurs when clicking too quickly on the - // accept button, before the page has completely loaded. Ignoring - // this error seems to provide a better experience than does immediately - // cancelling sign-in. - // - // This error also occurs whenever UIWebView is sent the stopLoading - // message, so if we ever send that message intentionally, we need to - // revisit this bypass. - return; - } - - [signIn_ loadFailedWithError:error]; - } else { - // UIWebview needs time to stabilize. Animations need time to complete. - [signIn_ performSelector:@selector(loadFailedWithError:) - withObject:error - afterDelay:0.5 - inModes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; - } -} - -#if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000 -// When running on a device with an OS version < 6, this gets called. -// -// Since it is never called in iOS 6 or greater, if your min deployment -// target is iOS6 or greater, then you don't need to have this method compiled -// into your app. -// -// When running on a device with an OS version 6 or greater, this code is -// not called. - (NSUInteger)supportedInterfaceOrientations; would be called, -// if it existed. Since it is absent, -// Allow the default orientations: All for iPad, all but upside down for iPhone. -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - BOOL value = YES; - if (!isInsideShouldAutorotateToInterfaceOrientation_) { - isInsideShouldAutorotateToInterfaceOrientation_ = YES; - UIViewController *navigationController = [self navigationController]; - if (navigationController != nil) { - value = [navigationController shouldAutorotateToInterfaceOrientation:interfaceOrientation]; - } else { - value = [super shouldAutorotateToInterfaceOrientation:interfaceOrientation]; - } - isInsideShouldAutorotateToInterfaceOrientation_ = NO; - } - return value; -} -#endif - - -@end - - -#pragma mark Common Code - -@implementation GTMOAuth2Keychain - -+ (GTMOAuth2Keychain *)defaultKeychain { - if (gGTMOAuth2DefaultKeychain == nil) { - gGTMOAuth2DefaultKeychain = [[self alloc] init]; - } - return gGTMOAuth2DefaultKeychain; -} - - -// For unit tests: allow setting a mock object -+ (void)setDefaultKeychain:(GTMOAuth2Keychain *)keychain { - if (gGTMOAuth2DefaultKeychain != keychain) { - [gGTMOAuth2DefaultKeychain release]; - gGTMOAuth2DefaultKeychain = [keychain retain]; - } -} - -- (NSString *)keyForService:(NSString *)service account:(NSString *)account { - return [NSString stringWithFormat:@"com.google.GTMOAuth.%@%@", service, account]; -} - -// The Keychain API isn't available on the iPhone simulator in SDKs before 3.0, -// so, on early simulators we use a fake API, that just writes, unencrypted, to -// NSUserDefaults. -#if TARGET_IPHONE_SIMULATOR && __IPHONE_OS_VERSION_MAX_ALLOWED < 30000 -#pragma mark Simulator - -// Simulator - just simulated, not secure. -- (NSString *)passwordForService:(NSString *)service account:(NSString *)account error:(NSError **)error { - NSString *result = nil; - if (0 < [service length] && 0 < [account length]) { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSString *key = [self keyForService:service account:account]; - result = [defaults stringForKey:key]; - if (result == nil && error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:kGTMOAuth2KeychainErrorNoPassword - userInfo:nil]; - } - } else if (error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:kGTMOAuth2KeychainErrorBadArguments - userInfo:nil]; - } - return result; - -} - - -// Simulator - just simulated, not secure. -- (BOOL)removePasswordForService:(NSString *)service account:(NSString *)account error:(NSError **)error { - BOOL didSucceed = NO; - if (0 < [service length] && 0 < [account length]) { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSString *key = [self keyForService:service account:account]; - [defaults removeObjectForKey:key]; - [defaults synchronize]; - } else if (error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:kGTMOAuth2KeychainErrorBadArguments - userInfo:nil]; - } - return didSucceed; -} - -// Simulator - just simulated, not secure. -- (BOOL)setPassword:(NSString *)password - forService:(NSString *)service - accessibility:(CFTypeRef)accessibility - account:(NSString *)account - error:(NSError **)error { - BOOL didSucceed = NO; - if (0 < [password length] && 0 < [service length] && 0 < [account length]) { - NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; - NSString *key = [self keyForService:service account:account]; - [defaults setObject:password forKey:key]; - [defaults synchronize]; - didSucceed = YES; - } else if (error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:kGTMOAuth2KeychainErrorBadArguments - userInfo:nil]; - } - return didSucceed; -} - -#else // ! TARGET_IPHONE_SIMULATOR -#pragma mark Device - -+ (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account { - NSMutableDictionary *query = [NSMutableDictionary dictionaryWithObjectsAndKeys: - (id)kSecClassGenericPassword, (id)kSecClass, - @"OAuth", (id)kSecAttrGeneric, - account, (id)kSecAttrAccount, - service, (id)kSecAttrService, - nil]; - return query; -} - -- (NSMutableDictionary *)keychainQueryForService:(NSString *)service account:(NSString *)account { - return [[self class] keychainQueryForService:service account:account]; -} - - - -// iPhone -- (NSString *)passwordForService:(NSString *)service account:(NSString *)account error:(NSError **)error { - OSStatus status = kGTMOAuth2KeychainErrorBadArguments; - NSString *result = nil; - if (0 < [service length] && 0 < [account length]) { - CFDataRef passwordData = NULL; - NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account]; - [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData]; - [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit]; - - status = SecItemCopyMatching((CFDictionaryRef)keychainQuery, - (CFTypeRef *)&passwordData); - if (status == noErr && 0 < [(NSData *)passwordData length]) { - result = [[[NSString alloc] initWithData:(NSData *)passwordData - encoding:NSUTF8StringEncoding] autorelease]; - } - if (passwordData != NULL) { - CFRelease(passwordData); - } - } - if (status != noErr && error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:status - userInfo:nil]; - } - return result; -} - - -// iPhone -- (BOOL)removePasswordForService:(NSString *)service account:(NSString *)account error:(NSError **)error { - OSStatus status = kGTMOAuth2KeychainErrorBadArguments; - if (0 < [service length] && 0 < [account length]) { - NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account]; - status = SecItemDelete((CFDictionaryRef)keychainQuery); - } - if (status != noErr && error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:status - userInfo:nil]; - } - return status == noErr; -} - -// iPhone -- (BOOL)setPassword:(NSString *)password - forService:(NSString *)service - accessibility:(CFTypeRef)accessibility - account:(NSString *)account - error:(NSError **)error { - OSStatus status = kGTMOAuth2KeychainErrorBadArguments; - if (0 < [service length] && 0 < [account length]) { - [self removePasswordForService:service account:account error:nil]; - if (0 < [password length]) { - NSMutableDictionary *keychainQuery = [self keychainQueryForService:service account:account]; - NSData *passwordData = [password dataUsingEncoding:NSUTF8StringEncoding]; - [keychainQuery setObject:passwordData forKey:(id)kSecValueData]; - - if (accessibility != NULL && &kSecAttrAccessible != NULL) { - [keychainQuery setObject:(id)accessibility - forKey:(id)kSecAttrAccessible]; - } - status = SecItemAdd((CFDictionaryRef)keychainQuery, NULL); - } - } - if (status != noErr && error != NULL) { - *error = [NSError errorWithDomain:kGTMOAuth2KeychainErrorDomain - code:status - userInfo:nil]; - } - return status == noErr; -} - -#endif // ! TARGET_IPHONE_SIMULATOR - -@end - -#endif // TARGET_OS_IPHONE - -#endif // #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES diff --git a/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewTouch.xib b/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewTouch.xib deleted file mode 100644 index 4f91fa4ad..000000000 --- a/Paco-iOS/vendor/gtm-oauth2/Source/Touch/GTMOAuth2ViewTouch.xib +++ /dev/null @@ -1,494 +0,0 @@ - - - - 1024 - 12C60 - 2840 - 1187.34 - 625.00 - - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - 1926 - - - YES - IBProxyObject - IBUIActivityIndicatorView - IBUIBarButtonItem - IBUIButton - IBUINavigationItem - IBUIView - IBUIWebView - - - YES - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - - - PluginDependencyRecalculationVersion - - - - YES - - IBFilesOwner - IBCocoaTouchFramework - - - IBFirstResponder - IBCocoaTouchFramework - - - OAuth - IBCocoaTouchFramework - - - IBCocoaTouchFramework - 1 - - - - 292 - - YES - - - 292 - {30, 30} - - - - NO - NO - IBCocoaTouchFramework - 0 - 0 - {0, -2} - - - 3 - MQA - - - 2 - MC41OTYwNzg0NiAwLjY4NjI3NDUzIDAuOTUyOTQxMjQgMC42MDAwMDAwMgA - - - - 3 - MC41AA - - - Helvetica-Bold - Helvetica - 2 - 24 - - - Helvetica-Bold - 24 - 16 - - - - - 292 - {{30, 0}, {30, 30}} - - - - NO - NO - IBCocoaTouchFramework - 0 - 0 - {0, -2} - - - - 2 - MC41ODQzMTM3NSAwLjY3NDUwOTgyIDAuOTUyOTQxMjQgMC42MDAwMDAwMgA - - - - - - - - {60, 30} - - - - - 3 - MSAwAA - - NO - NO - - 3 - 3 - - IBCocoaTouchFramework - - - - 274 - - YES - - - 274 - {320, 460} - - - - - 1 - MSAxIDEAA - - YES - YES - IBCocoaTouchFramework - 1 - YES - - - - 301 - {{150, 115}, {20, 20}} - - - - _NS:9 - NO - IBCocoaTouchFramework - NO - YES - 2 - - - {320, 460} - - - - - 3 - MQA - - 2 - - - IBCocoaTouchFramework - - - - - YES - - - rightBarButtonItem - - - - 20 - - - - navButtonsView - - - - 22 - - - - backButton - - - - 25 - - - - forwardButton - - - - 26 - - - - view - - - - 28 - - - - webView - - - - 29 - - - - initialActivityIndicator - - - - 33 - - - - delegate - - - - 9 - - - - rightBarButtonItem - - - - 14 - - - - goBack - - - 7 - - 18 - - - - goForward - - - 7 - - 19 - - - - - YES - - 0 - - YES - - - - - - -1 - - - File's Owner - - - -2 - - - - - 6 - - - YES - - - - - 10 - - - - - 15 - - - YES - - - - - - - 16 - - - - - 17 - - - - - 27 - - - YES - - - - - - - 4 - - - - - 31 - - - - - - - YES - - YES - -1.CustomClassName - -1.IBPluginDependency - -2.CustomClassName - -2.IBPluginDependency - 10.IBPluginDependency - 15.IBPluginDependency - 16.IBPluginDependency - 17.IBPluginDependency - 27.IBPluginDependency - 31.IBPluginDependency - 4.IBPluginDependency - 6.IBPluginDependency - - - YES - GTMOAuth2ViewControllerTouch - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - UIResponder - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - com.apple.InterfaceBuilder.IBCocoaTouchPlugin - - - - YES - - - - - - YES - - - - - 33 - - - - YES - - GTMOAuth2ViewControllerTouch - UIViewController - - YES - - YES - backButton - forwardButton - initialActivityIndicator - navButtonsView - rightBarButtonItem - webView - - - YES - UIButton - UIButton - UIActivityIndicatorView - UIView - UIBarButtonItem - UIWebView - - - - YES - - YES - backButton - forwardButton - initialActivityIndicator - navButtonsView - rightBarButtonItem - webView - - - YES - - backButton - UIButton - - - forwardButton - UIButton - - - initialActivityIndicator - UIActivityIndicatorView - - - navButtonsView - UIView - - - rightBarButtonItem - UIBarButtonItem - - - webView - UIWebView - - - - - IBProjectSource - ./Classes/GTMOAuth2ViewControllerTouch.h - - - - - 0 - IBCocoaTouchFramework - - com.apple.InterfaceBuilder.CocoaTouchPlugin.iPhoneOS - - - - com.apple.InterfaceBuilder.CocoaTouchPlugin.iPhoneOS - - - - com.apple.InterfaceBuilder.CocoaTouchPlugin.InterfaceBuilder3 - - - YES - 3 - 1926 - - diff --git a/Paco-iOS/vendor/jcnotificationbannerpresenter/Library/JCNotificationBannerPresenter.h b/Paco-iOS/vendor/jcnotificationbannerpresenter/Library/JCNotificationBannerPresenter.h index 46dc1c77f..037c6b9a9 100644 --- a/Paco-iOS/vendor/jcnotificationbannerpresenter/Library/JCNotificationBannerPresenter.h +++ b/Paco-iOS/vendor/jcnotificationbannerpresenter/Library/JCNotificationBannerPresenter.h @@ -5,7 +5,7 @@ typedef void (^JCNotificationBannerPresenterFinishedBlock)(); @class JCNotificationBannerWindow; -@interface JCNotificationBannerPresenter : NSObject +@interface JCNotificationBannerPresenter : NSObject - (void)willBeginPresentingNotifications; - (void)didFinishPresentingNotifications; diff --git a/Paco-iOS/vendor/sskeychain/SSKeychain.h b/Paco-iOS/vendor/sskeychain/SSKeychain.h deleted file mode 100755 index ae9360cf0..000000000 --- a/Paco-iOS/vendor/sskeychain/SSKeychain.h +++ /dev/null @@ -1,178 +0,0 @@ -/* - Copyright (c) 2010-2013 Sam Soffes. - - 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 "SSKeychainQuery.h" - -/** - Error code specific to SSKeychain that can be returned in NSError objects. - For codes returned by the operating system, refer to SecBase.h for your - platform. - */ -typedef enum { - - /** Some of the arguments were invalid. */ - SSKeychainErrorBadArguments = -1001, - -} SSKeychainErrorCode; - -/** SSKeychain error domain */ -extern NSString *const kSSKeychainErrorDomain; - -/** Account name. */ -extern NSString *const kSSKeychainAccountKey; - -/** - Time the item was created. - - The value will be a string. - */ -extern NSString *const kSSKeychainCreatedAtKey; - -/** Item class. */ -extern NSString *const kSSKeychainClassKey; - -/** Item description. */ -extern NSString *const kSSKeychainDescriptionKey; - -/** Item label. */ -extern NSString *const kSSKeychainLabelKey; - -/** Time the item was last modified. - - The value will be a string. - */ -extern NSString *const kSSKeychainLastModifiedKey; - -/** Where the item was created. */ -extern NSString *const kSSKeychainWhereKey; - -/** - Simple wrapper for accessing accounts, getting passwords, setting passwords, and deleting passwords using the system - Keychain on Mac OS X and iOS. - - This was originally inspired by EMKeychain and SDKeychain (both of which are now gone). Thanks to the authors. - SSKeychain has since switched to a simpler implementation that was abstracted from [SSToolkit](http://sstoolk.it). - */ -@interface SSKeychain : NSObject - -#pragma mark - Classic methods - -/** - Returns a string containing the password for a given account and service, or `nil` if the Keychain doesn't have a - password for the given parameters. - - @param serviceName The service for which to return the corresponding password. - - @param account The account for which to return the corresponding password. - - @return Returns a string containing the password for a given account and service, or `nil` if the Keychain doesn't - have a password for the given parameters. - */ -+ (NSString *)passwordForService:(NSString *)serviceName account:(NSString *)account; -+ (NSString *)passwordForService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error; - - -/** - Deletes a password from the Keychain. - - @param serviceName The service for which to delete the corresponding password. - - @param account The account for which to delete the corresponding password. - - @return Returns `YES` on success, or `NO` on failure. - */ -+ (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account; -+ (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error; - - -/** - Sets a password in the Keychain. - - @param password The password to store in the Keychain. - - @param serviceName The service for which to set the corresponding password. - - @param account The account for which to set the corresponding password. - - @return Returns `YES` on success, or `NO` on failure. - */ -+ (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account; -+ (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account error:(NSError **)error; - - -/** - Returns an array containing the Keychain's accounts, or `nil` if the Keychain has no accounts. - - See the `NSString` constants declared in SSKeychain.h for a list of keys that can be used when accessing the - dictionaries returned by this method. - - @return An array of dictionaries containing the Keychain's accounts, or `nil` if the Keychain doesn't have any - accounts. The order of the objects in the array isn't defined. - */ -+ (NSArray *)allAccounts; - - -/** - Returns an array containing the Keychain's accounts for a given service, or `nil` if the Keychain doesn't have any - accounts for the given service. - - See the `NSString` constants declared in SSKeychain.h for a list of keys that can be used when accessing the - dictionaries returned by this method. - - @param serviceName The service for which to return the corresponding accounts. - - @return An array of dictionaries containing the Keychain's accountsfor a given `serviceName`, or `nil` if the Keychain - doesn't have any accounts for the given `serviceName`. The order of the objects in the array isn't defined. - */ -+ (NSArray *)accountsForService:(NSString *)serviceName; - - -#pragma mark - Configuration - -#if __IPHONE_4_0 && TARGET_OS_IPHONE -/** - Returns the accessibility type for all future passwords saved to the Keychain. - - @return Returns the accessibility type. - - The return value will be `NULL` or one of the "Keychain Item Accessibility - Constants" used for determining when a keychain item should be readable. - - @see setAccessibilityType - */ -+ (CFTypeRef)accessibilityType; - -/** - Sets the accessibility type for all future passwords saved to the Keychain. - - @param accessibilityType One of the "Keychain Item Accessibility Constants" - used for determining when a keychain item should be readable. - - If the value is `NULL` (the default), the Keychain default will be used. - - @see accessibilityType - */ -+ (void)setAccessibilityType:(CFTypeRef)accessibilityType; -#endif - -@end diff --git a/Paco-iOS/vendor/sskeychain/SSKeychain.m b/Paco-iOS/vendor/sskeychain/SSKeychain.m deleted file mode 100755 index 33d5f70ec..000000000 --- a/Paco-iOS/vendor/sskeychain/SSKeychain.m +++ /dev/null @@ -1,109 +0,0 @@ -/* - Copyright (c) 2010-2013 Sam Soffes. - - 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 "SSKeychain.h" - -NSString *const kSSKeychainErrorDomain = @"com.samsoffes.sskeychain"; -NSString *const kSSKeychainAccountKey = @"acct"; -NSString *const kSSKeychainCreatedAtKey = @"cdat"; -NSString *const kSSKeychainClassKey = @"labl"; -NSString *const kSSKeychainDescriptionKey = @"desc"; -NSString *const kSSKeychainLabelKey = @"labl"; -NSString *const kSSKeychainLastModifiedKey = @"mdat"; -NSString *const kSSKeychainWhereKey = @"svce"; - -#if __IPHONE_4_0 && TARGET_OS_IPHONE - static CFTypeRef SSKeychainAccessibilityType = NULL; -#endif - -@implementation SSKeychain - -+ (NSString *)passwordForService:(NSString *)serviceName account:(NSString *)account { - return [self passwordForService:serviceName account:account error:nil]; -} - - -+ (NSString *)passwordForService:(NSString *)serviceName account:(NSString *)account error:(NSError *__autoreleasing *)error { - SSKeychainQuery *query = [[SSKeychainQuery alloc] init]; - query.service = serviceName; - query.account = account; - [query fetch:error]; - return query.password; -} - - -+ (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account { - return [self deletePasswordForService:serviceName account:account error:nil]; -} - - -+ (BOOL)deletePasswordForService:(NSString *)serviceName account:(NSString *)account error:(NSError *__autoreleasing *)error { - SSKeychainQuery *query = [[SSKeychainQuery alloc] init]; - query.service = serviceName; - query.account = account; - return [query deleteItem:error]; -} - - -+ (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account { - return [self setPassword:password forService:serviceName account:account error:nil]; -} - - -+ (BOOL)setPassword:(NSString *)password forService:(NSString *)serviceName account:(NSString *)account error:(NSError *__autoreleasing *)error { - SSKeychainQuery *query = [[SSKeychainQuery alloc] init]; - query.service = serviceName; - query.account = account; - query.password = password; - return [query save:error]; -} - - -+ (NSArray *)allAccounts { - return [self accountsForService:nil]; -} - - -+ (NSArray *)accountsForService:(NSString *)serviceName { - SSKeychainQuery *query = [[SSKeychainQuery alloc] init]; - query.service = serviceName; - return [query fetchAll:nil]; -} - - -#if __IPHONE_4_0 && TARGET_OS_IPHONE -+ (CFTypeRef)accessibilityType { - return SSKeychainAccessibilityType; -} - - -+ (void)setAccessibilityType:(CFTypeRef)accessibilityType { - CFRetain(accessibilityType); - if (SSKeychainAccessibilityType) { - CFRelease(SSKeychainAccessibilityType); - } - SSKeychainAccessibilityType = accessibilityType; -} -#endif - -@end diff --git a/Paco-iOS/vendor/sskeychain/SSKeychainQuery.h b/Paco-iOS/vendor/sskeychain/SSKeychainQuery.h deleted file mode 100755 index b5f50d0bb..000000000 --- a/Paco-iOS/vendor/sskeychain/SSKeychainQuery.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright (c) 2010-2013 Sam Soffes. - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - **/ - -#import -#import - -#ifdef __IPHONE_7_0 - #define SSKEYCHAIN_SYNCHRONIZABLE_AVAILABLE 1 -#endif - -#ifdef __MAC_10_9 - #define SSKEYCHAIN_SYNCHRONIZABLE_AVAILABLE 1 -#endif - -/** - Simple interface for querying or modifying keychain items. - */ -@interface SSKeychainQuery : NSObject - -/** kSecAttrAccount */ -@property (nonatomic, copy) NSString *account; - -/** kSecAttrService */ -@property (nonatomic, copy) NSString *service; - -/** kSecAttrLabel */ -@property (nonatomic, copy) NSString *label; - -#if __IPHONE_3_0 && TARGET_OS_IPHONE -/** kSecAttrAccessGroup (only used on iOS) */ -@property (nonatomic, copy) NSString *accessGroup; -#endif - -#ifdef SSKEYCHAIN_SYNCHRONIZABLE_AVAILABLE -/** kSecAttrSynchronizable */ -@property (nonatomic, getter = isSynchronizable) BOOL synchronizable; -#endif - -/** Root storage for password information */ -@property (nonatomic, copy) NSData *passwordData; - -/** - This property automatically transitions between an object and the value of - `passwordData` using NSKeyedArchiver and NSKeyedUnarchiver. - */ -@property (nonatomic, copy) id passwordObject; - -/** - Convenience accessor for setting and getting a password string. Passes through - to `passwordData` using UTF-8 string encoding. - */ -@property (nonatomic, copy) NSString *password; - -/** - Save the receiver's attributes as a keychain item. Existing items with the - given account, service, and access group will first be deleted. - - @param error Populated should an error occur. - - @return `YES` if saving was successful, `NO` otherwise. - */ -- (BOOL)save:(NSError **)error; - -/** - Dete keychain items that match the given account, service, and access group. - - @param error Populated should an error occur. - - @return `YES` if saving was successful, `NO` otherwise. - */ -- (BOOL)deleteItem:(NSError **)error; - -/** - Fetch all keychain items that match the given account, service, and access - group. The values of `password` and `passwordData` are ignored when fetching. - - @param error Populated should an error occur. - - @return An array of dictionaries that represent all matching keychain items or - `nil` should an error occur. - The order of the items is not determined. - */ -- (NSArray *)fetchAll:(NSError **)error; - -/** - Fetch the keychain item that matches the given account, service, and access - group. The `password` and `passwordData` properties will be populated unless - an error occurs. The values of `password` and `passwordData` are ignored when - fetching. - - @param error Populated should an error occur. - - @return `YES` if fetching was successful, `NO` otherwise. - */ -- (BOOL)fetch:(NSError **)error; - -@end diff --git a/Paco-iOS/vendor/sskeychain/SSKeychainQuery.m b/Paco-iOS/vendor/sskeychain/SSKeychainQuery.m deleted file mode 100755 index f950641d6..000000000 --- a/Paco-iOS/vendor/sskeychain/SSKeychainQuery.m +++ /dev/null @@ -1,267 +0,0 @@ -/* - Copyright (c) 2010-2013 Sam Soffes. - - 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 "SSKeychainQuery.h" -#import "SSKeychain.h" - -@implementation SSKeychainQuery - -@synthesize account = _account; -@synthesize service = _service; -@synthesize label = _label; -@synthesize passwordData = _passwordData; - -#if __IPHONE_3_0 && TARGET_OS_IPHONE -@synthesize accessGroup = _accessGroup; -#endif - -#ifdef SSKEYCHAIN_SYNCHRONIZABLE_AVAILABLE -@synthesize synchronizable = _synchronizable; -#endif - -#pragma mark - Public - -- (BOOL)save:(NSError *__autoreleasing *)error { - OSStatus status = SSKeychainErrorBadArguments; - if (!self.service || !self.account || !self.passwordData) { - if (error) { - *error = [[self class] errorWithCode:status]; - } - return NO; - } - - [self deleteItem:nil]; - - NSMutableDictionary *query = [self query]; - [query setObject:self.passwordData forKey:(__bridge id)kSecValueData]; - if (self.label) { - [query setObject:self.label forKey:(__bridge id)kSecAttrLabel]; - } -#if __IPHONE_4_0 && TARGET_OS_IPHONE - CFTypeRef accessibilityType = [SSKeychain accessibilityType]; - if (accessibilityType) { - [query setObject:(__bridge id)accessibilityType forKey:(__bridge id)kSecAttrAccessible]; - } -#endif - status = SecItemAdd((__bridge CFDictionaryRef)query, NULL); - - if (status != errSecSuccess && error != NULL) { - *error = [[self class] errorWithCode:status]; - } - - return (status == errSecSuccess); -} - - -- (BOOL)deleteItem:(NSError *__autoreleasing *)error { - OSStatus status = SSKeychainErrorBadArguments; - if (!self.service || !self.account) { - if (error) { - *error = [[self class] errorWithCode:status]; - } - return NO; - } - - NSMutableDictionary *query = [self query]; -#if TARGET_OS_IPHONE - status = SecItemDelete((__bridge CFDictionaryRef)query); -#else - CFTypeRef result = NULL; - [query setObject:@YES forKey:(__bridge id)kSecReturnRef]; - status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); - if (status == errSecSuccess) { - status = SecKeychainItemDelete((SecKeychainItemRef)result); - CFRelease(result); - } -#endif - - if (status != errSecSuccess && error != NULL) { - *error = [[self class] errorWithCode:status]; - } - - return (status == errSecSuccess); -} - - -- (NSArray *)fetchAll:(NSError *__autoreleasing *)error { - OSStatus status = SSKeychainErrorBadArguments; - NSMutableDictionary *query = [self query]; - [query setObject:@YES forKey:(__bridge id)kSecReturnAttributes]; - [query setObject:(__bridge id)kSecMatchLimitAll forKey:(__bridge id)kSecMatchLimit]; - - CFTypeRef result = NULL; - status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); - if (status != errSecSuccess && error != NULL) { - *error = [[self class] errorWithCode:status]; - return nil; - } - - return (__bridge NSArray *)result; -} - - -- (BOOL)fetch:(NSError *__autoreleasing *)error { - OSStatus status = SSKeychainErrorBadArguments; - if (!self.service || !self.account) { - if (error) { - *error = [[self class] errorWithCode:status]; - } - return NO; - } - - CFTypeRef result = NULL; - NSMutableDictionary *query = [self query]; - [query setObject:@YES forKey:(__bridge_transfer id)kSecReturnData]; - [query setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit]; - status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result); - - if (status != errSecSuccess && error != NULL) { - *error = [[self class] errorWithCode:status]; - return NO; - } - - self.passwordData = (__bridge_transfer NSData *)result; - return YES; -} - - -#pragma mark - Accessors - -- (void)setPasswordObject:(id)object { - self.passwordData = [NSKeyedArchiver archivedDataWithRootObject:object]; -} - - -- (id)passwordObject { - if ([self.passwordData length]) { - return [NSKeyedUnarchiver unarchiveObjectWithData:self.passwordData]; - } - return nil; -} - - -- (void)setPassword:(NSString *)password { - self.passwordData = [password dataUsingEncoding:NSUTF8StringEncoding]; -} - - -- (NSString *)password { - if ([self.passwordData length]) { - return [[NSString alloc] initWithData:self.passwordData encoding:NSUTF8StringEncoding]; - } - return nil; -} - - -#pragma mark - Private - -- (NSMutableDictionary *)query { - NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:3]; - [dictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; - - if (self.service) { - [dictionary setObject:self.service forKey:(__bridge id)kSecAttrService]; - } - - if (self.account) { - [dictionary setObject:self.account forKey:(__bridge id)kSecAttrAccount]; - } - -#if __IPHONE_3_0 && TARGET_OS_IPHONE -#if !(TARGET_IPHONE_SIMULATOR) - if (self.accessGroup) { - [dictionary setObject:self.accessGroup forKey:(__bridge id)kSecAttrAccessGroup]; - } -#endif -#endif - -#ifdef SSKEYCHAIN_SYNCHRONIZABLE_AVAILABLE - if (self.isSynchronizable) { - [dictionary setObject:@YES forKey:(__bridge id)(kSecAttrSynchronizable)]; - } -#endif - - return dictionary; -} - - -+ (NSError *)errorWithCode:(OSStatus) code { - NSString *message = nil; - switch (code) { - case errSecSuccess: return nil; - case SSKeychainErrorBadArguments: message = NSLocalizedStringFromTable(@"SSKeychainErrorBadArguments", @"SSKeychain", nil); break; - -#if TARGET_OS_IPHONE - case errSecUnimplemented: { - message = NSLocalizedStringFromTable(@"errSecUnimplemented", @"SSKeychain", nil); - break; - } - case errSecParam: { - message = NSLocalizedStringFromTable(@"errSecParam", @"SSKeychain", nil); - break; - } - case errSecAllocate: { - message = NSLocalizedStringFromTable(@"errSecAllocate", @"SSKeychain", nil); - break; - } - case errSecNotAvailable: { - message = NSLocalizedStringFromTable(@"errSecNotAvailable", @"SSKeychain", nil); - break; - } - case errSecDuplicateItem: { - message = NSLocalizedStringFromTable(@"errSecDuplicateItem", @"SSKeychain", nil); - break; - } - case errSecItemNotFound: { - message = NSLocalizedStringFromTable(@"errSecItemNotFound", @"SSKeychain", nil); - break; - } - case errSecInteractionNotAllowed: { - message = NSLocalizedStringFromTable(@"errSecInteractionNotAllowed", @"SSKeychain", nil); - break; - } - case errSecDecode: { - message = NSLocalizedStringFromTable(@"errSecDecode", @"SSKeychain", nil); - break; - } - case errSecAuthFailed: { - message = NSLocalizedStringFromTable(@"errSecAuthFailed", @"SSKeychain", nil); - break; - } - default: { - message = NSLocalizedStringFromTable(@"errSecDefault", @"SSKeychain", nil); - } -#else - default: - message = (__bridge_transfer NSString *)SecCopyErrorMessageString(code, NULL); -#endif - } - - NSDictionary *userInfo = nil; - if (message != nil) { - userInfo = @{ NSLocalizedDescriptionKey : message }; - } - return [NSError errorWithDomain:kSSKeychainErrorDomain code:code userInfo:userInfo]; -} - -@end diff --git a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleAppEngineAuth.h b/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleAppEngineAuth.h deleted file mode 100644 index 699ad5830..000000000 --- a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleAppEngineAuth.h +++ /dev/null @@ -1,44 +0,0 @@ -// -// GoogleAppEngineAuth.h -// whaleops -// -// Created by cameron ring on 2/26/10. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import -#import "GoogleClientLogin.h" - - -// GoogleAppEngineAuth is a GoogleClientLoginDelegate because we need to do some more work after getting the auth -// cookie to get the app engine auth cookie -@interface GoogleAppEngineAuth : NSObject { - - id m_delegate; - GoogleClientLogin *m_googleClientLogin; - NSURL *m_appURL; - BOOL m_useDevServer; -} - - -// Delegate is a weak pointer. If the delegate can go away before this class, you need to clear -// the delegate in the delegate's dealloc method -@property (nonatomic, assign) id delegate; - --(id)initWithDelegate:(id)delegate andAppURL:(NSURL *)appURL; - - -// Try to auth with the passed-in credentials for Google App Engine: -// username User's full email address. It must include the domain (i.e. johndoe@gmail.com). -// password User's password -// source Short string identifying your application, for logging purposes. This string should take the form: -// "companyName-applicationName-versionID". -// captcha (optional) String entered by the user as an answer to a CAPTCHA challenge. -// captchaToken (optional) Token representing the specific CAPTCHA challenge. Google supplies this token and the CAPTCHA image URL -// in a login failed response with the error code "CaptchaRequired". - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password withSource:(NSString *)source; --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password andCaptcha:(NSString *)captcha - andCaptchaToken:(NSString *)captchaToken withSource:(NSString *)source; - -@end diff --git a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleAppEngineAuth.m b/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleAppEngineAuth.m deleted file mode 100644 index 915b812a7..000000000 --- a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleAppEngineAuth.m +++ /dev/null @@ -1,175 +0,0 @@ -// -// GoogleAppEngineAuth.m -// whaleops -// -// Created by cameron ring on 2/26/10. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import "GoogleAppEngineAuth.h" -#import "GTMNSString+URLArguments.h" -#import - -@interface GoogleAppEngineAuth (private) - --(void)authForDevServerWith:(NSString *)username; --(NSString *)userIdForUsername:(NSString *)username; - -@end - - -@implementation GoogleAppEngineAuth -@synthesize delegate = m_delegate; - --(id)initWithDelegate:(id)delegate andAppURL:(NSURL *)appURL { - - if (!(self = [super init])) - return self; - - m_googleClientLogin = [[GoogleClientLogin alloc] initWithDelegate:self]; - m_delegate = delegate; - - m_appURL = [appURL retain]; - - m_useDevServer = [[appURL host] isEqualToString:@"localhost"]; - - return self; -} - --(void)dealloc { - [m_appURL release]; - [m_googleClientLogin setDelegate:nil]; - [m_googleClientLogin release]; - [super dealloc]; -} - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password withSource:(NSString *)source { - - [self authWithUsername:username andPassword:password andCaptcha:nil andCaptchaToken:nil withSource:source]; -} - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password andCaptcha:(NSString *)captcha - andCaptchaToken:(NSString *)captchaToken withSource:(NSString *)source { - - if (m_useDevServer) { - [self authForDevServerWith:username]; - return; - } - - // ah is the service for app engine, apparently - [m_googleClientLogin authWithUsername:username andPassword:password andCaptcha:captcha andCaptchaToken:captchaToken - forService:@"ah" withSource:source]; - -} - - -////////////////////////////////////////////////////////////////////////////////////////////////// -// MARK: GoogleClientLoginDelegate methods - --(void)authSucceeded:(NSString *)authKey { - - // request correct cookie - NSURL *cookieURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@/_ah/login?continue=%@/&auth=%@", - m_appURL, - m_appURL, - [authKey gtm_stringByEscapingForURLArgument] - ] - ]; - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:cookieURL]; - [request setHTTPMethod:@"GET"]; - - [NSURLConnection connectionWithRequest:request delegate:self]; -} - --(void)authFailed:(NSString *)error { - [m_delegate authFailed:error]; -} - --(void)authCaptchaTestNeededFor:(NSString *)captchaToken withCaptchaURL:(NSURL *)captchaURL { - [m_delegate authCaptchaTestNeededFor:captchaToken withCaptchaURL:captchaURL]; -} - -////////////////////////////////////////////////////////////////////////////////////////////////// -// MARK: NSURLConnection delegate methods - --(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { - - if (![response isKindOfClass:[NSHTTPURLResponse class]]) { - [m_delegate authFailed:@"UnknownClientError"]; - [connection cancel]; - return; - } - - // no need to read body - [connection cancel]; - - NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[response URL]]; - - // iterate over cookies looking for ACSID - for (NSHTTPCookie *cookie in cookies) { - if (!([[cookie name] isEqualToString:@"ACSID"] || [[cookie name] isEqualToString:@"SACSID"])) - continue; - - [m_delegate authSucceeded:[cookie value]]; - return; - } - - [m_delegate authFailed:@"UnknownAppEngineClientError"]; -} - --(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { - -} - --(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - NSString *msg = [NSString stringWithFormat:@"Connection Error (%@)", [error localizedDescription]]; - [m_delegate authFailed:msg]; -} - --(void)connectionDidFinishLoading:(NSURLConnection *)connection { - -} - -////////////////////////////////////////////////////////////////////////////////////////////////// -// MARK: Private methods - -// only used when generating a cookie for authing against the dev server --(NSString *)userIdForUsername:(NSString *)username { - const char *cStr = [username UTF8String]; - unsigned char result[CC_MD5_DIGEST_LENGTH]; - - CC_MD5(cStr, strlen(cStr), result); - return [NSString - stringWithFormat: @"1%02d%02d%02d%02d%02d%02d%02d%02d", - result[0], result[1], - result[2], result[3], - result[4], result[5], - result[6], result[7], - result[8], result[9], - result[10], result[11], - result[12], result[13], - result[14], result[15] - ]; - -} - -// if we're authing against the dev server, just set the right cookie --(void)authForDevServerWith:(NSString *)username { - - NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; - - NSString *value = [NSString stringWithFormat:@"%@:False:%@", username, [self userIdForUsername:username]]; - - NSDictionary *properties = [NSDictionary dictionaryWithObjectsAndKeys: - @"dev_appserver_login", NSHTTPCookieName, - value, NSHTTPCookieValue, - @"/", NSHTTPCookiePath, - @"localhost", NSHTTPCookieDomain, - nil]; - - [m_delegate authSucceeded:value]; - - [cookieJar setCookie:[NSHTTPCookie cookieWithProperties:properties]]; -} - -@end diff --git a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleClientLogin.h b/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleClientLogin.h deleted file mode 100644 index e352a8d98..000000000 --- a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleClientLogin.h +++ /dev/null @@ -1,57 +0,0 @@ -// -// GoogleClientLogin.h -// -// Created by cameron ring on 2/26/10. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// -// This class implements the client side of Google'a ClientLogin API. For more information: -// http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html -// - -#import - -@protocol GoogleClientLoginDelegate - --(void)authSucceeded:(NSString *)authKey; --(void)authFailed:(NSString *)error; --(void)authCaptchaTestNeededFor:(NSString *)captchaToken withCaptchaURL:(NSURL *)captchaURL; - -@end - - -@interface GoogleClientLogin : NSObject { - - id m_delegate; - NSMutableData *m_receivedData; - NSUInteger m_statusCode; -} - -// Delegate is a weak pointer. If the delegate can go away before this class, you need to clear -// the delegate in the delegate's dealloc method -@property (nonatomic, assign) id delegate; - -+ (NSString *)descriptionForError:(NSString *)error; - --(id)initWithDelegate:(id)delegate; - - -// Try to auth with the passed-in credentials for a particular service: -// username User's full email address. It must include the domain (i.e. johndoe@gmail.com). -// password User's password -// service Name of the Google service you're requesting authorization for. Each service using the Authorization service -// is assigned a name value; for example, the name associated with Google Calendar is 'cl'. This parameter is -// required when accessing services based on Google Data APIs. For specific service names, refer to the service -// documentation. -// source Short string identifying your application, for logging purposes. This string should take the form: -// "companyName-applicationName-versionID". -// captcha (optional) String entered by the user as an answer to a CAPTCHA challenge. -// captchaToken (optional) Token representing the specific CAPTCHA challenge. Google supplies this token and the CAPTCHA image URL -// in a login failed response with the error code "CaptchaRequired". - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password forService:(NSString *)service - withSource:(NSString *)source; - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password andCaptcha:(NSString *)captcha - andCaptchaToken:(NSString *)captchaToken forService:(NSString *)service withSource:(NSString *)source; - -@end diff --git a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleClientLogin.m b/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleClientLogin.m deleted file mode 100644 index 761a16adc..000000000 --- a/Paco-iOS/vendor/touchengine/iPhone/GoogleAppEngineAuthGithub/GoogleClientLogin.m +++ /dev/null @@ -1,197 +0,0 @@ -// -// GoogleClientLogin.m -// whaleops -// -// Created by cameron ring on 2/26/10. -// Copyright 2010 __MyCompanyName__. All rights reserved. -// - -#import "GoogleClientLogin.h" -#import "GTMNSString+URLArguments.h" - - -#define CAPTCHA_PREFIX @"http://www.google.com/accounts/" -#define UNKNOWN_CLIENT_ERROR @"UnknownClientError" -#define CONNECTION_ERROR @"ConnetionError" - -@interface GoogleClientLogin (private) - --(void)handleAuthResponse:(NSString *)response; --(NSDictionary *)parseResponseBody:(NSString *)body; - -@end - - -@implementation GoogleClientLogin -@synthesize delegate = m_delegate; - --(id)initWithDelegate:(id)delegate { - if (!(self = [super init])) - return self; - - // weak pointer to delegate - m_delegate = delegate; - - return self; -} - --(void)dealloc { - [m_receivedData release]; - [super dealloc]; -} - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password forService:(NSString *)service - withSource:(NSString *)source { - [self authWithUsername:username andPassword:password andCaptcha:nil andCaptchaToken:nil forService:service - withSource:source]; -} - --(void)authWithUsername:(NSString *)username andPassword:(NSString *)password andCaptcha:(NSString *)captcha - andCaptchaToken:(NSString *)captchaToken forService:(NSString *)service withSource:(NSString *)source { - - NSString *content = [NSString stringWithFormat:@"accountType=HOSTED_OR_GOOGLE&Email=%@&Passwd=%@&service=%@&source=%@", - [username gtm_stringByEscapingForURLArgument], - [password gtm_stringByEscapingForURLArgument], - [service gtm_stringByEscapingForURLArgument], - [source gtm_stringByEscapingForURLArgument]]; - - if (captcha && captchaToken) { - content = [NSString stringWithFormat:@"%@&logintoken=%@&logincaptcha=%@", - content, - [captchaToken gtm_stringByEscapingForURLArgument], - [captcha gtm_stringByEscapingForURLArgument]]; - } - - NSURL *authURL = [NSURL URLWithString:@"https://www.google.com/accounts/ClientLogin"]; - - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:authURL]; - [request setHTTPMethod:@"POST"]; - [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"]; - [request setHTTPBody:[content dataUsingEncoding:NSASCIIStringEncoding]]; - - [NSURLConnection connectionWithRequest:request delegate:self]; -} - -+ (NSString *)descriptionForError:(NSString *)error { - - if ([error isEqualToString:CONNECTION_ERROR]) { - return @"There was an error communication with the server"; - } else if ([error isEqualToString:@"BadAuthentication"]) { - return @"Invalid username or password"; - } else if ([error isEqualToString:@"NotVerified"]) { - return @"That email address has not been validated. You must verify that address with your Google account before continuing"; - } else if ([error isEqualToString:@"TermsNotAgreed"]) { - return @"You have not agreed to the terms yet. You must sign in to your Google account on the web before continuing"; - } else if ([error isEqualToString:@"CaptchaRequired"]) { - return @"A CAPTCHA is required."; - } else if ([error isEqualToString:@"Unknown"]) { - return @"There was an unknown error"; - } else if ([error isEqualToString:@"AccountDeleted"]) { - return @"That account has been deleted"; - } else if ([error isEqualToString:@"AccountDisabled"]) { - return @"That account has been disabled"; - } else if ([error isEqualToString:@"ServiceDisabled"]) { - return @"Your access to that service has been disabled"; - } else if ([error isEqualToString:@"ServiceUnavailable"]) { - return @"That service is currently unavailable. Please try again later"; - } - - return @"There was an unknown error (client)"; -} - -////////////////////////////////////////////////////////////////////////////////////////////////// -// MARK: NSURLConnection delegate methods - --(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { - - if (![response isKindOfClass:[NSHTTPURLResponse class]]) - return; - - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; - - m_statusCode = [httpResponse statusCode]; - - [m_receivedData release]; - m_receivedData = [[NSMutableData alloc] init]; -} - --(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { - [m_receivedData appendData:data]; -} - --(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - [m_delegate authFailed:CONNECTION_ERROR]; -} - --(void)connectionDidFinishLoading:(NSURLConnection *)connection { - - // process the body - NSString *body = [[NSString alloc] initWithData:m_receivedData encoding:NSUTF8StringEncoding]; - - [self handleAuthResponse:body]; - - [body release]; - [m_receivedData release]; - m_receivedData = nil; -} - - -////////////////////////////////////////////////////////////////////////////////////////////////// -// MARK: Private method - --(void)handleAuthResponse:(NSString *)response { - - NSDictionary *keys = [self parseResponseBody:response]; - - if (m_statusCode == 200) { - NSString *auth = [keys objectForKey:@"Auth"]; - - if ([auth length]) { - [m_delegate authSucceeded:auth]; - return; - } - } - - NSString *error = [keys objectForKey:@"Error"]; - - if ((m_statusCode != 403) || ![error length]) { - [m_delegate authFailed:UNKNOWN_CLIENT_ERROR]; - return; - } - - if (![error isEqualToString:@"CaptchaRequired"]) { - // a regular error - [m_delegate authFailed:error]; - return; - } - - // we need to show a captcha - NSString *captchaToken = [keys objectForKey:@"CaptchaToken"]; - NSString *captchaPath = [keys objectForKey:@"CaptchaUrl"]; - - NSURL *captchaURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", CAPTCHA_PREFIX, captchaPath]]; - - [m_delegate authCaptchaTestNeededFor:captchaToken withCaptchaURL:captchaURL]; -} - --(NSDictionary *)parseResponseBody:(NSString *)body { - - NSMutableDictionary *keys = [NSMutableDictionary dictionary]; - NSArray *lines = [body componentsSeparatedByString:@"\n"]; - for (NSString *line in lines) { - - NSRange separatorRange = [line rangeOfString:@"="]; - - if (separatorRange.location == NSNotFound) - break; - - NSString *key = [line substringToIndex:separatorRange.location]; - NSString *value = [line substringFromIndex:separatorRange.location + separatorRange.length]; - [keys setObject:value forKey:key]; - } - - return keys; -} - - -@end