diff --git a/OC Share Sheet/Info.plist b/OC Share Sheet/Info.plist index baa3ccaa03..b21dc9675e 100644 --- a/OC Share Sheet/Info.plist +++ b/OC Share Sheet/Info.plist @@ -17,11 +17,11 @@ CFBundlePackageType XPC! CFBundleShortVersionString - 3.6.2 + 3.7.0 CFBundleSignature ???? CFBundleVersion - 1.0 + 1.0.5 ITSAppUsesNonExemptEncryption NSAppTransportSecurity diff --git a/OC Share Sheet/ShareViewController.swift b/OC Share Sheet/ShareViewController.swift index 42c342c846..3359fbd68b 100644 --- a/OC Share Sheet/ShareViewController.swift +++ b/OC Share Sheet/ShareViewController.swift @@ -39,7 +39,7 @@ fileprivate func > (lhs: T?, rhs: T?) -> Bool { -@objc class ShareViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, KKPasscodeViewControllerDelegate, CheckAccessToServerDelegate { +@objc class ShareViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, KKPasscodeViewControllerDelegate { @IBOutlet weak var navigationBar: UINavigationBar? @IBOutlet weak var shareTable: UITableView? @@ -255,7 +255,7 @@ fileprivate func > (lhs: T?, rhs: T?) -> Bool { upload.uploadFileName = fileName upload.kindOfError = enumKindOfError.notAnError.rawValue upload.estimateLength = fileLength - upload.userId = (user?.idUser)! + upload.userId = (user?.userId)! upload.status = enumUpload.generatedByDocumentProvider.rawValue upload.chunksLength = Int(k_lenght_chunk) upload.isNotNecessaryCheckIfExist = false @@ -344,7 +344,7 @@ fileprivate func > (lhs: T?, rhs: T?) -> Bool { if error == nil { if let url = item as? URL{ - print("item as url: \(item)") + print("item as url: \(url)") self.filesSelected.append(url) diff --git a/OCCommunicationLib b/OCCommunicationLib index ecd1d3603a..16bc3fbf9b 160000 --- a/OCCommunicationLib +++ b/OCCommunicationLib @@ -1 +1 @@ -Subproject commit ecd1d3603a65aa5042fa1ef956b66dd80fab2491 +Subproject commit 16bc3fbf9b60e3f23e6d445989c8c7fa2fd120b7 diff --git a/Owncloud iOs Client.xcodeproj/project.pbxproj b/Owncloud iOs Client.xcodeproj/project.pbxproj index 19f9416d58..77f19a3abd 100644 --- a/Owncloud iOs Client.xcodeproj/project.pbxproj +++ b/Owncloud iOs Client.xcodeproj/project.pbxproj @@ -53,9 +53,6 @@ 13B721ED169D78BE00B24A51 /* Twitter.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 13B721EC169D78BE00B24A51 /* Twitter.framework */; }; 13D6B7CA18855EE40090A96C /* AppsActivityProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 13D6B7C918855EE40090A96C /* AppsActivityProvider.m */; }; 13D8741F169DBE05000FBE6D /* MessageUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 13D8741E169DBE05000FBE6D /* MessageUI.framework */; }; - 1420C3AA178A9F5000C0455C /* LoginViewController_iPad.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1420C3A6178A9F5000C0455C /* LoginViewController_iPad.xib */; }; - 1420C3AB178A9F5000C0455C /* LoginViewController_iPhone.xib in Resources */ = {isa = PBXBuildFile; fileRef = 1420C3A7178A9F5000C0455C /* LoginViewController_iPhone.xib */; }; - 1420C3AC178A9F5000C0455C /* LoginViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1420C3A9178A9F5000C0455C /* LoginViewController.m */; }; 1428F675178422AE0092F42A /* UploadsOfflineDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 1428F674178422AE0092F42A /* UploadsOfflineDto.m */; }; 1428F678178422BE0092F42A /* UtilsDtos.m in Sources */ = {isa = PBXBuildFile; fileRef = 1428F677178422BE0092F42A /* UtilsDtos.m */; }; 145EA7D117786FAC0087CDDB /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 145EA7CA17786FAC0087CDDB /* Localizable.strings */; }; @@ -189,11 +186,6 @@ 148DD5DB177851E700FB9977 /* UploadRecentCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD5D5177851E700FB9977 /* UploadRecentCell.m */; }; 148DD5DC177851E700FB9977 /* UploadRecentCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD5D6177851E700FB9977 /* UploadRecentCell.xib */; }; 148DD5FD1778556500FB9977 /* MBProgressHUD.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD5FC1778556500FB9977 /* MBProgressHUD.m */; }; - 148DD612177855B600FB9977 /* AuthenticationDbService.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD609177855B600FB9977 /* AuthenticationDbService.m */; }; - 148DD613177855B600FB9977 /* AuthenticationResponseTypeCodeTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD60B177855B600FB9977 /* AuthenticationResponseTypeCodeTask.m */; }; - 148DD614177855B600FB9977 /* RetrieveAccessTokenTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD60D177855B600FB9977 /* RetrieveAccessTokenTask.m */; }; - 148DD615177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD60F177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.m */; }; - 148DD616177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD611177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.m */; }; 148DD619177855D900FB9977 /* Reachability.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD618177855D900FB9977 /* Reachability.m */; settings = {COMPILER_FLAGS = "-fno-objc-arc"; }; }; 148DD62417785D6900FB9977 /* DetailView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD61F17785D6900FB9977 /* DetailView.xib */; }; 148DD62517785D6900FB9977 /* DetailViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD62117785D6900FB9977 /* DetailViewController.m */; }; @@ -222,12 +214,8 @@ 148DD6B3177866A400FB9977 /* FilesViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6B0177866A400FB9977 /* FilesViewController.xib */; }; 148DD6B71778693000FB9977 /* RecentViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD6B51778693000FB9977 /* RecentViewController.m */; }; 148DD6B81778693000FB9977 /* RecentViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6B61778693000FB9977 /* RecentViewController.xib */; }; - 148DD6BC1778695E00FB9977 /* AddAccountViewController_iPhone.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6B91778695E00FB9977 /* AddAccountViewController_iPhone.xib */; }; - 148DD6BD1778695E00FB9977 /* AddAccountViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD6BB1778695E00FB9977 /* AddAccountViewController.m */; }; 148DD6C11778697100FB9977 /* AccountCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD6BF1778697100FB9977 /* AccountCell.m */; }; 148DD6C21778697100FB9977 /* AccountCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6C01778697100FB9977 /* AccountCell.xib */; }; - 148DD6C61778698300FB9977 /* EditAccountViewController_iPhone.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6C31778698300FB9977 /* EditAccountViewController_iPhone.xib */; }; - 148DD6C71778698300FB9977 /* EditAccountViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD6C51778698300FB9977 /* EditAccountViewController.m */; }; 148DD6D8177869C800FB9977 /* Impressum.rtf in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6D4177869C800FB9977 /* Impressum.rtf */; }; 148DD6D9177869C800FB9977 /* ImpressumViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 148DD6D6177869C800FB9977 /* ImpressumViewController.m */; }; 148DD6DA177869C800FB9977 /* ImpressumViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 148DD6D7177869C800FB9977 /* ImpressumViewController.xib */; }; @@ -353,9 +341,13 @@ 405D06C51BFB670100591604 /* ManageCapabilitiesDB.m in Sources */ = {isa = PBXBuildFile; fileRef = EA0EFA1E1BEA6C6E009971AF /* ManageCapabilitiesDB.m */; }; 405D06C71BFB670200591604 /* ManageCapabilitiesDB.m in Sources */ = {isa = PBXBuildFile; fileRef = EA0EFA1E1BEA6C6E009971AF /* ManageCapabilitiesDB.m */; }; 405D06C81BFB670800591604 /* ManageCapabilitiesDB.m in Sources */ = {isa = PBXBuildFile; fileRef = EA0EFA1E1BEA6C6E009971AF /* ManageCapabilitiesDB.m */; }; + 407B51BC1F0A34DB00DDFA65 /* Customization.m in Sources */ = {isa = PBXBuildFile; fileRef = 407B51BB1F0A34DB00DDFA65 /* Customization.m */; }; + 40904B2C1EF04ACE00C72619 /* DetectAuthenticationMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40904B2B1EF04ACE00C72619 /* DetectAuthenticationMethod.swift */; }; 4096E2491EB8650200318240 /* ShareWarningLinkCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4096E2471EB8650200318240 /* ShareWarningLinkCell.swift */; }; 4096E24A1EB8650200318240 /* ShareWarningLinkCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4096E2481EB8650200318240 /* ShareWarningLinkCell.xib */; }; 40A1F17E1D8857740078C901 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 40A1F1801D8857740078C901 /* InfoPlist.strings */; }; + 40A226AB1F179620003C678E /* ManageAccounts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40A226AA1F179620003C678E /* ManageAccounts.swift */; }; + 40A226AE1F179C2B003C678E /* ManageFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40A226AD1F179C2B003C678E /* ManageFiles.swift */; }; 40A3A0EB1CEC9B3A0056016A /* more-filledBlack.png in Resources */ = {isa = PBXBuildFile; fileRef = 40A3A0E91CEC9B3A0056016A /* more-filledBlack.png */; }; 40A3A0EC1CEC9B3A0056016A /* more-filledBlack@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 40A3A0EA1CEC9B3A0056016A /* more-filledBlack@2x.png */; }; 40AB1F5B1A12392E003E7397 /* cancel_download_white@3x.png in Resources */ = {isa = PBXBuildFile; fileRef = 40AB1F591A12392E003E7397 /* cancel_download_white@3x.png */; }; @@ -370,12 +362,24 @@ 40AB650D1EAF4DCE00379361 /* ShareMainLinkCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 40AB650B1EAF4DCE00379361 /* ShareMainLinkCell.xib */; }; 40AB65111EAFA10000379361 /* ShareLinkViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 40AB650F1EAFA10000379361 /* ShareLinkViewController.m */; }; 40AB65121EAFA10000379361 /* ShareLinkViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 40AB65101EAFA10000379361 /* ShareLinkViewController.xib */; }; - 40AC24D219FE725600582867 /* CredentialsDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 40AC24D119FE725600582867 /* CredentialsDto.m */; }; + 40B083991F1607D90072574A /* Log.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40B083981F1607D90072574A /* Log.swift */; }; + 40B5700F1F1E137D00A98A8E /* UtilsLogin.m in Sources */ = {isa = PBXBuildFile; fileRef = 40B5700E1F1E137D00A98A8E /* UtilsLogin.m */; }; + 40B5AB7E1F7AB6420022F3A2 /* SSLCertificateManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 40B5AB7D1F7AB6420022F3A2 /* SSLCertificateManager.m */; }; + 40B5AB801F7ABBE70022F3A2 /* SSLCertificateManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 40B5AB7D1F7AB6420022F3A2 /* SSLCertificateManager.m */; }; + 40B5AB821F7ABBE70022F3A2 /* SSLCertificateManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 40B5AB7D1F7AB6420022F3A2 /* SSLCertificateManager.m */; }; + 40BCC2BA1F3B5FA500F5DC6F /* (null) in Sources */ = {isa = PBXBuildFile; }; + 40BCC2BC1F3B5FA700F5DC6F /* (null) in Sources */ = {isa = PBXBuildFile; }; + 40BCC2BD1F3B5FA700F5DC6F /* (null) in Sources */ = {isa = PBXBuildFile; }; + 40C01ED91F0FA923002DCAAA /* DetectListOfFiles.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40C01ED81F0FA923002DCAAA /* DetectListOfFiles.swift */; }; 40C0BDB91C46562A0057B1DD /* SharePrivilegeCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 40C0BDB81C46562A0057B1DD /* SharePrivilegeCell.xib */; }; 40C0BDBC1C465F390057B1DD /* SharePrivilegeCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40C0BDBB1C465F390057B1DD /* SharePrivilegeCell.swift */; }; + 40C663AA1EFA4FBE004AF994 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 40C663A91EFA4FBE004AF994 /* Main.storyboard */; }; + 40C663B01EFA94B1004AF994 /* UniversalLoginViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40C663AF1EFA94B1004AF994 /* UniversalLoginViewController.swift */; }; 40CC7F0D1B4E665400231D73 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 40CC7F0C1B4E665400231D73 /* Images.xcassets */; }; 40CF2C6C1C491C610047969A /* ShareUserPrivilegeCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 40CF2C6B1C491C610047969A /* ShareUserPrivilegeCell.xib */; }; 40CF2C6F1C491D200047969A /* ShareUserPrivilegeCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40CF2C6E1C491D200047969A /* ShareUserPrivilegeCell.swift */; }; + 40D090841F97BA6A0030B9F9 /* DetectUserData.m in Sources */ = {isa = PBXBuildFile; fileRef = 40D090831F97BA6A0030B9F9 /* DetectUserData.m */; }; + 40D3F18E1EFD53E7004F0E22 /* WebLoginViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 40D3F18D1EFD53E7004F0E22 /* WebLoginViewController.swift */; }; 40DC9C671CDA191B00F5F5EF /* EditFileViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 40DC9C651CDA191B00F5F5EF /* EditFileViewController.m */; }; 40DC9C681CDA191B00F5F5EF /* EditFileViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 40DC9C661CDA191B00F5F5EF /* EditFileViewController.xib */; }; 40DD9AE01D228E0C008E99D6 /* UtilsNotifications.m in Sources */ = {isa = PBXBuildFile; fileRef = 40DD9ADF1D228E0C008E99D6 /* UtilsNotifications.m */; }; @@ -516,7 +520,6 @@ 599D99F81A026004008A9DB3 /* UserDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F148177C315D004A1A5A /* UserDto.m */; }; 599D99F91A0294A0008A9DB3 /* Owncloud iOs Client.entitlements in Resources */ = {isa = PBXBuildFile; fileRef = 593F7CAD19F01134004136F7 /* Owncloud iOs Client.entitlements */; }; 599DDD4F1A19FBD3008725DE /* OCKeychain.m in Sources */ = {isa = PBXBuildFile; fileRef = 40FF874219F81396008B7C62 /* OCKeychain.m */; }; - 599DDD511A19FBF8008725DE /* CredentialsDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 40AC24D119FE725600582867 /* CredentialsDto.m */; }; 599E57351A08E62700744EC9 /* FileDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F146177C315D004A1A5A /* FileDto.m */; }; 599E5C271A0CD0E500E83C03 /* EmptyCell.m in Sources */ = {isa = PBXBuildFile; fileRef = 14B0083E18FD1B5B004CB06B /* EmptyCell.m */; }; 599E5C291A0CD0EF00E83C03 /* EmptyCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 14B0083F18FD1B5B004CB06B /* EmptyCell.xib */; }; @@ -630,6 +633,8 @@ 59F123E51C89C1250094CF70 /* SWLongPressGestureRecognizer.m in Sources */ = {isa = PBXBuildFile; fileRef = EABF690D1891379C00A2217C /* SWLongPressGestureRecognizer.m */; }; 59F123E61C89C14D0094CF70 /* SWUtilityButtonTapGestureRecognizer.m in Sources */ = {isa = PBXBuildFile; fileRef = EABF69111891379C00A2217C /* SWUtilityButtonTapGestureRecognizer.m */; }; 59F470321C5F97BA005B6091 /* Launch Screen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 59F470311C5F97BA005B6091 /* Launch Screen.storyboard */; }; + 7F9B91BD1F1F472700B77260 /* ServerURLNormalizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F9B91BC1F1F472700B77260 /* ServerURLNormalizer.swift */; }; + 7F9B91C81F1F817700B77260 /* GetPublicInfoFromServerJob.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F9B91C71F1F817700B77260 /* GetPublicInfoFromServerJob.swift */; }; 905B3D3B1C8867AA00BCC93B /* SortManager.m in Sources */ = {isa = PBXBuildFile; fileRef = 905B3D3A1C8867AA00BCC93B /* SortManager.m */; }; 905C594F1C50DA490051D223 /* ManageTouchID.m in Sources */ = {isa = PBXBuildFile; fileRef = 906177E11C4FABF600BBE648 /* ManageTouchID.m */; }; 905C59501C50DA680051D223 /* ManageTouchID.m in Sources */ = {isa = PBXBuildFile; fileRef = 906177E11C4FABF600BBE648 /* ManageTouchID.m */; }; @@ -697,7 +702,6 @@ EA1F62D71A5EBF8500D6346F /* ManageFilesDB.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F13A177C2F73004A1A5A /* ManageFilesDB.m */; }; EA1F62D81A5EBFC700D6346F /* ManageUsersDB.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F140177C2FC1004A1A5A /* ManageUsersDB.m */; }; EA1F62D91A5EBFDF00D6346F /* OCKeychain.m in Sources */ = {isa = PBXBuildFile; fileRef = 40FF874219F81396008B7C62 /* OCKeychain.m */; }; - EA1F62DA1A5EBFF100D6346F /* CredentialsDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 40AC24D119FE725600582867 /* CredentialsDto.m */; }; EA1F62DD1A5EC08300D6346F /* libownCloudiOS.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EA8667E118AA291C00D3550D /* libownCloudiOS.a */; }; EA1F62DE1A5EC11900D6346F /* FileDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F146177C315D004A1A5A /* FileDto.m */; }; EA2243EA1B71276D00F62E2A /* ShareLinkHeaderCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = EA2243E81B71276D00F62E2A /* ShareLinkHeaderCell.swift */; }; @@ -935,7 +939,6 @@ EAF7217F1AAF2E5B009F5596 /* FMDatabase.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F14F177C3392004A1A5A /* FMDatabase.m */; }; EAF721801AAF3325009F5596 /* Managers.swift in Sources */ = {isa = PBXBuildFile; fileRef = EAF7217C1AAF2E0D009F5596 /* Managers.swift */; }; EAF721811AAF33F8009F5596 /* OCKeychain.m in Sources */ = {isa = PBXBuildFile; fileRef = 40FF874219F81396008B7C62 /* OCKeychain.m */; }; - EAF721821AAF3402009F5596 /* CredentialsDto.m in Sources */ = {isa = PBXBuildFile; fileRef = 40AC24D119FE725600582867 /* CredentialsDto.m */; }; EAF721831AAF340D009F5596 /* ManageUsersDB.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F140177C2FC1004A1A5A /* ManageUsersDB.m */; }; EAF721841AAF3C5C009F5596 /* FMResultSet.m in Sources */ = {isa = PBXBuildFile; fileRef = 1487F157177C3392004A1A5A /* FMResultSet.m */; }; EAF721851AAF3C86009F5596 /* UtilsUrls.m in Sources */ = {isa = PBXBuildFile; fileRef = 593F7CA919EFDE96004136F7 /* UtilsUrls.m */; }; @@ -1109,10 +1112,6 @@ 13D6B7C818855EE40090A96C /* AppsActivityProvider.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppsActivityProvider.h; path = Tabs/FileTab/Share/AppsActivityProvider.h; sourceTree = ""; }; 13D6B7C918855EE40090A96C /* AppsActivityProvider.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppsActivityProvider.m; path = Tabs/FileTab/Share/AppsActivityProvider.m; sourceTree = ""; }; 13D8741E169DBE05000FBE6D /* MessageUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MessageUI.framework; path = System/Library/Frameworks/MessageUI.framework; sourceTree = SDKROOT; }; - 1420C3A6178A9F5000C0455C /* LoginViewController_iPad.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = LoginViewController_iPad.xib; path = Login/Login/LoginViewController_iPad.xib; sourceTree = ""; }; - 1420C3A7178A9F5000C0455C /* LoginViewController_iPhone.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = LoginViewController_iPhone.xib; path = Login/Login/LoginViewController_iPhone.xib; sourceTree = ""; }; - 1420C3A8178A9F5000C0455C /* LoginViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = LoginViewController.h; path = Login/Login/LoginViewController.h; sourceTree = ""; }; - 1420C3A9178A9F5000C0455C /* LoginViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = LoginViewController.m; path = Login/Login/LoginViewController.m; sourceTree = ""; }; 1428F673178422AE0092F42A /* UploadsOfflineDto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UploadsOfflineDto.h; path = DataBase/DTOs/UploadsOfflineDto.h; sourceTree = ""; }; 1428F674178422AE0092F42A /* UploadsOfflineDto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = UploadsOfflineDto.m; path = DataBase/DTOs/UploadsOfflineDto.m; sourceTree = ""; }; 1428F676178422BE0092F42A /* UtilsDtos.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UtilsDtos.h; path = Utils/UtilsDtos.h; sourceTree = ""; }; @@ -1271,16 +1270,6 @@ 148DD5D6177851E700FB9977 /* UploadRecentCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = UploadRecentCell.xib; path = Cells/UploadCell/UploadRecentCell.xib; sourceTree = ""; }; 148DD5FB1778556500FB9977 /* MBProgressHUD.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MBProgressHUD.h; path = ExternalLibreries/LoadingScreen/MBProgressHUD.h; sourceTree = ""; }; 148DD5FC1778556500FB9977 /* MBProgressHUD.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = MBProgressHUD.m; path = ExternalLibreries/LoadingScreen/MBProgressHUD.m; sourceTree = ""; }; - 148DD608177855B600FB9977 /* AuthenticationDbService.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AuthenticationDbService.h; path = ExternalLibreries/OAuth/AuthenticationDbService.h; sourceTree = ""; }; - 148DD609177855B600FB9977 /* AuthenticationDbService.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AuthenticationDbService.m; path = ExternalLibreries/OAuth/AuthenticationDbService.m; sourceTree = ""; }; - 148DD60A177855B600FB9977 /* AuthenticationResponseTypeCodeTask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AuthenticationResponseTypeCodeTask.h; path = ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.h; sourceTree = ""; }; - 148DD60B177855B600FB9977 /* AuthenticationResponseTypeCodeTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AuthenticationResponseTypeCodeTask.m; path = ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.m; sourceTree = ""; }; - 148DD60C177855B600FB9977 /* RetrieveAccessTokenTask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RetrieveAccessTokenTask.h; path = ExternalLibreries/OAuth/RetrieveAccessTokenTask.h; sourceTree = ""; }; - 148DD60D177855B600FB9977 /* RetrieveAccessTokenTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RetrieveAccessTokenTask.m; path = ExternalLibreries/OAuth/RetrieveAccessTokenTask.m; sourceTree = ""; }; - 148DD60E177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RetrieveDataResponseTypeCodeTask.h; path = ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.h; sourceTree = ""; }; - 148DD60F177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RetrieveDataResponseTypeCodeTask.m; path = ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.m; sourceTree = ""; }; - 148DD610177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RetrieveRefreshAndAccessTokenTask.h; path = ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.h; sourceTree = ""; }; - 148DD611177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RetrieveRefreshAndAccessTokenTask.m; path = ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.m; sourceTree = ""; }; 148DD617177855D900FB9977 /* Reachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Reachability.h; path = ExternalLibreries/Reachability/Reachability.h; sourceTree = ""; }; 148DD618177855D900FB9977 /* Reachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Reachability.m; path = ExternalLibreries/Reachability/Reachability.m; sourceTree = ""; }; 148DD61F17785D6900FB9977 /* DetailView.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = DetailView.xib; path = Files/Preview/DetailView/DetailView.xib; sourceTree = ""; }; @@ -1330,15 +1319,9 @@ 148DD6B41778693000FB9977 /* RecentViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RecentViewController.h; path = Tabs/RecentTab/RecentViewController.h; sourceTree = ""; }; 148DD6B51778693000FB9977 /* RecentViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = RecentViewController.m; path = Tabs/RecentTab/RecentViewController.m; sourceTree = ""; }; 148DD6B61778693000FB9977 /* RecentViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = RecentViewController.xib; path = Tabs/RecentTab/RecentViewController.xib; sourceTree = ""; }; - 148DD6B91778695E00FB9977 /* AddAccountViewController_iPhone.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = AddAccountViewController_iPhone.xib; path = Tabs/SettingTab/Account/AddAccount/AddAccountViewController_iPhone.xib; sourceTree = ""; }; - 148DD6BA1778695E00FB9977 /* AddAccountViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AddAccountViewController.h; path = Tabs/SettingTab/Account/AddAccount/AddAccountViewController.h; sourceTree = ""; }; - 148DD6BB1778695E00FB9977 /* AddAccountViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AddAccountViewController.m; path = Tabs/SettingTab/Account/AddAccount/AddAccountViewController.m; sourceTree = ""; }; 148DD6BE1778697100FB9977 /* AccountCell.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AccountCell.h; path = Tabs/SettingTab/Account/Cell/AccountCell.h; sourceTree = ""; }; 148DD6BF1778697100FB9977 /* AccountCell.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AccountCell.m; path = Tabs/SettingTab/Account/Cell/AccountCell.m; sourceTree = ""; }; 148DD6C01778697100FB9977 /* AccountCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = AccountCell.xib; path = Tabs/SettingTab/Account/Cell/AccountCell.xib; sourceTree = ""; }; - 148DD6C31778698300FB9977 /* EditAccountViewController_iPhone.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = EditAccountViewController_iPhone.xib; path = Tabs/SettingTab/Account/EditAccount/EditAccountViewController_iPhone.xib; sourceTree = ""; }; - 148DD6C41778698300FB9977 /* EditAccountViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = EditAccountViewController.h; path = Tabs/SettingTab/Account/EditAccount/EditAccountViewController.h; sourceTree = ""; }; - 148DD6C51778698300FB9977 /* EditAccountViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = EditAccountViewController.m; path = Tabs/SettingTab/Account/EditAccount/EditAccountViewController.m; sourceTree = ""; }; 148DD6D4177869C800FB9977 /* Impressum.rtf */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.rtf; name = Impressum.rtf; path = Tabs/SettingTab/Imprint/Impressum.rtf; sourceTree = ""; }; 148DD6D5177869C800FB9977 /* ImpressumViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ImpressumViewController.h; path = Tabs/SettingTab/Imprint/ImpressumViewController.h; sourceTree = ""; }; 148DD6D6177869C800FB9977 /* ImpressumViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ImpressumViewController.m; path = Tabs/SettingTab/Imprint/ImpressumViewController.m; sourceTree = ""; }; @@ -1358,7 +1341,7 @@ 148DD6F517786BDA00FB9977 /* UIImage+RoundedCorner.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "UIImage+RoundedCorner.m"; path = "Utils/ImagenScale/UIImage+RoundedCorner.m"; sourceTree = ""; }; 148DD6FB17786BF200FB9977 /* FileNameUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FileNameUtils.h; path = Utils/FileNameUtils.h; sourceTree = ""; }; 148DD6FC17786BF200FB9977 /* FileNameUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = FileNameUtils.m; path = Utils/FileNameUtils.m; sourceTree = ""; }; - 1493D8CE185702D70090FEFB /* CheckSSOServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CheckSSOServer.m; path = Login/SSO/CheckSSOServer.m; sourceTree = ""; }; + 1493D8CE185702D70090FEFB /* CheckSSOServer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = CheckSSOServer.m; sourceTree = ""; }; 149532F917DA09DA00E77D71 /* topBar.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = topBar.png; path = Bar/TopBar/topBar.png; sourceTree = ""; }; 149532FA17DA09DA00E77D71 /* topBar@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; name = "topBar@2x.png"; path = "Bar/TopBar/topBar@2x.png"; sourceTree = ""; }; 14987090187D6702000D9C49 /* CWStatusBarNotification.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CWStatusBarNotification.h; path = ExternalLibreries/CustomStatusBar/CWStatusBarNotification.h; sourceTree = ""; }; @@ -1530,9 +1513,13 @@ 405655191CE0A204001266EE /* UtilsFileSystem.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UtilsFileSystem.h; path = Utils/UtilsFileSystem.h; sourceTree = ""; }; 4056551A1CE0A204001266EE /* UtilsFileSystem.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = UtilsFileSystem.m; path = Utils/UtilsFileSystem.m; sourceTree = ""; }; 405AD0C01B56C26A00271424 /* iphoneShare.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = iphoneShare.png; sourceTree = ""; }; + 407B51BB1F0A34DB00DDFA65 /* Customization.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Customization.m; path = Branding/Customization.m; sourceTree = ""; }; + 40904B2B1EF04ACE00C72619 /* DetectAuthenticationMethod.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DetectAuthenticationMethod.swift; sourceTree = ""; }; 4096E2471EB8650200318240 /* ShareWarningLinkCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ShareWarningLinkCell.swift; path = Tabs/FileTab/Share/Cells/ShareWarningLinkCell.swift; sourceTree = ""; }; 4096E2481EB8650200318240 /* ShareWarningLinkCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = ShareWarningLinkCell.xib; path = Tabs/FileTab/Share/Cells/ShareWarningLinkCell.xib; sourceTree = ""; }; 40A1F17F1D8857740078C901 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + 40A226AA1F179620003C678E /* ManageAccounts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ManageAccounts.swift; path = Tabs/SettingTab/Account/ManageAccounts.swift; sourceTree = ""; }; + 40A226AD1F179C2B003C678E /* ManageFiles.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ManageFiles.swift; path = Tabs/FileTab/ManageFiles.swift; sourceTree = ""; }; 40A3A0E91CEC9B3A0056016A /* more-filledBlack.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "more-filledBlack.png"; sourceTree = ""; }; 40A3A0EA1CEC9B3A0056016A /* more-filledBlack@2x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "more-filledBlack@2x.png"; sourceTree = ""; }; 40AB1F591A12392E003E7397 /* cancel_download_white@3x.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "cancel_download_white@3x.png"; sourceTree = ""; }; @@ -1548,13 +1535,22 @@ 40AB650E1EAFA10000379361 /* ShareLinkViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ShareLinkViewController.h; path = Tabs/FileTab/Share/ShareLinkViewController.h; sourceTree = ""; }; 40AB650F1EAFA10000379361 /* ShareLinkViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ShareLinkViewController.m; path = Tabs/FileTab/Share/ShareLinkViewController.m; sourceTree = ""; }; 40AB65101EAFA10000379361 /* ShareLinkViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = ShareLinkViewController.xib; path = Tabs/FileTab/Share/ShareLinkViewController.xib; sourceTree = ""; }; - 40AC24D019FE725600582867 /* CredentialsDto.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CredentialsDto.h; path = DataBase/DTOs/CredentialsDto.h; sourceTree = ""; }; - 40AC24D119FE725600582867 /* CredentialsDto.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CredentialsDto.m; path = DataBase/DTOs/CredentialsDto.m; sourceTree = ""; }; + 40B083981F1607D90072574A /* Log.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Log.swift; sourceTree = ""; }; + 40B5700D1F1E137D00A98A8E /* UtilsLogin.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UtilsLogin.h; sourceTree = ""; }; + 40B5700E1F1E137D00A98A8E /* UtilsLogin.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = UtilsLogin.m; sourceTree = ""; }; + 40B5AB7C1F7AB6420022F3A2 /* SSLCertificateManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SSLCertificateManager.h; path = Utils/SSL/SSLCertificateManager.h; sourceTree = ""; }; + 40B5AB7D1F7AB6420022F3A2 /* SSLCertificateManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SSLCertificateManager.m; path = Utils/SSL/SSLCertificateManager.m; sourceTree = ""; }; + 40C01ED81F0FA923002DCAAA /* DetectListOfFiles.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = DetectListOfFiles.swift; path = Network/ReadFolder/DetectListOfFiles.swift; sourceTree = ""; }; 40C0BDB81C46562A0057B1DD /* SharePrivilegeCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = SharePrivilegeCell.xib; path = Tabs/FileTab/Share/Cells/SharePrivilegeCell.xib; sourceTree = ""; }; 40C0BDBB1C465F390057B1DD /* SharePrivilegeCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = SharePrivilegeCell.swift; path = Tabs/FileTab/Share/Cells/SharePrivilegeCell.swift; sourceTree = ""; }; + 40C663A91EFA4FBE004AF994 /* Main.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = Main.storyboard; sourceTree = ""; }; + 40C663AF1EFA94B1004AF994 /* UniversalLoginViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UniversalLoginViewController.swift; sourceTree = ""; }; 40CC7F0C1B4E665400231D73 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; 40CF2C6B1C491C610047969A /* ShareUserPrivilegeCell.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = ShareUserPrivilegeCell.xib; path = Tabs/FileTab/Share/Cells/ShareUserPrivilegeCell.xib; sourceTree = ""; }; 40CF2C6E1C491D200047969A /* ShareUserPrivilegeCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = ShareUserPrivilegeCell.swift; path = Tabs/FileTab/Share/Cells/ShareUserPrivilegeCell.swift; sourceTree = ""; }; + 40D090821F97BA6A0030B9F9 /* DetectUserData.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DetectUserData.h; sourceTree = ""; }; + 40D090831F97BA6A0030B9F9 /* DetectUserData.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = DetectUserData.m; sourceTree = ""; }; + 40D3F18D1EFD53E7004F0E22 /* WebLoginViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WebLoginViewController.swift; sourceTree = ""; }; 40DC9C641CDA191B00F5F5EF /* EditFileViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EditFileViewController.h; sourceTree = ""; }; 40DC9C651CDA191B00F5F5EF /* EditFileViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EditFileViewController.m; sourceTree = ""; }; 40DC9C661CDA191B00F5F5EF /* EditFileViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = EditFileViewController.xib; sourceTree = ""; }; @@ -1586,9 +1582,9 @@ 590F1FF91C7474AE00AAF1C7 /* he */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = he; path = he.lproj/Localizable.strings; sourceTree = ""; }; 590F1FFA1C7474B700AAF1C7 /* ja */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ja; path = ja.lproj/Localizable.strings; sourceTree = ""; }; 593D14881C60BE1E005161E2 /* SplashImage.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = SplashImage.png; sourceTree = ""; }; - 593D531A17BF701800191846 /* SSOViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SSOViewController.h; path = Login/SSO/SSOViewController.h; sourceTree = ""; }; - 593D531B17BF701800191846 /* SSOViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SSOViewController.m; path = Login/SSO/SSOViewController.m; sourceTree = ""; }; - 593D531C17BF701800191846 /* SSOViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; name = SSOViewController.xib; path = Login/SSO/SSOViewController.xib; sourceTree = ""; }; + 593D531A17BF701800191846 /* SSOViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SSOViewController.h; sourceTree = ""; }; + 593D531B17BF701800191846 /* SSOViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SSOViewController.m; sourceTree = ""; }; + 593D531C17BF701800191846 /* SSOViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = SSOViewController.xib; sourceTree = ""; }; 593F7CA819EFDE96004136F7 /* UtilsUrls.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UtilsUrls.h; path = Utils/UtilsUrls.h; sourceTree = ""; }; 593F7CA919EFDE96004136F7 /* UtilsUrls.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = UtilsUrls.m; path = Utils/UtilsUrls.m; sourceTree = ""; }; 593F7CAD19F01134004136F7 /* Owncloud iOs Client.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = "Owncloud iOs Client.entitlements"; sourceTree = ""; }; @@ -1720,6 +1716,8 @@ 59EF1F0C1CE0BD8900184F8F /* DeleteUtils.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DeleteUtils.h; path = Utils/DeleteUtils.h; sourceTree = ""; }; 59EF1F0D1CE0BD8900184F8F /* DeleteUtils.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = DeleteUtils.m; path = Utils/DeleteUtils.m; sourceTree = ""; }; 59F470311C5F97BA005B6091 /* Launch Screen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; path = "Launch Screen.storyboard"; sourceTree = ""; }; + 7F9B91BC1F1F472700B77260 /* ServerURLNormalizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ServerURLNormalizer.swift; sourceTree = ""; }; + 7F9B91C71F1F817700B77260 /* GetPublicInfoFromServerJob.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GetPublicInfoFromServerJob.swift; sourceTree = ""; }; 905B3D3A1C8867AA00BCC93B /* SortManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SortManager.m; path = Tabs/FileTab/Sort/SortManager.m; sourceTree = ""; }; 905B3D3E1C88681000BCC93B /* SortManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SortManager.h; path = Tabs/FileTab/Sort/SortManager.h; sourceTree = ""; }; 906177E11C4FABF600BBE648 /* ManageTouchID.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ManageTouchID.m; sourceTree = ""; }; @@ -1922,7 +1920,7 @@ EAD281BA1A38A2F900A00D54 /* DPDownload.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = DPDownload.m; path = Network/DPDownload.m; sourceTree = ""; }; EAD774F11AD2B01E0007C4DB /* OCSplitViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = OCSplitViewController.h; sourceTree = ""; }; EAD774F21AD2B01E0007C4DB /* OCSplitViewController.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OCSplitViewController.m; sourceTree = ""; }; - EAE005F0180EF03E0066E8D4 /* CheckSSOServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CheckSSOServer.h; path = Login/SSO/CheckSSOServer.h; sourceTree = ""; }; + EAE005F0180EF03E0066E8D4 /* CheckSSOServer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CheckSSOServer.h; sourceTree = ""; }; EAEE0830192B35CC00E1AA25 /* SystemConstants.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SystemConstants.h; path = Utils/SystemConstants.h; sourceTree = ""; }; EAF13F7B1BE8F5EA00F87E9F /* CheckCapabilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CheckCapabilities.h; path = "Network/Server Version Checks/CheckCapabilities.h"; sourceTree = ""; }; EAF13F7C1BE8F5EA00F87E9F /* CheckCapabilities.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CheckCapabilities.m; path = "Network/Server Version Checks/CheckCapabilities.m"; sourceTree = ""; }; @@ -2093,6 +2091,7 @@ 1324298B15ADBB3700DF823E /* AppDelegate.h */, 1324298C15ADBB3700DF823E /* AppDelegate.m */, 59F470311C5F97BA005B6091 /* Launch Screen.storyboard */, + 40C663A91EFA4FBE004AF994 /* Main.storyboard */, 148DD5B11778425400FB9977 /* Branding */, 148DD5B81778501B00FB9977 /* Cells */, 40EDF89D1B4D112900700E3A /* HelpGuide */, @@ -2123,6 +2122,7 @@ 1324298815ADBB3700DF823E /* main.m */, 1324298A15ADBB3700DF823E /* Owncloud iOs Client-Prefix.pch */, 40A1F1801D8857740078C901 /* InfoPlist.strings */, + 40B083981F1607D90072574A /* Log.swift */, ); name = "Supporting Files"; sourceTree = ""; @@ -2152,6 +2152,7 @@ isa = PBXGroup; children = ( 599D809E1A23366D0071B66E /* SimpleFileList */, + 40A226AD1F179C2B003C678E /* ManageFiles.swift */, EA42FA52180565CB0006DB7C /* OCTabBarController.h */, EA42FA53180565CB0006DB7C /* OCTabBarController.m */, EA42FA4C1804217D0006DB7C /* OCToolBar.h */, @@ -2213,7 +2214,7 @@ 593D531917BF6F7600191846 /* SSO */, 13C4DEEC163672CA00638B1D /* Login */, ); - name = Login; + path = Login; sourceTree = ""; }; 137E485115B6A37F00628EB1 /* Database */ = { @@ -2236,8 +2237,6 @@ 1487F147177C315D004A1A5A /* UserDto.h */, 1487F148177C315D004A1A5A /* UserDto.m */, 59A9A723196E8A370042FEAC /* CookiesStorageDto.h */, - 40AC24D019FE725600582867 /* CredentialsDto.h */, - 40AC24D119FE725600582867 /* CredentialsDto.m */, 59A9A724196E8A370042FEAC /* CookiesStorageDto.m */, EAC598581A56A150003192B2 /* ProvidingFileDto.h */, EAC598591A56A150003192B2 /* ProvidingFileDto.m */, @@ -2471,44 +2470,25 @@ 13C4DEEC163672CA00638B1D /* Login */ = { isa = PBXGroup; children = ( - 1420C3A6178A9F5000C0455C /* LoginViewController_iPad.xib */, - 1420C3A7178A9F5000C0455C /* LoginViewController_iPhone.xib */, - 1420C3A8178A9F5000C0455C /* LoginViewController.h */, - 1420C3A9178A9F5000C0455C /* LoginViewController.m */, + 40C663AF1EFA94B1004AF994 /* UniversalLoginViewController.swift */, + 40D3F18D1EFD53E7004F0E22 /* WebLoginViewController.swift */, + 40B5700D1F1E137D00A98A8E /* UtilsLogin.h */, + 40B5700E1F1E137D00A98A8E /* UtilsLogin.m */, + 7F9B91BC1F1F472700B77260 /* ServerURLNormalizer.swift */, + 7F9B91C71F1F817700B77260 /* GetPublicInfoFromServerJob.swift */, ); - name = Login; + path = Login; sourceTree = ""; }; 13C4DEF51636735800638B1D /* Accounts */ = { isa = PBXGroup; children = ( - 13C4DEF71636736800638B1D /* Add Account */, 13C4DEF81636737300638B1D /* Cell */, - 13C4DEF61636736200638B1D /* Edit Account */, + 40A226AA1F179620003C678E /* ManageAccounts.swift */, ); name = Accounts; sourceTree = ""; }; - 13C4DEF61636736200638B1D /* Edit Account */ = { - isa = PBXGroup; - children = ( - 148DD6C31778698300FB9977 /* EditAccountViewController_iPhone.xib */, - 148DD6C41778698300FB9977 /* EditAccountViewController.h */, - 148DD6C51778698300FB9977 /* EditAccountViewController.m */, - ); - name = "Edit Account"; - sourceTree = ""; - }; - 13C4DEF71636736800638B1D /* Add Account */ = { - isa = PBXGroup; - children = ( - 148DD6B91778695E00FB9977 /* AddAccountViewController_iPhone.xib */, - 148DD6BA1778695E00FB9977 /* AddAccountViewController.h */, - 148DD6BB1778695E00FB9977 /* AddAccountViewController.m */, - ); - name = "Add Account"; - sourceTree = ""; - }; 13C4DEF81636737300638B1D /* Cell */ = { isa = PBXGroup; children = ( @@ -2873,6 +2853,7 @@ isa = PBXGroup; children = ( 148DD5B21778436A00FB9977 /* Customization.h */, + 407B51BB1F0A34DB00DDFA65 /* Customization.m */, 148DD5B31778436A00FB9977 /* UIColor+Constants.h */, 148DD5B41778436A00FB9977 /* UIColor+Constants.m */, ); @@ -2931,7 +2912,6 @@ EA68968317F598EB0033B3C1 /* KKPasscodeLock */, 13A9FCDD17E9857300FF48D7 /* ELCPickerLib */, 148DD5FA177854D900FB9977 /* LoadingScreen */, - 148DD6071778559D00FB9977 /* OAuth */, 595333F81A1DF26000C57ED5 /* UIAlertViewWithBlocks */, EAC3AC3B15ED2A4F00B59805 /* Reachability */, 59C71CE81A9216AE00F66166 /* VFR Pdf Reader */, @@ -2948,23 +2928,6 @@ name = LoadingScreen; sourceTree = ""; }; - 148DD6071778559D00FB9977 /* OAuth */ = { - isa = PBXGroup; - children = ( - 148DD608177855B600FB9977 /* AuthenticationDbService.h */, - 148DD609177855B600FB9977 /* AuthenticationDbService.m */, - 148DD60A177855B600FB9977 /* AuthenticationResponseTypeCodeTask.h */, - 148DD60B177855B600FB9977 /* AuthenticationResponseTypeCodeTask.m */, - 148DD60C177855B600FB9977 /* RetrieveAccessTokenTask.h */, - 148DD60D177855B600FB9977 /* RetrieveAccessTokenTask.m */, - 148DD60E177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.h */, - 148DD60F177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.m */, - 148DD610177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.h */, - 148DD611177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.m */, - ); - name = OAuth; - sourceTree = ""; - }; 148DD61D17785D4200FB9977 /* Files */ = { isa = PBXGroup; children = ( @@ -2987,6 +2950,9 @@ 148DD6661778625100FB9977 /* Network */ = { isa = PBXGroup; children = ( + 40904B291EF046DA00C72619 /* Authentication */, + 404681F41F913B3800A4D402 /* UserData */, + 40C01ED61F0FA784002DCAAA /* ReadFolder */, 59AE9EAE1990FE74003380A8 /* Server Version Checks */, 59A6B65019458D0C000B107D /* URLSession Subclasses */, EAD036BC19053BAB003665CD /* Favorites */, @@ -3057,6 +3023,16 @@ path = HelpGuide; sourceTree = ""; }; + 404681F41F913B3800A4D402 /* UserData */ = { + isa = PBXGroup; + children = ( + 40D090821F97BA6A0030B9F9 /* DetectUserData.h */, + 40D090831F97BA6A0030B9F9 /* DetectUserData.m */, + ); + name = UserData; + path = Network/UserData; + sourceTree = ""; + }; 4052B4AC1B4E951F000788DA /* HelpPageButtons */ = { isa = PBXGroup; children = ( @@ -3078,6 +3054,15 @@ path = HelpPageButtons; sourceTree = ""; }; + 40904B291EF046DA00C72619 /* Authentication */ = { + isa = PBXGroup; + children = ( + 40904B2B1EF04ACE00C72619 /* DetectAuthenticationMethod.swift */, + ); + name = Authentication; + path = Network/Authentication; + sourceTree = ""; + }; 40A969DD1A5EDF900046A36C /* InstantUpload */ = { isa = PBXGroup; children = ( @@ -3087,6 +3072,14 @@ path = InstantUpload; sourceTree = ""; }; + 40C01ED61F0FA784002DCAAA /* ReadFolder */ = { + isa = PBXGroup; + children = ( + 40C01ED81F0FA923002DCAAA /* DetectListOfFiles.swift */, + ); + name = ReadFolder; + sourceTree = ""; + }; 40DAF1A31B8C7D3400D100D3 /* ExternalLibraries */ = { isa = PBXGroup; children = ( @@ -3187,8 +3180,7 @@ 40FF874119F81396008B7C62 /* OCKeychain.h */, 40FF874219F81396008B7C62 /* OCKeychain.m */, ); - name = Keychain; - path = Login/Keychain; + path = Keychain; sourceTree = ""; }; 593D531917BF6F7600191846 /* SSO */ = { @@ -3200,7 +3192,7 @@ EAE005F0180EF03E0066E8D4 /* CheckSSOServer.h */, 1493D8CE185702D70090FEFB /* CheckSSOServer.m */, ); - name = SSO; + path = SSO; sourceTree = ""; }; 595333F81A1DF26000C57ED5 /* UIAlertViewWithBlocks */ = { @@ -3248,6 +3240,8 @@ 59A0DAD71941A5060088FECD /* SSL */ = { isa = PBXGroup; children = ( + 40B5AB7C1F7AB6420022F3A2 /* SSLCertificateManager.h */, + 40B5AB7D1F7AB6420022F3A2 /* SSLCertificateManager.m */, 59A0DADA1941A7A60088FECD /* CheckAccessToServer.h */, 59A0DAD91941A7A60088FECD /* CheckAccessToServer.m */, ); @@ -4132,6 +4126,7 @@ 137E485E15B6A3A400628EB1 /* DB.sqlite in Resources */, 40AB1F5B1A12392E003E7397 /* cancel_download_white@3x.png in Resources */, 148DD5C3177850B100FB9977 /* CustomCellFileAndDirectory.xib in Resources */, + 40C663AA1EFA4FBE004AF994 /* Main.storyboard in Resources */, 14A4796B18EC6FDF003500BA /* FileFavoriteIcon@2x.png in Resources */, 59F470321C5F97BA005B6091 /* Launch Screen.storyboard in Resources */, EABD88F91BBE82C400DA5281 /* NotificationBackgroundSuccess.png in Resources */, @@ -4161,11 +4156,9 @@ 14A7F7A118ED5781009AF347 /* presentation_icon@2x~ipad.png in Resources */, 148DD6B3177866A400FB9977 /* FilesViewController.xib in Resources */, 148DD6B81778693000FB9977 /* RecentViewController.xib in Resources */, - 148DD6BC1778695E00FB9977 /* AddAccountViewController_iPhone.xib in Resources */, 14A7F7AF18ED5C06009AF347 /* folder_icon~ipad.png in Resources */, EABF68F2188FC2FA00A2217C /* TABShares.png in Resources */, 148DD6C21778697100FB9977 /* AccountCell.xib in Resources */, - 148DD6C61778698300FB9977 /* EditAccountViewController_iPhone.xib in Resources */, 148DD6D8177869C800FB9977 /* Impressum.rtf in Resources */, 148DD6DA177869C800FB9977 /* ImpressumViewController.xib in Resources */, 148DD6E917786A1400FB9977 /* SettingsViewController.xib in Resources */, @@ -4426,11 +4419,9 @@ EABD88E91BBE82C400DA5281 /* NotificationBackgroundErrorIcon.png in Resources */, 4030D8EF1A1626CC00DB0871 /* file_icon@2x~ipad.png in Resources */, 4030D8F71A16277100DB0871 /* file_icon@3x.png in Resources */, - 1420C3AA178A9F5000C0455C /* LoginViewController_iPad.xib in Resources */, 908A3C5D1D01732C00A34FDB /* file_available_offline_icon.png in Resources */, EA4914771AC0346100BECF0B /* TTOpenInAppActivity8@2x.png in Resources */, 9064143F1D005B5C000AEFE5 /* file_new_server_version_available_icon.png in Resources */, - 1420C3AB178A9F5000C0455C /* LoginViewController_iPhone.xib in Resources */, EA4914781AC0346100BECF0B /* TTOpenInAppActivity8@3x.png in Resources */, 14A7F7AA18ED578E009AF347 /* spreadsheet_icon@2x~ipad.png in Resources */, 4007876D1C44EAEE00486A26 /* ShareEditUserViewController.xib in Resources */, @@ -4735,13 +4726,16 @@ 59BF9B371A2C8BEA009D9CF0 /* FileListDocumentProviderViewController.m in Sources */, 1324298915ADBB3700DF823E /* main.m in Sources */, EA4070FE1C11B82B008B1507 /* UIImage+Thumbnail.m in Sources */, + 40D3F18E1EFD53E7004F0E22 /* WebLoginViewController.swift in Sources */, 40DD9AE01D228E0C008E99D6 /* UtilsNotifications.m in Sources */, EABD89361BBE82D900DA5281 /* TSMessage.m in Sources */, + 40A226AE1F179C2B003C678E /* ManageFiles.swift in Sources */, 59C71D231A9216AE00F66166 /* ThumbsMainToolbar.m in Sources */, 59C71D1A1A9216AE00F66166 /* ReaderMainToolbar.m in Sources */, 59EA36241BBE6C1E00C6CED0 /* IndexedForest.m in Sources */, 1324298D15ADBB3700DF823E /* AppDelegate.m in Sources */, 148DD5B51778436A00FB9977 /* UIColor+Constants.m in Sources */, + 407B51BC1F0A34DB00DDFA65 /* Customization.m in Sources */, 59EC94E81BBAA0210085190F /* FolderSyncDto.m in Sources */, 148DD5C2177850B100FB9977 /* CustomCellFileAndDirectory.m in Sources */, 905B3D3B1C8867AA00BCC93B /* SortManager.m in Sources */, @@ -4759,19 +4753,15 @@ EAC5985A1A56A150003192B2 /* ProvidingFileDto.m in Sources */, 400A63641B4FD75600890579 /* IFTTTAlphaAnimation.m in Sources */, 59C71D161A9216AE00F66166 /* ReaderContentView.m in Sources */, - 148DD612177855B600FB9977 /* AuthenticationDbService.m in Sources */, EA0599931BB94F3F002C2864 /* ShareSearchUserViewController.m in Sources */, 59C71D1C1A9216AE00F66166 /* ReaderThumbFetch.m in Sources */, EA5C6F841B70BEE30088071B /* ShareFileCell.swift in Sources */, 59E20C7A1AEFAA8E00554D7E /* InitializeDatabase.m in Sources */, EABD88C91BBE638300DA5281 /* ShareLoadingCell.swift in Sources */, EA42FA54180565CB0006DB7C /* OCTabBarController.m in Sources */, - 148DD613177855B600FB9977 /* AuthenticationResponseTypeCodeTask.m in Sources */, - 148DD614177855B600FB9977 /* RetrieveAccessTokenTask.m in Sources */, + 7F9B91C81F1F817700B77260 /* GetPublicInfoFromServerJob.swift in Sources */, 59C71D171A9216AE00F66166 /* ReaderDocument.m in Sources */, - 148DD615177855B600FB9977 /* RetrieveDataResponseTypeCodeTask.m in Sources */, 400A636C1B4FD75600890579 /* IFTTTCornerRadiusAnimation.m in Sources */, - 148DD616177855B600FB9977 /* RetrieveRefreshAndAccessTokenTask.m in Sources */, EAD774F31AD2B01E0007C4DB /* OCSplitViewController.m in Sources */, 59EA98941BC5718600C3125D /* DownloadFileSyncFolder.m in Sources */, EA68968D17F599060033B3C1 /* KKKeychain.m in Sources */, @@ -4806,6 +4796,7 @@ EAABAB2A18585CD700909831 /* NSString+Encoding.m in Sources */, EABD89321BBE82D900DA5281 /* TSBlurView.m in Sources */, EABF69161891379C00A2217C /* SWLongPressGestureRecognizer.m in Sources */, + 40D090841F97BA6A0030B9F9 /* DetectUserData.m in Sources */, 4096E2491EB8650200318240 /* ShareWarningLinkCell.swift in Sources */, 14AB382E18C8E35200B34697 /* InfoFileUtils.m in Sources */, 40CF2C6F1C491D200047969A /* ShareUserPrivilegeCell.swift in Sources */, @@ -4848,18 +4839,19 @@ EA707223199CC59E00CE7079 /* ManageDownloads.m in Sources */, 148DD6B71778693000FB9977 /* RecentViewController.m in Sources */, 400A636F1B4FD75600890579 /* IFTTTFilmstrip.m in Sources */, + 40C663B01EFA94B1004AF994 /* UniversalLoginViewController.swift in Sources */, + 40C01ED91F0FA923002DCAAA /* DetectListOfFiles.swift in Sources */, 40AB65111EAFA10000379361 /* ShareLinkViewController.m in Sources */, - 148DD6BD1778695E00FB9977 /* AddAccountViewController.m in Sources */, EAAD688F1C560AF2005F3B28 /* ShareUtils.m in Sources */, 14987095187DB14A000D9C49 /* NotificationStatusBarViewController.m in Sources */, 148DD6C11778697100FB9977 /* AccountCell.m in Sources */, 400A637B1B4FD75600890579 /* IFTTTTransform3DAnimation.m in Sources */, - 148DD6C71778698300FB9977 /* EditAccountViewController.m in Sources */, 400A637A1B4FD75600890579 /* IFTTTTextColorAnimation.m in Sources */, 14B0084018FD1B5B004CB06B /* EmptyCell.m in Sources */, 59C9D324195C0EFB00400AE2 /* ManageNetworkErrors.m in Sources */, BC855ACD1E0D4B0200998CB7 /* FLAnimatedImage.m in Sources */, EA68969017F599060033B3C1 /* KKPasscodeSettingsViewController.m in Sources */, + 40B083991F1607D90072574A /* Log.swift in Sources */, 59C71D121A9216AE00F66166 /* CGPDFDocument.m in Sources */, 400A63671B4FD75600890579 /* IFTTTAnimation.m in Sources */, EAD036C019053BEE003665CD /* ManageFavorites.m in Sources */, @@ -4868,11 +4860,14 @@ 400A636E1B4FD75600890579 /* IFTTTFillColorAnimation.m in Sources */, 148DD6D9177869C800FB9977 /* ImpressumViewController.m in Sources */, 400A636D1B4FD75600890579 /* IFTTTEasingFunction.m in Sources */, + 40904B2C1EF04ACE00C72619 /* DetectAuthenticationMethod.swift in Sources */, 59915D9E1BBC00930015FBF3 /* CWLOrderedDictionary.m in Sources */, 148DD6E817786A1400FB9977 /* SettingsViewController.m in Sources */, + 40B5700F1F1E137D00A98A8E /* UtilsLogin.m in Sources */, 59D774CE1910EE0F004322BA /* UtilsTableView.m in Sources */, 148DD6EA17786A1400FB9977 /* WebViewController.m in Sources */, EA4071031C11CAA0008B1507 /* NSObject+AssociatedObject.m in Sources */, + 40B5AB7E1F7AB6420022F3A2 /* SSLCertificateManager.m in Sources */, EABF69151891379C00A2217C /* SWCellScrollView.m in Sources */, EABF69141891379C00A2217C /* NSMutableArray+SWUtilityButtons.m in Sources */, EA68968F17F599060033B3C1 /* KKPasscodeLock.m in Sources */, @@ -4887,6 +4882,7 @@ 599D80A21A23366D0071B66E /* SimpleFileListTableViewController.m in Sources */, EA0EFA1F1BEA6C6E009971AF /* ManageCapabilitiesDB.m in Sources */, 148DD6FE17786BF200FB9977 /* FileNameUtils.m in Sources */, + 40A226AB1F179620003C678E /* ManageAccounts.swift in Sources */, 400A63741B4FD75600890579 /* IFTTTRotationAnimation.m in Sources */, 400A637C1B4FD75600890579 /* IFTTTTranslationAnimation.m in Sources */, 59C71D201A9216AE00F66166 /* ReaderThumbsView.m in Sources */, @@ -4898,6 +4894,7 @@ 1487F13B177C2F73004A1A5A /* ManageFilesDB.m in Sources */, 1487F13E177C2F9C004A1A5A /* ManageUploadsDB.m in Sources */, 59A9A725196E8A370042FEAC /* CookiesStorageDto.m in Sources */, + 7F9B91BD1F1F472700B77260 /* ServerURLNormalizer.swift in Sources */, 59A9A721196E89170042FEAC /* ManageCookiesStorageDB.m in Sources */, 1487F141177C2FC1004A1A5A /* ManageUsersDB.m in Sources */, 59C71D1E1A9216AE00F66166 /* ReaderThumbRender.m in Sources */, @@ -4926,7 +4923,6 @@ EA1762A01B78B50100D36186 /* ShareMainViewController.m in Sources */, 1428F678178422BE0092F42A /* UtilsDtos.m in Sources */, 59C71D181A9216AE00F66166 /* ReaderDocumentOutline.m in Sources */, - 1420C3AC178A9F5000C0455C /* LoginViewController.m in Sources */, 400A63661B4FD75600890579 /* IFTTTAnimatedScrollViewController.m in Sources */, EA8ADE6A1A31E9AB008D3612 /* UIColor+iOS7.m in Sources */, FCE228D11CFE08EF00E4827F /* InstantUpload.m in Sources */, @@ -4937,7 +4933,6 @@ 59C71D131A9216AE00F66166 /* ReaderConstants.m in Sources */, 148BEA62178C01C300696246 /* FailedUploadCell.m in Sources */, EAF33C891C2AF5EE003A5AA2 /* ManageThumbnails.m in Sources */, - 40AC24D219FE725600582867 /* CredentialsDto.m in Sources */, 596C060D1CF47278004BCF51 /* ELCImagePickerController.m in Sources */, 596C060E1CF47278004BCF51 /* ELCOverlayImageView.m in Sources */, 1339D939178DA3FC00002156 /* UtilsNetworkRequest.m in Sources */, @@ -4965,13 +4960,13 @@ files = ( 59F123E61C89C14D0094CF70 /* SWUtilityButtonTapGestureRecognizer.m in Sources */, 59F123E41C89C1250094CF70 /* SWCellScrollView.m in Sources */, + 40B5AB821F7ABBE70022F3A2 /* SSLCertificateManager.m in Sources */, 59F123E51C89C1250094CF70 /* SWLongPressGestureRecognizer.m in Sources */, 59F123E31C89C1180094CF70 /* SWUtilityButtonView.m in Sources */, 59F123E21C89C0E00094CF70 /* SWTableViewCell.m in Sources */, 59F123E11C89BFB50094CF70 /* CustomCellFileAndDirectory.m in Sources */, 90D608FC1C8984760049CCE4 /* SortManager.m in Sources */, 905C594F1C50DA490051D223 /* ManageTouchID.m in Sources */, - EAF721821AAF3402009F5596 /* CredentialsDto.m in Sources */, EAC6E5F91AB0985200CCF8C4 /* UINavigationController+KeyboardDismiss.m in Sources */, EAF7216F1AADE7EE009F5596 /* UIColor+Constants.m in Sources */, 59E20C7C1AEFAA8E00554D7E /* InitializeDatabase.m in Sources */, @@ -5011,6 +5006,7 @@ EAC6E5FE1AB0A41900CCF8C4 /* OCNavigationController.m in Sources */, EAF721871AB03DB9009F5596 /* ManageFilesDB.m in Sources */, EA66069A1AA767F800BA2C65 /* ShareViewController.swift in Sources */, + 40BCC2BD1F3B5FA700F5DC6F /* (null) in Sources */, EA1415A61AB1B89E0083EACE /* OCToolBar.m in Sources */, EAF7217D1AAF2E0D009F5596 /* Managers.swift in Sources */, 4056551D1CE1DD5E001266EE /* UtilsFileSystem.m in Sources */, @@ -5034,12 +5030,12 @@ EA1C3B601BC29B7F0085F540 /* ManageSharesDB.m in Sources */, 59C3AC1A1A287DE3005433A1 /* KKKeychain.m in Sources */, 59C3AC1B1A287DE3005433A1 /* KKPasscodeLock.m in Sources */, + 40B5AB801F7ABBE70022F3A2 /* SSLCertificateManager.m in Sources */, EA4070FF1C11B82B008B1507 /* UIImage+Thumbnail.m in Sources */, EAE80E271A6D31810061BD86 /* ManageUploadsDB.m in Sources */, 59C3AC1C1A287DE3005433A1 /* KKPasscodeSettingsViewController.m in Sources */, 59C3AC1D1A287DE3005433A1 /* KKPasscodeViewController.m in Sources */, 59C521F91A1B7C3A00C5EF76 /* ManageNetworkErrors.m in Sources */, - 599DDD511A19FBF8008725DE /* CredentialsDto.m in Sources */, EAE80E281A6D31980061BD86 /* UploadsOfflineDto.m in Sources */, EA8ADE691A31E9AB008D3612 /* FFCircularProgressView.m in Sources */, 599DDD4F1A19FBD3008725DE /* OCKeychain.m in Sources */, @@ -5059,6 +5055,7 @@ 59990A251A0BD67A00D3B842 /* InfoFileUtils.m in Sources */, 590849F11A0A811000D3E842 /* NSMutableArray+SWUtilityButtons.m in Sources */, EA8ADE601A31D759008D3612 /* DocumentPickerCell.m in Sources */, + 40BCC2BA1F3B5FA500F5DC6F /* (null) in Sources */, 590849F21A0A811000D3E842 /* SWCellScrollView.m in Sources */, EAD281BB1A38A2F900A00D54 /* DPDownload.m in Sources */, 590849F31A0A811000D3E842 /* SWLongPressGestureRecognizer.m in Sources */, @@ -5099,7 +5096,6 @@ EAE80E241A6CFDE50061BD86 /* UploadsOfflineDto.m in Sources */, EAB0AB4719ED356A00764C31 /* FileProvider.m in Sources */, EA1F62D21A5EBD2400D6346F /* ManageProvidingFilesDB.m in Sources */, - EA1F62DA1A5EBFF100D6346F /* CredentialsDto.m in Sources */, EA1F62CF1A5EBCA800D6346F /* FMDatabaseQueue.m in Sources */, EA1F62DE1A5EC11900D6346F /* FileDto.m in Sources */, EA1F62D11A5EBD2000D6346F /* ProvidingFileDto.m in Sources */, @@ -5110,6 +5106,7 @@ EA1F62D81A5EBFC700D6346F /* ManageUsersDB.m in Sources */, EAE80E261A6D317C0061BD86 /* ManageUploadsDB.m in Sources */, EA1F62D71A5EBF8500D6346F /* ManageFilesDB.m in Sources */, + 40BCC2BC1F3B5FA700F5DC6F /* (null) in Sources */, EA1F62D91A5EBFDF00D6346F /* OCKeychain.m in Sources */, 405D06C71BFB670200591604 /* ManageCapabilitiesDB.m in Sources */, EAFDF1771A76372A00655DBF /* NSString+Encoding.m in Sources */, @@ -5267,6 +5264,7 @@ 132429BD15ADBB3800DF823E /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ENABLE_OBJC_ARC = YES; @@ -5284,6 +5282,7 @@ CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; + DEFINES_MODULE = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; @@ -5314,6 +5313,7 @@ 132429BE15ADBB3800DF823E /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; CLANG_ENABLE_OBJC_ARC = YES; @@ -5331,6 +5331,7 @@ CODE_SIGN_IDENTITY = ""; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; + DEFINES_MODULE = YES; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; @@ -5362,7 +5363,7 @@ CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CODE_SIGN_RESOURCE_RULES_PATH = ""; - DEFINES_MODULE = YES; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( @@ -5395,6 +5396,7 @@ PROVISIONING_PROFILE = ""; "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "CONTAINER_APP=1"; SWIFT_INSTALL_OBJC_HEADER = YES; SWIFT_OBJC_BRIDGING_HEADER = "Owncloud iOs Client/Owncloud iOS Client-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -5414,7 +5416,7 @@ CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; CODE_SIGN_RESOURCE_RULES_PATH = ""; - DEFINES_MODULE = YES; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; FRAMEWORK_SEARCH_PATHS = ( @@ -5442,6 +5444,7 @@ PROVISIONING_PROFILE = ""; "PROVISIONING_PROFILE[sdk=iphoneos*]" = ""; SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "CONTAINER_APP=1"; SWIFT_INSTALL_OBJC_HEADER = YES; SWIFT_OBJC_BRIDGING_HEADER = "Owncloud iOs Client/Owncloud iOS Client-Bridging-Header.h"; SWIFT_VERSION = 3.0; @@ -5522,6 +5525,7 @@ CODE_SIGN_ENTITLEMENTS = "OC Share Sheet/OC Share Sheet.entitlements"; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; GCC_PREFIX_HEADER = "Owncloud iOs Client/Owncloud iOs Client-Prefix.pch"; @@ -5552,7 +5556,9 @@ PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "SHARE_IN=1"; SWIFT_OBJC_BRIDGING_HEADER = "Owncloud iOs Client/OCExtensions-Bridging-Header.h"; + SWIFT_OBJC_INTERFACE_HEADER_NAME = "$(SWIFT_MODULE_NAME)-Swift.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 3.0; }; @@ -5570,6 +5576,7 @@ CODE_SIGN_ENTITLEMENTS = "OC Share Sheet/OC Share Sheet.entitlements"; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; ENABLE_NS_ASSERTIONS = NO; @@ -5597,7 +5604,9 @@ PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "SHARE_IN=1"; SWIFT_OBJC_BRIDGING_HEADER = "Owncloud iOs Client/OCExtensions-Bridging-Header.h"; + SWIFT_OBJC_INTERFACE_HEADER_NAME = "$(SWIFT_MODULE_NAME)-Swift.h"; SWIFT_VERSION = 3.0; }; name = Release; @@ -5605,6 +5614,7 @@ EAB0AB5219ED356A00764C31 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -5620,7 +5630,7 @@ CODE_SIGN_ENTITLEMENTS = ownCloudExtApp/ownCloudExtApp.entitlements; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - DEFINES_MODULE = YES; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -5661,6 +5671,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "FILE_PICKER=1"; SWIFT_OBJC_BRIDGING_HEADER = "Owncloud iOs Client/OCExtensions-Bridging-Header.h"; SWIFT_VERSION = 3.0; }; @@ -5669,6 +5680,7 @@ EAB0AB5319ED356A00764C31 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; @@ -5684,7 +5696,7 @@ CODE_SIGN_ENTITLEMENTS = ownCloudExtApp/ownCloudExtApp.entitlements; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - DEFINES_MODULE = YES; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; ENABLE_NS_ASSERTIONS = NO; @@ -5720,6 +5732,7 @@ PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "FILE_PICKER=1"; SWIFT_OBJC_BRIDGING_HEADER = "Owncloud iOs Client/OCExtensions-Bridging-Header.h"; SWIFT_VERSION = 3.0; }; @@ -5744,7 +5757,7 @@ CODE_SIGN_ENTITLEMENTS = ownCloudExtAppFileProvider/ownCloudExtAppFileProvider.entitlements; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - DEFINES_MODULE = YES; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -5802,7 +5815,7 @@ CODE_SIGN_ENTITLEMENTS = ownCloudExtAppFileProvider/ownCloudExtAppFileProvider.entitlements; CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - DEFINES_MODULE = YES; + DEFINES_MODULE = NO; DEVELOPMENT_TEAM = 9B5WD74GWJ; ENABLE_BITCODE = NO; ENABLE_NS_ASSERTIONS = NO; diff --git a/Owncloud iOs Client/AppDelegate.h b/Owncloud iOs Client/AppDelegate.h index 2e579d5fb2..882d8fedd3 100644 --- a/Owncloud iOs Client/AppDelegate.h +++ b/Owncloud iOs Client/AppDelegate.h @@ -12,10 +12,6 @@ along with this program. If not, see . */ - - - - #import #import "UserDto.h" #import "MediaAVPlayerViewController.h" @@ -27,11 +23,12 @@ #import "DetailViewController.h" #import "ManageDownloads.h" #import "CheckAccessToServer.h" +#import "UtilsLogin.h" +#import "OCOAuth2Configuration.h" @class FilesViewController; @class RecentViewController; @class SettingsViewController; -@class LoginViewController; @class HelpGuideViewController; @class Download; @class OCCommunication; @@ -42,6 +39,10 @@ @class CheckHasShareSupport; @class CheckCapabilities; +@class UniversalLoginViewController; +@class ManageAccounts; + + extern NSString * CloseAlertViewWhenApplicationDidEnterBackground; extern NSString * RefreshSharesItemsAfterCheckServerVersion; extern NSString * NotReachableNetworkForUploadsNotification; @@ -59,8 +60,7 @@ extern NSString * NotReachableNetworkForDownloadsNotification; RecentViewController *_recentViewController; FilesViewController *_filesViewController; - //Pointer to a actual files view controller where the user is. - FilesViewController *_presentFilesViewController; + //FavouritesViewController *_favouritesViewController; SettingsViewController *_settingsViewController; //OCTabBarController *_tabBarController; @@ -108,10 +108,8 @@ extern NSString * NotReachableNetworkForDownloadsNotification; } -@property (strong, nonatomic) LoginViewController *loginWindowViewController; @property (strong, nonatomic) HelpGuideViewController *helpGuideWindowViewController; @property (strong, nonatomic) UIWindow *window; -@property (strong, nonatomic) LoginViewController *loginViewController; @property (strong, nonatomic) UserDto *activeUser; @property (strong, nonatomic) OCTabBarController *ocTabBarController; @property (nonatomic, strong) NSMutableArray *uploadArray; @@ -119,6 +117,7 @@ extern NSString * NotReachableNetworkForDownloadsNotification; @property (nonatomic, strong) SharedViewController *sharedViewController; @property (nonatomic, strong) RecentViewController *recentViewController; @property (nonatomic, strong) FilesViewController *filesViewController; +//Pointer to a actual files view controller where the user is. @property (nonatomic, strong) FilesViewController *presentFilesViewController; @property (nonatomic, strong) SettingsViewController *settingsViewController; @property (nonatomic, strong) UISplitViewController *splitViewController; @@ -153,6 +152,7 @@ extern NSString * NotReachableNetworkForDownloadsNotification; @property (nonatomic, strong) ManageDownloads *downloadManager; @property (nonatomic, strong) NSString *userSessionCurrentToken; +@property (nonatomic, strong) OCOAuth2Configuration *oauth2Configuration; /* * Method to get a Singleton of the OCCommunication to manage all the communications @@ -180,9 +180,6 @@ extern NSString * NotReachableNetworkForDownloadsNotification; - (void) updateRecents; - (void) updateProgressView:(NSUInteger)num withPercent:(float)percent; - (void) restartAppAfterDeleteAllAccounts; -- (void) showLoginView; - -- (void)doLoginWithOauthToken; //Method that erase the data of the detail view in iPad. - (void)presentWithView; @@ -258,7 +255,7 @@ extern NSString * NotReachableNetworkForDownloadsNotification; * for a specific user * */ -- (void) cancelTheCurrentUploadsWithTheSameUserId:(NSInteger)idUser; +- (void) cancelTheCurrentUploadsWithTheSameUserId:(NSInteger)userId; ///----------------------------------- /// @name Cancel the Currents Uploads @@ -271,16 +268,16 @@ extern NSString * NotReachableNetworkForDownloadsNotification; * @param userId -> id of user * */ -- (void) cancelTheCurrentUploadsOfTheUser:(NSInteger)idUser; +- (void) cancelTheCurrentUploadsOfTheUser:(NSInteger)userId; /* * This method is called after that this class receive the notification that the user * has resolved the credentials error. * In this method we changed the kind of error of uploads failed "errorCredentials" to "notAndError" * for a specific user - * @idUser -> idUser for a scpecific user. + * @userId -> userId for a scpecific user. */ -- (void)changeTheStatusOfCredentialsFilesErrorOfAnUserId:(NSInteger)idUser; +- (void)changeTheStatusOfCredentialsFilesErrorOfAnUserId:(NSInteger)userId; ///----------------------------------- @@ -302,19 +299,6 @@ extern NSString * NotReachableNetworkForDownloadsNotification; */ - (void) generateAppInterfaceFromLoginScreen:(BOOL)isFromLogin; -///----------------------------------- -/// @name Check if server support different things -///----------------------------------- - -/** - * This method check if the server support multipple things: - * - If support Share - * - If support Cookies - * - */ -- (void)checkIfServerSupportThings; - - //----------------------------------- /// @name reloadTableFromDataBaseIfFileIsVisibleOnList @@ -337,4 +321,16 @@ extern NSString * NotReachableNetworkForDownloadsNotification; - (void) showPassCodeIfNeeded; + +//--------------------------- +/// @name switchActiveUser +///------------------------- + +/** + * Method that switches the active user to that passed as a parameter + * + * @param user -> UserDto to set as active user + */ +- (void) switchActiveUserTo:(UserDto *) user inHardMode:(BOOL)hardMode withCompletionHandler:(void (^)(void)) completionHandler; + @end diff --git a/Owncloud iOs Client/AppDelegate.m b/Owncloud iOs Client/AppDelegate.m index 550cda4e39..6e5d0cd225 100644 --- a/Owncloud iOs Client/AppDelegate.m +++ b/Owncloud iOs Client/AppDelegate.m @@ -19,12 +19,8 @@ #import "CheckAccessToServer.h" #import "DetailViewController.h" #import "constants.h" -#import "LoginViewController.h" #import "UploadFromOtherAppViewController.h" -#import "AuthenticationDbService.h" -#import "RetrieveRefreshAndAccessTokenTask.h" #import "Download.h" -#import "EditAccountViewController.h" #import "UIColor+Constants.h" #import "Customization.h" #import "FMDatabaseQueue.h" @@ -62,6 +58,8 @@ #import "OCKeychain.h" #import "UtilsCookies.h" #import "PresentedViewUtils.h" +#import "OCLoadingSpinner.h" +#import "OCOAuth2Configuration.h" NSString * CloseAlertViewWhenApplicationDidEnterBackground = @"CloseAlertViewWhenApplicationDidEnterBackground"; NSString * RefreshSharesItemsAfterCheckServerVersion = @"RefreshSharesItemsAfterCheckServerVersion"; @@ -71,7 +69,6 @@ @implementation AppDelegate @synthesize window = _window; -@synthesize loginViewController = _loginViewController; @synthesize uploadArray=_uploadArray; @synthesize webDavArray=_webDavArray; @synthesize recentViewController=_recentViewController; @@ -84,7 +81,6 @@ @implementation AppDelegate @synthesize filePathFromOtherApp=_filePathFromOtherApp; @synthesize isFileFromOtherAppWaitting=_isFileFromOtherAppWaitting; @synthesize isSharedToOwncloudPresent=_isSharedToOwncloudPresent; -@synthesize presentFilesViewController=_presentFilesViewController; @synthesize isRefreshInProgress=_isRefreshInProgress; @synthesize oauthToken = _oauthToken; @synthesize avMoviePlayer=_avMoviePlayer; @@ -155,6 +151,7 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( //Check if the server support shared api [CheckFeaturesSupported updateServerFeaturesAndCapabilitiesOfActiveUser]; + //Needed to use on background tasks if (!k_is_sso_active) { [[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; @@ -187,6 +184,9 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( ((CheckAccessToServer*)[CheckAccessToServer sharedManager]).delegate = self; [[CheckAccessToServer sharedManager] isConnectionToTheServerByUrl:user.url withTimeout:k_timeout_fast]; + ManageAccounts *manageAccounts = [ManageAccounts new]; + [manageAccounts updateDisplayNameOfUserWithUser:self.activeUser]; + //if we are migrating url not relaunch sync if (![UtilsUrls isNecessaryUpdateToPredefinedUrlByPreviousUrl:self.activeUser.predefinedUrl]) { //Update favorites files if there are active user @@ -213,6 +213,14 @@ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:( //Set up user agent, so this way all UIWebView will use it NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[UtilsUrls getUserAgent], @"UserAgent", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary]; + + //Set OAuth2Configuration object + self.oauth2Configuration = [[OCOAuth2Configuration alloc] + initWithClientId:k_oauth2_client_id + clientSecret:k_oauth2_client_secret + redirectUri:k_oauth2_redirect_uri + authorizationEndpoint:k_oauth2_authorization_endpoint + tokenEndpoint:k_oauth2_token_endpoint]; return YES; } @@ -257,80 +265,34 @@ -(void)setUINavigationBarApperanceForNativeMail { -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { - //OAuth - AuthenticationDbService *dbService = [AuthenticationDbService sharedInstance]; - NSString *scheme = [dbService getScheme]; + DLog(@"URL from %@ application", sourceApplication); + DLog(@"the path is: %@", url.path); - if ([[ url scheme] isEqualToString:scheme] ) { - if (dbService.isDebugLogEnabled) { - DLog(@"found %@", scheme); - } - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - NSString *text = [url absoluteString]; - - if ([[ dbService getResponseType] isEqualToString:@"code"]) { - if (dbService.isTraceLogEnabled) { - DLog(@"Response type = code"); - } - NSArray *param_s = [text componentsSeparatedByString:@"?"]; - - if (param_s.count > 1) { - NSString *param_1 = [param_s objectAtIndex:1]; - - NSMutableDictionary *result = [NSMutableDictionary dictionary]; - NSArray *parameters = [param_1 componentsSeparatedByString:@"&"]; - for (NSString *parameter in parameters) - { - NSArray *parts = [parameter componentsSeparatedByString:@"="]; - NSString *key = [[parts objectAtIndex:0] stringByRemovingPercentEncoding]; - if ([parts count] > 1) - { - id value = [[parts objectAtIndex:1] stringByRemovingPercentEncoding]; - [result setObject:value forKey:key]; - } - } - if (dbService.isDebugLogEnabled) { - DLog(@"code = %@", [result objectForKey:@"code"]); - self.oauthToken = [result objectForKey:@"code"]; - } - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - [dbService setAuthorizationCode:[result objectForKey:@"code"]]; - - RetrieveRefreshAndAccessTokenTask *task = [[RetrieveRefreshAndAccessTokenTask alloc] init]; - [task executeRetrieveTask]; - } - } - } else { - DLog(@"URL from %@ application", sourceApplication); - DLog(@"the path is: %@", url.path); - - - //Create File Path - NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"]; - NSString *fileName = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]]; - NSString *filePath; - - //We have a bug on iOS8 that can not upload a file on background from Documents/Inbox. So we move the file to the getTempFolderForUploadFiles - [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:fileName] toPath:[[UtilsUrls getTempFolderForUploadFiles] stringByAppendingPathComponent:fileName] error:nil]; - - filePath = [[UtilsUrls getTempFolderForUploadFiles] stringByAppendingPathComponent:fileName]; - - _filePathFromOtherApp=filePath; - - DLog(@"File path: %@", filePath); - - if (_activeUser.username==nil) { - _activeUser = [ManageUsersDB getActiveUser]; - } - - //_firstInit don't works yet - if (_activeUser.username==nil || [ManageAppSettingsDB isPasscode] || _isLoadingVisible==YES) { - //Deleta file - //[[NSFileManager defaultManager] removeItemAtPath: filePath error: nil]; - _isFileFromOtherAppWaitting=YES; - }else{ - [self performSelector:@selector(presentUploadFromOtherApp) withObject:nil afterDelay:halfASecondDelay]; - } + //Create File Path + NSArray *splitedUrl = [url.path componentsSeparatedByString:@"/"]; + NSString *fileName = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-1)]]; + NSString *filePath; + + //We have a bug on iOS8 that can not upload a file on background from Documents/Inbox. So we move the file to the getTempFolderForUploadFiles + [[NSFileManager defaultManager]moveItemAtPath:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Inbox"] stringByAppendingPathComponent:fileName] toPath:[[UtilsUrls getTempFolderForUploadFiles] stringByAppendingPathComponent:fileName] error:nil]; + + filePath = [[UtilsUrls getTempFolderForUploadFiles] stringByAppendingPathComponent:fileName]; + + _filePathFromOtherApp=filePath; + + DLog(@"File path: %@", filePath); + + if (_activeUser.credDto.userName==nil) { + _activeUser = [ManageUsersDB getActiveUser]; + } + + //_firstInit don't works yet + if (_activeUser.username==nil || [ManageAppSettingsDB isPasscode] || _isLoadingVisible==YES) { + //Deleta file + //[[NSFileManager defaultManager] removeItemAtPath: filePath error: nil]; + _isFileFromOtherAppWaitting=YES; + }else{ + [self performSelector:@selector(presentUploadFromOtherApp) withObject:nil afterDelay:halfASecondDelay]; } return YES; @@ -378,17 +340,13 @@ - (void) initAppWithEtagRequest:(BOOL)isEtagRequestNecessary { [DownloadUtils setThePermissionsForFolderPath:localTempPath]; //First Call when init the app - self.activeUser = [ManageUsersDB getActiveUserWithoutUserNameAndPassword]; + self.activeUser = [ManageUsersDB getActiveUserWithoutCredentials]; //if is null we do not have any active user on the database if(!self.activeUser) { - self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; - - self.loginViewController = [[LoginViewController alloc] initWithLoginMode:LoginModeCreate]; - - self.window.rootViewController = self.loginViewController; - [self.window makeKeyAndVisible]; + //Show new universal login view + [self showLoginView:[UtilsLogin getLoginVCWithMode:LoginModeCreate andUser:nil]]; } else { @@ -407,35 +365,6 @@ - (void) initAppWithEtagRequest:(BOOL)isEtagRequestNecessary { } } -- (void) doLoginWithOauthToken { - - if (_activeUser.username==nil) { - _activeUser=[ManageUsersDB getActiveUser]; - } - - if(_activeUser.idUser > 0) { - _activeUser.password = self.oauthToken; - - //update keychain user - if(![OCKeychain updateCredentialsById:[NSString stringWithFormat:@"%ld", (long)_activeUser.idUser] withUsername:_activeUser.username andPassword:_activeUser.password]) { - DLog(@"Error updating credentials of userId:%ld on keychain",(long)_activeUser.idUser); - } - - [UtilsCookies eraseCredentialsAndUrlCacheOfActiveUser]; - - [self initAppWithEtagRequest:NO]; - } else { - self.loginViewController.usernameTextField = [[UITextField alloc] init]; - self.loginViewController.usernameTextField.text = @"OAuth"; - - self.loginViewController.passwordTextField = [[UITextField alloc] init]; - self.loginViewController.passwordTextField.text = self.oauthToken; - - [self.loginViewController goTryToDoLogin]; - } - -} - - (void) restartAppAfterDeleteAllAccounts { DLog(@"Restart After Delete All Accounts"); @@ -445,34 +374,13 @@ - (void) restartAppAfterDeleteAllAccounts { _filesViewController.alert = nil; } - self.loginWindowViewController = [[LoginViewController alloc] initWithLoginMode:LoginModeCreate]; - - self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; - - self.window.rootViewController = self.loginWindowViewController; - [self.window makeKeyAndVisible]; + [self showLoginView:[UtilsLogin getLoginVCWithMode:LoginModeCreate andUser:nil]]; } -///----------------------------------- -/// @name Generate App Interface -///----------------------------------- -/** - * This method generate the app interface - * - * For iPhone: - * - TabBarController with three items: - * - File list - * - Recents view - * - Settings view - * For iPad: - * - The same TabBarController with three items. - * - Detail View. - * - */ - (void) generateAppInterfaceFromLoginScreen:(BOOL)isFromLogin{ - self.activeUser = [ManageUsersDB getActiveUserWithoutUserNameAndPassword]; + self.activeUser = [ManageUsersDB getActiveUserWithoutCredentials]; NSString *wevDavString = [UtilsUrls getFullRemoteServerPathWithWebDav:_activeUser]; NSString *localSystemPath = nil; @@ -480,7 +388,7 @@ - (void) generateAppInterfaceFromLoginScreen:(BOOL)isFromLogin{ //Check if we generate the interface from login screen or not if (isFromLogin) { //From login screen we create the user folder to haver multiuser - localSystemPath = [NSString stringWithFormat:@"%@%ld/",[UtilsUrls getOwnCloudFilePath],(long)_activeUser.idUser]; + localSystemPath = [NSString stringWithFormat:@"%@%ld/",[UtilsUrls getOwnCloudFilePath],(long)_activeUser.userId]; //DLog(@"current: %@", localSystemPath); //If not exist we create @@ -492,7 +400,7 @@ - (void) generateAppInterfaceFromLoginScreen:(BOOL)isFromLogin{ } else { //We get the current folder to create the local tree - localSystemPath = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath],(long)_activeUser.idUser]; + localSystemPath = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath],(long)_activeUser.userId]; //DLog(@"localRootUrlString: %@", localSystemPath); } @@ -679,9 +587,23 @@ + (OCCommunication*)sharedOCCommunication sharedOCCommunication = [[OCCommunication alloc] initWithUploadSessionManager:uploadSessionManager andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:networkSessionManager]; //Cookies is allways available in current supported Servers - sharedOCCommunication.isCookiesAvailable = YES; - - } + [sharedOCCommunication setIsCookiesAvailable:YES]; + + [sharedOCCommunication setOauth2Configuration: [[OCOAuth2Configuration alloc] + initWithClientId:k_oauth2_client_id + clientSecret:k_oauth2_client_secret + redirectUri:k_oauth2_redirect_uri + authorizationEndpoint:k_oauth2_authorization_endpoint + tokenEndpoint:k_oauth2_token_endpoint]]; + + [sharedOCCommunication setUserAgent:[UtilsUrls getUserAgent]]; + + OCKeychain *oKeychain = [[OCKeychain alloc] init]; + [sharedOCCommunication setValueCredentialsStorage:oKeychain]; + + SSLCertificateManager *sslCertificateManager = [[SSLCertificateManager alloc] init]; + [sharedOCCommunication setValueTrustedCertificatesStore: sslCertificateManager]; + } return sharedOCCommunication; } @@ -707,8 +629,23 @@ + (OCCommunication*)sharedOCCommunicationDownloadFolder { sharedOCCommunicationDownloadFolder = [[OCCommunication alloc] initWithUploadSessionManager:nil andDownloadSessionManager:downloadSessionManager andNetworkSessionManager:nil]; //Cookies is allways available in current supported Servers - sharedOCCommunicationDownloadFolder.isCookiesAvailable = YES; + [sharedOCCommunicationDownloadFolder setIsCookiesAvailable:YES]; + + [sharedOCCommunicationDownloadFolder setOauth2Configuration: [[OCOAuth2Configuration alloc] + initWithClientId:k_oauth2_client_id + clientSecret:k_oauth2_client_secret + redirectUri:k_oauth2_redirect_uri + authorizationEndpoint:k_oauth2_authorization_endpoint + tokenEndpoint:k_oauth2_token_endpoint]]; + + [sharedOCCommunicationDownloadFolder setUserAgent:[UtilsUrls getUserAgent]]; + OCKeychain *oKeychain = [[OCKeychain alloc] init]; + [sharedOCCommunicationDownloadFolder setValueCredentialsStorage:oKeychain]; + + SSLCertificateManager *sslCertificateManager = [[SSLCertificateManager alloc] init]; + [sharedOCCommunicationDownloadFolder setValueTrustedCertificatesStore:sslCertificateManager]; + } return sharedOCCommunicationDownloadFolder; } @@ -744,7 +681,7 @@ + (ManageFavorites*)sharedManageFavorites { - (void) launchProcessToSyncAllFavorites { //Do operations in background thread - [[AppDelegate sharedManageFavorites] syncAllFavoritesOfUser:self.activeUser.idUser]; + [[AppDelegate sharedManageFavorites] syncAllFavoritesOfUser:self.activeUser.userId]; } @@ -1104,7 +1041,7 @@ - (void) restoreUploadsInProccessFromSystemWithIdentificator: (NSString*)identif //Set uploadOffline currentManageUploadRequest.currentUpload = uploadDB; currentManageUploadRequest.lenghtOfFile = [UploadUtils makeLengthString:uploadDB.estimateLength]; - currentManageUploadRequest.userUploading = [ManageUsersDB getUserByIdUser:uploadDB.userId]; + currentManageUploadRequest.userUploading = [ManageUsersDB getUserByUserId:uploadDB.userId]; currentManageUploadRequest.pathOfUpload = [UtilsUrls getPathWithAppNameByDestinyPath:uploadDB.destinyFolder andUser:currentManageUploadRequest.userUploading]; @@ -1245,7 +1182,7 @@ - (void) restoreDownloadsInProccessFromSystemWithIdentificator: (NSString*)ident //Local folder NSString *localFolder = nil; - localFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath], (long)self.activeUser.idUser, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:file.filePath andUser:self.activeUser]]; + localFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath], (long)self.activeUser.userId, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:file.filePath andUser:self.activeUser]]; localFolder = [localFolder stringByRemovingPercentEncoding]; download.currentLocalFolder = localFolder; @@ -1928,7 +1865,7 @@ - (void)itemToUploadFromOtherAppWithName:(NSString*)name andPathName:(NSString*) currentUpload.uploadFileName = name; currentUpload.kindOfError = notAnError; currentUpload.estimateLength = (long)fileLength; - currentUpload.userId = _activeUser.idUser; + currentUpload.userId = _activeUser.userId; currentUpload.isLastUploadFileOfThisArray = YES; currentUpload.status = waitingAddToUploadList; currentUpload.chunksLength = k_lenght_chunk; @@ -1998,23 +1935,13 @@ - (void)errorWhileUpload{ - (void) errorLogin { - [self performSelector:@selector(delayLoadEditAccountAfterErroLogin) withObject:nil afterDelay:0.1]; + [self performSelector:@selector(delayLoadEditAccountAfterErrorLogin) withObject:nil afterDelay:0.1]; } --(void) delayLoadEditAccountAfterErroLogin { +-(void) delayLoadEditAccountAfterErrorLogin { - EditAccountViewController *viewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:_activeUser andLoginMode:LoginModeExpire]; - - if (IS_IPHONE) - { - OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController]; - [_ocTabBarController presentViewController:navController animated:YES completion:nil]; - } else { - - OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController]; - navController.modalPresentationStyle = UIModalPresentationFormSheet; - [self.splitViewController presentViewController:navController animated:YES completion:nil]; - } + [self showLoginView:[UtilsLogin getLoginVCWithMode:LoginModeExpire andUser:self.activeUser]]; + } @@ -2061,13 +1988,13 @@ -(void) moveIfIsNecessaryFilesAfterUpdateAppFromTheOldFolderArchitecture { * for a specific user * */ -- (void) cancelTheCurrentUploadsWithTheSameUserId:(NSInteger)idUser{ +- (void) cancelTheCurrentUploadsWithTheSameUserId:(NSInteger)userId{ __block ManageUploadRequest *currentManageUploadRequest = nil; //__block BOOL shouldBeContinue=NO; - DLog(@"id user: %ld", (long)idUser); + DLog(@"id user: %ld", (long)userId); NSArray *currentUploadsTemp = [NSArray arrayWithArray:_uploadArray]; @@ -2079,7 +2006,7 @@ - (void) cancelTheCurrentUploadsWithTheSameUserId:(NSInteger)idUser{ if (currentManageUploadRequest.currentUpload.status == waitingForUpload || currentManageUploadRequest.currentUpload.status == uploading) { DLog(@"this upload is waiting for upload"); - if (currentManageUploadRequest.currentUpload.userId == idUser) { + if (currentManageUploadRequest.currentUpload.userId == userId) { //change the credentiasl [currentManageUploadRequest changeTheStatusToFailForCredentials]; DLog(@"%@ its change to fail", currentManageUploadRequest.currentUpload.originPath); @@ -2351,7 +2278,7 @@ - (void) createAManageRequestUploadWithTheUploadOffline: (UploadsOfflineDto*) cu //Set uploadOffline currentManageUploadRequest.currentUpload = currentUploadBackground; currentManageUploadRequest.lenghtOfFile = [UploadUtils makeLengthString:currentUploadBackground.estimateLength]; - currentManageUploadRequest.userUploading = [ManageUsersDB getUserByIdUser:currentUploadBackground.userId]; + currentManageUploadRequest.userUploading = [ManageUsersDB getUserByUserId:currentUploadBackground.userId]; currentManageUploadRequest.pathOfUpload = [UtilsUrls getPathWithAppNameByDestinyPath:currentUploadBackground.destinyFolder andUser:currentManageUploadRequest.userUploading]; @@ -2411,7 +2338,7 @@ - (void) addFinishedUploadsOfflineDataToUploadsArray{ //Set uploadOffline currentManageUploadRequest.currentUpload = current; currentManageUploadRequest.lenghtOfFile = [UploadUtils makeLengthString:current.estimateLength]; - currentManageUploadRequest.userUploading = [ManageUsersDB getUserByIdUser:current.userId]; + currentManageUploadRequest.userUploading = [ManageUsersDB getUserByUserId:current.userId]; currentManageUploadRequest.pathOfUpload = [UtilsUrls getPathWithAppNameByDestinyPath:current.destinyFolder andUser:currentManageUploadRequest.userUploading]; @@ -2443,7 +2370,7 @@ - (void) addErrorUploadsToRecentsTab { //Set uploadOffline currentManageUploadRequest.currentUpload = uploadOffline; currentManageUploadRequest.lenghtOfFile = [UploadUtils makeLengthString:uploadOffline.estimateLength]; - currentManageUploadRequest.userUploading = [ManageUsersDB getUserByIdUser:uploadOffline.userId]; + currentManageUploadRequest.userUploading = [ManageUsersDB getUserByUserId:uploadOffline.userId]; currentManageUploadRequest.pathOfUpload = [UtilsUrls getPathWithAppNameByDestinyPath:uploadOffline.destinyFolder andUser:currentManageUploadRequest.userUploading]; @@ -2470,7 +2397,7 @@ - (void) addPendingToCheckUploadsToRecentsTab { //Set uploadOffline currentManageUploadRequest.currentUpload = uploadOffline; currentManageUploadRequest.lenghtOfFile = [UploadUtils makeLengthString:uploadOffline.estimateLength]; - currentManageUploadRequest.userUploading = [ManageUsersDB getUserByIdUser:uploadOffline.userId]; + currentManageUploadRequest.userUploading = [ManageUsersDB getUserByUserId:uploadOffline.userId]; currentManageUploadRequest.pathOfUpload = [UtilsUrls getPathWithAppNameByDestinyPath:uploadOffline.destinyFolder andUser:currentManageUploadRequest.userUploading]; @@ -2615,7 +2542,7 @@ - (void) removeFromTabRecentsAllInfoByUser:(UserDto *)user { ManageUploadRequest *current = [_uploadArray objectAtIndex:i]; - if (current.currentUpload.userId == user.idUser) { + if (current.currentUpload.userId == user.userId) { [arrayOfPositionsToDelete addObject:[NSNumber numberWithInt:i]]; } } @@ -2641,7 +2568,7 @@ - (void) removeFromTabRecentsAllInfoByUser:(UserDto *)user { * @param userId -> id of user * */ -- (void) cancelTheCurrentUploadsOfTheUser:(NSInteger)idUser{ +- (void) cancelTheCurrentUploadsOfTheUser:(NSInteger)userId{ //Check the currents uploads from a user NSArray *uploadsArray = [NSArray arrayWithArray:_uploadArray]; @@ -2652,7 +2579,7 @@ - (void) cancelTheCurrentUploadsOfTheUser:(NSInteger)idUser{ currentManageUploadRequest=obj; - if (currentManageUploadRequest.currentUpload.kindOfError == notAnError && currentManageUploadRequest.currentUpload.status != uploaded && currentManageUploadRequest.currentUpload.userId == idUser) { + if (currentManageUploadRequest.currentUpload.kindOfError == notAnError && currentManageUploadRequest.currentUpload.status != uploaded && currentManageUploadRequest.currentUpload.userId == userId) { //Indicate Error Credentials [currentManageUploadRequest changeTheStatusToFailForCredentials]; } @@ -2670,12 +2597,12 @@ - (void) cancelTheCurrentUploadsOfTheUser:(NSInteger)idUser{ * In this method we changed the kind of error of uploads failed "errorCredentials" to "notAndError" * for a specific user * - * @param idUser -> idUser for a scpecific user. + * @param userId -> userId for a scpecific user. * * @discussion Maybe could be better move this kind of method to a singleton class inicializate in appDelegate. * */ -- (void)changeTheStatusOfCredentialsFilesErrorOfAnUserId:(NSInteger)idUser{ +- (void)changeTheStatusOfCredentialsFilesErrorOfAnUserId:(NSInteger)userId{ __block ManageUploadRequest *currentManageUploadRequest; @@ -2684,7 +2611,7 @@ - (void)changeTheStatusOfCredentialsFilesErrorOfAnUserId:(NSInteger)idUser{ [failedUploadsTemp enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { currentManageUploadRequest = obj; - if (currentManageUploadRequest.currentUpload.kindOfError == errorCredentials && currentManageUploadRequest.currentUpload.userId == idUser) { + if (currentManageUploadRequest.currentUpload.kindOfError == errorCredentials && currentManageUploadRequest.currentUpload.userId == userId) { DLog(@"ub with name %@ not an error", currentManageUploadRequest.currentUpload.uploadFileName); currentManageUploadRequest.currentUpload.kindOfError=notAnError; [ManageUploadsDB setStatus:currentManageUploadRequest.currentUpload.status andKindOfError:notAnError byUploadOffline:currentManageUploadRequest.currentUpload]; @@ -2808,17 +2735,22 @@ -(void)reloadCellByKey:(NSString *)key{ FileDto *folderRemoved = [ManageFilesDB getFileDtoByFileName:[folderToRemoveName encodeString:NSUTF8StringEncoding] andFilePath:[folderToRemovePath encodeString:NSUTF8StringEncoding] andUser:app.activeUser]; [self reloadCellByFile:folderRemoved]; } -- (void) showLoginView { - DLog(@"ShowLoginView"); - - self.loginWindowViewController = [[LoginViewController alloc] initWithLoginMode:LoginModeCreate]; + + + +- (void)showLoginView:(UniversalLoginViewController *)loginView { + DLog(@"ShowUniversalLoginView in window root vc"); self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; - self.window.rootViewController = self.loginWindowViewController; + self.window.rootViewController = loginView; + [self.window makeKeyAndVisible]; + } + + #pragma mark - SplashScreenFake - (void) showSplashScreenFake { @@ -2836,17 +2768,85 @@ - (void) showSplashScreenFake { #pragma mark - CheckAccessToServerDelegate --(void)connectionToTheServer:(BOOL)isConnection { - ((CheckAccessToServer*)[CheckAccessToServer sharedManager]).delegate = nil; - [self showPassCodeIfNeeded]; +-(void)connectionToTheServerWasChecked:(BOOL)isConnected withHttpStatusCode:(NSInteger)statusCode andError:(NSError *)error { + [self repeatTheCheckToTheServer]; } -(void)repeatTheCheckToTheServer { ((CheckAccessToServer*)[CheckAccessToServer sharedManager]).delegate = nil; [self showPassCodeIfNeeded]; } --(void)badCertificateNoAcceptedByUser { - ((CheckAccessToServer*)[CheckAccessToServer sharedManager]).delegate = nil; - [self showPassCodeIfNeeded]; +-(void)badCertificateNotAcceptedByUser { + [self repeatTheCheckToTheServer]; +} + + +#pragma mark - Active User + +- (void) switchActiveUserTo:(UserDto *)user inHardMode:(BOOL)hardMode withCompletionHandler:(void (^)(void)) completionHandler { + + // all the switch is performed in background, without blocking the caller thread, that should be main + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ + + self.userSessionCurrentToken = nil; + // should be here or right after checking the user really changed? for the moment, here + + if (self.activeUser.userId != user.userId || hardMode) { + + //We delete the cookies on SAML + if (k_is_sso_active) { + [UtilsCookies eraseCredentialsAndUrlCacheOfActiveUser]; + } + + // Cancel downloads of the previous user, in the same background thread + [self portedCancelAllDownloads]; + + // update active state of users in DB + [ManageUsersDB setAllUsersNoActive]; + [ManageUsersDB setActiveAccountByUserId:user.userId]; + user.activeaccount = YES; + + //Restore the cookies of the future activeUser + //1- Store the new cookies on the Database + [UtilsCookies setOnDBStorageCookiesByUser:self.activeUser]; + //2- Clean the cookies storage + [UtilsFramework deleteAllCookies]; + //3- We restore the previous cookies of the active user on the System cookies storage + [UtilsCookies setOnSystemStorageCookiesByUser:user]; + //4- We delete the cookies of the active user on the database because it could change and it is not necessary keep them there + [ManageCookiesStorageDB deleteCookiesByUser:user]; + + //Change the active user in appDelegate global variable + self.activeUser = user; + + [CheckFeaturesSupported updateServerFeaturesAndCapabilitiesOfActiveUser]; + + [UtilsCookies eraseURLCache]; + + //we create the user folder to haver multiuser + [UtilsFileSystem createFolderForUser:APP_DELEGATE.activeUser]; + + self.isNewUser = YES; + + ManageAccounts *manageAccounts = [ManageAccounts new]; + [manageAccounts updateDisplayNameOfUserWithUser:self.activeUser]; + } + + // completion handler is called in main thread + dispatch_async(dispatch_get_main_queue(), ^{ + if (completionHandler) { + completionHandler(); + } + }); + }); } + +- (void) portedCancelAllDownloads { + //Cancel downloads in ipad + [self.downloadManager cancelDownloads]; + + [[AppDelegate sharedSyncFolderManager] cancelAllDownloads]; +} + + @end diff --git a/Owncloud iOs Client/Branding/Customization.h b/Owncloud iOs Client/Branding/Customization.h index 780ffa19aa..c5272cca93 100644 --- a/Owncloud iOs Client/Branding/Customization.h +++ b/Owncloud iOs Client/Branding/Customization.h @@ -6,7 +6,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -40,13 +40,10 @@ //Have image background on navigation bar #define k_have_image_background_navigation_bar NO -//Have oauth active -#define k_is_oauth_active NO - //Have SAML active #define k_is_sso_active NO -//OAuth server +//OAuth server //not use, use Oauth2 instead #define k_oauth_login @"" #define k_oauth_authorize @"" #define k_oauth_token @"" @@ -157,3 +154,23 @@ //Force passcode #define k_is_passcode_forced NO +//Oauth2 +#define k_oauth2_authorization_endpoint @"index.php/apps/oauth2/authorize" +#define k_oauth2_token_endpoint @"index.php/apps/oauth2/api/v1/token" +#define k_oauth2_redirect_uri @"oc://ios.owncloud.com" +#define k_oauth2_client_id @"mxd5OQDk6es5LzOzRvidJNfXLUZS2oN3oUFeXPP8LpPrhx3UroJFduGEYIBOxkY1" +#define k_oauth2_client_secret @"KFeFWWEZO9TkisIQzR3fo7hfiMXlOpaqP8CFuTbSHzV1TUuGECglPxpiVKJfOXIx" + + + +//Following getters required to Bridging with Swift +@interface Customization : NSObject + ++(BOOL)kHideUrlServer; ++(BOOL)kForceUpdateOfServerUrl; ++(BOOL)kMultiaccountAvailable; ++(BOOL)kIsSsoActive; ++(BOOL)kIsTextLoginStatusBarWhite; ++(BOOL)kIsShownHelpLinkOnLogin; + +@end diff --git a/Owncloud iOs Client/Branding/Customization.m b/Owncloud iOs Client/Branding/Customization.m new file mode 100644 index 0000000000..3fc6804f37 --- /dev/null +++ b/Owncloud iOs Client/Branding/Customization.m @@ -0,0 +1,49 @@ +// +// Customization.m +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 03/07/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +#import "Customization.h" + +@implementation Customization + +//Add all boolean constants to use in swift classes + ++(BOOL)kHideUrlServer { + return k_hide_url_server; +} + ++(BOOL)kForceUpdateOfServerUrl { + return k_force_update_of_server_url; +} + ++(BOOL)kMultiaccountAvailable { + return k_multiaccount_available; +} + ++(BOOL)kIsSsoActive { + return k_is_sso_active; +} + ++(BOOL)kIsTextLoginStatusBarWhite { + return k_is_text_login_status_bar_white; +} + ++(BOOL)kIsShownHelpLinkOnLogin { + return k_is_shown_help_link_on_login; +} + + +@end + diff --git a/Owncloud iOs Client/Branding/UIColor+Constants.h b/Owncloud iOs Client/Branding/UIColor+Constants.h index 52325fcecb..b0bb4a7589 100644 --- a/Owncloud iOs Client/Branding/UIColor+Constants.h +++ b/Owncloud iOs Client/Branding/UIColor+Constants.h @@ -60,7 +60,7 @@ + (UIColor*)colorOfLoginBackground; //Text color of url in login view + (UIColor*)colorOfURLUserPassword; -//Text color of login text +//Text color of login text, used in Help Guide texts + (UIColor*)colorOfLoginText ; //Text color of error credentials + (UIColor*)colorOfLoginErrorText; @@ -71,14 +71,12 @@ //Text color of the text of the login button +(UIColor *)colorOfLoginButtonTextColor; + //FILE LIST -//Text color of selected folder -+ (UIColor*)colorOfTxtSelectFolderToolbar; -//Section index color +//Section index color, Color of the letter separators shown when there are more than 20 files. + (UIColor*)colorOfSectionIndexColorFileList; -//Header section index color -+ (UIColor*)colorOfHeaderTableSectionFileList; + //WEB VIEW diff --git a/Owncloud iOs Client/Branding/UIColor+Constants.m b/Owncloud iOs Client/Branding/UIColor+Constants.m index 8f9e7a855b..a845c8d973 100644 --- a/Owncloud iOs Client/Branding/UIColor+Constants.m +++ b/Owncloud iOs Client/Branding/UIColor+Constants.m @@ -96,7 +96,7 @@ +(UIColor*)colorOfTextButtonOnList { //Background color of login view + (UIColor*)colorOfLoginBackground{ - return [UIColor colorWithRed:245/255.0f green:245/255.0f blue:241/255.0f alpha:1.0f]; + return [UIColor colorWithRed:255/255.0f green:255/255.0f blue:255/255.0f alpha:1.0f]; } //Text color of url in login view @@ -133,20 +133,11 @@ +(UIColor *)colorOfLoginButtonTextColor{ //FILE LIST -//Text color of selected folder -+ (UIColor*)colorOfTxtSelectFolderToolbar { - return [UIColor whiteColor]; -} - -//Section index color +//Section index color, Color of the letter separators shown when there are more than 20 files. + (UIColor*)colorOfSectionIndexColorFileList { return [UIColor colorWithRed:28/255.0f green:44/255.0f blue:67/255.0f alpha:0.7f]; } -//Header section index color -+ (UIColor*)colorOfHeaderTableSectionFileList { - return [UIColor colorWithRed:248/255.0f green:248/255.0f blue:248/255.0f alpha:0.85f]; -} //WEB VIEW diff --git a/Owncloud iOs Client/DataBase/DTOs/CredentialsDto.m b/Owncloud iOs Client/DataBase/DTOs/CredentialsDto.m deleted file mode 100644 index 099f65ceb0..0000000000 --- a/Owncloud iOs Client/DataBase/DTOs/CredentialsDto.m +++ /dev/null @@ -1,21 +0,0 @@ -// -// CredentialsDto.m -// Owncloud iOs Client -// -// Created by Noelia Alvarez on 27/10/14. -// - -/* - Copyright (C) 2016, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ - -#import "CredentialsDto.h" - -@implementation CredentialsDto - - -@end diff --git a/Owncloud iOs Client/DataBase/DTOs/UserDto.h b/Owncloud iOs Client/DataBase/DTOs/UserDto.h index 72789790a2..150448ef15 100644 --- a/Owncloud iOs Client/DataBase/DTOs/UserDto.h +++ b/Owncloud iOs Client/DataBase/DTOs/UserDto.h @@ -6,7 +6,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -14,25 +14,26 @@ */ #import "OCCapabilities.h" +#import "OCCredentialsDto.h" -typedef enum { +typedef NS_ENUM(NSInteger, enumHasShareApiSupport) { serverFunctionalityNotChecked = 0, - serverFunctionalitySupported =1 , + serverFunctionalitySupported = 1, serverFunctionalityNotSupported = 2 - -} enumHasShareApiSupport; +}; -typedef enum { +typedef NS_ENUM(NSInteger, enumSortingType) { sortByName = 0, - sortByModificationDate = 1 -} enumSortingType; + sortByModificationDate = 1, +}; -@interface UserDto : NSObject +@interface UserDto : NSObject -@property NSInteger idUser; +@property NSInteger userId; @property (nonatomic, copy) NSString *url; @property (nonatomic, copy) NSString *username; -@property (nonatomic, copy) NSString *password; +@property (nonatomic, copy) OCCredentialsDto *credDto; + @property BOOL ssl; @property BOOL activeaccount; @property long storageOccupied; @@ -57,4 +58,11 @@ typedef enum { @property enumSortingType sortingType; @property (nonatomic, copy) NSString *predefinedUrl; + +- (void)encodeWithCoder:(NSCoder *)aCoder; +- (id)initWithCoder:(NSCoder *)aDecoder; + +- (NSString *) nameToDisplay; + + @end diff --git a/Owncloud iOs Client/DataBase/DTOs/UserDto.m b/Owncloud iOs Client/DataBase/DTOs/UserDto.m index a35d7a5c4a..8cf4235b81 100644 --- a/Owncloud iOs Client/DataBase/DTOs/UserDto.m +++ b/Owncloud iOs Client/DataBase/DTOs/UserDto.m @@ -6,7 +6,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -17,4 +17,124 @@ @implementation UserDto +#pragma mark - NSCopying + +-(id) copyWithZone:(NSZone *)zone { + UserDto *userCopy = [[UserDto alloc]init]; + userCopy.userId = self.userId; + userCopy.url = self.url; + userCopy.username = self.username; + userCopy.credDto = self.credDto; + userCopy.ssl = self.ssl; + userCopy.activeaccount = self.activeaccount; + userCopy.storageOccupied = self.storageOccupied; + userCopy.storage = self.storage; + userCopy.hasShareApiSupport = self.hasShareApiSupport; + userCopy.hasShareeApiSupport = self.hasShareeApiSupport; + userCopy.hasCookiesSupport = self.hasCookiesSupport; + userCopy.hasForbiddenCharactersSupport = self.hasForbiddenCharactersSupport; + userCopy.hasCapabilitiesSupport = self.hasCapabilitiesSupport; + userCopy.hasFedSharesOptionShareSupport = self.hasFedSharesOptionShareSupport; + userCopy.hasPublicShareLinkOptionNameSupport = self.hasPublicShareLinkOptionNameSupport; + userCopy.hasPublicShareLinkOptionUploadOnlySupport = self.hasPublicShareLinkOptionUploadOnlySupport; + userCopy.imageInstantUpload = self.imageInstantUpload; + userCopy.videoInstantUpload = self.videoInstantUpload; + userCopy.backgroundInstantUpload = self.backgroundInstantUpload; + userCopy.pathInstantUpload = self.pathInstantUpload; + userCopy.onlyWifiInstantUpload = self.onlyWifiInstantUpload; + userCopy.timestampInstantUploadImage = self.timestampInstantUploadImage; + userCopy.timestampInstantUploadImage = self.timestampInstantUploadVideo; + userCopy.urlRedirected = self.urlRedirected; + userCopy.capabilitiesDto = self.capabilitiesDto; + userCopy.sortingType = self.sortingType; + userCopy.predefinedUrl = self.predefinedUrl; + + return userCopy; +} + +#pragma mark - NSSecureCoding + ++ (BOOL)supportsSecureCoding { + return YES; +} + +- (void)encodeWithCoder:(NSCoder *)coder +{ + [coder encodeInteger:self.userId forKey:@"userId"]; + [coder encodeObject:self.url forKey:@"url"]; + [coder encodeObject:self.username forKey:@"username"]; + [coder encodeObject:self.credDto forKey:@"credDto"]; + [coder encodeBool:self.ssl forKey:@"ssl"]; + [coder encodeBool:self.activeaccount forKey:@"activeaccount"]; + [coder encodeDouble:self.storageOccupied forKey:@"storageOccupied"]; + [coder encodeDouble:self.storage forKey:@"storage"]; + [coder encodeInteger:self.hasShareApiSupport forKey:@"hasShareApiSupport"]; + [coder encodeInteger:self.hasShareeApiSupport forKey:@"hasShareeApiSupport"]; + [coder encodeInteger:self.hasCookiesSupport forKey:@"hasCookiesSupport"]; + [coder encodeInteger:self.hasForbiddenCharactersSupport forKey:@"hasForbiddenCharactersSupport"]; + [coder encodeInteger:self.hasCapabilitiesSupport forKey:@"hasCapabilitiesSupport"]; + [coder encodeInteger:self.hasFedSharesOptionShareSupport forKey:@"hasFedSharesOptionShareSupport"]; + [coder encodeInteger:self.hasPublicShareLinkOptionNameSupport forKey:@"hasPublicShareLinkOptionNameSupport"]; + [coder encodeInteger:self.hasPublicShareLinkOptionUploadOnlySupport forKey:@"hasPublicShareLinkOptionUploadOnlySupport"]; + [coder encodeBool:self.imageInstantUpload forKey:@"imageInstantUpload"]; + [coder encodeBool:self.videoInstantUpload forKey:@"videoInstantUpload"]; + [coder encodeBool:self.backgroundInstantUpload forKey:@"backgroundInstantUpload"]; + [coder encodeObject:self.pathInstantUpload forKey:@"pathInstantUpload"]; + [coder encodeBool:self.onlyWifiInstantUpload forKey:@"onlyWifiInstantUpload"]; + [coder encodeDouble:self.timestampInstantUploadImage forKey:@"timestampInstantUploadImage"]; + [coder encodeDouble:self.timestampInstantUploadVideo forKey:@"timestampInstantUploadVideo"]; + [coder encodeObject:self.urlRedirected forKey:@"urlRedirected"]; + [coder encodeObject:self.capabilitiesDto forKey:@"capabilitiesDto"]; + [coder encodeInteger:self.sortingType forKey:@"sortingType"]; + [coder encodeObject:self.predefinedUrl forKey:@"predefinedUrl"]; +} + +- (instancetype)initWithCoder:(NSCoder *)decoder +{ + if (self = [super init]) { + self.userId = [decoder decodeIntegerForKey:@"userId"]; + self.url = [decoder decodeObjectForKey:@"url"]; + self.username = [decoder decodeObjectForKey:@"username"]; + self.credDto = [decoder decodeObjectForKey:@"credDto"]; + self.ssl = [decoder decodeBoolForKey:@"sll"]; + self.activeaccount = [decoder decodeBoolForKey:@"activeaccount"]; + self.storageOccupied = [decoder decodeDoubleForKey:@"storageOccupied"]; + self.storage = [decoder decodeDoubleForKey:@"storage"]; + self.hasShareApiSupport = [decoder decodeIntegerForKey:@"hasShareApiSupport"]; + self.hasShareeApiSupport = [decoder decodeIntegerForKey:@"hasShareeApiSupport"]; + self.hasCookiesSupport = [decoder decodeIntegerForKey:@"hasCookiesSupport"]; + self.hasForbiddenCharactersSupport = [decoder decodeIntegerForKey:@"hasForbiddenCharactersSupport"]; + self.hasCapabilitiesSupport = [decoder decodeIntegerForKey:@"hasCapabilitiesSupport"]; + self.hasFedSharesOptionShareSupport = [decoder decodeIntegerForKey:@"hasFedSharesOptionShareSupport"]; + self.hasPublicShareLinkOptionNameSupport = [decoder decodeIntegerForKey:@"hasPublicShareLinkOptionNameSupport"]; + self.hasPublicShareLinkOptionUploadOnlySupport = [decoder decodeIntegerForKey:@"hasPublicShareLinkOptionUploadOnlySupport"]; + self.imageInstantUpload = [decoder decodeBoolForKey:@"imageInstantUpload"]; + self.videoInstantUpload = [decoder decodeBoolForKey:@"videoInstantUpload"]; + self.backgroundInstantUpload = [decoder decodeBoolForKey:@"backgroundInstantUpload"]; + self.pathInstantUpload = [decoder decodeObjectForKey:@"pathInstantUpload"]; + self.onlyWifiInstantUpload = [decoder decodeBoolForKey:@"onlyWifiInstantUpload"]; + self.timestampInstantUploadImage = [decoder decodeDoubleForKey:@"timestampInstantUploadImage"]; + self.timestampInstantUploadVideo = [decoder decodeDoubleForKey:@"timestampInstantUploadVideo"]; + self.urlRedirected = [decoder decodeObjectForKey:@"urlRedirected"]; + self.capabilitiesDto = [decoder decodeObjectForKey:@"capabilitiesDto"]; + self.sortingType = [decoder decodeIntegerForKey:@"sortingType"]; + self.predefinedUrl = [decoder decodeObjectForKey:@"predefinedUrl"]; + } + return self; +} + + + +- (NSString *) nameToDisplay { + + if (self.credDto.userDisplayName == nil || [self.credDto.userDisplayName isEqualToString:@""]) { + + return self.credDto.userName; + + } else { + + return self.credDto.userDisplayName; + } +} + @end diff --git a/Owncloud iOs Client/DataBase/Queries/InitializeDatabase.m b/Owncloud iOs Client/DataBase/Queries/InitializeDatabase.m index 7e68b30f61..4387c1471b 100644 --- a/Owncloud iOs Client/DataBase/Queries/InitializeDatabase.m +++ b/Owncloud iOs Client/DataBase/Queries/InitializeDatabase.m @@ -15,7 +15,7 @@ */ #import "InitializeDatabase.h" -#import "CredentialsDto.h" +#import "OCCredentialsDto.h" #import "OCKeychain.h" #import "ManageDB.h" #import "ManageFilesDB.h" @@ -44,6 +44,7 @@ #define k_DB_version_19 19 #define k_DB_version_20 20 #define k_DB_version_21 21 +#define k_DB_version_22 22 @implementation InitializeDatabase @@ -57,7 +58,7 @@ @implementation InitializeDatabase + (void) initDataBase { //New version - static int dbVersion = k_DB_version_21; + static int dbVersion = k_DB_version_22; //This method make a new database [ManageDB createDataBase]; @@ -89,7 +90,7 @@ + (void) initDataBase { case k_DB_version_8: [ManageDB updateDBVersion8To9]; case k_DB_version_9: - [ManageDB updateDBVersion9To10]; + [ManageDB updateDBVersion9To10];//Updates in Keychain case k_DB_version_10: [ManageDB updateDBVersion10To11]; case k_DB_version_11: @@ -97,7 +98,7 @@ + (void) initDataBase { case k_DB_version_12: [ManageDB updateDBVersion12To13]; //Update keychain of all the users - [OCKeychain updateAllKeychainsToUseTheLockProperty]; + [OCKeychain updateAllKeychainItemsToUseTheLockProperty];//Updates in Keychain case k_DB_version_13: [ManageDB updateDBVersion13To14]; case k_DB_version_14: @@ -114,6 +115,8 @@ + (void) initDataBase { [ManageDB updateDBVersion19To20]; case k_DB_version_20: [ManageDB updateDBVersion20To21]; + case k_DB_version_21: + [ManageDB updateDBVersion21To22];//Updates in Keychain break; //Insert your migration above this final break. } } diff --git a/Owncloud iOs Client/DataBase/Queries/ManageCookiesStorageDB.m b/Owncloud iOs Client/DataBase/Queries/ManageCookiesStorageDB.m index d73e919f70..5c4ddf1cd4 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageCookiesStorageDB.m +++ b/Owncloud iOs Client/DataBase/Queries/ManageCookiesStorageDB.m @@ -66,7 +66,7 @@ + (NSMutableArray *) getCookiesByUser:(UserDto *) user { [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, cookie, user_id FROM cookies_storage WHERE user_id = ?", [NSNumber numberWithInteger:user.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT id, cookie, user_id FROM cookies_storage WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; while ([rs next]) { @@ -102,7 +102,7 @@ + (void) deleteCookiesByUser:(UserDto *) user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM cookies_storage WHERE user_id = ?", [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM cookies_storage WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error deleting an upload offline"); diff --git a/Owncloud iOs Client/DataBase/Queries/ManageDB.h b/Owncloud iOs Client/DataBase/Queries/ManageDB.h index 797cf98bbb..440252da54 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageDB.h +++ b/Owncloud iOs Client/DataBase/Queries/ManageDB.h @@ -266,5 +266,11 @@ */ + (void) updateDBVersion20To21; +/** + * Changes: + * + * Alter Keychain items to use credentialsDto as value instead password + */ ++ (void) updateDBVersion21To22; @end diff --git a/Owncloud iOs Client/DataBase/Queries/ManageDB.m b/Owncloud iOs Client/DataBase/Queries/ManageDB.m index 59c1ef465a..e83ff78a0d 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageDB.m +++ b/Owncloud iOs Client/DataBase/Queries/ManageDB.m @@ -618,7 +618,7 @@ + (void) updateDBVersion8To9 { /** * Changes: * - * Migrate the current usersname and password stored in users table to the new keychain + * Migrate the current username and password stored in users table to the new keychain * Do a backup of the users table in users_backup table * Remove users table * Create a new users table without username and password @@ -631,8 +631,7 @@ + (void) updateDBVersion9To10{ NSArray *currentUsers = [NSArray arrayWithArray:[ManageUsersDB getAllOldUsersUntilVersion10]]; for (UserDto *user in currentUsers) { - NSString *idString = [NSString stringWithFormat:@"%ld", (long)user.idUser]; - if (![OCKeychain setCredentialsById:idString withUsername:user.username andPassword:user.password]){ + if (![OCKeychain storeCredentialsOfUserFromDBVersion9To10:user]){ DLog(@"Failed setting credentials"); } @@ -1260,4 +1259,14 @@ + (void) updateDBVersion20To21 { } + ++ (void) updateDBVersion21To22 { + + //1.- Migrate the current password stored in keychain + + [OCKeychain updateAllKeychainItemsFromDBVersion21To22ToStoreCredentialsDtoAsValueAndAuthenticationType]; + +} + + @end diff --git a/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.h b/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.h index 425b3a3905..d1535ff59f 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.h +++ b/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.h @@ -94,9 +94,10 @@ /* * Method to insert all the files of a folder * @listOfFiles -> List of all the files - * @fileId -> id of the folder father + * @fileId -> id of its parent folder + * @user -> UserDto owner of files */ -+(void) insertManyFiles:(NSMutableArray *)listOfFiles andFileId:(NSInteger)fileId; ++(void) insertManyFiles:(NSMutableArray *)listOfFiles ofFileId:(NSInteger)fileId andUser:(UserDto *)user; /* * Method to delete a file @@ -330,14 +331,14 @@ /** * Method that indicate if a specific file is into a specific path * - * @param idFile -> NSInteger of id file - * @param idUser -> NSInteger of id user + * @param idFile -> NSInteger of file id + * @param userId -> NSInteger of user id * @param folder -> Folder path * * @return YES/NO * */ -+ (BOOL) isThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)idUser intoThisFolder:(NSString *)folder; ++ (BOOL) isThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)userId intoThisFolder:(NSString *)folder; /* @@ -373,23 +374,23 @@ * * @param value -> NSInteger * @param idFile -> NSInteger - * @param idUser -> NSInteger + * @param userId -> NSInteger * */ -+ (void) updateShareFileSource:(NSInteger)value forThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)idUser; ++ (void) updateShareFileSource:(NSInteger)value forThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)userId; ///----------------------------------- -/// @name setUnShareAllFilesByIdUser +/// @name setUnShareAllFilesByUserId ///----------------------------------- /** * Method to unshare all the files of one user * - * @param idUser -> NSInteger + * @param userId -> NSInteger * */ -+ (void) setUnShareAllFilesByIdUser:(NSInteger)idUser; ++ (void) setUnShareAllFilesByUserId:(NSInteger)userId; ///----------------------------------- /// @name updateFilesAndSetSharedOfUser @@ -546,10 +547,15 @@ ///----------------------------------- /// @name update file with task identifier ///----------------------------------- - + (void) updateFile:(NSInteger)idFile withTaskIdentifier:(NSInteger)taskIdentifier; +///----------------------------------- +/// @name deleteAlleTagOfTheDirectoties +///----------------------------------- +/** + * This method is necessary for updateDBVersion7To8. With it the etag are deleted in order to force the refresh of the file list + */ +(void) deleteAlleTagOfTheDirectoties; diff --git a/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.m b/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.m index aede439f67..04d5e073b2 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.m +++ b/Owncloud iOs Client/DataBase/Queries/ManageFilesDB.m @@ -36,13 +36,9 @@ @implementation ManageFilesDB -/* - * Method that give all files from a single folder - * @fileId -> id of the folder father and we want all his files and folders - */ + + (NSMutableArray *) getFilesByFileIdForActiveUser:(NSInteger) fileId { - UserDto *mUser; #ifdef CONTAINER_APP @@ -58,7 +54,7 @@ + (NSMutableArray *) getFilesByFileIdForActiveUser:(NSInteger) fileId { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_id = ? AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_id = ? AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { FileDto *currentFile = [[FileDto alloc] init]; @@ -90,10 +86,7 @@ + (NSMutableArray *) getFilesByFileIdForActiveUser:(NSInteger) fileId { return output; } -/* - * Method that give all folders from a single folder - * @fileId -> id of the folder father and we want all his files and folders - */ + + (NSMutableArray *) getFoldersByFileIdForActiveUser:(NSInteger) fileId { UserDto *mUser; @@ -111,7 +104,7 @@ + (NSMutableArray *) getFoldersByFileIdForActiveUser:(NSInteger) fileId { [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_id = ? AND is_directory = 1 AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_id = ? AND is_directory = 1 AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { @@ -144,19 +137,7 @@ + (NSMutableArray *) getFoldersByFileIdForActiveUser:(NSInteger) fileId { return output; } -///----------------------------------- -/// @name Get Files by idFile -///----------------------------------- -/** - * Method that return an array of files, this files are sons of fileId - * - * @param fileId -> NSInteger - * - * @return list of files -> NSMutableArray - * - * @warning For filePath and localFolder is necessary the user, but we call this method before to check the user - */ + (NSMutableArray *) getFilesByFileId:(NSInteger) fileId { __block NSMutableArray *output = [NSMutableArray new]; @@ -211,7 +192,7 @@ + (FileDto *) getFileDtoByIdFile:(NSInteger) idFile { [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE id = ? AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:idFile], [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE id = ? AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:idFile], [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { @@ -243,6 +224,7 @@ + (FileDto *) getFileDtoByIdFile:(NSInteger) idFile { return output; } + +(FileDto *) getFileDtoByFileName:(NSString *) fileName andFilePath:(NSString *) filePath andUser:(UserDto *) user { __block FileDto *output = nil; @@ -250,7 +232,7 @@ +(FileDto *) getFileDtoByFileName:(NSString *) fileName andFilePath:(NSString *) FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_name = ? AND file_path= ? AND user_id = ? ORDER BY file_name ASC",fileName, filePath, [NSNumber numberWithInteger:user.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_name = ? AND file_path= ? AND user_id = ? ORDER BY file_name ASC",fileName, filePath, [NSNumber numberWithInteger:user.userId]]; while ([rs next]) { @@ -283,6 +265,7 @@ +(FileDto *) getFileDtoByFileName:(NSString *) fileName andFilePath:(NSString *) return output; } + +(NSMutableArray *) getAllFoldersByBeginFilePath:(NSString *) beginFilePath { DLog(@"getAllFoldersByBeginFilePath"); @@ -304,7 +287,7 @@ +(NSMutableArray *) getAllFoldersByBeginFilePath:(NSString *) beginFilePath { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT DISTINCT file_path, file_name, id FROM files WHERE user_id = ? AND file_path LIKE ? ORDER BY file_name ASC", [NSNumber numberWithInteger:mUser.idUser], beginFilePath]; + FMResultSet *rs = [db executeQuery:@"SELECT DISTINCT file_path, file_name, id FROM files WHERE user_id = ? AND file_path LIKE ? ORDER BY file_name ASC", [NSNumber numberWithInteger:mUser.userId], beginFilePath]; while ([rs next]) { FileDto *currentFile = [FileDto new]; @@ -321,6 +304,7 @@ +(NSMutableArray *) getAllFoldersByBeginFilePath:(NSString *) beginFilePath { return output; } + +(void) setFileIsDownloadState: (NSInteger) idFile andState:(enumDownload)downloadState { DLog(@"setFileIsDownloadState"); @@ -347,7 +331,7 @@ +(void) updateDownloadStateOfFileDtoByFileName:(NSString *) fileName andFilePath [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET is_download=? WHERE file_path = ? AND file_name=? AND user_id = ?", [NSNumber numberWithInt:downloadState], filePath, fileName, [NSNumber numberWithInteger:aciveUser.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE files SET is_download=? WHERE file_path = ? AND file_name=? AND user_id = ?", [NSNumber numberWithInt:downloadState], filePath, fileName, [NSNumber numberWithInteger:aciveUser.userId]]; if (!correctQuery) { DLog(@"Error in setFileIsDownloadState"); @@ -356,6 +340,7 @@ +(void) updateDownloadStateOfFileDtoByFileName:(NSString *) fileName andFilePath }]; } + +(void) setFilePath: (NSString * ) filePath byIdFile: (NSInteger) idFile { DLog(@"NewFilePath: %@", filePath); @@ -373,20 +358,12 @@ +(void) setFilePath: (NSString * ) filePath byIdFile: (NSInteger) idFile { }]; } -+(void) insertManyFiles:(NSMutableArray *)listOfFiles andFileId:(NSInteger)fileId { + ++(void) insertManyFiles:(NSMutableArray *)listOfFiles ofFileId:(NSInteger)fileId andUser:(UserDto *)user { NSString *sql = @""; NSMutableArray *arrayOfSqlRequests = [NSMutableArray new]; - UserDto *mUser; - -#ifdef CONTAINER_APP - AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; - mUser = app.activeUser; -#else - mUser = [ManageUsersDB getActiveUser]; -#endif - NSInteger numberOfInsertEachTime = 0; //if count == 1 the file is the current folder so there is nothing to insert @@ -397,7 +374,7 @@ +(void) insertManyFiles:(NSMutableArray *)listOfFiles andFileId:(NSInteger)fileI //INSERT INTO files(file_path, file_name, is_directory,user_id, is_download, size, file_id, date FileDto *current = [listOfFiles objectAtIndex:i]; current.fileId = fileId; - current.userId = mUser.idUser; + current.userId = user.userId; //to jump the first becouse it is not necesary (is the same directory) and the other if is to insert 450 by 450 if(numberOfInsertEachTime == 0) { @@ -471,11 +448,12 @@ +(void) insertManyFiles:(NSMutableArray *)listOfFiles andFileId:(NSInteger)fileI } if (!correctQuery) { - DLog(@"Error in insertManyFiles"); + DLog(@"Error inserting %lu files in DB for file directory id=%ld of user %@", (unsigned long)[listOfFiles count], (long)fileId, user.username); + } else { + DLog(@"Inserted %lu files in DB for file directory id=%ld", (unsigned long)[listOfFiles count], (long)fileId); } }]; - } } @@ -496,7 +474,7 @@ +(void) deleteFileByIdFileOfActiveUser:(NSInteger) idFile { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM files WHERE id = ? AND user_id = ?",[NSNumber numberWithInteger:idFile], [NSNumber numberWithInteger:mUser.idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM files WHERE id = ? AND user_id = ?",[NSNumber numberWithInteger:idFile], [NSNumber numberWithInteger:mUser.userId]]; if (!correctQuery) { DLog(@"Error in deleteFileByIdFile"); @@ -505,15 +483,7 @@ +(void) deleteFileByIdFileOfActiveUser:(NSInteger) idFile { }]; } -///----------------------------------- -/// @name Delete File by idfile -///----------------------------------- -/** - * Method that delete a file/folder of the database - * - * @param idFile -> NSInteger (Item to delete) - */ +(void) deleteFileByIdFile:(NSInteger) idFile { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -530,6 +500,7 @@ +(void) deleteFileByIdFile:(NSInteger) idFile { }]; } + +(void) deleteFilesFromDBBeforeRefreshByFileId: (NSInteger) fileId { DLog(@"deleteFilesFromDBBeforeRefreshByFileId"); @@ -548,7 +519,7 @@ +(void) deleteFilesFromDBBeforeRefreshByFileId: (NSInteger) fileId { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM files WHERE file_id = ? AND user_id = ?", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:mUser.idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM files WHERE file_id = ? AND user_id = ?", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:mUser.userId]]; if (!correctQuery) { DLog(@"Error in deleteFilesFromDBBeforeRefreshByFileId"); @@ -557,6 +528,7 @@ +(void) deleteFilesFromDBBeforeRefreshByFileId: (NSInteger) fileId { }]; } + + (void) backupOfTheProcessingFilesAndFoldersByFileId:(NSInteger) fileId { UserDto *mUser; @@ -573,7 +545,7 @@ + (void) backupOfTheProcessingFilesAndFoldersByFileId:(NSInteger) fileId { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"INSERT INTO files_backup SELECT * FROM files WHERE user_id =? and file_id=?", [NSNumber numberWithInteger:mUser.idUser], [NSNumber numberWithInteger:fileId]]; + correctQuery = [db executeUpdate:@"INSERT INTO files_backup SELECT * FROM files WHERE user_id =? and file_id=?", [NSNumber numberWithInteger:mUser.userId], [NSNumber numberWithInteger:fileId]]; if (!correctQuery) { DLog(@"Error in backupFoldersDownloadedFavoritesByFileId"); @@ -597,7 +569,7 @@ +(void) updateRelatedFilesFromBackup { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT files.id, back.file_id, back.etag, back.is_favorite FROM files, (SELECT DISTINCT files.file_id, files_backup.file_path, files_backup.file_name, files_backup.etag, files_backup.is_favorite FROM files_backup, files WHERE files.file_id = files_backup.id AND files_backup.is_directory = 1) back WHERE user_id = ? AND files.file_path = back.file_path AND files.file_name = back.file_name ORDER BY id DESC", [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT files.id, back.file_id, back.etag, back.is_favorite FROM files, (SELECT DISTINCT files.file_id, files_backup.file_path, files_backup.file_name, files_backup.etag, files_backup.is_favorite FROM files_backup, files WHERE files.file_id = files_backup.id AND files_backup.is_directory = 1) back WHERE user_id = ? AND files.file_path = back.file_path AND files.file_name = back.file_name ORDER BY id DESC", [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { FileDto *currentFile = [[FileDto alloc] init]; @@ -635,19 +607,6 @@ +(void) updateRelatedFilesFromBackup { } -///----------------------------------- -/// @name updateFilesFromBackup -///----------------------------------- - -/** - * This method update the files DB with the datas located on the files_backup DB - * - * If the file is overwritten we update the fileds: is_download, shared_file_source and - * is_overwritten - * - * If other case we update the fields: is_download, shared_file_source and is_overwritten - * AND etag - */ +(void) updateFilesFromBackup { //1 - Select the files from the files_backup DB that want to be updated on the files DB @@ -698,18 +657,7 @@ +(void) updateFilesFromBackup { }]; } -///----------------------------------- -/// @name setUpdateIsNecessaryFromBackup -///----------------------------------- -/** - * This method set the field isNecessaryUpdate to YES on the files DB when the file stored etag - * on the files DB is diferent that the one stored on the files_backup DB - * The only exception is that the field is not set to YES is the file is overwritten, in this - * case the etag must be updated on the files DB: check the method updateFilesFromBackup - * - * @param idFile -> NSInteger, the file that want to update - */ +(void) setUpdateIsNecessaryFromBackup:(NSInteger) idFile { //1-Select the files from the files_backup DB @@ -775,15 +723,6 @@ +(void) setUpdateIsNecessaryFromBackup:(NSInteger) idFile { } -///----------------------------------- -/// @name setIsNecessaryUpdateOfTheFile -///----------------------------------- - -/** - * This method updates the is_necessary_update field of the file - * - * @param idFile -> int - */ + (void) setIsNecessaryUpdateOfTheFile: (NSInteger) idFile { DLog(@"setIsNecessaryUpdateOfTheFile"); FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -800,18 +739,6 @@ + (void) setIsNecessaryUpdateOfTheFile: (NSInteger) idFile { } -///----------------------------------- -/// @name Delete OffSpring of this Folder -///----------------------------------- - -/** - * - * Recursive method to delete the offspring of a specific folder. - * This is neccesary when in the server array after a proffind process - * the folder does not appear. - * - * @param folder -> FileDto - */ + (void) deleteOffspringOfThisFolder:(FileDto *)folder{ //Get Files of the Folder @@ -850,7 +777,7 @@ +(void) deleteAllFilesAndFoldersThatNotExistOnServerFromBackup { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT files_backup.id, files_backup.file_path, files_backup.file_name, files_backup.is_directory FROM files_backup WHERE files_backup.id NOT IN (SELECT back.id FROM (SELECT id, file_path, file_name FROM files_backup) back, (SELECT id, file_path, file_name FROM files WHERE user_id = ?) files WHERE files.file_path = back.file_path AND files.file_name = back.file_name)", [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT files_backup.id, files_backup.file_path, files_backup.file_name, files_backup.is_directory FROM files_backup WHERE files_backup.id NOT IN (SELECT back.id FROM (SELECT id, file_path, file_name FROM files_backup) back, (SELECT id, file_path, file_name FROM files WHERE user_id = ?) files WHERE files.file_path = back.file_path AND files.file_name = back.file_name)", [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { FileDto *currentFile = [[FileDto alloc] init]; @@ -895,6 +822,7 @@ +(void) deleteAllFilesAndFoldersThatNotExistOnServerFromBackup { } } + +(void) deleteAllThumbnailsWithDifferentEtagFromBackup { DLog(@"deleteAllThumbnailsWithDifferentEtagFromBackup"); @@ -959,6 +887,7 @@ +(void) updateFavoriteFilesFromBackup { }]; } + + (void) deleteFilesBackup { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -975,6 +904,7 @@ + (void) deleteFilesBackup { }]; } + +(void) renameFileByFileDto:(FileDto *) file andNewName:(NSString *) mNewName { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -991,6 +921,7 @@ +(void) renameFileByFileDto:(FileDto *) file andNewName:(NSString *) mNewName { }]; } + +(void) renameFolderByFileDto:(FileDto *) file andNewName:(NSString *) mNewName { mNewName=[NSString stringWithFormat:@"%@/", mNewName]; @@ -1009,6 +940,7 @@ +(void) renameFolderByFileDto:(FileDto *) file andNewName:(NSString *) mNewName }]; } + +(BOOL) isFileOnDataBase: (FileDto *)fileDto { __block int size = 0; @@ -1033,6 +965,7 @@ +(BOOL) isFileOnDataBase: (FileDto *)fileDto { return output; } + +(void) deleteFileByFilePath: (NSString *) filePathToDelete andFileName: (NSString*)fileName { DLog(@"deleteFileByFilePath: %@ filePathToDelete andFileName: %@", filePathToDelete, fileName); @@ -1051,7 +984,7 @@ +(void) deleteFileByFilePath: (NSString *) filePathToDelete andFileName: (NSStri [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM files WHERE file_path = ? AND file_name = ? AND user_id = ?",filePathToDelete, fileName, [NSNumber numberWithInteger:mUser.idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM files WHERE file_path = ? AND file_name = ? AND user_id = ?",filePathToDelete, fileName, [NSNumber numberWithInteger:mUser.userId]]; if (!correctQuery) { DLog(@"Error in deleteFileByFilePath"); @@ -1059,6 +992,7 @@ +(void) deleteFileByFilePath: (NSString *) filePathToDelete andFileName: (NSStri }]; } + +(FileDto *) getFolderByFilePath: (NSString *) newFilePath andFileName: (NSString *) fileName { __block FileDto *output = nil; @@ -1075,7 +1009,7 @@ +(FileDto *) getFolderByFilePath: (NSString *) newFilePath andFileName: (NSStrin FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_path = ? AND file_name = ? AND user_id = ? AND is_directory = 1 ORDER BY file_name ASC", newFilePath, fileName, [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE file_path = ? AND file_name = ? AND user_id = ? AND is_directory = 1 ORDER BY file_name ASC", newFilePath, fileName, [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { @@ -1101,6 +1035,7 @@ +(FileDto *) getFolderByFilePath: (NSString *) newFilePath andFileName: (NSStrin return output; } + + (void) updateFolderOfFileDtoByNewFilePath:(NSString *) newFilePath andDestinationFileDto:(FileDto *) folderDto andNewFileName:(NSString *)changedFileName andFileDto:(FileDto *) selectedFile { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1117,6 +1052,7 @@ + (void) updateFolderOfFileDtoByNewFilePath:(NSString *) newFilePath andDestinat }]; } + +(void) updatePath:(NSString *) oldFilePath withNew:(NSString *) newFilePath andFileId:(NSInteger) fileId andSelectedFileId:(NSInteger) selectedFileId andChangedFileName:(NSString *) fileName { UserDto *mUser; @@ -1133,7 +1069,7 @@ +(void) updatePath:(NSString *) oldFilePath withNew:(NSString *) newFilePath and [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET file_path=?, file_id=?, file_name=? WHERE user_id = ? AND id = ?", newFilePath, [NSNumber numberWithInteger:fileId], fileName, [NSNumber numberWithInteger:mUser.idUser], [NSNumber numberWithInteger:selectedFileId]]; + correctQuery = [db executeUpdate:@"UPDATE files SET file_path=?, file_id=?, file_name=? WHERE user_id = ? AND id = ?", newFilePath, [NSNumber numberWithInteger:fileId], fileName, [NSNumber numberWithInteger:mUser.userId], [NSNumber numberWithInteger:selectedFileId]]; if (!correctQuery) { DLog(@"Error in updateFolderOfFileDtoByNewFilePath"); @@ -1142,6 +1078,7 @@ +(void) updatePath:(NSString *) oldFilePath withNew:(NSString *) newFilePath and }]; } + +(void) updatePathwithNewPath:(NSString *) newFilePath andFileDto:(FileDto *) selectedFile { UserDto *mUser; @@ -1158,7 +1095,7 @@ +(void) updatePathwithNewPath:(NSString *) newFilePath andFileDto:(FileDto *) se [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET file_path=? WHERE user_id = ? AND id=?", newFilePath, [NSNumber numberWithInteger:mUser.idUser], [NSNumber numberWithInteger:selectedFile.idFile]]; + correctQuery = [db executeUpdate:@"UPDATE files SET file_path=? WHERE user_id = ? AND id=?", newFilePath, [NSNumber numberWithInteger:mUser.userId], [NSNumber numberWithInteger:selectedFile.idFile]]; if (!correctQuery) { DLog(@"Error in updatePathwithNewPath"); @@ -1167,6 +1104,7 @@ +(void) updatePathwithNewPath:(NSString *) newFilePath andFileDto:(FileDto *) se }]; } + +(BOOL) isExistRootFolderByUser:(UserDto *) currentUser { __block int size = 0; @@ -1177,7 +1115,7 @@ +(BOOL) isExistRootFolderByUser:(UserDto *) currentUser { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT COUNT(*) AS NUM FROM files WHERE user_id = ? AND is_root_folder = 1", [NSNumber numberWithInteger:currentUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT COUNT(*) AS NUM FROM files WHERE user_id = ? AND is_root_folder = 1", [NSNumber numberWithInteger:currentUser.userId]]; while ([rs next]) { size = [rs intForColumn:@"NUM"]; } @@ -1191,6 +1129,7 @@ +(BOOL) isExistRootFolderByUser:(UserDto *) currentUser { return output; } + +(void) insertFile:(FileDto *)fileDto { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1206,6 +1145,7 @@ +(void) insertFile:(FileDto *)fileDto { }]; } + +(FileDto *) getRootFileDtoByUser:(UserDto *) currentUser { __block FileDto *output = nil; @@ -1213,7 +1153,7 @@ +(FileDto *) getRootFileDtoByUser:(UserDto *) currentUser { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE user_id = ? AND is_root_folder = 1 ORDER BY file_name ASC", [NSNumber numberWithInteger:currentUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE user_id = ? AND is_root_folder = 1 ORDER BY file_name ASC", [NSNumber numberWithInteger:currentUser.userId]]; while ([rs next]) { @@ -1263,7 +1203,6 @@ +(void) updateEtagOfFileDtoByid:(NSInteger) idFile andNewEtag: (NSString *)etag } - +(void) updateEtagOfFileDtoByFileName:(NSString *) fileName andFilePath: (NSString *) filePath andActiveUser: (UserDto *) aciveUser withNewEtag: (NSString *)etag { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1271,7 +1210,7 @@ +(void) updateEtagOfFileDtoByFileName:(NSString *) fileName andFilePath: (NSStri [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET etag=? WHERE file_path = ? AND file_name=? AND user_id = ?", etag, filePath, fileName, [NSNumber numberWithInteger:aciveUser.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE files SET etag=? WHERE file_path = ? AND file_name=? AND user_id = ?", etag, filePath, fileName, [NSNumber numberWithInteger:aciveUser.userId]]; if (!correctQuery) { DLog(@"Error in updatePathwithNewPath"); @@ -1279,6 +1218,7 @@ +(void) updateEtagOfFileDtoByFileName:(NSString *) fileName andFilePath: (NSStri }]; } + + (void) updateFilesWithFileId:(NSInteger) oldFileId withNewFileId:(NSInteger) fileId { UserDto *mUser; @@ -1295,7 +1235,7 @@ + (void) updateFilesWithFileId:(NSInteger) oldFileId withNewFileId:(NSInteger) f [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET file_id=? WHERE file_id = ? AND user_id = ?", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:oldFileId], [NSNumber numberWithInteger:mUser.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE files SET file_id=? WHERE file_id = ? AND user_id = ?", [NSNumber numberWithInteger:fileId], [NSNumber numberWithInteger:oldFileId], [NSNumber numberWithInteger:mUser.userId]]; if (!correctQuery) { DLog(@"Error in updatePathwithNewPath"); @@ -1304,6 +1244,7 @@ + (void) updateFilesWithFileId:(NSInteger) oldFileId withNewFileId:(NSInteger) f }]; } + + (void) setFile:(NSInteger)idFile isNecessaryUpdate:(BOOL)isNecessaryUpdate { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1328,7 +1269,7 @@ + (BOOL) isGetFilesByDownloadState:(enumDownload)downloadState andByUser:(UserDt FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT COUNT(*) as NUM FROM files WHERE is_download = ? AND user_id = ? AND file_path LIKE ? ORDER BY file_name ASC", [NSNumber numberWithInteger:downloadState], [NSNumber numberWithInteger:currentUser.idUser], [NSString stringWithFormat:@"%@%%", folder]]; + FMResultSet *rs = [db executeQuery:@"SELECT COUNT(*) as NUM FROM files WHERE is_download = ? AND user_id = ? AND file_path LIKE ? ORDER BY file_name ASC", [NSNumber numberWithInteger:downloadState], [NSNumber numberWithInteger:currentUser.userId], [NSString stringWithFormat:@"%@%%", folder]]; while ([rs next]) { int numberOfFiles = [rs intForColumn:@"NUM"]; if(numberOfFiles > 0) { @@ -1341,24 +1282,11 @@ + (BOOL) isGetFilesByDownloadState:(enumDownload)downloadState andByUser:(UserDt return output; } -///----------------------------------- -/// @name File is in the Path? -///----------------------------------- -/** - * Method that indicate if a specific file is into a specific path - * - * @param idFile -> NSInteger of id file - * @param idUser -> NSInteger of id user - * @param folder -> Folder path - * - * @return YES/NO - * - */ -+ (BOOL) isThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)idUser intoThisFolder:(NSString *)folder{ ++ (BOOL) isThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)userId intoThisFolder:(NSString *)folder{ DLog(@"ManageFiles -> idFile: %ld", (long)idFile); - DLog(@"ManageFiles -> idUser: %ld", (long)idUser); + DLog(@"ManageFiles -> userId: %ld", (long)userId); DLog(@"ManageFiles -> folder: %@", folder); @@ -1367,7 +1295,7 @@ + (BOOL) isThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)idUser intoThisFol FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id FROM files WHERE user_id = ? AND file_path LIKE ?", [NSNumber numberWithInteger:idUser], [NSString stringWithFormat:@"%@%%", folder]]; + FMResultSet *rs = [db executeQuery:@"SELECT id FROM files WHERE user_id = ? AND file_path LIKE ?", [NSNumber numberWithInteger:userId], [NSString stringWithFormat:@"%@%%", folder]]; while ([rs next]) { @@ -1383,10 +1311,9 @@ + (BOOL) isThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)idUser intoThisFol }]; return output; - - } + + (void) updateFilesByUser:(UserDto *) currentUser andFolder:(NSString *) folder toDownloadState:(enumDownload)downloadState andIsNecessaryUpdate:(BOOL) isNecessaryUpdate { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1394,7 +1321,7 @@ + (void) updateFilesByUser:(UserDto *) currentUser andFolder:(NSString *) folder [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET is_download = ?, is_necessary_update = ? WHERE user_id = ? AND file_path LIKE ? ", [NSNumber numberWithInteger:downloadState],[NSNumber numberWithInt:isNecessaryUpdate], [NSNumber numberWithInteger:currentUser.idUser], [NSString stringWithFormat:@"%@%%", folder]]; + correctQuery = [db executeUpdate:@"UPDATE files SET is_download = ?, is_necessary_update = ? WHERE user_id = ? AND file_path LIKE ? ", [NSNumber numberWithInteger:downloadState],[NSNumber numberWithInt:isNecessaryUpdate], [NSNumber numberWithInteger:currentUser.userId], [NSString stringWithFormat:@"%@%%", folder]]; if (!correctQuery) { DLog(@"Error in updateFilesByUserAndFolder"); @@ -1403,30 +1330,17 @@ + (void) updateFilesByUser:(UserDto *) currentUser andFolder:(NSString *) folder }]; } -#pragma mark - Share Querys. - -///----------------------------------- -/// @name Update Share File Source -///----------------------------------- +#pragma mark - Share Querys. -/** - * Method that update share file source - * - * - * @param value -> NSInteger - * @param idFile -> NSInteger - * @param idUser -> NSInteger - * - */ -+ (void) updateShareFileSource:(NSInteger)value forThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)idUser{ ++ (void) updateShareFileSource:(NSInteger)value forThisFile:(NSInteger)idFile ofThisUserId:(NSInteger)userId{ FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET shared_file_source = ? WHERE id = ? AND user_id= ?", [NSNumber numberWithInteger:value], [NSNumber numberWithInteger:idFile],[NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"UPDATE files SET shared_file_source = ? WHERE id = ? AND user_id= ?", [NSNumber numberWithInteger:value], [NSNumber numberWithInteger:idFile],[NSNumber numberWithInteger:userId]]; if (!correctQuery) { DLog(@"Error in update share file source"); @@ -1435,23 +1349,14 @@ + (void) updateShareFileSource:(NSInteger)value forThisFile:(NSInteger)idFile of }]; } -///----------------------------------- -/// @name setUnShareAllFilesByIdUser -///----------------------------------- -/** - * Method to unshare all the files of one user - * - * @param idUser -> NSInteger - * - */ -+ (void) setUnShareAllFilesByIdUser:(NSInteger)idUser { ++ (void) setUnShareAllFilesByUserId:(NSInteger)userId { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET shared_file_source = 0 WHERE user_id= ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"UPDATE files SET shared_file_source = 0 WHERE user_id= ?", [NSNumber numberWithInteger:userId]]; if (!correctQuery) { DLog(@"Error in update share file source"); @@ -1460,16 +1365,7 @@ + (void) setUnShareAllFilesByIdUser:(NSInteger)idUser { }]; } -///----------------------------------- -/// @name updateFilesAndSetSharedOfUser -///----------------------------------- -/** - * This method update the Files table and set the relation with the shared - * - * @param userId -> NSInteger - * - */ + (void) updateFilesAndSetSharedOfUser:(NSInteger)userId { NSMutableArray *listOfFileSource = [NSMutableArray new]; @@ -1507,19 +1403,9 @@ + (void) updateFilesAndSetSharedOfUser:(NSInteger)userId { } }]; - } -///----------------------------------- -/// @name Delete Shared Data of a list of files -///----------------------------------- -/** - * This method update to 0 {not shared by link} the status of a list of files - * - * @param pathItems -> NSArray - * @param userId -> NSInteger - */ + (void) deleteShareDataOfThisFiles:(NSArray*)pathItems ofUser:(NSInteger)userId{ for (FileDto *file in pathItems) { @@ -1530,18 +1416,6 @@ + (void) deleteShareDataOfThisFiles:(NSArray*)pathItems ofUser:(NSInteger)userId } - -///----------------------------------- -/// @name Get files by download status -///----------------------------------- - -/** - * This method get all the file where the download status is equal to status - * - * @param int -> The download status - * - * @return NSMutableArray -> The array with the files - */ + (NSMutableArray *) getFilesByDownloadStatus:(NSInteger) status andUser:(UserDto *) user { __block NSMutableArray *output = [NSMutableArray new]; DLog(@"getFilesByDownloadStatus: %ld",(long)status); @@ -1550,7 +1424,7 @@ + (NSMutableArray *) getFilesByDownloadStatus:(NSInteger) status andUser:(UserDt [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE is_download = ? AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:status], [NSNumber numberWithInteger:user.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE is_download = ? AND user_id = ? ORDER BY file_name ASC", [NSNumber numberWithInteger:status], [NSNumber numberWithInteger:user.userId]]; while ([rs next]) { FileDto *currentFile = [[FileDto alloc] init]; @@ -1583,17 +1457,6 @@ + (NSMutableArray *) getFilesByDownloadStatus:(NSInteger) status andUser:(UserDt } - -///----------------------------------- -/// @name setUnShareFilesByListOfOCShared -///----------------------------------- - -/** - * Method to unshare by link the files that are not unshare anymore - * - * @param listOfRemoved -> NSArray - * - */ + (void) setUnShareFilesByUser:(UserDto *) user { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1601,7 +1464,7 @@ + (void) setUnShareFilesByUser:(UserDto *) user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE files SET shared_file_source = 0 WHERE user_id = ?", [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE files SET shared_file_source = 0 WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error in update share file source"); @@ -1631,22 +1494,9 @@ + (void) setUnShareFilesByUser:(UserDto *) user { } }]; }*/ - } -///----------------------------------- -/// @name Get the filedto equal with the share dto pah -///----------------------------------- -/** - * This method return a FileDto with equal share dto path, if - * is not catched this method return nil - * - * @param path -> NSString - * - * @return FileDto - * - */ + (FileDto *) getFileEqualWithShareDtoPath:(NSString*)path andByUser:(UserDto *) user { UserDto *mUser; @@ -1665,7 +1515,7 @@ + (FileDto *) getFileEqualWithShareDtoPath:(NSString*)path andByUser:(UserDto *) __block NSString *comparePath = nil; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE user_id = ?", [NSNumber numberWithInteger:user.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; while ([rs next]) { comparePath = [NSString stringWithFormat:@"/%@%@", [rs stringForColumn:@"file_path"], [rs stringForColumn:@"file_name"]]; @@ -1705,17 +1555,7 @@ + (FileDto *) getFileEqualWithShareDtoPath:(NSString*)path andByUser:(UserDto *) return output; } -///----------------------------------- -/// @name is Catched in data base this path -///----------------------------------- -/** - * This method check if a path is inside the DB - * - * @param path -> NSString {/folder1/folder1_1} - * - * @return YES/NO - */ + (BOOL) isCatchedInDataBaseThisPath: (NSString*)path{ //Ex: /folder1/folder1_1/folder1_1_1/folder1_1_1_1 @@ -1737,7 +1577,7 @@ + (BOOL) isCatchedInDataBaseThisPath: (NSString*)path{ [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE user_id = ? AND is_directory = 1", [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE user_id = ? AND is_directory = 1", [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { @@ -1755,19 +1595,9 @@ + (BOOL) isCatchedInDataBaseThisPath: (NSString*)path{ }]; return isExist; - } -///----------------------------------- -/// @name setUnShareFilesOfFolder -///----------------------------------- -/** - * Method to unshare all the shared of a folder - * - * @param folder -> FileDto - * - */ + (void) setUnShareFilesOfFolder:(FileDto *) folder { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1784,16 +1614,6 @@ + (void) setUnShareFilesOfFolder:(FileDto *) folder { #pragma mark - Favorites method -///----------------------------------- -/// @name updateTheFileID:asFavorite: -///----------------------------------- - -/** - * This method updates the favorite field of the file - * - * @param idFile -> int - * @param isFavorite -> BOOL - */ + (void) updateTheFileID: (NSInteger)idFile asFavorite: (BOOL) isFavorite { DLog(@"updateTheFavoriteFile"); FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1809,24 +1629,14 @@ + (void) updateTheFileID: (NSInteger)idFile asFavorite: (BOOL) isFavorite { }]; } -///----------------------------------- -/// @name getAllFavoritesFilesOfUserId:userId -///----------------------------------- -/** - * This method returned all favorites files of a specific user - * - * @param userId -> NSInterger - * - * @return NSArray -> Array of favorites items - */ + (NSArray*) getAllFavoritesFilesOfUserId:(NSInteger)userId { FMDatabaseQueue *queue = Managers.sharedDatabase; NSMutableArray *tempArray = [NSMutableArray new]; //Get the user - UserDto *mUser = [ManageUsersDB getUserByIdUser:userId]; + UserDto *mUser = [ManageUsersDB getUserByUserId:userId]; [queue inDatabase:^(FMDatabase *db) { FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE is_favorite = 1 AND user_id = ? AND is_directory = 0", [NSNumber numberWithInteger:userId]]; @@ -1863,20 +1673,9 @@ + (NSArray*) getAllFavoritesFilesOfUserId:(NSInteger)userId { tempArray = nil; return output; - } -///----------------------------------- -/// @name getAllFavoritesByFolder:userId -///----------------------------------- -/** - * This method returned all favorites files of a specific user - * - * @param folder -> FolderDto - * - * @return NSArray -> Array of favorites items - */ + (NSArray*) getAllFavoritesByFolder:(FileDto *) folder { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1920,19 +1719,9 @@ + (NSArray*) getAllFavoritesByFolder:(FileDto *) folder { tempArray = nil; return output; - } -///----------------------------------- -/// @name setNoFavoritesAllFilesOfAFolder -///----------------------------------- -/** - * This method set all files and folders of a folder as no favorite - * - * @param folder -> FolderDto - * - */ + (void) setNoFavoritesAllFilesOfAFolder:(FileDto *) folder { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -1968,7 +1757,7 @@ +(NSArray*) getFavoritesOfPath:(NSString*)path andUserId:(NSInteger)userId{ NSMutableArray *tempArray = [NSMutableArray new]; //Get the user - UserDto *mUser = [ManageUsersDB getUserByIdUser:userId]; + UserDto *mUser = [ManageUsersDB getUserByUserId:userId]; __block NSString *comparePath = nil; @@ -2015,17 +1804,9 @@ +(NSArray*) getFavoritesOfPath:(NSString*)path andUserId:(NSInteger)userId{ tempArray = nil; return output; - } -///----------------------------------- -/// @name deleteAlleTagOfTheDirectoties -///----------------------------------- - -/** - * This method is necessary for updateDBVersion7To8. With it the etag are deleted in order to force the refresh of the file list - */ +(void) deleteAlleTagOfTheDirectoties { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -2043,10 +1824,6 @@ +(void) deleteAlleTagOfTheDirectoties { #pragma mark - TaskIdentifier methods -///----------------------------------- -/// @name update file with task identifier -///----------------------------------- - + (void) updateFile:(NSInteger)idFile withTaskIdentifier:(NSInteger)taskIdentifier { FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -2077,19 +1854,16 @@ + (void) updateFile:(NSInteger)idFile withProvidingFile:(NSInteger)providingFile DLog(@"Error in update providing file"); } }]; - - } + (FileDto *) getFileDtoRelatedWithProvidingFileId:(NSInteger)providingFileId ofUser:(NSInteger)userId{ - FMDatabaseQueue *queue = Managers.sharedDatabase; __block FileDto *fileTemp = nil; //Get the user - UserDto *user = [ManageUsersDB getUserByIdUser:userId]; + UserDto *user = [ManageUsersDB getUserByUserId:userId]; [queue inDatabase:^(FMDatabase *db) { FMResultSet *rs = [db executeQuery:@"SELECT * FROM files WHERE providing_file_id = ?", [NSNumber numberWithInteger:providingFileId]]; @@ -2122,9 +1896,7 @@ + (FileDto *) getFileDtoRelatedWithProvidingFileId:(NSInteger)providingFileId of [rs close]; }]; - return fileTemp; - } @end diff --git a/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.h b/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.h index 1f420a6143..9ff9268bbf 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.h +++ b/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.h @@ -41,9 +41,9 @@ /** * Method that delete all shares element of a specific user * - * @param idUser -> NSInteger + * @param userId -> NSInteger */ -+ (void) deleteAllSharesOfUser:(NSInteger)idUser; ++ (void) deleteAllSharesOfUser:(NSInteger)userId; ///----------------------------------- @@ -54,7 +54,7 @@ * Get the shared items of a specific path of a specific user * * @param path -> NSString - * @param idUser -> NSInteger + * @param userId -> NSInteger * * @return NSMutableArray * @@ -70,7 +70,7 @@ * Get the shared items of a specific folder * * @param path -> NSString - * @param idUser -> NSInteger + * @param userId -> NSInteger * * @return NSMutableArray * @@ -85,13 +85,13 @@ /** * Get the shared items of a specific user and path * - * @param idUser -> NSInteger + * @param userId -> NSInteger * @param path -> NSString * * @return NSMutableArray * */ -+ (NSMutableArray*) getSharesByUser:(NSInteger)idUser andPath:(NSString *) path; ++ (NSMutableArray*) getSharesByUser:(NSInteger)userId andPath:(NSString *) path; @@ -103,12 +103,12 @@ * Get the shared items of a specific path of a specific user * * @param sharedFileSource -> NSInteger - * @param idUser -> NSInteger + * @param userId -> NSInteger * * @return NSMutableArray * */ -+ (NSMutableArray*) getSharesBySharedFileSource:(NSInteger) sharedFileSource forUser:(NSInteger)idUser; ++ (NSMutableArray*) getSharesBySharedFileSource:(NSInteger) sharedFileSource forUser:(NSInteger)userId; ///----------------------------------- @@ -118,10 +118,10 @@ /** * Method to return all shares that have a user * - * @param idUser -> NSInteger + * @param userId -> NSInteger * */ -+ (NSMutableArray *) getAllSharesByUser:(NSInteger)idUser; ++ (NSMutableArray *) getAllSharesByUser:(NSInteger)userId; ///----------------------------------- @@ -132,11 +132,11 @@ /** * Method to return all shares that have a user of shared type * - * @param idUser -> NSInteger + * @param userId -> NSInteger * @param sharedType -> NSInteger * */ -+ (NSMutableArray *) getAllSharesByUser:(NSInteger)idUser anTypeOfShare: (NSInteger) shareType; ++ (NSMutableArray *) getAllSharesByUser:(NSInteger)userId anTypeOfShare: (NSInteger) shareType; ///----------------------------------- diff --git a/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.m b/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.m index 554beb279c..8b5a0887d9 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.m +++ b/Owncloud iOs Client/DataBase/Queries/ManageSharesDB.m @@ -69,7 +69,7 @@ + (void) insertSharedList:(NSArray *)elements{ [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { - BOOL correctQuery = NO; + BOOL correctQuery = YES; // DLog(@"shared items: %@", elements); @@ -90,12 +90,12 @@ + (void) insertSharedList:(NSArray *)elements{ shareDto.token, shareDto.shareWithDisplayName, shareDto.isDirectory, - (long)mUser.idUser, + (long)mUser.userId, (long)shareDto.idRemoteShared, shareDto.name, shareDto.url]; - correctQuery = [db executeUpdate:sqlQuery]; + correctQuery &= [db executeUpdate:sqlQuery]; } if (!correctQuery) { @@ -107,14 +107,14 @@ + (void) insertSharedList:(NSArray *)elements{ } -+ (void) deleteAllSharesOfUser:(NSInteger)idUser{ ++ (void) deleteAllSharesOfUser:(NSInteger)userId{ FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:userId]]; if (!correctQuery) { DLog(@"Error in delete shares of user"); @@ -183,14 +183,14 @@ + (NSMutableArray*) getSharesByFolderPath:(NSString *) path { } -+ (NSMutableArray*) getSharesByUser:(NSInteger)idUser andPath:(NSString *) path { ++ (NSMutableArray*) getSharesByUser:(NSInteger)userId andPath:(NSString *) path { __block NSMutableArray *output = [NSMutableArray new]; FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE path = ? AND user_id = ? ", path, [NSNumber numberWithInteger:idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE path = ? AND user_id = ? ", path, [NSNumber numberWithInteger:userId]]; while ([rs next]) { @@ -203,7 +203,7 @@ + (NSMutableArray*) getSharesByUser:(NSInteger)idUser andPath:(NSString *) path } -+ (NSMutableArray*) getSharesBySharedFileSource:(NSInteger) sharedFileSource forUser:(NSInteger)idUser { ++ (NSMutableArray*) getSharesBySharedFileSource:(NSInteger) sharedFileSource forUser:(NSInteger)userId { __block NSMutableArray *output = [NSMutableArray new]; @@ -211,7 +211,7 @@ + (NSMutableArray*) getSharesBySharedFileSource:(NSInteger) sharedFileSource for [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ? AND file_source = ?", [NSNumber numberWithInteger:idUser], [NSNumber numberWithInteger:sharedFileSource]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ? AND file_source = ?", [NSNumber numberWithInteger:userId], [NSNumber numberWithInteger:sharedFileSource]]; while ([rs next]) { [output addObject:[self shareDtoFromDBResults:rs]]; @@ -223,14 +223,14 @@ + (NSMutableArray*) getSharesBySharedFileSource:(NSInteger) sharedFileSource for } -+ (NSMutableArray *) getAllSharesByUser:(NSInteger)idUser { ++ (NSMutableArray *) getAllSharesByUser:(NSInteger)userId { __block NSMutableArray *output = [NSMutableArray new]; FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:userId]]; while ([rs next]) { [output addObject:[self shareDtoFromDBResults:rs]]; @@ -242,14 +242,14 @@ + (NSMutableArray *) getAllSharesByUser:(NSInteger)idUser { } -+ (NSMutableArray *) getAllSharesByUser:(NSInteger)idUser anTypeOfShare: (NSInteger) shareType { ++ (NSMutableArray *) getAllSharesByUser:(NSInteger)userId anTypeOfShare: (NSInteger) shareType { __block NSMutableArray *output = [NSMutableArray new]; FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ? AND share_type = ?", [NSNumber numberWithInteger:idUser], [NSNumber numberWithInteger:shareType]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ? AND share_type = ?", [NSNumber numberWithInteger:userId], [NSNumber numberWithInteger:shareType]]; while ([rs next]) { [output addObject:[self shareDtoFromDBResults:rs]]; @@ -289,7 +289,7 @@ + (void) deleteSharedNotRelatedByUser:(UserDto *) user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM shared WHERE user_id = ? AND file_source NOT IN (SELECT shared_file_source FROM files WHERE user_id = ?)", [NSNumber numberWithInteger:user.idUser], [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM shared WHERE user_id = ? AND file_source NOT IN (SELECT shared_file_source FROM files WHERE user_id = ?)", [NSNumber numberWithInteger:user.userId], [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error in deleteListOfSharedByList"); @@ -311,7 +311,7 @@ + (OCSharedDto *) getSharedEqualWithFileDtoPath:(NSString*)path{ __block NSString *comparePath = nil; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:mUser.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:mUser.userId]]; while ([rs next]) { comparePath = [rs stringForColumn:@"path"]; @@ -339,7 +339,7 @@ + (OCSharedDto *) getTheOCShareByFileDto:(FileDto*)file andShareType:(NSInteger) [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ? AND file_source = ? AND share_type = ?", [NSNumber numberWithInteger:user.idUser], [NSNumber numberWithInteger:file.sharedFileSource], [NSNumber numberWithInteger:shareType]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM shared WHERE user_id = ? AND file_source = ? AND share_type = ?", [NSNumber numberWithInteger:user.userId], [NSNumber numberWithInteger:file.sharedFileSource], [NSNumber numberWithInteger:shareType]]; while ([rs next]) { sharedDto = [self shareDtoFromDBResults:rs]; diff --git a/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.h b/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.h index 1a6e5ead74..8ded792257 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.h +++ b/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.h @@ -27,7 +27,7 @@ * Method that adds user into database * @userDto -> userDto (Object of a user info) */ -+(void) insertUser:(UserDto *)userDto; ++(UserDto *) insertUser:(UserDto *)userDto; /* * This method returns the active user of the app @@ -35,15 +35,15 @@ + (UserDto *) getActiveUser; /* - * This method returns the active user of the app without user name and password + * This method returns the active user of the app without credentials */ -+ (UserDto *) getActiveUserWithoutUserNameAndPassword; ++ (UserDto *) getActiveUserWithoutCredentials; /* - * Method that returns the user object of the idUser - * @idUser -> id User. + * Method that returns the user object of the userId + * @userId -> User id. */ -+ (UserDto *) getUserByIdUser:(NSInteger) idUser; ++ (UserDto *) getUserByUserId:(NSInteger) userId; /* * Method that returns if the user exist or not @@ -70,9 +70,9 @@ /* * Method that sets a user like a active account - * @idUser -> id user + * @userId -> user id */ -+(void) setActiveAccountByIdUser: (NSInteger) idUser; ++(void) setActiveAccountByUserId: (NSInteger) userId; /* * Method that sets all acount as a no active. @@ -87,12 +87,12 @@ /* * Method that removes user data in all tables - * @idUser -> id user + * @user -> userDto */ -+(void) removeUserAndDataByIdUser:(NSInteger)idUser; ++(void) removeUserAndDataByUser:(UserDto *)user; /* - * Method that set the user storage of a user + * Method that set the user storage of a user, -> Not in use */ +(void) updateStorageByUserDto:(UserDto *) user; diff --git a/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.m b/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.m index 1b95bc299c..46b5f76081 100644 --- a/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.m +++ b/Owncloud iOs Client/DataBase/Queries/ManageUsersDB.m @@ -18,9 +18,10 @@ #import "FMDatabase.h" #import "UserDto.h" #import "OCKeychain.h" -#import "CredentialsDto.h" +#import "OCCredentialsDto.h" #import "constants.h" #import "ManageCapabilitiesDB.h" +#import "Customization.h" #ifdef CONTAINER_APP #import "AppDelegate.h" @@ -36,9 +37,8 @@ @implementation ManageUsersDB -+(void) insertUser:(UserDto *)userDto { ++(UserDto *) insertUser:(UserDto *)userDto { - DLog(@"Insert user"); FMDatabaseQueue *queue = Managers.sharedDatabase; @@ -54,14 +54,18 @@ +(void) insertUser:(UserDto *)userDto { }]; - //Insert last user inserted in the keychain + UserDto *lastUser = [self getLastUserInserted]; - NSString *idString = [NSString stringWithFormat:@"%ld", (long)lastUser.idUser]; - if (![OCKeychain setCredentialsById:idString withUsername:userDto.username andPassword:userDto.password]) { - DLog(@"Failed setting credentials"); + if (lastUser) { + lastUser.username = userDto.username; + DLog(@"User %@ inserted in DB", userDto.username); + } else { + DLog(@"Error, not possible to insert user %@ in DB", userDto.username); } + return lastUser; + } @@ -74,7 +78,7 @@ + (UserDto *) getActiveUser { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, url, ssl, activeaccount, storage_occupied, storage, has_share_api_support, has_sharee_api_support, has_cookies_support, has_capabilities_support, has_forbidden_characters_support, image_instant_upload, video_instant_upload, background_instant_upload, path_instant_upload, only_wifi_instant_upload, timestamp_last_instant_upload_image, timestamp_last_instant_upload_video, url_redirected, sorting_type, predefined_url FROM users WHERE activeaccount = 1 ORDER BY id ASC LIMIT 1"]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM users WHERE activeaccount = 1 ORDER BY id ASC LIMIT 1"]; DLog(@"RSColumnt count: %d", rs.columnCount); @@ -83,7 +87,7 @@ + (UserDto *) getActiveUser { output=[UserDto new]; - output.idUser = [rs intForColumn:@"id"]; + output.userId = [rs intForColumn:@"id"]; output.url = [rs stringForColumn:@"url"]; output.ssl = [rs intForColumn:@"ssl"]; output.activeaccount = [rs intForColumn:@"activeaccount"]; @@ -104,15 +108,7 @@ + (UserDto *) getActiveUser { output.timestampInstantUploadVideo = [rs doubleForColumn:@"timestamp_last_instant_upload_video"]; output.urlRedirected = [rs stringForColumn:@"url_redirected"]; - - NSString *idString = [NSString stringWithFormat:@"%ld", (long)output.idUser]; - - CredentialsDto *credDto = [OCKeychain getCredentialsById:idString]; - output.username = credDto.userName; - output.password = credDto.password; - output.sortingType = [rs intForColumn:@"sorting_type"]; - output.predefinedUrl = [rs stringForColumn:@"predefined_url"]; } @@ -120,20 +116,29 @@ + (UserDto *) getActiveUser { }]; + if (output != nil) { + OCCredentialsDto *credDto = [OCKeychain getCredentialsOfUser:output]; + output.username = credDto.userName; + output.credDto = credDto; + + OCCapabilities *capDB = [ManageCapabilitiesDB getCapabilitiesOfUserId: output.userId]; + output.capabilitiesDto = capDB; + } + return output; } -+ (UserDto *) getActiveUserWithoutUserNameAndPassword { ++ (UserDto *) getActiveUserWithoutCredentials { - DLog(@"getActiveUser"); + DLog(@"getActiveUserWithoutCredentials"); __block UserDto *output = nil; FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, url, ssl, activeaccount, storage_occupied, storage, has_share_api_support, has_sharee_api_support, has_cookies_support, has_forbidden_characters_support, image_instant_upload, video_instant_upload, background_instant_upload, path_instant_upload, only_wifi_instant_upload, timestamp_last_instant_upload_image, timestamp_last_instant_upload_video, url_redirected, sorting_type, predefined_url FROM users WHERE activeaccount = 1 ORDER BY id ASC LIMIT 1"]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM users WHERE activeaccount = 1 ORDER BY id ASC LIMIT 1"]; DLog(@"RSColumnt count: %d", rs.columnCount); @@ -142,7 +147,7 @@ + (UserDto *) getActiveUserWithoutUserNameAndPassword { output=[UserDto new]; - output.idUser = [rs intForColumn:@"id"]; + output.userId = [rs intForColumn:@"id"]; output.url = [rs stringForColumn:@"url"]; output.ssl = [rs intForColumn:@"ssl"]; output.activeaccount = [rs intForColumn:@"activeaccount"]; @@ -152,6 +157,7 @@ + (UserDto *) getActiveUserWithoutUserNameAndPassword { output.hasShareeApiSupport = [rs intForColumn:@"has_sharee_api_support"]; output.hasCookiesSupport = [rs intForColumn:@"has_cookies_support"]; output.hasForbiddenCharactersSupport = [rs intForColumn:@"has_forbidden_characters_support"]; + output.hasCapabilitiesSupport = [rs intForColumn:@"has_capabilities_support"]; output.imageInstantUpload = [rs intForColumn:@"image_instant_upload"]; output.videoInstantUpload = [rs intForColumn:@"video_instant_upload"]; @@ -164,7 +170,7 @@ + (UserDto *) getActiveUserWithoutUserNameAndPassword { output.urlRedirected = [rs stringForColumn:@"url_redirected"]; output.username = nil; - output.password = nil; + output.credDto = nil; output.sortingType = [rs intForColumn:@"sorting_type"]; @@ -180,60 +186,56 @@ + (UserDto *) getActiveUserWithoutUserNameAndPassword { } -+ (UserDto *) getUserByIdUser:(NSInteger) idUser { ++ (UserDto *) getUserByUserId:(NSInteger) userId { - DLog(@"getUserByIdUser:(int) idUser"); + DLog(@"getUserByUserId:(int) userId"); - __block UserDto *output = nil; + __block UserDto *user = nil; - output=[UserDto new]; + user = [UserDto new]; FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, url, ssl, activeaccount, storage_occupied, storage, has_share_api_support, has_sharee_api_support, has_cookies_support, has_forbidden_characters_support, has_capabilities_support, image_instant_upload, video_instant_upload, background_instant_upload, path_instant_upload, only_wifi_instant_upload, timestamp_last_instant_upload_image, timestamp_last_instant_upload_video, url_redirected, sorting_type, predefined_url FROM users WHERE id = ?", [NSNumber numberWithInteger:idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM users WHERE id = ?", [NSNumber numberWithInteger:userId]]; while ([rs next]) { - output.idUser = [rs intForColumn:@"id"]; - output.url = [rs stringForColumn:@"url"]; - output.ssl = [rs intForColumn:@"ssl"]; - output.activeaccount = [rs intForColumn:@"activeaccount"]; - output.storageOccupied = [rs longForColumn:@"storage_occupied"]; - output.storage = [rs longForColumn:@"storage"]; - output.hasShareApiSupport = [rs intForColumn:@"has_share_api_support"]; - output.hasShareeApiSupport = [rs intForColumn:@"has_sharee_api_support"]; - output.hasCookiesSupport = [rs intForColumn:@"has_cookies_support"]; - output.hasForbiddenCharactersSupport = [rs intForColumn:@"has_forbidden_characters_support"]; - output.hasCapabilitiesSupport = [rs intForColumn:@"has_capabilities_support"]; - - output.imageInstantUpload = [rs intForColumn:@"image_instant_upload"]; - output.videoInstantUpload = [rs intForColumn:@"video_instant_upload"]; - output.backgroundInstantUpload = [rs intForColumn:@"background_instant_upload"]; - output.pathInstantUpload = [rs stringForColumn:@"path_instant_upload"]; - output.onlyWifiInstantUpload = [rs intForColumn:@"only_wifi_instant_upload"]; - output.timestampInstantUploadImage = [rs doubleForColumn:@"timestamp_last_instant_upload_image"]; - output.timestampInstantUploadVideo = [rs doubleForColumn:@"timestamp_last_instant_upload_video"]; - - output.urlRedirected = [rs stringForColumn:@"url_redirected"]; - - NSString *idString = [NSString stringWithFormat:@"%ld", (long)output.idUser]; - - CredentialsDto *credDto = [OCKeychain getCredentialsById:idString]; - output.username = credDto.userName; - output.password = credDto.password; - - output.sortingType = [rs intForColumn:@"sorting_type"]; - - output.predefinedUrl = [rs stringForColumn:@"predefined_url"]; + user.userId = [rs intForColumn:@"id"]; + user.url = [rs stringForColumn:@"url"]; + user.ssl = [rs intForColumn:@"ssl"]; + user.activeaccount = [rs intForColumn:@"activeaccount"]; + user.storageOccupied = [rs longForColumn:@"storage_occupied"]; + user.storage = [rs longForColumn:@"storage"]; + user.hasShareApiSupport = [rs intForColumn:@"has_share_api_support"]; + user.hasShareeApiSupport = [rs intForColumn:@"has_sharee_api_support"]; + user.hasCookiesSupport = [rs intForColumn:@"has_cookies_support"]; + user.hasForbiddenCharactersSupport = [rs intForColumn:@"has_forbidden_characters_support"]; + user.hasCapabilitiesSupport = [rs intForColumn:@"has_capabilities_support"]; + + user.imageInstantUpload = [rs intForColumn:@"image_instant_upload"]; + user.videoInstantUpload = [rs intForColumn:@"video_instant_upload"]; + user.backgroundInstantUpload = [rs intForColumn:@"background_instant_upload"]; + user.pathInstantUpload = [rs stringForColumn:@"path_instant_upload"]; + user.onlyWifiInstantUpload = [rs intForColumn:@"only_wifi_instant_upload"]; + user.timestampInstantUploadImage = [rs doubleForColumn:@"timestamp_last_instant_upload_image"]; + user.timestampInstantUploadVideo = [rs doubleForColumn:@"timestamp_last_instant_upload_video"]; + + user.urlRedirected = [rs stringForColumn:@"url_redirected"]; + user.sortingType = [rs intForColumn:@"sorting_type"]; + user.predefinedUrl = [rs stringForColumn:@"predefined_url"]; } [rs close]; }]; + if (user != nil) { + user.credDto = [OCKeychain getCredentialsOfUser:user]; + user.username = user.credDto.userName; + } - return output; + return user; } @@ -265,7 +267,7 @@ + (NSMutableArray *) getAllUsers { [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, url, ssl, activeaccount, storage_occupied, storage, has_share_api_support, has_sharee_api_support, has_cookies_support, has_forbidden_characters_support, has_capabilities_support, image_instant_upload, video_instant_upload, background_instant_upload, path_instant_upload, only_wifi_instant_upload, timestamp_last_instant_upload_image, timestamp_last_instant_upload_video, url_redirected, sorting_type, predefined_url FROM users ORDER BY id ASC"]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM users ORDER BY id ASC"]; UserDto *current = nil; @@ -273,7 +275,7 @@ + (NSMutableArray *) getAllUsers { current = [UserDto new]; - current.idUser= [rs intForColumn:@"id"]; + current.userId= [rs intForColumn:@"id"]; current.url = [rs stringForColumn:@"url"]; current.ssl = [rs intForColumn:@"ssl"]; current.activeaccount = [rs intForColumn:@"activeaccount"]; @@ -295,16 +297,14 @@ + (NSMutableArray *) getAllUsers { current.urlRedirected = [rs stringForColumn:@"url_redirected"]; - NSString *idString = [NSString stringWithFormat:@"%ld", (long)current.idUser]; - - CredentialsDto *credDto = [OCKeychain getCredentialsById:idString]; - current.username = credDto.userName; - current.password = credDto.password; - current.sortingType = [rs intForColumn:@"sorting_type"]; current.predefinedUrl = [rs stringForColumn:@"predefined_url"]; + OCCredentialsDto *credDto = [OCKeychain getCredentialsOfUser:current]; + current.username = credDto.userName; + current.credDto = credDto; + [output addObject:current]; } @@ -328,7 +328,7 @@ + (NSMutableArray *) getAllUsersWithOutCredentialInfo{ [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, url, ssl, activeaccount, storage_occupied, storage, has_share_api_support, has_sharee_api_support, has_cookies_support, has_forbidden_characters_support, has_capabilities_support, image_instant_upload, video_instant_upload, background_instant_upload, path_instant_upload, only_wifi_instant_upload, timestamp_last_instant_upload_image, timestamp_last_instant_upload_video, sorting_type, predefined_url FROM users ORDER BY id ASC"]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM users ORDER BY id ASC"]; UserDto *current = nil; @@ -336,7 +336,7 @@ + (NSMutableArray *) getAllUsersWithOutCredentialInfo{ current = [UserDto new]; - current.idUser= [rs intForColumn:@"id"]; + current.userId= [rs intForColumn:@"id"]; current.url = [rs stringForColumn:@"url"]; current.ssl = [rs intForColumn:@"ssl"]; current.activeaccount = [rs intForColumn:@"activeaccount"]; @@ -358,6 +358,9 @@ + (NSMutableArray *) getAllUsersWithOutCredentialInfo{ current.urlRedirected = [rs stringForColumn:@"url_redirected"]; + current.username = nil; + current.credDto = nil; + current.sortingType = [rs intForColumn:@"sorting_type"]; current.predefinedUrl = [rs stringForColumn:@"predefined_url"]; @@ -394,21 +397,24 @@ + (NSMutableArray *) getAllOldUsersUntilVersion10 { current = [UserDto new]; - current.idUser= [rs intForColumn:@"id"]; + current.userId= [rs intForColumn:@"id"]; current.url = [rs stringForColumn:@"url"]; current.username = [rs stringForColumn:@"username"]; - current.password = [rs stringForColumn:@"password"]; + current.credDto = [OCCredentialsDto new]; + current.credDto.userName = current.username; + current.credDto.accessToken = [rs stringForColumn:@"password"]; + current.credDto.authenticationMethod = k_is_sso_active ? AuthenticationMethodSAML_WEB_SSO : AuthenticationMethodBASIC_HTTP_AUTH; current.ssl = [rs intForColumn:@"ssl"]; current.activeaccount = [rs intForColumn:@"activeaccount"]; current.storageOccupied = [rs longForColumn:@"storage_occupied"]; current.storage = [rs longForColumn:@"storage"]; current.hasShareApiSupport = [rs intForColumn:@"has_share_api_support"]; - DLog(@"id user: %ld", (long)current.idUser); + DLog(@"id user: %ld", (long)current.userId); DLog(@"url user: %@", current.url); DLog(@"username user: %@", current.username); - DLog(@"password user: %@", current.password); + DLog(@"password user: %@", current.credDto.accessToken); [output addObject:current]; @@ -424,14 +430,14 @@ + (NSMutableArray *) getAllOldUsersUntilVersion10 { } -+(void) setActiveAccountByIdUser: (NSInteger) idUser { ++(void) setActiveAccountByUserId: (NSInteger) userId { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE users SET activeaccount=1 WHERE id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"UPDATE users SET activeaccount=1 WHERE id = ?", [NSNumber numberWithInteger:userId]]; if (!correctQuery) { DLog(@"Error setting the active account"); @@ -478,49 +484,49 @@ +(void) setActiveAccountAutomatically { } -+(void) removeUserAndDataByIdUser:(NSInteger)idUser { ++(void) removeUserAndDataByUser:(UserDto *)user { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"DELETE FROM users WHERE id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM users WHERE id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error delete files from files users table"); } - correctQuery = [db executeUpdate:@"DELETE FROM files WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM files WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error delete files from files files table"); } - correctQuery = [db executeUpdate:@"DELETE FROM files_backup WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM files_backup WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error delete files from files_backup backup table"); } - correctQuery = [db executeUpdate:@"DELETE FROM uploads_offline WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM uploads_offline WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error delete files from uploads uploads_offline table"); } - correctQuery = [db executeUpdate:@"DELETE FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM shared WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error delete info of shared table"); } - correctQuery = [db executeUpdate:@"DELETE FROM cookies_storage WHERE user_id = ?", [NSNumber numberWithInteger:idUser]]; + correctQuery = [db executeUpdate:@"DELETE FROM cookies_storage WHERE user_id = ?", [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error delete info of cookies_storage table"); @@ -529,8 +535,7 @@ +(void) removeUserAndDataByIdUser:(NSInteger)idUser { }]; - NSString *idString = [NSString stringWithFormat:@"%ld", (long)idUser]; - if (![OCKeychain removeCredentialsById:idString]) { + if (![OCKeychain removeCredentialsOfUser:user]) { DLog(@"Error delete keychain credentials"); } @@ -544,7 +549,7 @@ +(void) updateStorageByUserDto:(UserDto *) user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE users SET storage_occupied=?, storage=? WHERE id = ?", [NSNumber numberWithLong:user.storageOccupied], [NSNumber numberWithLong:user.storage], [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE users SET storage_occupied=?, storage=? WHERE id = ?", [NSNumber numberWithLong:user.storageOccupied], [NSNumber numberWithLong:user.storage], [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error updating storage of user"); @@ -565,11 +570,11 @@ + (UserDto *) getLastUserInserted { [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT id, url, ssl, activeaccount, storage_occupied, storage, has_share_api_support, has_sharee_api_support, has_cookies_support, has_forbidden_characters_support, has_capabilities_support, image_instant_upload, video_instant_upload, background_instant_upload, path_instant_upload, only_wifi_instant_upload, timestamp_last_instant_upload_image, timestamp_last_instant_upload_video, url_redirected, sorting_type, predefined_url FROM users ORDER BY id DESC LIMIT 1"]; + FMResultSet *rs = [db executeQuery:@"SELECT * FROM users ORDER BY id DESC LIMIT 1"]; while ([rs next]) { - output.idUser = [rs intForColumn:@"id"]; + output.userId = [rs intForColumn:@"id"]; output.url = [rs stringForColumn:@"url"]; output.ssl = [rs intForColumn:@"ssl"]; output.activeaccount = [rs intForColumn:@"activeaccount"]; @@ -611,7 +616,7 @@ + (void) updateUserByUserDto:(UserDto *) user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE users SET url=?, ssl=?, activeaccount=?, storage_occupied=?, storage=?, has_share_api_support=?, has_sharee_api_support=?, has_cookies_support=?, has_forbidden_characters_support=?, has_capabilities_support=?, image_instant_upload=?, video_instant_upload=?, background_instant_upload=?, path_instant_upload=?, only_wifi_instant_upload=?, timestamp_last_instant_upload_image=?, timestamp_last_instant_upload_video=?, url_redirected=?, sorting_type=?, predefined_url=? WHERE id = ?", user.url, [NSNumber numberWithBool:user.ssl], [NSNumber numberWithBool:user.activeaccount], [NSNumber numberWithLong:user.storageOccupied], [NSNumber numberWithLong:user.storage], [NSNumber numberWithInteger:user.hasShareApiSupport], [NSNumber numberWithInteger:user.hasShareeApiSupport], [NSNumber numberWithInteger:user.hasCookiesSupport], [NSNumber numberWithInteger:user.hasForbiddenCharactersSupport], [NSNumber numberWithInteger:user.hasCapabilitiesSupport], [NSNumber numberWithBool:user.imageInstantUpload], [NSNumber numberWithBool:user.videoInstantUpload], [NSNumber numberWithBool:user.backgroundInstantUpload], user.pathInstantUpload, [NSNumber numberWithBool:user.onlyWifiInstantUpload], [NSNumber numberWithLong:user.timestampInstantUploadImage], [NSNumber numberWithLong:user.timestampInstantUploadVideo], user.urlRedirected, [NSNumber numberWithInteger:user.sortingType],user.predefinedUrl, [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE users SET url=?, ssl=?, activeaccount=?, storage_occupied=?, storage=?, has_share_api_support=?, has_sharee_api_support=?, has_cookies_support=?, has_forbidden_characters_support=?, has_capabilities_support=?, image_instant_upload=?, video_instant_upload=?, background_instant_upload=?, path_instant_upload=?, only_wifi_instant_upload=?, timestamp_last_instant_upload_image=?, timestamp_last_instant_upload_video=?, url_redirected=?, sorting_type=?, predefined_url=? WHERE id = ?", user.url, [NSNumber numberWithBool:user.ssl], [NSNumber numberWithBool:user.activeaccount], [NSNumber numberWithLong:user.storageOccupied], [NSNumber numberWithLong:user.storage], [NSNumber numberWithInteger:user.hasShareApiSupport], [NSNumber numberWithInteger:user.hasShareeApiSupport], [NSNumber numberWithInteger:user.hasCookiesSupport], [NSNumber numberWithInteger:user.hasForbiddenCharactersSupport], [NSNumber numberWithInteger:user.hasCapabilitiesSupport], [NSNumber numberWithBool:user.imageInstantUpload], [NSNumber numberWithBool:user.videoInstantUpload], [NSNumber numberWithBool:user.backgroundInstantUpload], user.pathInstantUpload, [NSNumber numberWithBool:user.onlyWifiInstantUpload], [NSNumber numberWithLong:user.timestampInstantUploadImage], [NSNumber numberWithLong:user.timestampInstantUploadVideo], user.urlRedirected, [NSNumber numberWithInteger:user.sortingType],user.predefinedUrl, [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error updating a user"); @@ -645,7 +650,7 @@ + (void) updateSortingWayForUserDto:(UserDto *)user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE users SET sorting_type=? WHERE id = ?", [NSNumber numberWithInteger:user.sortingType], [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE users SET sorting_type=? WHERE id = ?", [NSNumber numberWithInteger:user.sortingType], [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error updating sorting type"); @@ -663,7 +668,7 @@ +(void)updateUrlRedirected:(NSString *)newValue byUserDto:(UserDto *)user { [queue inTransaction:^(FMDatabase *db, BOOL *rollback) { BOOL correctQuery=NO; - correctQuery = [db executeUpdate:@"UPDATE users SET url_redirected=? WHERE id = ?", newValue, [NSNumber numberWithInteger:user.idUser]]; + correctQuery = [db executeUpdate:@"UPDATE users SET url_redirected=? WHERE id = ?", newValue, [NSNumber numberWithInteger:user.userId]]; if (!correctQuery) { DLog(@"Error updating url_redirected"); @@ -679,7 +684,7 @@ +(NSString *)getUrlRedirectedByUserDto:(UserDto *)user { FMDatabaseQueue *queue = Managers.sharedDatabase; [queue inDatabase:^(FMDatabase *db) { - FMResultSet *rs = [db executeQuery:@"SELECT url_redirected FROM users WHERE id = ?", [NSNumber numberWithInteger:user.idUser]]; + FMResultSet *rs = [db executeQuery:@"SELECT url_redirected FROM users WHERE id = ?", [NSNumber numberWithInteger:user.userId]]; while ([rs next]) { diff --git a/Owncloud iOs Client/ExternalLibreries/ELCPickerLib/ELCAlbumPickerController.m b/Owncloud iOs Client/ExternalLibreries/ELCPickerLib/ELCAlbumPickerController.m index f1ccbc283f..7e30b66258 100755 --- a/Owncloud iOs Client/ExternalLibreries/ELCPickerLib/ELCAlbumPickerController.m +++ b/Owncloud iOs Client/ExternalLibreries/ELCPickerLib/ELCAlbumPickerController.m @@ -319,7 +319,7 @@ - (void) addToolBar { //Button to select folder to upload NSString *folderName = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"location", nil), _locationInfo]; - folderName = [[NSString stringWithString:folderName] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + folderName = [[NSString stringWithString:folderName] stringByRemovingPercentEncoding]; [_folderToUploadButton setTitle:folderName]; NSShadow *shadow = [[NSShadow alloc] init]; @@ -360,7 +360,7 @@ - (IBAction) selectFolderToUploadFiles:(id)sender { sf.currentRemoteFolder=self.currentRemoteFolder; //We get the current folder to create the local tree - NSString *localRootUrlString = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.idUser]; + NSString *localRootUrlString = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.userId]; sf.currentLocalFolder = localRootUrlString; @@ -393,7 +393,7 @@ - (void)folderSelected:(NSString*)folder{ // int cont = [splitedUrl count]; NSString *folderName = [NSString stringWithFormat:@"%@",[splitedUrl objectAtIndex:([splitedUrl count]-2)]]; - folderName = [[NSString stringWithString:folderName] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + folderName = [[NSString stringWithString:folderName] stringByRemovingPercentEncoding]; DLog(@"Folder is:%@", folderName); if ([self.currentRemoteFolder isEqualToString:[NSString stringWithFormat:@"%@%@", app.activeUser.url,k_url_webdav_server]]) { diff --git a/Owncloud iOs Client/ExternalLibreries/KKPasscodeLock/KKPasscodeSettingsViewController.m b/Owncloud iOs Client/ExternalLibreries/KKPasscodeLock/KKPasscodeSettingsViewController.m index 74d7b4ac89..174a6969ee 100755 --- a/Owncloud iOs Client/ExternalLibreries/KKPasscodeLock/KKPasscodeSettingsViewController.m +++ b/Owncloud iOs Client/ExternalLibreries/KKPasscodeLock/KKPasscodeSettingsViewController.m @@ -122,7 +122,7 @@ - (void)actionSheet:(UIActionSheet*)actionSheet clickedButtonAtIndex:(NSInteger) - (void)eraseDataSwitchChanged:(id)sender { if (_eraseDataSwitch.on) { - NSString* title = [NSString stringWithFormat:KKPasscodeLockLocalizedString(@"All data in this app will be erased after %d failed passcode attempts.", @""), [[KKPasscodeLock sharedLock] attemptsAllowed]]; +// NSString* title = [NSString stringWithFormat:KKPasscodeLockLocalizedString(@"All data in this app will be erased after %d failed passcode attempts.", @""), [[KKPasscodeLock sharedLock] attemptsAllowed]]; /*UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:KKPasscodeLockLocalizedString(@"Cancel", @"") destructiveButtonTitle:KKPasscodeLockLocalizedString(@"Enable", @"") otherButtonTitles:nil]; [sheet showInView:self.view];*/ diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationDbService.h b/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationDbService.h deleted file mode 100644 index 322d6d7274..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationDbService.h +++ /dev/null @@ -1,72 +0,0 @@ -/** - * SURFnetConextIOSClient AuthenticationDbService - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 - -@interface AuthenticationDbService : NSObject { - - NSString * _authorization_code; - NSString * _access_token; - NSString * _token_type; - NSString * _refresh_token; - NSInteger * _expires_in; - - NSDictionary * demoProperties; - NSString * _data; -} - -+ (id)sharedInstance; - -- (NSString*) getAuthorizeUrl; - -- (NSString*) getAuthorizationCode; -- (void) setAuthorizationCode:(NSString*)authorization_code; - -- (NSString*) getAccessToken; -- (void) setAccessToken:(NSString*)access_token; - -- (NSString*) getTokenType; -- (void) setTokenType:(NSString*)token_type; - -- (NSString*) getRefreshToken; -- (void) setRefreshToken:(NSString*)refresh_token; - -- (NSInteger*) getExpiresIn; -- (void) setExpiresIn:(NSInteger*)expires_in; - -- (NSString*) getScheme; -- (NSString*) getTokenUrl; -- (NSString*) getGrantType; -- (NSString*) getResponseType; -- (NSString*) getClientId; -- (NSString*) getScope; -- (NSString*) getRedirectUri; -- (NSString*) getWebserviceUrl; - -- (NSString*) getData; -- (void) setData:(NSString*)newdata; -- (void) addData:(NSString*)newdata; -- (NSString*) resetData; - - -- (BOOL) isDebugLogEnabled; -- (BOOL) isTraceLogEnabled; - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationDbService.m b/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationDbService.m deleted file mode 100644 index 3e8334dfde..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationDbService.m +++ /dev/null @@ -1,196 +0,0 @@ -/** - * SURFnetConextIOSClient AuthenticationDbService - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 "AuthenticationDbService.h" -#import "constants.h" -#import "Customization.h" - -@implementation AuthenticationDbService - -static AuthenticationDbService *sharedInstance = nil; - -// Get the shared instance and create it if necessary. -+ (AuthenticationDbService *)sharedInstance { - if (sharedInstance == nil) { - sharedInstance = [[super allocWithZone:NULL] init]; - } - - return sharedInstance; -} - -- (id)init -{ - self = [super init]; - - if (self) { - - demoProperties = [NSDictionary dictionaryWithObjectsAndKeys: - @"owncloud", @"scheme", - k_oauth_authorize, @"authorize_url", - @"code", @"authorize_response_type", - @"authorization_code", @"authorize_grant_type", - k_oauth_client_id, @"authorize_client_id", - @"grades", @"authorize_scope", - @"owncloud://callback", @"authorize_redirect_uri", - k_oauth_token, @"token_url", - @"authorization_code", @"token_grant_type", - k_oauth_webservice, @"webservice_url", - @"trace", @"logging", - nil]; - - } - - return self; -} - -- (NSString*) getAuthorizationCode { - return _authorization_code; -} - -- (void) setAuthorizationCode:(NSString*)authorization_code { - _authorization_code = authorization_code; -} - -- (NSString*) getAccessToken -{ - return _access_token; -} - -- (void) setAccessToken:(NSString*)access_token -{ - _access_token = access_token; -} - -- (NSString*) getTokenType -{ - return _token_type; -} -- (void) setTokenType:(NSString*)token_type -{ - _token_type = token_type; -} - -- (NSString*) getRefreshToken -{ - return _refresh_token; -} -- (void) setRefreshToken:(NSString*)refresh_token -{ - _refresh_token = refresh_token; -} - -- (NSInteger*) getExpiresIn -{ - return _expires_in; -} -- (void) setExpiresIn:(NSInteger*)expires_in -{ - _expires_in = expires_in; -} - -- (NSString*) getScheme -{ - return (NSString*)[demoProperties objectForKey:@"scheme"]; -} - -- (NSString*) getAuthorizeUrl -{ - return (NSString*)[demoProperties objectForKey:@"authorize_url"]; -} - -- (NSString*) getTokenUrl -{ - return (NSString*)[demoProperties objectForKey:@"token_url"]; -} - -- (NSString*) getGrantType -{ - return (NSString*)[demoProperties objectForKey:@"authorize_grant_type"]; -} - -- (NSString*) getResponseType -{ - return (NSString*)[demoProperties objectForKey:@"authorize_response_type"]; -} - -- (NSString*) getClientId -{ - return (NSString*)[demoProperties objectForKey:@"authorize_client_id"]; -} - -- (NSString*) getScope -{ - return (NSString*)[demoProperties objectForKey:@"authorize_scope"]; -} - -- (NSString*) getRedirectUri -{ - return (NSString*)[demoProperties objectForKey:@"authorize_redirect_uri"]; -} - -- (NSString*) getWebserviceUrl -{ - return (NSString*)[demoProperties objectForKey:@"webservice_url"]; -} - -- (NSString*) getData { - return _data; -} - -- (void) setData:(NSString*)newdata -{ - _data = newdata; -} - -- (void) addData:(NSString*)newdata -{ - if (_data != nil) { - _data = [NSString stringWithFormat:@"%@%@", _data, newdata]; - } else { - _data = newdata; - } - -} -- (NSString*) resetData -{ - _data = @""; - return _data; -} - - -- (BOOL) isDebugLogEnabled -{ - NSString *level = (NSString*)[demoProperties objectForKey:@"logging"]; - if ([level isEqualToString:@"debug"]) { - return TRUE; - } - - return self.isTraceLogEnabled; -} - -- (BOOL) isTraceLogEnabled -{ - NSString *level = (NSString*)[demoProperties objectForKey:@"logging"]; - if ([level isEqualToString:@"trace"]) { - return TRUE; - } - return FALSE; -} -@end \ No newline at end of file diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.h b/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.h deleted file mode 100644 index f002a4de98..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.h +++ /dev/null @@ -1,29 +0,0 @@ -/** - * SURFnetConextIOSClient AuthenticationResponseTypeCodeTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 - -@interface AuthenticationResponseTypeCodeTask : NSObject { - -} - -- (void)executeRetrieveTask; - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.m b/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.m deleted file mode 100644 index be6e5aee28..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/AuthenticationResponseTypeCodeTask.m +++ /dev/null @@ -1,49 +0,0 @@ -/** - * SURFnetConextIOSClient AuthenticationResponseTypeCodeTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 "AuthenticationResponseTypeCodeTask.h" -#import "AuthenticationDbService.h" - -@implementation AuthenticationResponseTypeCodeTask - -- (NSString*)getUrl -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - - NSString *authorize_url= [dbService getAuthorizeUrl]; - NSString *response_type = [dbService getResponseType]; - NSString *client_id = [dbService getClientId]; - NSString *scope = [dbService getScope]; - NSString *redirect_uri = [dbService getRedirectUri]; - - NSString *full_token_url = [NSString stringWithFormat:@"%@?response_type=%@&client_id=%@&scope=%@&redirect_uri=%@", authorize_url, response_type, client_id, scope, redirect_uri]; - - DLog(@"%@", full_token_url); - - return full_token_url; -} - -- (void)executeRetrieveTask -{ - NSURL *url = [NSURL URLWithString:self.getUrl]; - [[UIApplication sharedApplication] openURL:url]; -} - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveAccessTokenTask.h b/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveAccessTokenTask.h deleted file mode 100644 index 5f601435fc..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveAccessTokenTask.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * SURFnetConextIOSClient RetrieveAccessTokenTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 - -@interface RetrieveAccessTokenTask : NSObject { - - NSURLConnection *_connection; - NSMutableData *receivedData; - -} -- (void)executeRetrieveTask; - - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveAccessTokenTask.m b/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveAccessTokenTask.m deleted file mode 100644 index b7676235cd..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveAccessTokenTask.m +++ /dev/null @@ -1,182 +0,0 @@ -/** - * SURFnetConextIOSClient RetrieveAccessTokenTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 "RetrieveAccessTokenTask.h" -#import "AuthenticationDbService.h" -#import "RetrieveDataResponseTypeCodeTask.h" -#import "AuthenticationResponseTypeCodeTask.h" - -@implementation RetrieveAccessTokenTask - -- (NSString*)getUrl -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - - NSString *token_url= [dbService getTokenUrl]; - - NSString *full_token_url = [NSString stringWithFormat:@"%@", token_url]; - - return full_token_url; -} - -- (NSString*)getParameters -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - - NSString *grant_type = @"refresh_token"; - NSString *refresh_token = [dbService getRefreshToken]; - - NSString *full_token_param = [NSString stringWithFormat:@"grant_type=%@&refresh_token=%@", grant_type, refresh_token]; - - return full_token_param; -} - -- (void)executeRetrieveTask -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isDebugLogEnabled) { - DLog(@"Trying to connect to %@", self.getUrl); - DLog(@"Trying to connect with %@", self.getParameters); - } - NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.getUrl] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:60.0]; - - [theRequest setHTTPMethod:@"POST"]; - [theRequest setHTTPBody:[self.getParameters dataUsingEncoding:NSUTF8StringEncoding]]; - - NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; - if (theConnection) { - receivedData = [[NSMutableData alloc] init]; - } else { - // Inform the user that the connection failed. - } - -} - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didReceiveResponse"); - } - if ([response isKindOfClass:[NSHTTPURLResponse class]]) - { - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response; - if (dbService.isDebugLogEnabled) { - DLog(@"http statuscode = %ld", (long)[httpResponse statusCode]); - } - NSInteger statusCode = [httpResponse statusCode]; - if (statusCode != 200) { - [connection cancel]; - if (dbService.isTraceLogEnabled) { - DLog(@"refresh token is invalid."); - } - AuthenticationResponseTypeCodeTask *task = [[AuthenticationResponseTypeCodeTask alloc] init]; - [task executeRetrieveTask]; - - } else { - - } - - - - } - - [receivedData setLength:0]; -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didReceiveData"); - } - [receivedData appendData:data]; -} - -- (void)connection:(NSURLConnection *)connection - didFailWithError:(NSError *)error -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didFailWithError"); - } - // inform the user - DLog(@"Connection failed! Error - %@ %@", - [error localizedDescription], - [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"connectionDidFinishLoading"); - } - NSError* error; - - NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error]; - - NSString * access_token = [dictionary objectForKey:@"access_token"]; - if (dbService.isDebugLogEnabled) { - DLog(@"access_token = %@", access_token); - } - [dbService setAccessToken:access_token]; - if (dbService.isDebugLogEnabled) { - DLog(@"access_token = %@", [dbService getAccessToken]); - } - - NSString * token_type = [dictionary objectForKey:@"token_type"]; - if (dbService.isDebugLogEnabled) { - DLog(@"token_type = %@", token_type); - } - [dbService setTokenType:token_type]; - - NSString * refresh_token = [dictionary objectForKey:@"refresh_token"]; - if (refresh_token != nil) { - if (dbService.isDebugLogEnabled) { - DLog(@"refresh_token = %@", refresh_token); - } - [dbService setRefreshToken:refresh_token]; - } - - int expires_in = (int)[dictionary objectForKey:@"expires_in"]; - if (expires_in != 0) { - if (dbService.isDebugLogEnabled) { - DLog(@"expires_in = %d", expires_in); - } - NSInteger expiresin = [[NSNumber numberWithInt:expires_in] integerValue]; - [dbService setExpiresIn:(NSInteger*)expiresin]; - } - - NSString * scope = [dictionary objectForKey:@"scope"]; - if (scope != nil) { - if (dbService.isDebugLogEnabled) { - DLog(@"scope = %@", scope); - } - } - - RetrieveDataResponseTypeCodeTask *task = [[RetrieveDataResponseTypeCodeTask alloc] init]; - [task executeRetrieveTask]; -} - -@end - diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.h b/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.h deleted file mode 100644 index b456f1dd34..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.h +++ /dev/null @@ -1,31 +0,0 @@ -/** - * SURFnetConextIOSClient RetrieveDataResponseTypeCodeTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 - -@interface RetrieveDataResponseTypeCodeTask : NSObject { - -NSURLConnection *_connection; -NSMutableData *receivedData; - -} -- (void)executeRetrieveTask; - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.m b/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.m deleted file mode 100644 index 80a42eead2..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveDataResponseTypeCodeTask.m +++ /dev/null @@ -1,144 +0,0 @@ -/** - * SURFnetConextIOSClient RetrieveDataResponseTypeCodeTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 "RetrieveDataResponseTypeCodeTask.h" -#import "AuthenticationDbService.h" -#import "RetrieveAccessTokenTask.h" -#import "AuthenticationResponseTypeCodeTask.h" - -@implementation RetrieveDataResponseTypeCodeTask - -- (NSString*)getUrl -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - - NSString *webserviceUrl = [dbService getWebserviceUrl]; - - NSString *full_token_url = [NSString stringWithFormat:@"%@", webserviceUrl]; - - return full_token_url; -} - -- (void)executeRetrieveTask -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isDebugLogEnabled) { - DLog(@"Trying to connect to %@", self.getUrl); - } - - NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.getUrl] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:60.0]; - - NSString *authHeader = [@"Bearer " stringByAppendingFormat:@"%@", [dbService getAccessToken]]; - [theRequest addValue:authHeader forHTTPHeaderField:@"Authorization"]; - - - NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; - if (theConnection) { - receivedData = [[NSMutableData alloc] init]; - } else { - // Inform the user that the connection failed. - } - -} - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didReceiveResponse"); - } - if ([response isKindOfClass:[NSHTTPURLResponse class]]) - { - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response; - if (dbService.isDebugLogEnabled) { - DLog(@"http statuscode = %ld", (long)[httpResponse statusCode]); - } - NSInteger statusCode = [httpResponse statusCode]; - if (statusCode != 200) { - [connection cancel]; - if (dbService.isTraceLogEnabled) { - DLog(@"retrieve new tokens"); - } - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - [dbService addData:@"retrieve new tokens\n"]; - if ([dbService getRefreshToken] != nil) { - RetrieveAccessTokenTask *task = [[RetrieveAccessTokenTask alloc] init]; - [task executeRetrieveTask]; - } else { - AuthenticationResponseTypeCodeTask *task = [[AuthenticationResponseTypeCodeTask alloc] init]; - [task executeRetrieveTask]; - } - - } else { - - } - } - - [receivedData setLength:0]; -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didReceiveData"); - } - [receivedData appendData:data]; -} - -- (void)connection:(NSURLConnection *)connection - didFailWithError:(NSError *)error -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didFailWithError"); - } - - // inform the user - DLog(@"Connection failed! Error - %@ %@", - [error localizedDescription], - [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"connectionDidFinishLoading"); - } - NSError* error; - - NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error]; - - NSString *str = [dictionary description]; - NSString *truncatedString = [str substringToIndex:[str length]-1]; - NSString * finalTruncatedString = [truncatedString substringFromIndex:1]; - - [dbService addData:finalTruncatedString]; - - [[NSNotificationCenter defaultCenter] postNotificationName:@"ResultViewUpdate" object:nil]; - -} - - - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.h b/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.h deleted file mode 100644 index 30e0d23efe..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.h +++ /dev/null @@ -1,32 +0,0 @@ -/** - * SURFnetConextIOSClient RetrieveRefreshAndAccessTokenTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 - -@interface RetrieveRefreshAndAccessTokenTask : NSObject { - - NSURLConnection *_connection; - NSMutableData *receivedData; - -} -- (void)executeRetrieveTask; - - -@end diff --git a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.m b/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.m deleted file mode 100644 index 5591b273f0..0000000000 --- a/Owncloud iOs Client/ExternalLibreries/OAuth/RetrieveRefreshAndAccessTokenTask.m +++ /dev/null @@ -1,199 +0,0 @@ -/** - * SURFnetConextIOSClient RetrieveRefreshAndAccessTokenTask - * Created by Jochem Knoops. - - * LICENSE - * - * Copyright 2012 SURFnet bv, The Netherlands - * - * 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 "RetrieveRefreshAndAccessTokenTask.h" -#import "AuthenticationDbService.h" -#import "RetrieveDataResponseTypeCodeTask.h" -#import "UserDto.h" -#import "constants.h" - -#import "AppDelegate.h" - - -@implementation RetrieveRefreshAndAccessTokenTask - -- (NSString*)getUrl -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - - NSString *token_url= [dbService getTokenUrl]; - NSString *grant_type = [dbService getGrantType]; - NSString *client_id = [dbService getClientId]; - NSString *redirect_uri = [dbService getRedirectUri]; - NSString *code = [dbService getAuthorizationCode]; - - NSString *full_token_url = [NSString stringWithFormat:@"%@?grant_type=%@&client_id=%@&redirect_uri=%@&code=%@", token_url, grant_type, client_id, redirect_uri, code]; - - DLog(@"TOKEN: %@", token_url); - - return full_token_url; -} - -- (NSString*)getParameters -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - - NSString *grant_type = [dbService getGrantType]; - NSString *client_id = [dbService getClientId]; - NSString *redirect_uri = [dbService getRedirectUri]; - NSString *code = [dbService getAuthorizationCode]; - - NSString *full_token_param = [NSString stringWithFormat:@"grant_type=%@&client_id=%@&redirect_uri=%@&code=%@", grant_type, client_id, redirect_uri, code]; - - return full_token_param; -} - -- (void)executeRetrieveTask -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isDebugLogEnabled) { - DLog(@"Trying to connect to %@", self.getUrl); - DLog(@"Trying to connect with %@", self.getParameters); - } - NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.getUrl] - cachePolicy:NSURLRequestUseProtocolCachePolicy - timeoutInterval:60.0]; - - [theRequest setHTTPMethod:@"POST"]; - [theRequest setHTTPBody:[self.getParameters dataUsingEncoding:NSUTF8StringEncoding]]; - - NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; - if (theConnection) { - receivedData = [[NSMutableData alloc] init]; - } else { - // Inform the user that the connection failed. - } - -} - -- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didReceiveResponse"); - } - if ([response isKindOfClass:[NSHTTPURLResponse class]]) - { - NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response; - if (dbService.isDebugLogEnabled) { - DLog(@"response1 = %ld", (long)[httpResponse statusCode]); - DLog(@"response2 = %@", [httpResponse allHeaderFields]); - } - } - - [receivedData setLength:0]; -} - -- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didReceiveData"); - } - [receivedData appendData:data]; -} - -- (void)connection:(NSURLConnection *)connection - didFailWithError:(NSError *)error -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"didFailWithError"); - } - - // inform the user - DLog(@"Connection failed! Error - %@ %@", - [error localizedDescription], - [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); -} - -- (void)connectionDidFinishLoading:(NSURLConnection *)connection -{ - AuthenticationDbService * dbService = [AuthenticationDbService sharedInstance]; - if (dbService.isTraceLogEnabled) { - DLog(@"connectionDidFinishLoading"); - } - NSError* error; - - NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error]; - - NSString * access_token = [dictionary objectForKey:@"access_token"]; - if (dbService.isDebugLogEnabled) { - DLog(@"access_token = %@", access_token); - - - /* - UserDto *userDto = [[UserDto alloc] init]; - - - NSString *userName = @"OAuth"; - NSString *password = access_token; - - userDto.url = k_default_url_server; - userDto.username = userName; - userDto.password = password; - userDto.ssl = [k_default_url_server hasPrefix:@"https"]; - userDto.activeaccount = YES; - - [ExecuteManager insertUser:userDto];*/ - - AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - appDelegate.oauthToken = access_token; - [appDelegate doLoginWithOauthToken]; - } - [dbService setAccessToken:access_token]; - - NSString * token_type = [dictionary objectForKey:@"token_type"]; - if (dbService.isDebugLogEnabled) { - DLog(@"token_type = %@", token_type); - } - [dbService setTokenType:token_type]; - - NSString * refresh_token = [dictionary objectForKey:@"refresh_token"]; - if (refresh_token != nil) { - if (dbService.isDebugLogEnabled) { - DLog(@"refresh_token = %@", refresh_token); - } - [dbService setRefreshToken:refresh_token]; - } - - int expires_in = (int)[dictionary objectForKey:@"expires_in"]; - if (expires_in != 0) { - if (dbService.isDebugLogEnabled) { - DLog(@"expires_in = %d", expires_in); - } - NSInteger expiresin = [[NSNumber numberWithInt:expires_in] integerValue]; - [dbService setExpiresIn:(NSInteger*)expiresin]; - } - - NSString * scope = [dictionary objectForKey:@"scope"]; - if (scope != nil) { - if (dbService.isDebugLogEnabled) { - DLog(@"scope = %@", scope); - } - } - - - - /*RetrieveDataResponseTypeCodeTask *task = [[RetrieveDataResponseTypeCodeTask alloc] init]; - [task executeRetrieveTask];*/ -} - -@end diff --git a/Owncloud iOs Client/Files/Preview/DetailView/DetailViewController.m b/Owncloud iOs Client/Files/Preview/DetailView/DetailViewController.m index 0532a8546d..b385e5bc7e 100755 --- a/Owncloud iOs Client/Files/Preview/DetailView/DetailViewController.m +++ b/Owncloud iOs Client/Files/Preview/DetailView/DetailViewController.m @@ -18,7 +18,6 @@ #import "AppDelegate.h" #import "UIColor+Constants.h" #import "constants.h" -#import "EditAccountViewController.h" #import "UtilsDtos.h" #import "UIImage+Resize.h" #import "FileNameUtils.h" @@ -160,7 +159,7 @@ - (void)configureView //TitleLabel if (_file) { - [_titleLabel setText:[_file.fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]]; + [_titleLabel setText:[_file.fileName stringByRemovingPercentEncoding]]; } else if (_isFileCharged==NO && _file==nil){ [_titleLabel setText:_linkTitle]; } else { @@ -270,8 +269,8 @@ - (void) handleFile:(FileDto*)myFile fromController:(NSInteger)controller andIsF self.isForceDownload = isForceDownload; //Get the current local folder - _currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.idUser, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:myFile.filePath andUser:app.activeUser]]; - _currentLocalFolder = [_currentLocalFolder stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + _currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.userId, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:myFile.filePath andUser:app.activeUser]]; + _currentLocalFolder = [_currentLocalFolder stringByRemovingPercentEncoding]; //Quit the title _linkTitle=@""; @@ -286,7 +285,7 @@ - (void) handleFile:(FileDto*)myFile fromController:(NSInteger)controller andIsF //Stop the notification [self stopNotificationUpdatingFile]; //Put the title in the toolBar - [_titleLabel setText:[_file.fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]]; + [_titleLabel setText:[_file.fileName stringByRemovingPercentEncoding]]; _isViewBlocked = NO; //Remove the views @@ -728,7 +727,7 @@ - (void) removeSelectedIndexPath { */ - (void)putTitleInNavBarByName:(NSString *) fileName{ - [_titleLabel setText:[fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]]; + [_titleLabel setText:[fileName stringByRemovingPercentEncoding]]; } @@ -1831,20 +1830,13 @@ - (void)errorLogin { AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate]; [appDelegate.downloadManager errorLogin]; - - if(k_is_oauth_active) { - NSURL *url = [NSURL URLWithString:k_oauth_login]; - [[UIApplication sharedApplication] openURL:url]; - - } else { - EditAccountViewController *viewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:appDelegate.activeUser andLoginMode:LoginModeExpire]; - [viewController setBarForCancelForLoadingFromModal]; + + UniversalLoginViewController *viewController = [UtilsLogin getLoginVCWithMode:LoginModeExpire andUser:APP_DELEGATE.activeUser]; - OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController]; - navController.modalPresentationStyle = UIModalPresentationFormSheet; - [appDelegate.splitViewController presentViewController:navController animated:YES completion:nil]; - } + OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController]; + navController.modalPresentationStyle = UIModalPresentationFormSheet; + [appDelegate.splitViewController presentViewController:navController animated:YES completion:nil]; } #pragma mark - Notifications methods @@ -1957,7 +1949,7 @@ - (void) showTextInStatusBar { } //File name - NSString *notificationText = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"updating", nil), [nameFileToUpdate stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *notificationText = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"updating", nil), [nameFileToUpdate stringByRemovingPercentEncoding]]; DLog(@"name: %@",notificationText); [_notification displayNotificationWithMessage:notificationText completion:nil]; } diff --git a/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.h b/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.h index a7e45f683d..70835d280b 100644 --- a/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.h +++ b/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.h @@ -35,7 +35,7 @@ extern NSString * iPhoneCleanPreviewNotification; extern NSString * iPhoneShowNotConnectionWithServerMessageNotification; -@interface FilePreviewViewController : UIViewController +@interface FilePreviewViewController : UIViewController { //Autolayout attributes IBOutlet NSLayoutConstraint *_progressViewHeightConstraint; diff --git a/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.m b/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.m index cacbd7b1af..ba22ac2fec 100644 --- a/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.m +++ b/Owncloud iOs Client/Files/Preview/FilePreview/FilePreviewViewController.m @@ -19,7 +19,6 @@ #import "UIColor+Constants.h" #import "constants.h" #import "AppDelegate.h" -#import "EditAccountViewController.h" #import "UtilsDtos.h" #import "UIImage+Resize.h" #import "UserDto.h" @@ -129,8 +128,8 @@ - (void)viewDidLoad //Get current local folder AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - _currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.idUser, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:_file.filePath andUser:app.activeUser]]; - _currentLocalFolder = [_currentLocalFolder stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + _currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.userId, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:_file.filePath andUser:app.activeUser]]; + _currentLocalFolder = [_currentLocalFolder stringByRemovingPercentEncoding]; //Obtain the type of file _typeOfFile = [FileNameUtils checkTheTypeOfFile:_file.fileName]; @@ -231,7 +230,6 @@ - (void) didSelectEditView { navController.navigationBar.translucent = NO; if (IS_IPHONE) { - viewController.hidesBottomBarWhenPushed = YES; [self presentViewController:navController animated:YES completion:nil]; } else { navController.modalPresentationStyle = UIModalPresentationFormSheet; @@ -359,7 +357,7 @@ - (void) showTextInStatusBar { } //File name - NSString *notificationText = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"updating", nil), [nameFileToUpdate stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *notificationText = [NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"updating", nil), [nameFileToUpdate stringByRemovingPercentEncoding]]; DLog(@"name: %@",notificationText); [_notification displayNotificationWithMessage:notificationText completion:nil]; } @@ -1694,21 +1692,14 @@ - (void) errorLogin { AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate]; [appDelegate.downloadManager errorLogin]; - if(k_is_oauth_active) { - NSURL *url = [NSURL URLWithString:k_oauth_login]; - [[UIApplication sharedApplication] openURL:url]; - } else { - //Edit Account - AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; + //Edit Account - EditAccountViewController *viewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:app.activeUser andLoginMode:LoginModeExpire]; + UniversalLoginViewController *loginVC = [UtilsLogin getLoginVCWithMode:LoginModeExpire andUser: APP_DELEGATE.activeUser]; - viewController.hidesBottomBarWhenPushed = YES; - OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController]; - [self.navigationController presentViewController:navController animated:YES completion:nil]; + OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:loginVC]; + [self.navigationController presentViewController:navController animated:YES completion:nil]; - } [self didPressCancelButton:nil]; } diff --git a/Owncloud iOs Client/Files/PreviewSupportedFiles/Gallery/GalleryView.m b/Owncloud iOs Client/Files/PreviewSupportedFiles/Gallery/GalleryView.m index 838eaf9418..45a5e30cc7 100644 --- a/Owncloud iOs Client/Files/PreviewSupportedFiles/Gallery/GalleryView.m +++ b/Owncloud iOs Client/Files/PreviewSupportedFiles/Gallery/GalleryView.m @@ -220,8 +220,8 @@ - (void)initScrollView{ */ - (void)updateTheCurrentLocalFolder{ AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - _currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.idUser, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:_file.filePath andUser:app.activeUser]]; - _currentLocalFolder = [_currentLocalFolder stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + _currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.userId, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:_file.filePath andUser:app.activeUser]]; + _currentLocalFolder = [_currentLocalFolder stringByRemovingPercentEncoding]; } diff --git a/Owncloud iOs Client/Files/UploadFromOtherApp/UploadFromOtherAppViewController.m b/Owncloud iOs Client/Files/UploadFromOtherApp/UploadFromOtherAppViewController.m index 2991ea86b5..197fecfd30 100644 --- a/Owncloud iOs Client/Files/UploadFromOtherApp/UploadFromOtherAppViewController.m +++ b/Owncloud iOs Client/Files/UploadFromOtherApp/UploadFromOtherAppViewController.m @@ -31,7 +31,6 @@ #import "OCErrorMsg.h" #import "FileNameUtils.h" #import "UtilsNetworkRequest.h" -#import "EditAccountViewController.h" #import "Download.h" #import "FilePreviewViewController.h" #import "NSString+Encoding.h" @@ -400,7 +399,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N NSString *accountString=[NSString stringWithFormat:@"%@@%@", _userName, _serverName]; //If SAML enabled replacing the escapes if (k_is_sso_active) { - accountString=[accountString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + accountString=[accountString stringByRemovingPercentEncoding]; } cell.textLabel.text=accountString; cell.textLabel.font=cellBoldFont; @@ -410,7 +409,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N }else if (indexPath.section==2) { cell.selectionStyle=UITableViewCellSelectionStyleBlue; - NSString *fName= [_folderName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *fName= [_folderName stringByRemovingPercentEncoding]; cell.textLabel.text=fName; cell.textLabel.font=cellBoldFont; [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; @@ -442,7 +441,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N } else { NSString *fileName; fileName=[self getFileName:_filePath]; - [_nameFileTextField setText:[fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + [_nameFileTextField setText:[fileName stringByRemovingPercentEncoding]]; } [cell.contentView addSubview:_nameFileTextField]; @@ -486,7 +485,7 @@ - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath sf.currentRemoteFolder=_remoteFolder; //We get the current folder to create the local tree - NSString *localRootUrlString = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.idUser]; + NSString *localRootUrlString = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath],(long)app.activeUser.userId]; sf.currentLocalFolder = localRootUrlString; @@ -568,7 +567,7 @@ - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger [nameLabel setLineBreakMode:NSLineBreakByTruncatingMiddle]; [nameLabel setClipsToBounds:YES]; - nameLabel.text=[fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + nameLabel.text=[fileName stringByRemovingPercentEncoding]; // nameLabel.text=fileName; //Label of size @@ -865,8 +864,7 @@ - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRang - (void)showEditAccountViewController{ AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - - EditAccountViewController *viewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:app.activeUser andLoginMode:LoginModeExpire]; + UniversalLoginViewController *viewController = [UtilsLogin getLoginVCWithMode:LoginModeExpire andUser: app.activeUser]; if (IS_IPHONE) { diff --git a/Owncloud iOs Client/Launch Screen.storyboard b/Owncloud iOs Client/Launch Screen.storyboard index f2340029d8..609c38a15e 100644 --- a/Owncloud iOs Client/Launch Screen.storyboard +++ b/Owncloud iOs Client/Launch Screen.storyboard @@ -1,10 +1,11 @@ - - + + + + + - - - - + + @@ -16,25 +17,15 @@ - + - - - - - + + + - - - - - - - - - + diff --git a/Owncloud iOs Client/Log.swift b/Owncloud iOs Client/Log.swift new file mode 100644 index 0000000000..96a7eeb73e --- /dev/null +++ b/Owncloud iOs Client/Log.swift @@ -0,0 +1,40 @@ +// +// Log.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 12/07/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + + +import Foundation + + +//class Log { +// +// var intFor : Int +// +// init() { +// intFor = 42 +// } +// +// func DLog(message: String, function: String = #function) { +// +// #if DEBUG_MODE +// let lastPathOfFile = (#file as NSString).lastPathComponent +// print("<\(self) \(lastPathOfFile):(\(#line)> (\(message)), \(##__VA_ARGS__)" ) +// #else +// print("\(message)") +// #endif +// } +//} + + diff --git a/Owncloud iOs Client/Login/Keychain/OCKeychain.h b/Owncloud iOs Client/Login/Keychain/OCKeychain.h index a6f3b99acb..9c87a42aea 100644 --- a/Owncloud iOs Client/Login/Keychain/OCKeychain.h +++ b/Owncloud iOs Client/Login/Keychain/OCKeychain.h @@ -6,7 +6,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -14,16 +14,49 @@ */ #import -#import "CredentialsDto.h" +#import "OCCredentialsDto.h" +#import "UtilsUrls.h" +#import "ManageUsersDB.h" +#import "UserDto.h" +#import "Customization.h" +#import "OCCredentialsStorage.h" -@interface OCKeychain : NSObject -+(BOOL)setCredentialsById:(NSString *)idUser withUsername:(NSString *)userName andPassword:(NSString *)password; -+(CredentialsDto *)getCredentialsById:(NSString *)idUser; -+(BOOL)removeCredentialsById:(NSString *)idUser; -+(BOOL)updateCredentialsById:(NSString *)idUser withUsername:(NSString *)userName andPassword:(NSString *)password; -+(BOOL)updateKeychainForUseLockPropertyForUser:(NSString *)idUser; +@interface OCKeychain : NSObject + ++(BOOL)storeCredentials:(OCCredentialsDto *)credDto; + +/** + * @return CredentialsDto -> New credentialDto with all the new data added to support oauth + */ ++(OCCredentialsDto *)getCredentialsOfUser:(UserDto *)user; + ++(BOOL)removeCredentialsOfUser:(UserDto *)user; ++(BOOL)updateCredentials:(OCCredentialsDto *)credDto; +(BOOL)resetKeychain; -+(void)updateAllKeychainsToUseTheLockProperty; + + +/** + * Following methods are used to migrate keychain items + */ + +/** + * Only used to migrate old database user into keychain items in change of DB version 9to10 + */ ++(BOOL)storeCredentialsOfUserFromDBVersion9To10:(UserDto *)user; + +///----------------------------------- +/// @name updateAllKeychainsToUseTheLockProperty +///----------------------------------- + +/** + * This method updates all the credentials to use a property to allow to access to them when the passcode system is set. + * Used in db update 12-13 + */ ++(BOOL)updateAllKeychainItemsToUseTheLockProperty; + + ++(void)updateAllKeychainItemsFromDBVersion21To22ToStoreCredentialsDtoAsValueAndAuthenticationType; + @end diff --git a/Owncloud iOs Client/Login/Keychain/OCKeychain.m b/Owncloud iOs Client/Login/Keychain/OCKeychain.m index 724f628788..f3932aca7c 100644 --- a/Owncloud iOs Client/Login/Keychain/OCKeychain.m +++ b/Owncloud iOs Client/Login/Keychain/OCKeychain.m @@ -6,7 +6,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -15,15 +15,31 @@ #import "OCKeychain.h" #import -#import "CredentialsDto.h" -#import "UtilsUrls.h" -#import "ManageUsersDB.h" -#import "UserDto.h" + @implementation OCKeychain +#pragma mark - OCCredentialsStorageDelegate +- (void) saveCredentials:(OCCredentialsDto *)credDto { -+(BOOL)setCredentialsById:(NSString *)idUser withUsername:(NSString *)userName andPassword:(NSString *)password{ + [OCKeychain updateCredentials:credDto]; + +#ifdef CONTAINER_APP + + if ([credDto.userId integerValue] == [ManageUsersDB getActiveUser].userId) { + APP_DELEGATE.activeUser = [ManageUsersDB getActiveUser]; + } +#endif +} + +#pragma mark - set credentials + ++(BOOL)storeCredentials:(OCCredentialsDto *)credDto { + return [OCKeychain storeCredentials:credDto migratingFromDB9to10:NO]; +} + +// private implementation, common to both setCredentialsOfUser and setCredentialsOfUserToFromDbVersion9To10 ++(BOOL)storeCredentials:(OCCredentialsDto *)credDto migratingFromDB9to10:(BOOL)migratingFromDB9to10 { BOOL output = NO; @@ -31,214 +47,245 @@ +(BOOL)setCredentialsById:(NSString *)idUser withUsername:(NSString *)userName a [keychainItem setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; [keychainItem setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlock) forKey:(__bridge id)kSecAttrAccessible]; - [keychainItem setObject:idUser forKey:(__bridge id)kSecAttrAccount]; - [keychainItem setObject:userName forKey:(__bridge id)kSecAttrDescription]; [keychainItem setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; - + + [keychainItem setObject:credDto.userId forKey:(__bridge id)kSecAttrAccount]; OSStatus stsExist = SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, NULL); if(stsExist == errSecSuccess) { - NSLog(@"Unable add item with id =%@ error",idUser); - }else { - [keychainItem setObject:[password dataUsingEncoding:NSUTF8StringEncoding] forKey:(__bridge id)kSecValueData]; + NSLog(@"Error, unable to add keychain item with username =%@",credDto.userName); + + } else { + + if (migratingFromDB9to10) { + //to support upgrades from 9to10 db version, in 21to22 is going to be updated to use credDto as kSecValueData + [keychainItem setObject:[credDto.accessToken dataUsingEncoding:NSUTF8StringEncoding] forKey:(__bridge id)kSecValueData]; + [keychainItem setObject:credDto.userName forKey:(__bridge id)kSecAttrDescription]; + } else { + NSData *encodedCredDto = [NSKeyedArchiver archivedDataWithRootObject:credDto]; + [keychainItem setObject:encodedCredDto forKey:(__bridge id)kSecValueData]; + } + OSStatus stsAdd = SecItemAdd((__bridge CFDictionaryRef)keychainItem, NULL); - NSLog(@"(setCredentials)Error Code: %d", (int)stsAdd); + NSLog(@"(setCredentials)Error Code: %d (0 = success)", (int)stsAdd); if (stsAdd == errSecSuccess) { output = YES; } - } return output; } +#pragma mark - get credentials -+(CredentialsDto *)getCredentialsById:(NSString *)idUser{ - - CredentialsDto *output = nil; ++(NSDictionary *)getKeychainDictionaryOfUserId:(NSString *)userId { + NSDictionary *resultDict = nil; + NSMutableDictionary *keychainItem = [NSMutableDictionary dictionary]; [keychainItem setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; - [keychainItem setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlock) forKey:(__bridge id)kSecAttrAccessible]; - [keychainItem setObject:idUser forKey:(__bridge id)kSecAttrAccount]; [keychainItem setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; + [keychainItem setObject:userId forKey:(__bridge id)kSecAttrAccount]; + [keychainItem setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData]; [keychainItem setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnAttributes]; CFDictionaryRef result = nil; - - DLog(@"keychainItem: %@", keychainItem); - + OSStatus stsExist = SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, (CFTypeRef *)&result); - DLog(@"(getCredentials)Error Code %d", (int)stsExist); + DLog(@"(getCredentials)Error Code %d (0 = success)", (int)stsExist); if (stsExist != errSecSuccess) { - NSLog(@"Unable to get the item with id =%@ ",idUser); + NSLog(@"Unable to get the item with userId=%@ ",userId); } else { - NSDictionary *resultDict = (__bridge_transfer NSDictionary *)result; + resultDict = (__bridge_transfer NSDictionary *)result; + } + + return resultDict; +} + ++(OCCredentialsDto *)getCredentialsOfUser:(UserDto *)user { + return [self getCredentialsOfUser:user fromPreviousDBVersion22:NO]; +} + ++(OCCredentialsDto *)getCredentialsOfUser:(UserDto *)user fromPreviousDBVersion22:(BOOL)previousDB22{ + + OCCredentialsDto *credentialsDto = nil; + + NSString *userId = [NSString stringWithFormat:@"%ld",(long)user.userId]; + NSDictionary *resultKeychainDict = [self getKeychainDictionaryOfUserId:userId]; + + if (resultKeychainDict) { - NSData *pswd = resultDict[(__bridge id)kSecValueData]; - NSString *password = [[NSString alloc] initWithData:pswd encoding:NSUTF8StringEncoding]; - output = [CredentialsDto new]; + NSData *resultData = resultKeychainDict[(__bridge id)kSecValueData]; - output.password = password; - output.userName = resultDict[(__bridge id)kSecAttrDescription]; + if (resultData) { + + if (previousDB22) { + credentialsDto = [OCCredentialsDto new]; + credentialsDto.userId = resultKeychainDict[(__bridge id)kSecAttrAccount]; + credentialsDto.userName = resultKeychainDict[(__bridge id)kSecAttrDescription]; + credentialsDto.accessToken = [[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding]; + credentialsDto.baseURL = [UtilsUrls getFullRemoteServerPath:user]; + credentialsDto.userDisplayName = @""; + } else { + credentialsDto = [NSKeyedUnarchiver unarchiveObjectWithData: resultData]; + } + } } - return output; - + return credentialsDto; } -+(BOOL)removeCredentialsById:(NSString *)idUser{ + +#pragma mark - remove credentials + ++(BOOL)removeCredentialsOfUser:(UserDto *)user { BOOL output = NO; - + NSMutableDictionary *keychainItem = [NSMutableDictionary dictionary]; [keychainItem setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; - [keychainItem setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlock) forKey:(__bridge id)kSecAttrAccessible]; - [keychainItem setObject:idUser forKey:(__bridge id)kSecAttrAccount]; [keychainItem setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; + NSString *userId = [NSString stringWithFormat:@"%ld",(long)user.userId]; + [keychainItem setObject:userId forKey:(__bridge id)kSecAttrAccount]; OSStatus stsExist = SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, NULL); NSLog(@"(removeCredentials)Error Code: %d", (int)stsExist); if(stsExist != errSecSuccess) { - NSLog(@"Unable to delete the item with id =%@ ",idUser); + NSLog(@"Unable to delete the item with username=%@ ",user.credDto.userName); } else { OSStatus sts = SecItemDelete((__bridge CFDictionaryRef)keychainItem); - NSLog(@"Error Code: %d", (int)sts); + NSLog(@"Error Code: %d (0 = success)", (int)sts); if (sts == errSecSuccess) { output = YES; } } return output; - } -+(BOOL)updateCredentialsById:(NSString *)idUser withUsername:(NSString *)userName andPassword:(NSString *)password { + +#pragma mark - update credentials + ++(BOOL)updateCredentials:(OCCredentialsDto *)credDto { BOOL output = NO; NSMutableDictionary *keychainItem = [NSMutableDictionary dictionary]; [keychainItem setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; - [keychainItem setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlock) forKey:(__bridge id)kSecAttrAccessible]; - [keychainItem setObject:idUser forKey:(__bridge id)kSecAttrAccount]; [keychainItem setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; + [keychainItem setObject:credDto.userId forKey:(__bridge id)kSecAttrAccount]; + + OSStatus stsExist = SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, NULL); if(stsExist != errSecSuccess) { - NSLog(@"Unable to update keychain item with id =%@ ",idUser); - + NSLog(@"Unable to update keychain item with userId=%@",credDto.userId); }else { NSMutableDictionary *attrToUpdate = [NSMutableDictionary dictionary]; - if (password != nil){ - [attrToUpdate setObject:[password dataUsingEncoding:NSUTF8StringEncoding] forKey:(__bridge id)kSecValueData]; - } - if (userName != nil) { - [attrToUpdate setObject:userName forKey:(__bridge id)kSecAttrDescription]; - } + NSData *encodedCredDto = [NSKeyedArchiver archivedDataWithRootObject:credDto]; + [attrToUpdate setObject:encodedCredDto forKey:(__bridge id)kSecValueData]; OSStatus stsUpd = SecItemUpdate((__bridge CFDictionaryRef)(keychainItem), (__bridge CFDictionaryRef)(attrToUpdate)); - NSLog(@"(updateKeychainCredentials)Error Code: %d", (int)stsUpd); + NSLog(@"(updateKeychainCredentials)Error Code: %d (0 = success)", (int)stsUpd); if (stsUpd == errSecSuccess) { output = YES; } + } - return output; } -+ (BOOL)updateKeychainForUseLockPropertyForUser:(NSString *)idUser{ + +#pragma mark - Reset all OC keychain items + ++(BOOL)resetKeychain{ BOOL output = NO; - NSMutableDictionary *keychainItem = [NSMutableDictionary dictionary]; - - [keychainItem setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; - [keychainItem setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey:(__bridge id)kSecAttrAccessible]; - [keychainItem setObject:idUser forKey:(__bridge id)kSecAttrAccount]; - [keychainItem setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; + NSMutableDictionary *keychainQuery = [NSMutableDictionary dictionary]; - OSStatus stsExist = SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, NULL); + [keychainQuery setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; + [keychainQuery setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; - if(stsExist != errSecSuccess) { - DLog(@"Unable to update item with id =%@ ",idUser); - - }else { - - NSMutableDictionary *attrToUpdate = [NSMutableDictionary dictionary]; - - [attrToUpdate setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlock) forKey:(__bridge id)kSecAttrAccessible]; - - OSStatus stsUpd = SecItemUpdate((__bridge CFDictionaryRef)(keychainItem), (__bridge CFDictionaryRef)(attrToUpdate)); - - DLog(@"(updateLockProperty)Error Code: %d", (int)stsUpd); - - if (stsUpd == errSecSuccess) { - output = YES; - } - + OSStatus sts = SecItemDelete((__bridge CFDictionaryRef)keychainQuery); + NSLog(@"Reset keychain Error Code: %d (0 = success)", (int)sts); + if (sts == errSecSuccess) { + output = YES; } return output; - } -+(BOOL)resetKeychain{ + +#pragma mark - Update all OC keychain items + ++ (BOOL) updateAllKeychainItemsToUseTheLockProperty { BOOL output = NO; - + NSMutableDictionary *keychainQuery = [NSMutableDictionary dictionary]; [keychainQuery setObject:(__bridge id)(kSecClassGenericPassword) forKey:(__bridge id)kSecClass]; [keychainQuery setObject:[UtilsUrls getFullBundleSecurityGroup] forKey:(__bridge id)kSecAttrAccessGroup]; - OSStatus sts = SecItemDelete((__bridge CFDictionaryRef)keychainQuery); - NSLog(@"Reset keychain Error Code: %d", (int)sts); - if (sts == errSecSuccess) { + NSMutableDictionary *attrToUpdate = [NSMutableDictionary dictionary]; + [attrToUpdate setObject:(__bridge id)(kSecAttrAccessibleAfterFirstUnlock) forKey:(__bridge id)kSecAttrAccessible]; + + OSStatus stsUpd = SecItemUpdate((__bridge CFDictionaryRef)(keychainQuery), (__bridge CFDictionaryRef)(attrToUpdate)); + DLog(@"(updateLockProperty)Error Code: %d (0 = success)", (int)stsUpd); + if (stsUpd == errSecSuccess) { output = YES; } - return output; +} + +#pragma mark - keychain updates after some db updates + +#pragma mark - used to update from db version 9to10, from db to keychain ++(BOOL)storeCredentialsOfUserFromDBVersion9To10:(UserDto *)user { + return [OCKeychain storeCredentials:user.credDto migratingFromDB9to10:YES]; } -///----------------------------------- -/// @name updateAllKeychainsToUseTheLockProperty -///----------------------------------- +#pragma mark - used to update from db version 21to22 -/** - * This method updates all the credentials to use a property to allow to access to them when the passcode system is set. - */ -+ (void) updateAllKeychainsToUseTheLockProperty{ ++ (void)updateAllKeychainItemsFromDBVersion21To22ToStoreCredentialsDtoAsValueAndAuthenticationType { for (UserDto *user in [ManageUsersDB getAllUsersWithOutCredentialInfo]) { - NSString *idString = [NSString stringWithFormat:@"%ld", (long)user.idUser]; - - [OCKeychain updateKeychainForUseLockPropertyForUser:idString]; + user.credDto = [OCKeychain getCredentialsOfUser:user fromPreviousDBVersion22:YES]; + if (user.credDto) { + user.credDto.authenticationMethod = k_is_sso_active ? AuthenticationMethodSAML_WEB_SSO : AuthenticationMethodBASIC_HTTP_AUTH; + + [OCKeychain updateCredentials:user.credDto]; + + } else { + DLog(@"Not possible to update keychain with userId: %ld", (long)user.userId); + } } - } + @end diff --git a/Owncloud iOs Client/Login/Login/GetPublicInfoFromServerJob.swift b/Owncloud iOs Client/Login/Login/GetPublicInfoFromServerJob.swift new file mode 100644 index 0000000000..d585d0f5ab --- /dev/null +++ b/Owncloud iOs Client/Login/Login/GetPublicInfoFromServerJob.swift @@ -0,0 +1,116 @@ +// +// GetPublicInfoFromServerJob.swift +// Owncloud iOs Client +// +// Created by David A. Velasco on 19/7/17. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +import Foundation + + +class GetPublicInfoFromServerJob: NSObject, CheckAccessToServerDelegate { + + var serverURL: String + + var enforcedScheme: String + + var fullUrl: String { + get { + return "\(self.enforcedScheme)\(self.serverURL)" + } + } + + var checkAccessToServerJob: CheckAccessToServer + + var completion: ((_ validatedURL: String?, _ serverAuthenticationMethods: Array?, _ error: Error?, _ httpStatusCode: NSInteger) -> Void)? + + override init() { + serverURL = "" + enforcedScheme = "" + checkAccessToServerJob = CheckAccessToServer.sharedManager() as! CheckAccessToServer + super.init() + } + + func start(serverURL: String, withCompletion completion: @escaping (_ validatedURL: String?, _ serverAuthenticationMethods: Array?, _ error: Error?, _ httpStatusCode: NSInteger) -> Void) { + + self.serverURL = serverURL + self.completion = completion + + enforcedScheme = "" + if serverURLHasNoScheme() { + enforcedScheme = "https://" + } + // STEP 1: check status of the server + checkAccessToServer() + + // STEP 2 will be started from connection(toTheServer: Bool), if check was fine + } + + func serverURLHasNoScheme() -> Bool { + return !(serverURL.hasPrefix("https://") || serverURL.hasPrefix("http://")) + } + + func checkAccessToServer() { + checkAccessToServerJob.delegate = self + checkAccessToServerJob.isConnectionToTheServer(byUrl: fullUrl) + } + + + // MARK: CheckAccessToServerDelegate implementation + + public func connection(toTheServerWasChecked isConnected: Bool, withHttpStatusCode statusCode: Int, andError error: Error!) { + if !isConnected { + print("No connection to the server") + + if serverURLHasNoScheme() && enforcedScheme == "https://" { + enforcedScheme = "http://" + // STEP 1(bis): check status of the server + checkAccessToServer() + + } else { + self.completion?(nil, nil, error, statusCode) + + print("No connection to the server") + } + + } else { + print("Ok connection to the server") + + // STEP 2: detect authentication methods accepted by the server + let stringUrl = fullUrl + k_url_webdav_server + let urlToCheck: URL = URL(string: stringUrl)! + + DetectAuthenticationMethod().getAuthenticationMethodsAvailableBy(url: urlToCheck, withCompletion: { (authMethods: Array?, error: Error?) in + + if error != nil { + self.completion?(nil, nil, error, 0) + } else { + // everything ok: return validated server URL and list of available authentication methods + self.completion?(self.fullUrl, authMethods as! [AuthenticationMethod], nil, 0) + } + }) + + } + + } + + public func repeatTheCheckToTheServer() { + // just glue + checkAccessToServer() + } + + public func badCertificateNotAcceptedByUser() { + let error = UtilsFramework.getErrorWithCode(Int(OCErrorSslRecoverablePeerUnverified.rawValue), andCustomMessageFromTheServer: "") + self.completion?(nil, nil, error, 0) + } + +} diff --git a/Owncloud iOs Client/Login/Login/LoginViewController.h b/Owncloud iOs Client/Login/Login/LoginViewController.h deleted file mode 100644 index fccc921281..0000000000 --- a/Owncloud iOs Client/Login/Login/LoginViewController.h +++ /dev/null @@ -1,119 +0,0 @@ -// -// LoginViewController.h -// Owncloud iOs Client -// -// Created by Javier Gonzalez on 10/8/12. -// - -/* - Copyright (C) 2016, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ - -#import -#import "MBProgressHUD.h" -#import "CheckAccessToServer.h" -#import "SSOViewController.h" -#import "CheckSSOServer.h" - -typedef NS_ENUM (NSInteger, LoginMode){ - LoginModeCreate, - LoginModeUpdate, - LoginModeExpire, - LoginModeMigrate, -}; - -extern NSString *loginViewControllerRotate; - -@interface LoginViewController : UIViewController { - - UITapGestureRecognizer *tapRecognizer; - - UIButton *refreshTestServerButton; - UIButton *showPasswordCharacterButton; - - NSThread *threadToCheckUrl; - - CGRect refreshButtonFrame; - CGRect showPasswordButtonFrame; - CGRect lockImageFrame; - CGRect okNokImageFrameFooter; - CGRect textFooterFrame1; - CGRect textFooterFrame2; - CGRect footerSection1Frame; - CGRect syncImageFrameForNoURL; - - IBOutlet UIImageView *logoImageView; - UIImageView *checkConnectionToTheServerImage; - UITextField *_usernameTextField; - UITextField *_passwordTextField; - - - //Flags - BOOL isUserTextUp; - BOOL isPasswordTextUp; - BOOL isConnectionToServer; - BOOL isNeedToCheckAgain; - BOOL isHttps; - BOOL isHttpsSecure; - BOOL isCheckingTheServerRightNow; - BOOL isSSLAccepted; - BOOL isErrorOnCredentials; - BOOL isLoginButtonEnabled; - BOOL urlEditable; - BOOL userNameEditable; - BOOL hasInvalidAuth; - - - - -} - -@property(nonatomic,strong)IBOutlet UITableView *tableView; -@property(nonatomic,strong) UITextField *urlTextField; -@property(nonatomic,strong) UITextField *usernameTextField; -@property(nonatomic,strong) UITextField *passwordTextField; -@property(nonatomic,strong)IBOutlet UIView *backCompanyView; - -@property(nonatomic,strong) NSString *auxUrlForReloadTable; -@property(nonatomic,strong) NSString *auxUsernameForReloadTable; -@property(nonatomic,strong) NSString *auxPasswordForReloadTable; -@property(nonatomic,strong) NSString *auxPasswordForShowPasswordOnEdit; - -@property(nonatomic,strong) NSString *connectString; - -@property(nonatomic)CGRect txtWithLogoWhenNoURLFrame; -@property(nonatomic)CGRect urlFrame; -@property(nonatomic)CGRect userAndPasswordFrame; -@property(nonatomic)CGRect imageTextFieldLeftFrame; - -@property(nonatomic)BOOL alreadyHaveValidSAMLCredentials; - -@property(nonatomic,strong) ManageNetworkErrors *manageNetworkErrors; - -@property (nonatomic) LoginMode loginMode; - -@property (nonatomic, strong) NSString *errorMessage; - --(void)checkUrlManually; --(void)hideOrShowPassword; --(void)goTryToDoLogin; --(void)badCertificateNoAcceptedByUser; --(NSString *)getUrlChecked:(NSString *)byUrl; --(void) hideTryingToLogin; --(void) potraitViewiPhone; --(void) addEditAccountsViewiPad; -- (void) restoreTheCookiesOfActiveUser; - -- (id)initWithLoginMode:(LoginMode)loginMode; - -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andLoginMode:(LoginMode)loginMode; - -- (void)setBarForCancelForLoadingFromModal; - -- (void) closeViewController; - -@end diff --git a/Owncloud iOs Client/Login/Login/LoginViewController.m b/Owncloud iOs Client/Login/Login/LoginViewController.m deleted file mode 100644 index 2c6e7b5e46..0000000000 --- a/Owncloud iOs Client/Login/Login/LoginViewController.m +++ /dev/null @@ -1,2540 +0,0 @@ -// -// LoginViewController.m -// Owncloud iOs Client -// -// Created by Javier Gonzalez on 10/8/12. -// - -/* - Copyright (C) 2016, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ - -#import "LoginViewController.h" -#import "AppDelegate.h" -#import "UserDto.h" -#import "MBProgressHUD.h" -#import "FilesViewController.h" -#import "SettingsViewController.h" -#import "RecentViewController.h" -#import "CheckAccessToServer.h" -#import "constants.h" -#import "AccountCell.h" -#import "constants.h" -#import "UIColor+Constants.h" -#import "Customization.h" -#import "ManageUsersDB.h" -#import "ManageFilesDB.h" -#import "FileNameUtils.h" -#import "OCNavigationController.h" -#import "OCTabBarController.h" -#import "UtilsDtos.h" -#import "UtilsUrls.h" -#import "OCCommunication.h" -#import "OCErrorMsg.h" -#import "UtilsFramework.h" -#import "UtilsCookies.h" -#import "ManageCookiesStorageDB.h" - -#define k_http_prefix @"http://" -#define k_https_prefix @"https://" - -#define k_remove_to_suffix @"/index.php" -#define k_remove_to_contains_path @"/index.php/apps/" - -NSString *loginViewControllerRotate = @"loginViewControllerRotate"; - -@interface LoginViewController () - -@end - - -@implementation LoginViewController - -- (id)initWithLoginMode:(LoginMode)loginMode { - - NSString *nibName = nil; - NSBundle *bundle = nil; - - if (IS_IPHONE) { - nibName = @"LoginViewController_iPhone"; - } else { - nibName = @"LoginViewController_iPad"; - } - - self = [self initWithNibName:nibName bundle:bundle andLoginMode:(LoginMode)loginMode]; - - return self; -} - -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andLoginMode:(LoginMode)loginMode { - self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; - if (self) { - _loginMode = loginMode; - self.auxUrlForReloadTable = k_default_url_server; - self.auxUsernameForReloadTable = @""; - self.auxPasswordForReloadTable = @""; - - if (_loginMode==LoginModeExpire){ - isErrorOnCredentials = YES; - } else { - isErrorOnCredentials = NO; - } - - if (_loginMode == LoginModeCreate || _loginMode == LoginModeMigrate) { - urlEditable = YES; - } else { - urlEditable = NO; - } - - if (loginMode == LoginModeCreate || loginMode == LoginModeMigrate) { - userNameEditable = YES; - } else { - userNameEditable = NO; - } - - isSSLAccepted = YES; - self.errorMessage = nil; - isCheckingTheServerRightNow = NO; - isConnectionToServer = NO; - isNeedToCheckAgain = YES; - hasInvalidAuth = NO; - isHttpsSecure = NO; - self.alreadyHaveValidSAMLCredentials = NO; - - showPasswordCharacterButton = [UIButton buttonWithType:UIButtonTypeCustom]; - [showPasswordCharacterButton setHidden:YES]; - - //We init the ManageNetworkErrors - if (!self.manageNetworkErrors) { - self.manageNetworkErrors = [ManageNetworkErrors new]; - self.manageNetworkErrors.delegate = self; - } - } - return self; -} - -- (void)viewDidLoad { - [super viewDidLoad]; - - [self setTableBackGroundColor]; - - //Set background company color like a comanyImageColor - [_backCompanyView setBackgroundColor:[UIColor colorOfLoginTopBackground]]; - - //Set background color of company image v - [logoImageView setBackgroundColor:[UIColor colorOfLoginTopBackground]]; - - //Configure view for interface position - [self configureViewForInterfacePosition]; - - isLoginButtonEnabled = NO; - - //Keyboard hidding after write url, name and password - NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - - [nc addObserver:self selector:@selector(keyboardWillShow:) name: - UIKeyboardWillShowNotification object:nil]; - - [nc addObserver:self selector:@selector(keyboardWillHide:) name: - UIKeyboardWillHideNotification object:nil]; - - tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapAnywhere:)]; - - isUserTextUp = NO; - isPasswordTextUp = NO; - -} - --(void) viewDidAppear:(BOOL)animated { - - [super viewDidAppear:animated]; - - if(![self.auxUrlForReloadTable isEqualToString:@""] && !self.alreadyHaveValidSAMLCredentials) { - DLog(@"1- self.auxUrlForReloadTable: %@",self.auxUrlForReloadTable); - [self checkUrlManually]; - } -} - -- (void)viewWillAppear:(BOOL)animated { - - [super viewWillAppear:animated]; - - ((CheckAccessToServer *)[CheckAccessToServer sharedManager]).delegate = self; - - - if (self.urlTextField.text.length > 0 && (!isConnectionToServer) && !self.alreadyHaveValidSAMLCredentials) { - DLog(@"_login view appear and no connection to server and no valid SAML credentials auto recheck server manually_"); - [self checkUrlManually]; - } - -} - -- (void)viewWillDisappear:(BOOL)animated { - - [super viewWillDisappear:animated]; - - //Cleaning boolean for next connections - self.alreadyHaveValidSAMLCredentials = NO; -} - -- (void)setTableBackGroundColor { - [self.tableView setBackgroundView: nil]; - [self.tableView setBackgroundColor:[UIColor colorOfLoginBackground]]; -} - -- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { - //return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft); - return YES; -} - -//Only for ios 6 -- (BOOL)shouldAutorotate { - - return YES; -} - -//For one of the next user story --(UIStatusBarStyle)preferredStatusBarStyle { - - if (k_is_text_login_status_bar_white) { - return UIStatusBarStyleLightContent; - } else { - return UIStatusBarStyleDefault; - } -} - -- (void)didReceiveMemoryWarning -{ - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} - -#pragma mark - Draw Position - -///----------------------------------- -/// @name Configure View for Interface Position -///----------------------------------- - -/** - * This method get the current interface position and call the - * specific method to configure the view for the current position - * - * There are direrents configurations depends of the device: - * iPhone 3.5" - * iPhone 4" - * iPad - * - * @discussion In this method we could use the toInterfaceOrientation object of the - * willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration method, but - * the "toInterfaceOrientation" gets in iPad in iOS 7 is wrong. - * - */ --(void)configureViewForInterfacePosition{ - - UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; - - switch (orientation) { - case UIInterfaceOrientationPortrait: - case UIInterfaceOrientationPortraitUpsideDown: - if (IS_IPHONE) { - [self potraitViewiPhone]; - } else { - [self potraitViewiPad]; - } - - break; - - case UIInterfaceOrientationLandscapeLeft: - case UIInterfaceOrientationLandscapeRight: - if (IS_IPHONE) { - if ([UIScreen mainScreen].bounds.size.height<=480.0) { - //3.5" screen - [self landscapeViewiPhone]; - } else { - //4" screen - [self landscapeViewiPhone5]; - } - } else { - //iPad landscape - [self landscapeViewiPad]; - } - - break; - - default: - if (IS_IPHONE) { - [self potraitViewiPhone]; - } else { - [self potraitViewiPad]; - } - - break; - } -} - --(void) potraitViewiPhone { - - DLog(@"Vertical iPhone"); - - //to set the scroll - self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 260, 0); - -//FIRST SECTION - - //Frame for url field - _urlFrame = CGRectMake(60,14,200,20); - - //Server image - User image - Password image - _imageTextFieldLeftFrame = CGRectMake(20.0, 10.0, 25.0, 25.0); - - //Refresh button - refreshButtonFrame = CGRectMake(260.0, 10.0, 25.0, 25.0); - - - -//FOOTER FOR FIRST SECTION - - //Frame used for Loading icon, secure or not secure connection - lockImageFrame = CGRectMake(20.0, 5.0, 25.0, 25.0); - - //Frame used for information message under the url field - textFooterFrame1 = CGRectMake((lockImageFrame.origin.x + lockImageFrame.size.width + 15), 7.0, (self.view.frame.size.width - ((lockImageFrame.origin.x + lockImageFrame.size.width) * 2)), 25.0); - - -//SECOND SECTION - - //user and password text fields frame - _userAndPasswordFrame = CGRectMake(60,14,200,20); - - //image about show/hide the password - showPasswordButtonFrame = CGRectMake(260.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR SECOND SECTION - - //Frame for uiview that contains image and text - footerSection1Frame = CGRectMake(0, 0, 320, 40); - - //Error image for bad credentials - okNokImageFrameFooter = CGRectMake(20.0, 7.5, 25.0, 25.0); - - //Test with information about the problem - textFooterFrame2 = CGRectMake((okNokImageFrameFooter.origin.x + okNokImageFrameFooter.size.width + 15), 0, (self.view.frame.size.width - ((okNokImageFrameFooter.origin.x + okNokImageFrameFooter.size.width) * 2)), 40.0); - - - -//HEADER OF THE TABLE WHEN THE ARE NOT URL FRAME - - //Frame used for add the information under the url field - _txtWithLogoWhenNoURLFrame = CGRectMake(0,0,320,90); - - //Frame used for reconection icon - syncImageFrameForNoURL = CGRectMake(280.0, 5.0, 25.0, 25.0); - - - -} - --(void) addEditAccountsViewiPad { - - DLog(@"Vertical iPhone"); - - //to set the scroll - self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 260, 0); - - //FIRST SECTION - - //Frame for url field - _urlFrame = CGRectMake(60,14,420,20); - - //Server image - User image - Password image - _imageTextFieldLeftFrame = CGRectMake(20.0, 10.0, 25.0, 25.0); - - //Refresh button - refreshButtonFrame = CGRectMake(480.0, 10.0, 25.0, 25.0); - - - - //FOOTER FOR FIRST SECTION - - //Frame used for Loading icon, secure or not secure connection - lockImageFrame = CGRectMake(20.0, 5.0, 25.0, 25.0); - - //Frame used for information message under the url field - textFooterFrame1 = CGRectMake((lockImageFrame.origin.x + lockImageFrame.size.width + 15), 7.0, (self.view.frame.size.width - ((lockImageFrame.origin.x + lockImageFrame.size.width) * 2)), 25.0); - - - //SECOND SECTION - - //user and password text fields frame - _userAndPasswordFrame = CGRectMake(60 ,14,420,20); - - //image about show/hide the password - showPasswordButtonFrame = CGRectMake(480.0, 10.0, 25.0, 25.0); - - - //FOOTER FOR SECOND SECTION - - //Frame for uiview that contains image and text - footerSection1Frame = CGRectMake(0, 0, 320, 40); - - //Error image for bad credentials - okNokImageFrameFooter = CGRectMake(20.0, 7.5, 25.0, 25.0); - - //Test with information about the problem - textFooterFrame2 = CGRectMake((okNokImageFrameFooter.origin.x + okNokImageFrameFooter.size.width + 15), 0, (self.view.frame.size.width - ((okNokImageFrameFooter.origin.x + okNokImageFrameFooter.size.width) * 2)), 40.0); - - - - //HEADER OF THE TABLE WHEN THE ARE NOT URL FRAME - - //Frame used for add the information under the url field - _txtWithLogoWhenNoURLFrame = CGRectMake(0,0,320,90); - - //Frame used for reconection icon - syncImageFrameForNoURL = CGRectMake(280.0, 5.0, 25.0, 25.0); - - - -} - --(void)landscapeViewiPhone{ - - DLog(@"Horizontal iPhone"); - - //to set the scroll - self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 170, 0); - - -//FIRST SECTION - - //Frame for url field - _urlFrame = CGRectMake(60,14,340,20); - - //Server image - User image - Password image - _imageTextFieldLeftFrame = CGRectMake(20.0, 10.0, 25.0, 25.0); - - //Refresh button - refreshButtonFrame = CGRectMake(420.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR FIRST SECTION - - //Frame used for Loading icon, secure or not secure connection - lockImageFrame = CGRectMake(20.0, 5.0, 25.0, 25.0); - - //Frame used for information message under the url field - textFooterFrame1 = CGRectMake((lockImageFrame.origin.x + lockImageFrame.size.width + 15), 5.0, (self.view.frame.size.width - (lockImageFrame.origin.x + lockImageFrame.size.width + 10)), 25.0); - - -//SECOND SECTION - - //user and password text fields frame - _userAndPasswordFrame = CGRectMake(60,14,340,20); - - //image about show/hide the password - showPasswordButtonFrame = CGRectMake(420.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR SECOND SECTION - - //Frame for uiview that contains image and text - footerSection1Frame = CGRectMake(0, 0, 480, 40); - - //Error image for bad credentials - okNokImageFrameFooter = CGRectMake(20.0, 7.5, 25.0, 25.0); - - //Test with information about the problem - textFooterFrame2 = CGRectMake((okNokImageFrameFooter.origin.x + okNokImageFrameFooter.size.width + 15), 0.0, 280.0, 40.0); - - -//HEADER OF THE TABLE WHEN THE ARE NOT URL FRAME - - //Frame used for add the information under the url field - _txtWithLogoWhenNoURLFrame = CGRectMake(0,0,480,90); - - //Frame used for reconection icon - syncImageFrameForNoURL = CGRectMake(420.0, 5.0, 25.0, 25.0); - - -} - --(void)landscapeViewiPhone5{ - - DLog(@"Horizontal iPhone 5"); - - self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 170, 0); - - -//FIRST SECTION - - //Frame for url field - _urlFrame = CGRectMake(60,14,430,20); - - //Server image - User image - Password image - _imageTextFieldLeftFrame = CGRectMake(20.0, 10.0, 25.0, 25.0); - - //Refresh button - refreshButtonFrame = CGRectMake(510.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR FIRST SECTION - - //Frame used for Loading icon, secure or not secure connection - lockImageFrame = CGRectMake(20.0, 5.0, 25.0, 25.0); - - //Frame used for information message under the url field - textFooterFrame1 = CGRectMake((lockImageFrame.origin.x + lockImageFrame.size.width + 15), 5.0, (self.view.frame.size.width - (lockImageFrame.origin.x + lockImageFrame.size.width + 10)), 25.0); - - - -//SECOND SECTION - - //user and password text fields frame - _userAndPasswordFrame = CGRectMake(60,14,430,20); - - //image about show/hide the password - showPasswordButtonFrame = CGRectMake(510.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR SECOND SECTION - - //Frame for uiview that contains image and text - footerSection1Frame = CGRectMake(0, 0, 568, 40); - - //Error image for bad credentials - okNokImageFrameFooter = CGRectMake(20.0, 7.5, 25.0, 25.0); - - //Test with information about the problem - textFooterFrame2 = CGRectMake((okNokImageFrameFooter.origin.x + okNokImageFrameFooter.size.width + 15), 0.0, 280.0, 40.0); - - - -//HEADER OF THE TABLE WHEN THE ARE NOT URL FRAME - - //Frame used for add the information under the url field - _txtWithLogoWhenNoURLFrame = CGRectMake(0,0,568,90); - - //Frame used for reconection icon - syncImageFrameForNoURL = CGRectMake(510.0, 5.0, 25.0, 25.0); - - -} - --(void)potraitViewiPad{ - - DLog(@"Vertical iPad"); - - [self.tableView setBackgroundView:nil]; - [self.tableView setBackgroundView:[[UIView alloc] init]]; - - -//FIRST SECTION - - //Frame for url field - _urlFrame = CGRectMake(280,14,420,20); - - //Server image - User image - Password image - _imageTextFieldLeftFrame = CGRectMake(235.0, 10.0, 25.0, 25.0); - - //Refresh button - refreshButtonFrame = CGRectMake(680.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR FIRST SECTION - - //Frame used for Loading icon, secure or not secure connection - lockImageFrame = CGRectMake(235.0, 5.0, 25.0, 25.0); - - //Frame used for information message under the url field - textFooterFrame1 = CGRectMake(280.0, 7.0, 300.0, 25.0); - - -//SECOND SECTION - - //user and password text fields frame - _userAndPasswordFrame = CGRectMake(280,14,220,20); - - //image about show/hide the password - showPasswordButtonFrame = CGRectMake(500.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR SECOND SECTION - - //Frame for uiview that contains image and text - footerSection1Frame = CGRectMake(0, 0, 685, 40); - - //Error image for bad credentials - okNokImageFrameFooter = CGRectMake(235.0, 7.5, 25.0, 25.0); - - //Test with information about the problem - textFooterFrame2 = CGRectMake(280, 0.0, 300.0, 40.0); - - -//HEADER OF THE TABLE WHEN THE ARE NOT URL FRAME - - //Frame used for add the information under the url field - _txtWithLogoWhenNoURLFrame = CGRectMake(0,0,768,195); - - //Frame used for reconection icon when there are not url frame - syncImageFrameForNoURL = CGRectMake(500.0, 5.0, 25.0, 25.0); - - - -} - --(void)landscapeViewiPad{ - - DLog(@"Horizontal iPad"); - - //to set the scroll - self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 500, 0); - - [self.tableView setBackgroundView:nil]; - [self.tableView setBackgroundView:[[UIView alloc] init]]; - - -//FIRST SECTION - - //Frame for url field - _urlFrame = CGRectMake(408.0,14,420,20); - - //Server image - User image - Password image - _imageTextFieldLeftFrame = CGRectMake(368.0, 10.0, 25.0, 25.0); - - //Refresh button - refreshButtonFrame = CGRectMake(828.0 , 10.0, 25.0, 25.0); - - -//FOOTER FOR FIRST SECTION - - //Frame used for Loading icon, secure or not secure connection - lockImageFrame = CGRectMake(368.0, 5.0, 25.0, 25.0); - - //Frame used for information message under the url field - textFooterFrame1 = CGRectMake(408.0, 7.0, 300.0, 25.0); - - - -//SECOND SECTION - - //user and password text fields frame - _userAndPasswordFrame = CGRectMake(408,14,220,20); - - - //image about show/hide the password - showPasswordButtonFrame = CGRectMake(628.0, 10.0, 25.0, 25.0); - - -//FOOTER FOR SECOND SECTION - - //Frame for uiview that contains image and text - footerSection1Frame = CGRectMake(0, 0, 785, 40); - - //Error image for bad credentials - okNokImageFrameFooter = CGRectMake(368.0, 7.5, 25.0, 25.0); - - - //Test with information about the problem - textFooterFrame2 = CGRectMake(408, 0.0, 300.0, 40.0); - - - -//HEADER OF THE TABLE WHEN THE ARE NOT URL FRAME - - //Frame used for add the information under the url field - _txtWithLogoWhenNoURLFrame = CGRectMake(0,0,1024,195); - - //Frame used for reconection icon when there are not url frame - syncImageFrameForNoURL = CGRectMake(628.0, 5.0, 25.0, 25.0); - - - -} - -//Only for ios 6 -- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { - [super didRotateFromInterfaceOrientation:fromInterfaceOrientation]; - //Configure View For interface position - [self configureViewForInterfacePosition]; - [self.tableView reloadData]; -} - -- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { - [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; - - //Send a notification - [[NSNotificationCenter defaultCenter] postNotificationName: loginViewControllerRotate object: nil]; -} - -//Only for ios6 -- (NSUInteger)supportedInterfaceOrientations { - if (IS_IPHONE) { - return UIInterfaceOrientationMaskAllButUpsideDown; - }else{ - return UIInterfaceOrientationMaskAll; - } -} - -#pragma mark - UITableView datasource - -// Asks the data source to return the number of sections in the table view. -- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView -{ - if(k_hide_url_server) { - return 2; - } else { - return 3; - } - - -} - -// Returns the table view managed by the controller object. -- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section -{ - NSInteger n = 0; - - if(k_hide_url_server) { - if(k_is_oauth_active || k_is_sso_active) { - if (section==0) { - n=0; - } else if (section==1) { - if (k_is_shown_help_link_on_login) { - n=2; - } else { - n=1; - } - } - } else { - if (section==0) { - n=2; - } else if (section==1) { - if (k_is_shown_help_link_on_login) { - n=2; - } else { - n=1; - } - } - } - } else { - if(k_is_oauth_active || k_is_sso_active) { - if (section==0) { - n=1; - } else if (section==1) { - if (k_is_shown_help_link_on_login) { - n=2; - } else { - n=1; - } - } else if (section==2) { - n=0; - } - } else { - if (section==0) { - n=1; - } else if (section==1) { - n=2; - } else if (section==2) { - if (k_is_shown_help_link_on_login) { - n=2; - } else { - n=1; - } - } - } - } - return n; -} - - -// Returns the table view managed by the controller object. -- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath -{ - - static NSString *CellIdentifier = @"AccountCell"; - - AccountCell *cell = (AccountCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; - if (cell == nil) { - - NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"AccountCell" owner:self options:nil]; - - for (id currentObject in topLevelObjects){ - if ([currentObject isKindOfClass:[UITableViewCell class]]){ - cell = (AccountCell *) currentObject; - break; - } - } - } - - UIFont *cellBoldFont = [UIFont boldSystemFontOfSize:16.0]; - cell.textLabel.font=cellBoldFont; - - if (indexPath.section==0) { - - if(k_hide_url_server) { - if(k_is_oauth_active || k_is_sso_active) { - switch (indexPath.row) { - case 0: - cell = [self configureCellToLoginByAccountCell:cell]; - - //we configure too the server url - self.urlTextField = [[UITextField alloc]initWithFrame:_urlFrame]; - self.urlTextField.delegate = self; - DLog(@"5- self.auxUrlForReloadTable: %@", self.auxUrlForReloadTable); - self.urlTextField.text = self.auxUrlForReloadTable; - - break; - case 1: - cell = [self configureCellToShowLinkByAccountCell:cell]; - - break; - - default: - break; - } - } else { - switch (indexPath.row) { - case 0: - cell = [self configureCellToUsernameByAccountCell:cell]; - - break; - case 1: - cell = [self configureCellToPasswordByAccountCell:cell]; - - break; - - default: - break; - } - } - } else { - switch (indexPath.row) { - case 0: - cell = [self configureCellToURLServerByAccountCell:cell]; - break; - - default: - break; - } - } - - }else if (indexPath.section==1) { - - if(k_hide_url_server) { - switch (indexPath.row) { - case 0: - cell = [self configureCellToLoginByAccountCell:cell]; - - //we configure too the server url - self.urlTextField = [[UITextField alloc]initWithFrame:_urlFrame]; - self.urlTextField.delegate = self; - DLog(@"4- self.auxUrlForReloadTable: %@", self.auxUrlForReloadTable); - self.urlTextField.text = self.auxUrlForReloadTable; - - break; - - case 1: - cell = [self configureCellToShowLinkByAccountCell:cell]; - - break; - - default: - break; - } - } else { - if(k_is_oauth_active || k_is_sso_active) { - switch (indexPath.row) { - case 0: - cell = [self configureCellToLoginByAccountCell:cell]; - - break; - - case 1: - cell = [self configureCellToShowLinkByAccountCell:cell]; - - break; - - default: - break; - } - } else { - switch (indexPath.row) { - case 0: - cell = [self configureCellToUsernameByAccountCell:cell]; - - break; - case 1: - cell = [self configureCellToPasswordByAccountCell:cell]; - - break; - - default: - break; - } - } - } - } else if (indexPath.section==2) { - - switch (indexPath.row) { - case 0: - cell = [self configureCellToLoginByAccountCell:cell]; - - break; - - case 1: - cell = [self configureCellToShowLinkByAccountCell:cell]; - - break; - default: - break; - } - } - return cell; -} - -#pragma mark - Configure cells - --(AccountCell *) configureCellToURLServerByAccountCell:(AccountCell *) cell { - - cell.textLabel.textColor = [UIColor colorWithRed:0/256.0f green:0/256.0f blue:0/256.0f alpha:1]; - - UIImageView *iconLeftImage= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"server.png"]]; - [iconLeftImage setFrame:_imageTextFieldLeftFrame]; - - self.urlTextField = [[UITextField alloc]initWithFrame:_urlFrame]; - self.urlTextField.delegate = self; - [self.urlTextField setKeyboardType:UIKeyboardTypeURL]; - [self.urlTextField setAutocorrectionType:UITextAutocorrectionTypeNo]; - - [self.urlTextField setClearButtonMode:UITextFieldViewModeNever]; - //searchField.borderStyle= UITextBorderStyleRoundedRect; - self.urlTextField.borderStyle= UITextBorderStyleNone; - //searchField.background=img; - [self.urlTextField setReturnKeyType:UIReturnKeyDone]; - [self.urlTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone]; - - self.urlTextField.textAlignment = NSTextAlignmentLeft; - self.urlTextField.font = [UIFont boldSystemFontOfSize:14.0]; - self.urlTextField.textColor = [UIColor colorOfURLUserPassword]; - self.urlTextField.placeholder = NSLocalizedString(@"url_sample", nil); - - if(!urlEditable) { - [self.urlTextField setEnabled:NO]; - } - - DLog(@"2- self.auxUrlForReloadTable: %@", self.auxUrlForReloadTable); - - self.urlTextField.text = self.auxUrlForReloadTable; - - refreshTestServerButton = [UIButton buttonWithType:UIButtonTypeCustom]; - - [refreshTestServerButton addTarget:self action:@selector(checkUrlManually) forControlEvents:UIControlEventTouchUpInside]; - [refreshTestServerButton setFrame:refreshButtonFrame]; - [refreshTestServerButton setBackgroundImage:[UIImage imageNamed:@"ReconnectIcon.png"] forState:UIControlStateNormal]; - - if(([self.urlTextField.text length] > 0) && !isConnectionToServer && !isCheckingTheServerRightNow) { - [refreshTestServerButton setHidden:NO]; - } else { - [refreshTestServerButton setHidden:YES]; - } - - [cell.contentView addSubview:iconLeftImage]; - [cell.contentView addSubview:self.urlTextField]; - [cell.contentView addSubview:refreshTestServerButton]; - - cell.selectionStyle = UITableViewCellSelectionStyleNone; - - return cell; -} - --(AccountCell *) configureCellToUsernameByAccountCell:(AccountCell *) cell { - - cell.textLabel.textColor = [UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:1]; - - UIImageView *iconLeftImage= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"user.png"]]; - [iconLeftImage setFrame:_imageTextFieldLeftFrame]; - - self.usernameTextField = [[UITextField alloc]initWithFrame:_userAndPasswordFrame]; - self.usernameTextField.delegate = self; - - - [self.usernameTextField setClearButtonMode:UITextFieldViewModeNever]; - //searchField.borderStyle= UITextBorderStyleRoundedRect; - self.usernameTextField.borderStyle= UITextBorderStyleNone; - //searchField.background=img; - [self.usernameTextField setReturnKeyType:UIReturnKeyDone]; - [self.usernameTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone]; - [self.usernameTextField setAutocorrectionType:UITextAutocorrectionTypeNo]; - - self.usernameTextField.textAlignment = NSTextAlignmentLeft; - self.usernameTextField.font = [UIFont boldSystemFontOfSize:14.0]; - self.usernameTextField.textColor = [UIColor colorOfURLUserPassword]; - self.usernameTextField.placeholder = NSLocalizedString(@"username", nil); - self.usernameTextField.text = self.auxUsernameForReloadTable; - - [self.usernameTextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged]; - - if(!userNameEditable) { - [self.usernameTextField setEnabled:NO]; - } - - [cell.contentView addSubview:iconLeftImage]; - [cell.contentView addSubview:self.usernameTextField]; - - //Separator (Not works in iOS 7 in iPad) - if (IS_IPHONE) { - UIView *separator = [UIView new]; - separator.backgroundColor = [UIColor lightGrayColor]; - separator.frame = CGRectMake(0, cell.contentView.frame.size.height - 0.5, cell.contentView.frame.size.width, 0.5); - separator.autoresizingMask = UIViewAutoresizingFlexibleWidth; - - [cell.contentView addSubview:separator]; - } - - cell.selectionStyle = UITableViewCellSelectionStyleNone; - - return cell; -} - --(AccountCell *) configureCellToPasswordByAccountCell:(AccountCell *) cell { - - cell.textLabel.textColor = [UIColor colorWithRed:0/256.0f green:0/256.0f blue:0/256.0f alpha:1]; - - UIImageView *iconLeftImage= [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"password.png"]]; - [iconLeftImage setFrame:_imageTextFieldLeftFrame]; - - self.passwordTextField = [[UITextField alloc]initWithFrame:_userAndPasswordFrame]; - self.passwordTextField.textColor = [UIColor colorOfURLUserPassword]; - self.passwordTextField.delegate = self; - [self.passwordTextField setSecureTextEntry:YES]; - - [self.passwordTextField setClearButtonMode:UITextFieldViewModeNever]; - //searchField.borderStyle= UITextBorderStyleRoundedRect; - self.passwordTextField.borderStyle= UITextBorderStyleNone; - //searchField.background=img; - [self.passwordTextField setReturnKeyType:UIReturnKeyDone]; - [self.passwordTextField setAutocapitalizationType:UITextAutocapitalizationTypeNone]; - [self.passwordTextField setAutocorrectionType:UITextAutocorrectionTypeNo]; - - self.passwordTextField.textAlignment = NSTextAlignmentLeft; - self.passwordTextField.font = [UIFont boldSystemFontOfSize:14.0]; - self.passwordTextField.placeholder = NSLocalizedString(@"password", nil); - self.passwordTextField.text = self.auxPasswordForReloadTable; - - [showPasswordCharacterButton addTarget:self action:@selector(hideOrShowPassword) forControlEvents:UIControlEventTouchUpInside]; - [showPasswordCharacterButton setFrame:showPasswordButtonFrame]; - - [showPasswordCharacterButton setBackgroundImage:[UIImage imageNamed:@"RevealPasswordIcon.png"] forState:UIControlStateNormal]; - - [cell.contentView addSubview:iconLeftImage]; - [cell.contentView addSubview:self.passwordTextField]; - [cell.contentView addSubview:showPasswordCharacterButton]; - - cell.selectionStyle = UITableViewCellSelectionStyleNone; - - - return cell; -} - --(AccountCell *) configureCellToLoginByAccountCell:(AccountCell *) cell { - - cell.textLabel.textAlignment = NSTextAlignmentCenter; - cell.textLabel.text= NSLocalizedString(@"login", nil); - cell.textLabel.textColor = [UIColor colorOfLoginButtonTextColor]; - // cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"gradImage.png"]]; - cell.backgroundColor = [UIColor colorOfLoginButtonBackground]; - - cell.selectionStyle = UITableViewCellSelectionStyleGray; - - if(!isLoginButtonEnabled) { - // Mac's native DigitalColor Meter reads exactly {R:143, G:143, B:143}. - cell.textLabel.alpha = 0.439216f; // (1 - alpha) * 255 = 143 - - cell.userInteractionEnabled = NO; - } - return cell; -} - --(AccountCell *) configureCellToShowLinkByAccountCell:(AccountCell *) cell { - - cell.textLabel.textAlignment = NSTextAlignmentCenter; - NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]; - cell.textLabel.text = [NSLocalizedString(@"help_link_login", nil) stringByReplacingOccurrencesOfString:@"$appname" withString:appName]; - cell.textLabel.textColor = [UIColor colorOfLoginText]; - cell.backgroundColor = [UIColor clearColor]; - - cell.selectionStyle = UITableViewCellSelectionStyleGray; - - return cell; -} - --(CGFloat)tableView:(UITableView*)tableView heightForFooterInSection:(NSInteger)section -{ - if (section==0) { - if(k_hide_url_server) { - return 40.0; - } else { - return 35.0; - } - }else if (section==1){ - return 40; - } else { - return 0; - } - -} - --(CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section -{ - if(section == 0) { - if(k_hide_url_server) { - return 35.0; - } else { - return 15.0; - } - } else { - return 1; - } - -} - -- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section -{ - - if(section == 0) { - if(k_hide_url_server) { - UIView *textView = [self configureViewForFooterURLServer]; - [textView setFrame:_txtWithLogoWhenNoURLFrame]; - - UIView *headerView = [[UIView alloc] init]; - - //[headerView addSubview:logoImageView]; - [headerView addSubview:textView]; - - return headerView; - } else { - // UIView *headerView = [[UIView alloc] init]; - // [headerView addSubview:logoImageView]; - - return nil; - } - } else { - return nil; - } -} - - -#pragma mark - UITableView delegate - - -// Tells the delegate that the specified row is now selected. -- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath -{ - [tableView deselectRowAtIndexPath:indexPath animated:YES]; - - DLog(@"cell tapped number: %ld, in section:%ld", (long)indexPath.row, (long)indexPath.section); - - //check if the constant k_hide_url_server is Yes or Not, depend of the branding - if(k_hide_url_server) { - //hide url - if (indexPath.section==1) { - - switch (indexPath.row) { - case 0: - //in oaut or saml is the login button - if(k_is_oauth_active) { - [self oAuthScreen]; - } else if (k_is_sso_active) { - [self checkURLServerForSSO]; - } else { - //login button - [self goTryToDoLogin]; - } - break; - - case 1: - //login button - [self showHelpURLInSafari]; - break; - - default: - break; - } - } - } else { - //show url - switch (indexPath.section) { - case 0: - //Nothing, is the url field - break; - - case 1: - switch (indexPath.row) { - case 0: - //in oauth or saml is the login button - if(k_is_oauth_active) { - [self oAuthScreen]; - } else if (k_is_sso_active) { - [self checkURLServerForSSO]; - } - break; - case 1: - break; - - default: - break; - } - break; - - case 2: - switch (indexPath.row) { - case 0: - //login button - [self goTryToDoLogin]; - break; - case 1: - //login button - [self showHelpURLInSafari]; - break; - - default: - break; - } - break; - - default: - break; - } - } -} - -- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section { - if (section == 0) { - if(k_hide_url_server) { - return [self generateFooterForUsernameAndPassword]; - } else { - return [self configureViewForFooterURLServer]; - } - } else if (section == 1) { - if(!k_hide_url_server) { - return [self generateFooterForUsernameAndPassword]; - } else { - return nil; - } - } else { - return nil; - } -} - --(UIView *) configureViewForFooterURLServer { - UIView *view = [[UIView alloc] initWithFrame:textFooterFrame1]; - - if (!([self.auxUrlForReloadTable isEqualToString:@""] || ((CheckAccessToServer *)[CheckAccessToServer sharedManager]).delegate == nil)) { - - UILabel *label = [self setTheDefaultStyleOfTheServerFooterLabel]; - UIImageView *errorImage; - - if (isCheckingTheServerRightNow) { - UIActivityIndicatorView *activity = [self setTheActivityIndicatorWhileTheConnectionIsBeenEstablished]; - [view addSubview:activity]; - label.text = NSLocalizedString(@"testing_connection",nil); - } else if (isConnectionToServer) { - if (hasInvalidAuth) { - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CredentialsError.png"]]; - label.text = NSLocalizedString(@"authentification_not_valid",nil); - label.numberOfLines = 1; - [label setAdjustsFontSizeToFitWidth:YES]; - } else if (isHttps) { - if (isHttpsSecure) { - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"SecureConnectionIcon.png"]]; - label.text = NSLocalizedString(@"secure_connection_established",nil); - } else { - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NonSecureConnectionIcon.png"]]; - label.text = NSLocalizedString(@"https_non_secure_connection_established",nil); - } - } else { - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"NonSecureConnectionIcon.png"]]; - label.text = NSLocalizedString(@"connection_established",nil); - } - } else { - if(isSSLAccepted) { - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CredentialsError.png"]]; - NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]; - label.text = [NSLocalizedString(@"server_instance_not_found",nil) stringByReplacingOccurrencesOfString:@"$appname" withString:appName]; - if(k_hide_url_server) { - UIButton *button = [self setTheButtonForReconnectWithTheCurrentServer]; - [view addSubview:button]; - } - } else if(self.loginMode == LoginModeMigrate){ - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CredentialsError.png"]]; - label.text = NSLocalizedString(@"error_updating_predefined_url",nil); - } else { - errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CredentialsError.png"]]; - label.text = NSLocalizedString(@"connection_declined",nil); - } - } - [errorImage setFrame:lockImageFrame]; - [view addSubview:errorImage]; - [view addSubview:label]; - } - return view; -} - - -///----------------------------------- -/// @name setTheDefaultStyleOfTheServerFooterLabel -///----------------------------------- - -/** - * This method set the default parameters of the label located on the server footer - */ -- (UILabel *) setTheDefaultStyleOfTheServerFooterLabel { - UILabel* label = [[UILabel alloc] initWithFrame:textFooterFrame1]; - label.backgroundColor = [UIColor clearColor]; - label.baselineAdjustment = UIBaselineAdjustmentAlignCenters; - label.lineBreakMode = NSLineBreakByWordWrapping; - label.textAlignment = NSTextAlignmentLeft; - label.textColor = [UIColor colorOfLoginText]; - label.numberOfLines = 0; - label.font = [UIFont fontWithName:@"Arial" size:12.5]; - - return label; -} - - -///----------------------------------- -/// @name setTheActivityIndicatorWhileTheConnectionIsBeenEstablished -///----------------------------------- - -/** - * This method set the activity indicator in the label located on the server footer - */ -- (UIActivityIndicatorView *) setTheActivityIndicatorWhileTheConnectionIsBeenEstablished { - UIActivityIndicatorView *activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; - [activity setFrame:lockImageFrame]; - [activity startAnimating]; - - return activity; -} - - -///----------------------------------- -/// @name setTheButtonForReconnectWithTheCurrentServer -///----------------------------------- - -/** - * This method set the button located on the server field for reconnect the server - */ -- (UIButton *) setTheButtonForReconnectWithTheCurrentServer { - UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; - [button setFrame:syncImageFrameForNoURL]; - [button setBackgroundImage:[UIImage imageNamed:@"ReconnectIcon.png"] forState:UIControlStateNormal]; - [button addTarget:self action:@selector(checkUrlManually) forControlEvents:UIControlEventTouchDown]; - - return button; -} - --(UIView *) generateFooterForUsernameAndPassword { - - NSString *errorMessage = @""; - - if (isErrorOnCredentials) { - - //In SAML the error message is about the session expired - if (k_is_sso_active) { - errorMessage = @"session_expired"; - } - else{ - errorMessage = @"error_login_message"; - } - - } else if (self.loginMode == LoginModeMigrate){ - - errorMessage = @"error_updating_predefined_url"; - - } else if (self.errorMessage) { - - errorMessage = self.errorMessage; - - } else { - - return nil; - } - - UIImageView *errorImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CredentialsError.png"]]; - [errorImage setFrame:okNokImageFrameFooter]; - - UILabel* label = [[UILabel alloc] initWithFrame:textFooterFrame2]; - label.backgroundColor = [UIColor clearColor]; - - label.baselineAdjustment= UIBaselineAdjustmentAlignCenters; - label.lineBreakMode = NSLineBreakByWordWrapping; - label.textAlignment = NSTextAlignmentLeft; - label.font = [UIFont fontWithName:@"Arial" size:13]; - label.textColor = [UIColor colorOfLoginErrorText]; - label.numberOfLines = 0; - - label.text = NSLocalizedString(errorMessage,nil); - - UIView *view = [[UIView alloc] initWithFrame:footerSection1Frame]; - - [view addSubview:errorImage]; - [view addSubview:label]; - - return view; - -} - -#pragma mark - Keyboard - --(void) keyboardWillShow:(NSNotification *) note { - [self.view addGestureRecognizer:tapRecognizer]; -} - --(void) keyboardWillHide:(NSNotification *) note -{ - [self.view removeGestureRecognizer:tapRecognizer]; -} - --(void)didTapAnywhere: (UITapGestureRecognizer*) recognizer { - [self.urlTextField resignFirstResponder]; - [self.usernameTextField resignFirstResponder]; - [self.passwordTextField resignFirstResponder]; - - if (isUserTextUp==YES || isPasswordTextUp==YES) { - [self undoAnimate]; - } - - //Hide password - [self hidePassword]; -} - -// Asks the delegate if the text field should process the pressing of the return button. -- (BOOL)textFieldShouldReturn:(UITextField *)textField -{ - - if (textField == self.urlTextField) { - //[self.usernameTextField becomeFirstResponder]; - [textField resignFirstResponder]; - } - else if (textField == self.usernameTextField) { - if([self.passwordTextField.text isEqualToString:@""]) { - [self.passwordTextField becomeFirstResponder]; - } else { - [textField resignFirstResponder]; - } - } else if (textField == self.passwordTextField) { - [[NSUserDefaults standardUserDefaults] synchronize]; - [textField resignFirstResponder]; - - //if the scrroll is not a the start of the tableview we move the scroll - /* if(self.tableView.contentOffset.y > 0) { - [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; - }*/ - } - - return YES; -} - -#pragma mark - Animation write - -- (void)textFieldDidBeginEditing:(UITextField *)textField { - - if (IS_IPHONE) { - [self animateTextField:textField up:YES]; - - if (textField == self.passwordTextField){ - [showPasswordCharacterButton setHidden:YES]; - } else if (textField == self.urlTextField) { - [refreshTestServerButton setHidden:YES]; - - [self.urlTextField setFrame:_urlFrame]; - } - - //Show or not show password - if (textField==self.passwordTextField) { - - }else{ - [self hidePassword]; - } - } -} - -- (void)animateTextField: (UITextField*) textField up: (BOOL) up { - DLog(@"Animate text field"); - - if (textField==self.usernameTextField) { - isUserTextUp=YES; - } - - if (textField==self.passwordTextField) { - isPasswordTextUp=YES; - } - - NSIndexPath *scrollIndexPath = nil; - - if(k_hide_url_server) { - - if(textField == self.usernameTextField) { - scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - } else if(textField == self.passwordTextField) { - scrollIndexPath = [NSIndexPath indexPathForRow:1 inSection:0]; - } - } else { - - if(textField == self.usernameTextField) { - scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:1]; - } else if(textField == self.passwordTextField) { - scrollIndexPath = [NSIndexPath indexPathForRow:1 inSection:1]; - } else if(textField == self.urlTextField) { - scrollIndexPath = [NSIndexPath indexPathForRow:0 inSection:0]; - } - } - - DLog(@"Before the scroll To Row At IndexPath Medhod"); - if (textField == _usernameTextField || textField == _passwordTextField) { - [[self tableView] scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; - } - - /* - if(textField == self.passwordTextField || textField == self.usernameTextField) { - const int movementDistancePortTrait = 100; // tweak as needed - const int movementDistanceLandscape = 150; // tweak as needed - const float movementDuration = 0.3f; // tweak as needed - - [UIView beginAnimations: @"anim" context: nil]; - [UIView setAnimationBeginsFromCurrentState: YES]; - [UIView setAnimationDuration: movementDuration]; - - UIInterfaceOrientation currentOrientation; - currentOrientation=[[UIApplication sharedApplication] statusBarOrientation]; - BOOL isPotrait = UIDeviceOrientationIsPortrait(currentOrientation); - - if(isPotrait) { - self.view.frame = CGRectOffset(self.view.frame, 0, -movementDistancePortTrait); - } else { - self.view.frame = CGRectOffset(self.view.frame, -movementDistanceLandscape, 0); - } - //[UIView commitAnimations]; - - NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:1 inSection:1]; - [[self tableView] scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES]; - }*/ -} - -- (void) undoAnimate { - - if (isUserTextUp==YES) { - isUserTextUp=NO; - } - - if (isPasswordTextUp==YES) { - isPasswordTextUp=NO; - } - - //[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; - [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES]; - - - - - - // DLog(@"undoAnimateTextField"); - - /*const int movementDistancePortTrait = 100; // tweak as needed - const int movementDistanceLandscape = 150; // tweak as needed - const float movementDuration = 0.3f; // tweak as needed - - //int movement = (up ? -movementDistance : movementDistance); - - [UIView beginAnimations: @"anim" context: nil]; - [UIView setAnimationBeginsFromCurrentState: YES]; - [UIView setAnimationDuration: movementDuration]; - - UIInterfaceOrientation currentOrientation; - currentOrientation=[[UIApplication sharedApplication] statusBarOrientation]; - BOOL isPotrait = UIDeviceOrientationIsPortrait(currentOrientation); - - if(isPotrait) { - self.view.frame = CGRectOffset(self.view.frame, 0, movementDistancePortTrait); - } else { - self.view.frame = CGRectOffset(self.view.frame, movementDistanceLandscape, 0); - } - - - //self.view.frame=CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height+20.0); - //[UIView commitAnimations]; - */ -} - -#pragma mark - Loading - --(void) showTryingToLogin { - dispatch_async(dispatch_get_main_queue(), ^{ - MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES]; - //hud.mode=MBProgressHUDModeDeterminate; - hud.labelText = NSLocalizedString(@"loading", nil); - hud.dimBackground = NO; - - self.view.userInteractionEnabled = NO; - self.navigationController.navigationBar.userInteractionEnabled = NO; - self.tabBarController.tabBar.userInteractionEnabled = NO; - }); -} - --(void) hideTryingToLogin { - dispatch_async(dispatch_get_main_queue(), ^{ - [MBProgressHUD hideHUDForView:self.view animated:YES]; - self.view.userInteractionEnabled = YES; - self.navigationController.navigationBar.userInteractionEnabled = YES; - self.tabBarController.tabBar.userInteractionEnabled = YES; - }); -} - -#pragma mark - TextField delegates - -- (void)textFieldDidEndEditing:(UITextField *)textField { - - DLog(@"6- self.auxUrlForReloadTable %@", self.auxUrlForReloadTable); - DLog(@"6- self.urlTextField.text %@", self.urlTextField.text); - DLog(@"6- textFieldDidEndEditing:textField %@", textField); - DLog(@"6- is in main thread? %d", [NSThread isMainThread]); - - if(self.urlTextField != nil) { - NSString *urlWithoutUserPassword = [self stripUsernameAndPassword:self.urlTextField.text]; - self.auxUrlForReloadTable = [self stripIndexPhpOrAppsFilesFromUrl:urlWithoutUserPassword]; - } else { - //This is when we deleted the last account and go to the login screen and when edit credentials in settings view - self.urlTextField = [[UITextField alloc]initWithFrame:self.urlFrame]; - self.urlTextField.text = self.auxUrlForReloadTable; - textField = self.urlTextField; - } - - if(self.usernameTextField.text == nil) { - self.usernameTextField = [[UITextField alloc]initWithFrame:self.userAndPasswordFrame]; - self.usernameTextField.text = self.auxUsernameForReloadTable; - } - - self.auxUsernameForReloadTable = self.usernameTextField.text; - self.auxPasswordForReloadTable = self.passwordTextField.text; - - //if it is nil the screen is not here - if(((CheckAccessToServer *)[CheckAccessToServer sharedManager]).delegate != nil) { - DLog(@"CheckAccessToServer nil"); - //[self undoAnimateTextField:textField up:YES]; - - if(isUserTextUp==YES || isPasswordTextUp==YES){ - // [self undoAnimate]; - } - - if(textField == self.urlTextField) { - self.errorMessage = nil; - } - - if(textField == self.urlTextField && self.urlTextField.text.length > 0) { - [self animateTextField: textField up: NO]; - - - if(textField == self.urlTextField) { - - if(threadToCheckUrl.isExecuting) { - [threadToCheckUrl cancel]; - } - - //[self.tableView reloadData]; - [self isConnectionToTheServerByUrlInOtherThread]; - - //[self performSelectorInBackground:@selector(isConnectionToTheServerByUrlInOtherThread) withObject:nil]; - } - } - - if(textField == self.passwordTextField && ![textField.text isEqualToString:self.auxPasswordForShowPasswordOnEdit]) { - self.auxPasswordForShowPasswordOnEdit = @""; - [showPasswordCharacterButton setHidden:NO]; - } else if (textField == self.urlTextField) { - [refreshTestServerButton setHidden:NO]; - } - - if ((self.urlTextField.text.length > 0 && self.passwordTextField.text.length > 0 && self.passwordTextField.text.length > 0 && isConnectionToServer && !hasInvalidAuth) || (isConnectionToServer && (k_is_oauth_active || k_is_sso_active))) { - //[loginButton setEnabled:YES]; - isLoginButtonEnabled = YES; - [self.tableView reloadData]; - }else { - isLoginButtonEnabled = NO; - } - - if(textField == self.urlTextField) { - [self.urlTextField setFrame:_urlFrame]; - } - - if (textField == _passwordTextField) { - //if the scrroll is not a the start of the tableview we move the scroll - if(_tableView.contentOffset.y > 0) { - //[_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; - [_tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES]; - } - } - } -} - --(void) textFieldDidChange { - - if(k_is_autocomplete_username_necessary) { - DLog(@"textFieldDidChange: %@", self.usernameTextField.text); - - if([self.usernameTextField.text hasSuffix:k_letter_to_begin_autocomplete]) { - self.usernameTextField.text = [NSString stringWithFormat:@"%@%@",self.usernameTextField.text,k_text_to_autocomplete]; - } - } -} - --(void) isConnectionToTheServerByUrlInOtherThread { - DLog(@"_isConnectionToTheServerByUrlInOtherThread_"); - dispatch_async(dispatch_get_main_queue(), ^{ - [self.tableView reloadData]; - }); - isCheckingTheServerRightNow = YES; - isConnectionToServer = NO; - - //Reset the url of redirected server at this point - AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - app.urlServerRedirected = nil; - - [[CheckAccessToServer sharedManager] isConnectionToTheServerByUrl:[self getUrlToCheck]]; -} - --(NSString *)stripIndexPhpOrAppsFilesFromUrl:(NSString *)url { - - NSRange range = [url rangeOfString:k_remove_to_contains_path]; - - if ([url hasSuffix:k_remove_to_suffix]) { - url = [url substringToIndex:[url length] - [(NSString *)k_remove_to_suffix length]]; - self.urlTextField.text = url; - } else if (range.length > 0) { - url = [url substringToIndex:range.location]; - self.urlTextField.text = url; - } - - return url; -} - -- (NSString *)stripUsernameAndPassword:(NSString *)url { - - NSString *fakeUrl = url; - - //fake url to compose full url propertly without use getUrlToCheck to compose components propertly - if (!([url hasPrefix:k_https_prefix] || [url hasPrefix:k_http_prefix])) { - fakeUrl = [NSString stringWithFormat:@"%@%@",k_https_prefix ,url]; - } - - NSURLComponents *components = [NSURLComponents componentsWithString:fakeUrl]; - - // if user component was set on the server URL, move it to the user field - if(components.user.length > 0) { - [self.usernameTextField setText:components.user]; - } - - // if password component was set on the server URL, move it to the password field - if(components.password.length > 0) { - [self.passwordTextField setText:components.password]; - } - - if (components.user.length > 0 || components.password.length >0) { - - components.user = nil; - components.password = nil; - - NSString *fullURLWithoutUsernamePassword = [self.urlTextField.text substringFromIndex:[self.urlTextField.text rangeOfString: @"@"].location+1]; - - url = fullURLWithoutUsernamePassword; - - [self.urlTextField setText:url]; - } - - return url; -} - --(NSString *)getUrlToCheck { - - DLog(@"getUrlToCheck"); - - NSString *url = [self getUrlChecked:self.urlTextField.text]; - - if ([url hasPrefix:k_https_prefix]) { - isNeedToCheckAgain = NO; - isHttps=YES; - url = [NSString stringWithFormat:@"%@", [self getUrlChecked: self.urlTextField.text]]; - } else if ([url hasPrefix:k_http_prefix]) { - isNeedToCheckAgain = NO; - isHttps = NO; - url = [NSString stringWithFormat:@"%@", [self getUrlChecked: self.urlTextField.text]]; - } else if (isNeedToCheckAgain) { - isNeedToCheckAgain = YES; - isHttps = YES; - url = [NSString stringWithFormat:@"%@%@",k_https_prefix,[self getUrlChecked: self.urlTextField.text]]; - } else { - isNeedToCheckAgain = NO; - isHttps = NO; - url = [NSString stringWithFormat:@"%@%@",k_http_prefix,[self getUrlChecked: self.urlTextField.text]]; - } - return url; -} - --(NSString *)getUrlChecked:(NSString *)byUrl { - - //We remove the accidentally last spaces " " - while([byUrl hasSuffix:@" "]) { - byUrl = [byUrl substringToIndex:[byUrl length] - 1]; - } - - DLog(@"byURL: |%@|",byUrl); - - //We check if the last char is a / if it is not we set it - char urlLastChar =[byUrl characterAtIndex:([byUrl length]-1)]; - if(urlLastChar != '/') { - byUrl = [byUrl stringByAppendingString:@"/"]; - } - - DLog(@"URL with /: %@", byUrl); - - //We remove the accidentally first spaces " " - while([byUrl hasPrefix:@" "]) { - byUrl = [byUrl substringFromIndex:1]; - - DLog(@"byURL: |%@|",byUrl); - } - - return byUrl; -} - --(void)repeatTheCheckToTheServer { - [self isConnectionToTheServerByUrlInOtherThread]; -} - - -///----------------------------------- -/// @name Update Interface With Connection to the server -///----------------------------------- - -/** - * This method update the login view depends of the server is - * conected or not. - * - * Is called from "connectionToTheServer" and "checkIfServerAutentificationIsNormalFromURL" - * - * @param isConnection -> BOOL - */ --(void)updateInterfaceWithConnectionToTheServer:(BOOL)isConnection{ - dispatch_async(dispatch_get_main_queue(), ^{ - if(isConnection) { - isConnectionToServer = YES; - if (self.urlTextField.text.length > 0 && self.usernameTextField.text.length > 0 && self.passwordTextField.text.length > 0 && !hasInvalidAuth) { - //[loginButton setEnabled:YES]; - isLoginButtonEnabled = YES; - } - - } else { - isConnectionToServer = NO; - //[loginButton setEnabled:NO]; - isLoginButtonEnabled = NO; - } - - - if (isNeedToCheckAgain && !isConnectionToServer) { - isNeedToCheckAgain = NO; - //[loginButton setEnabled:NO]; - isLoginButtonEnabled = NO; - - if (isConnection) { - isConnectionToServer = YES; - //[loginButton setEnabled:YES]; - isLoginButtonEnabled = YES; - - if (self.urlTextField.text.length > 0 && self.usernameTextField.text.length > 0 && self.passwordTextField.text.length > 0) { - //[loginButton setEnabled:YES]; - isLoginButtonEnabled = YES; - } - - } else { - isConnectionToServer = NO; - //[loginButton setEnabled:NO]; - isLoginButtonEnabled = NO; - } - } - - if (isConnectionToServer) { - if (isHttps) { - UIImage *currentImage = [UIImage imageNamed: @"SecureConnectionIcon.png"]; - [checkConnectionToTheServerImage setImage:currentImage]; - [checkConnectionToTheServerImage setHidden:NO]; - } else { - UIImage *currentImage = [UIImage imageNamed: @"NonSecureConnectionIcon.png"]; - [checkConnectionToTheServerImage setImage:currentImage]; - [checkConnectionToTheServerImage setHidden:NO]; - } - - } else { - - if (isHttps && ![self.urlTextField.text hasPrefix:k_https_prefix]) { - DLog(@"es HTTPS no hay conexión"); - [[CheckAccessToServer sharedManager] isConnectionToTheServerByUrl:[self getUrlToCheck]]; - - } else { - UIImage *currentImage = [UIImage imageNamed: @"CredentialsError.png"]; - [checkConnectionToTheServerImage setImage:currentImage]; - [checkConnectionToTheServerImage setHidden:NO]; - } - } - - isCheckingTheServerRightNow = NO; - [self.tableView reloadData]; - - isNeedToCheckAgain = YES; - }); -} - -///----------------------------------- -/// @name Connection to the server -///----------------------------------- - -/** - * It's a delegate method of CheckAccessToServer class that - * it's called when the app know if the server is connected or not - * - * @param isConnection -> BOOL - * - */ --(void)connectionToTheServer:(BOOL)isConnection { - //Set to NO, before the checking - hasInvalidAuth = NO; - - if (isConnection) { - [self checkIfServerAutentificationIsNormalFromURL]; - }else{ - //Update the interface - [self updateInterfaceWithConnectionToTheServer:isConnection]; - } -} - -#pragma mark - Checklogin - -///----------------------------------- -/// @name Update Connect String -///----------------------------------- - -/** - * This method update the global variable _connectString, - * it's called sometimes in the code in order to get a correct - * full url dependes of the protocol - * - */ -- (void) updateConnectString{ - - NSString *httpOrHttps = @""; - - if(isHttps) { - if([_urlTextField.text hasPrefix:k_https_prefix]) { - httpOrHttps = @""; - } else { - httpOrHttps = k_https_prefix; - - } - } else { - if([_urlTextField.text hasPrefix:k_http_prefix]) { - httpOrHttps = @""; - } else { - httpOrHttps = k_http_prefix; - } - } - - NSString *connectURL =[NSString stringWithFormat:@"%@%@%@",httpOrHttps,[self getUrlChecked: _urlTextField.text], k_url_webdav_server]; - _connectString=connectURL; -} - - - --(void) checkLogin { - DLog(@"_checkLogin_"); - - [self updateConnectString]; - - [UtilsFramework deleteAllCookies]; - [UtilsCookies eraseURLCache]; - [UtilsCookies eraseCredentialsWithURL:self.connectString]; - - [self performSelector:@selector(connectToServer) withObject:nil afterDelay:0.5]; -} - - -///----------------------------------- -/// @name Check if server autentification is normal -///----------------------------------- - -/** - * This method is called in a normal autentification to check if the autentification - * server is normal. - * - */ -- (void) checkIfServerAutentificationIsNormalFromURL { - - //Update connect string - [self updateConnectString]; - - [UtilsFramework deleteAllCookies]; - [UtilsCookies eraseURLCache]; - [UtilsCookies eraseCredentialsWithURL:self.connectString]; - - //Empty username and password to get a fail response to the server - NSString *userName=@""; - NSString *password=@""; - - DLog(@"connect string: %@", _connectString); - - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:userName andPassword:password]; - - [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - - [[AppDelegate sharedOCCommunication] checkServer:_connectString onCommunication:[AppDelegate sharedOCCommunication] successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) { - - //Update the interface depend of if isInvalid or not - - isLoginButtonEnabled = k_is_sso_active; - hasInvalidAuth = !k_is_sso_active; - - DLog(@"_Check server success_ InvalidAuth=%d",hasInvalidAuth); - - [self checkTheSecurityOfTheRedirectedURL:response.URL.absoluteString]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [_tableView reloadData]; - [self updateInterfaceWithConnectionToTheServer:YES]; - }); - } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) { - - BOOL isInvalid = YES; - - NSString *authenticationHeader = @"Www-Authenticate"; - NSString *outhAuthentication = @"bearer"; - NSString *basicAuthentication = @"basic"; - - if (!k_is_sso_active) { - if (response.statusCode == kOCErrorServerUnauthorized) { - //Get header related with autentication type - NSString *autenticationType = [[response allHeaderFields] valueForKey:authenticationHeader]; - - if ((autenticationType) && ([autenticationType.lowercaseString hasPrefix:outhAuthentication])) { - //Autentication type oauth - if (k_is_oauth_active) { - //Check if is activate oauth - isInvalid = NO; - } else { - isInvalid = YES; - } - } else if ((autenticationType) && ([autenticationType.lowercaseString hasPrefix:basicAuthentication])) { - isInvalid = NO; - } else { - //For the moment we have to mantain this value as valid because when we work with - //some Redirected Server our library lost the Wwww-Authenticate header - isInvalid = NO; - } - }else if (response != nil) { - [self.manageNetworkErrors returnErrorMessageWithHttpStatusCode:response.statusCode andError:error]; - } - - } else { - //If sso_active the check does not fail - //As we are receiving a SAML error from SAML server, we forced the flag to accept this connection - isInvalid = NO; - isLoginButtonEnabled = YES; - } - - - //Update the interface depend of if isInvalid or not - if (isInvalid) { - hasInvalidAuth = YES; - } else { - hasInvalidAuth = NO; - } - - DLog(@"_Check server failure_ InvalidAuth=%d",hasInvalidAuth); - - if (response == nil) { - [self checkTheSecurityOfTheRedirectedURL:redirectedServer]; - }else{ - [self checkTheSecurityOfTheRedirectedURL:response.URL.absoluteString]; - } - - - dispatch_async(dispatch_get_main_queue(), ^{ - [_tableView reloadData]; - [self updateInterfaceWithConnectionToTheServer:YES]; - }); - }]; -} - - -///----------------------------------- -/// @name checkTheSecurityOfTheRedirectedURL -///----------------------------------- - -/** - * This method checks if the redirected URL has a downgrade of the security - So, if the first URL has https but the redirected one has http, we show a message to the user - * - * @param repsonse -> NSHTTPURLResponse, the response of the server - */ -- (void) checkTheSecurityOfTheRedirectedURL: (NSString *)redirectionURLString { - - if (isHttps) { - if ([redirectionURLString hasPrefix:k_https_prefix]) { - isHttpsSecure = YES; - } else { - isHttpsSecure = NO; - } - } - - DLog(@"_Check the security of the redirectedURL_: %@ isHttps=%d", redirectionURLString, isHttps); -} - - -///----------------------------------- -/// @name Connect to Server -///----------------------------------- - -/** - * This method do the proffind request to the webdav server in order - * to do the login and get the root folder - * - * If the request "success" call the method "createUserAndDataInTheSystemWithRequest" - * - */ -- (void) connectToServer{ - DLog(@"_connectToServer_"); - - NSString *userName=self.usernameTextField.text; - NSString *password=self.passwordTextField.text; - - //Set the right credentials - - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:userName andPassword:password]; - } - - [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - - [[AppDelegate sharedOCCommunication] readFolder:_connectString withUserSessionToken:nil onCommunication:[AppDelegate sharedOCCommunication] successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer, NSString *token){ - - DLog(@"Operation success response code: %ld", (long)response.statusCode); - - BOOL isSamlCredentialsError = NO; - - //Check the login error in shibboleth - if (k_is_sso_active) { - //Check if there are fragmens of saml in url, in this case there are a credential error - isSamlCredentialsError = [FileNameUtils isURLWithSamlFragment:response]; - if (isSamlCredentialsError) { - [self errorLogin]; - } - - } else if (redirectedServer){ - //Manage the redirectedServer. This case will only happen if is a permanent redirection 301 - DLog(@"Set the redirectedServer as default URL for the new user"); - - redirectedServer = [redirectedServer substringToIndex:[redirectedServer length] - k_url_webdav_server.length]; - - self.urlTextField.text = redirectedServer; - } - - if (!isSamlCredentialsError) { - //Pass the items with OCFileDto to FileDto Array - NSMutableArray *directoryList = [UtilsDtos passToFileDtoArrayThisOCFileDtoArray:items]; - [self createUserAndDataInTheSystemWithRequest:directoryList andCode:response.statusCode]; - } - } failureRequest:^(NSHTTPURLResponse *response, NSError *error, NSString *token, NSString *redirectedServer) { - - DLog(@"error: %@", error); - DLog(@"Operation error: %ld", (long)response.statusCode); - - [self.manageNetworkErrors returnErrorMessageWithHttpStatusCode:response.statusCode andError:error]; - }]; - -} - - -- (void)showError:(NSString *) message { - DLog(@"showError"); - self.errorMessage = message; - [self hideTryingToLogin]; - dispatch_async(dispatch_get_main_queue(), ^{ - [self.tableView reloadData]; - }); -} - - -///----------------------------------- -/// @name Create data with server data -///----------------------------------- - -/** - * This method is called when the app receive the data of the login proffind - * - * @param items -> Items of the proffind - * @param requestCode -> webdav server response - * - * @warning This method it's present also in AddAcountViewController and EditViewController - */ --(void)createUserAndDataInTheSystemWithRequest:(NSArray *)items andCode:(NSInteger) requestCode { - DLog(@"_createUserAndDataInTheSystemWithRequest:andCode:_ %ld",(long)requestCode); - // DLog(@"Request Did Fetch Directory Listing And Test Authetification"); - - if(requestCode >= 400) { - [self.manageNetworkErrors returnErrorMessageWithHttpStatusCode:requestCode - andError:nil]; - } else { - - UserDto *userDto = [[UserDto alloc] init]; - - //We check if start with http or https to concat it - if([self.urlTextField.text hasPrefix:k_http_prefix] || [self.urlTextField.text hasPrefix:k_https_prefix]) { - userDto.url = [self getUrlChecked: self.urlTextField.text]; - - } else { - if(isHttps) { - userDto.url = [NSString stringWithFormat:@"%@%@",k_https_prefix, [self getUrlChecked: self.urlTextField.text]]; - } else { - userDto.url = [NSString stringWithFormat:@"%@%@",k_http_prefix, [self getUrlChecked: self.urlTextField.text]]; - } - } - - DLog(@"Request code >=400 and userDtoUrl: %@", userDto.url); - - AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - - NSString *userNameUTF8=self.usernameTextField.text; - NSString *passwordUTF8=self.passwordTextField.text; - - userDto.username = userNameUTF8; - userDto.password = passwordUTF8; - userDto.ssl = isHttps; - userDto.activeaccount = YES; - //Take into account that this global property can be stored bab value - //For that we reset this property when the system check the server in LoginViewController class - userDto.urlRedirected = app.urlServerRedirected; - userDto.predefinedUrl = k_default_url_server; - - [ManageUsersDB insertUser:userDto]; - - app.activeUser=[ManageUsersDB getActiveUser]; - - NSMutableArray *directoryList = [NSMutableArray arrayWithArray:items]; - - //Change the filePath from the library to our db format - for (FileDto *currentFile in directoryList) { - currentFile.filePath = [UtilsUrls getFilePathOnDBByFilePathOnFileDto:currentFile.filePath andUser:app.activeUser]; - } - - DLog(@"The directory List have: %ld elements", (unsigned long)directoryList.count); - - DLog(@"Directoy list: %@", directoryList); - - [ManageFilesDB insertManyFiles:directoryList andFileId:0]; - - [self hideTryingToLogin]; - - //Generate the app interface - [app generateAppInterfaceFromLoginScreen:YES]; - - } - -} - --(void) errorLogin { - - DLog(@"Error login"); - - [self hideTryingToLogin]; - - isErrorOnCredentials = YES; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self.tableView reloadData]; - }); -} - - -#pragma mark - Cookies support -//----------------------------------- -/// @name restoreTheCookiesOfActiveUserByNewUser -///----------------------------------- - -/** - * Method to restore the cookies of the active after add a new user - * - * @param UserDto -> user - * - */ -- (void) restoreTheCookiesOfActiveUser { - DLog(@"_restoreTheCookiesOfActiveUser_"); - AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - - //1- Clean the cookies storage - [UtilsFramework deleteAllCookies]; - //2- We restore the previous cookies of the active user on the System cookies storage - [UtilsCookies setOnSystemStorageCookiesByUser:app.activeUser]; - //3- We delete the cookies of the active user on the databse because it could change and it is not necessary keep them there - [ManageCookiesStorageDB deleteCookiesByUser:app.activeUser]; -} - -#pragma marK - Action Buttons - --(void)checkUrlManually { - DLog(@"_checkUrlManually_"); - [self textFieldDidEndEditing:self.urlTextField]; -} - --(void)hideOrShowPassword { - if ([self.passwordTextField isSecureTextEntry]) { - [self.passwordTextField setSecureTextEntry:NO]; - [showPasswordCharacterButton setBackgroundImage:[UIImage imageNamed:@"NonRevealPasswordIcon.png"] forState:UIControlStateNormal]; - } else { - [self.passwordTextField setSecureTextEntry:YES]; - [showPasswordCharacterButton setBackgroundImage:[UIImage imageNamed:@"RevealPasswordIcon.png"] forState:UIControlStateNormal]; - } -} - -- (void)hidePassword{ - [self.passwordTextField setSecureTextEntry:YES]; - [showPasswordCharacterButton setBackgroundImage:[UIImage imageNamed:@"RevealPasswordIcon.png"] forState:UIControlStateNormal]; -} - --(void)goTryToDoLogin { - DLog(@"_goTryToDoLogin_ with user: %@ | pass: %@", self.usernameTextField.text, self.passwordTextField.text); - - self.errorMessage = nil; - - DLog(@"_goTryToDoLogin_ log2 urlTextField: %@ username:%@ isConnectionToServer%d : hasInvalidAuth: %d", self.urlTextField.text, self.usernameTextField.text, isConnectionToServer, hasInvalidAuth); - if (self.urlTextField.text.length > 0 && self.usernameTextField.text.length > 0 && self.passwordTextField.text.length > 0 && isConnectionToServer && !hasInvalidAuth) { - DLog(@"_goTryToDoLogin_ logIf_ Connection with server OK, go to showTryingToLogin"); - - [self showTryingToLogin]; - DLog(@"Connection with server, try to login"); - [self checkLogin]; - - }else { - isLoginButtonEnabled = NO; - DLog(@"_goTryToDoLogin_ logElse urlTextField: %@ username:%@ isConnectionToServer%d : hasInvalidAuth: %d", self.urlTextField.text, self.usernameTextField.text, isConnectionToServer, hasInvalidAuth); - } -} - -- (void) showHelpURLInSafari { - DLog(@"_showHelpURLInSafari_"); - - NSURL *url = [NSURL URLWithString:k_url_link_on_login]; - - if (![[UIApplication sharedApplication] openURL:url]) { - DLog(@"Failed to open url: %@", [url description]); - } -} - -#pragma mark - SSL Certificates - --(void)badCertificateNoAcceptedByUser { - - isCheckingTheServerRightNow = NO; - isSSLAccepted = NO; - //[loginButton setEnabled:NO]; - isLoginButtonEnabled = NO; - - UIImage *currentImage = [UIImage imageNamed: @"CredentialsError.png"]; - [checkConnectionToTheServerImage setImage:currentImage]; - [checkConnectionToTheServerImage setHidden:NO]; - - isNeedToCheckAgain = YES; - - [self.tableView reloadData]; -} - - -#pragma mark - OAuth - --(void)oAuthScreen { - - NSURL *url = [NSURL URLWithString:k_oauth_login]; - [[UIApplication sharedApplication] openURL:url]; -} - -#pragma mark - SSO - -///----------------------------------- -/// @name Check URL Server For SSO -///----------------------------------- - -/** - * This method checks the URL in URLTextField in order to know if - * is a valid SSO server. - * - */ - --(void) checkURLServerForSSO { - - //Get the URL string - NSString *urlString = [self getUrlToCheck]; - DLog(@"_checkURLServerForSSO_ %@",urlString); - - //Check SSO Server - CheckSSOServer *checkSSOServer = [CheckSSOServer new]; - checkSSOServer.delegate = self; - [checkSSOServer checkURLServerForSSOForThisPath:urlString]; - - //Show Loading screen - [self showTryingToLogin]; -} - - - -#pragma mark - CheckSSOServer Delegate methods - -///----------------------------------- -/// @name Show Shibboleth Login Screen -///----------------------------------- - -/** - * Method called from CheckSSOServer that show the Shibboleth login Screen - * - */ -- (void) showSSOLoginScreen{ - - //Server url - NSString * urlString = [self getUrlToCheck]; - - DLog(@"_showSSOLoginScreen_ url: %@", urlString); - - //In main thread - dispatch_async(dispatch_get_main_queue(), ^{ - - //Hide the loading icon - [self hideTryingToLogin]; - - //WebView controller - SSOViewController *ssoViewController = [[SSOViewController alloc] initWithNibName:@"SSOViewController" bundle:nil]; - ssoViewController.delegate = self; - ssoViewController.urlString = urlString; - - //Branding navigation bar - OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:ssoViewController]; - - //Check if is iPhone or iPad - if (!IS_IPHONE) { - //iPad - navController.modalTransitionStyle=UIModalTransitionStyleCoverVertical; - navController.modalPresentationStyle = UIModalPresentationFormSheet; - } - - [self presentViewController:navController animated:YES completion:nil]; - }); - -} - - -///----------------------------------- -/// @name Show SSO Error Server -///----------------------------------- - -/** - * Method called from CheckSSOServer that shows an alert view when the URLTextField isn't a valid SSO server - * - */ -- (void) showSSOErrorServer { - - //In main thread - dispatch_async(dispatch_get_main_queue(), ^{ - [self hideTryingToLogin]; - - UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"auth_unsupported_auth_method", nil) message:@"" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil]; - [alertView show]; - }); -} - - -///----------------------------------- -/// @name Show Error Connection -///----------------------------------- - -/** - * Method called from CheckSSOServer that show an alert view with error connection - * - */ -- (void)showErrorConnection{ - - //In main thread - dispatch_async(dispatch_get_main_queue(), ^{ - [self hideTryingToLogin]; - - UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"not_possible_connect_to_server", nil) message:@"" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil]; - [alertView show]; - }); -} - - -#pragma mark - SSODelegate methods - -///----------------------------------- -/// @name Set Cookie For SSO -///----------------------------------- - -/** - * This delegate method is called from SSOViewController when the user - * sets a correct credencials - * - * @param cookieString -> NSString - * @param samUserName -> NSString - * - */ -- (void)setCookieForSSO:(NSString *) cookieString andSamlUserName:(NSString*)samlUserName { - DLog(@"_setCookieForSSO:andSamlUserName:_ %@", samlUserName); - - //We should be change this behaviour when in the server side update the cookies. - if (samlUserName) { - _usernameTextField = [UITextField new]; - _usernameTextField.text = samlUserName; - - _passwordTextField = [UITextField new]; - _passwordTextField.text = cookieString; - self.alreadyHaveValidSAMLCredentials = YES; - - [self goTryToDoLogin]; - - }else if ([samlUserName isEqual: @""]){ - - //Show message in main thread - dispatch_async(dispatch_get_main_queue(), ^{ - UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"saml_server_does_not_give_user_id", nil) message:@"" delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", nil) otherButtonTitles:nil, nil]; - [alertView show]; - }); - }else { - //It's nil - //nothing to do - DLog(@"saml user name is nil"); - } - -} - - -- (void)setBarForCancelForLoadingFromModal { - - UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(closeViewController)]; - [self.navigationItem setLeftBarButtonItem:cancelButton]; -} - -- (void) closeViewController { - [self dismissViewControllerAnimated:YES completion:nil]; -} - -@end diff --git a/Owncloud iOs Client/Login/Login/LoginViewController_iPad.xib b/Owncloud iOs Client/Login/Login/LoginViewController_iPad.xib deleted file mode 100644 index 0b23f93ecd..0000000000 --- a/Owncloud iOs Client/Login/Login/LoginViewController_iPad.xib +++ /dev/null @@ -1,52 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Owncloud iOs Client/Login/Login/LoginViewController_iPhone.xib b/Owncloud iOs Client/Login/Login/LoginViewController_iPhone.xib deleted file mode 100644 index d26b103bb6..0000000000 --- a/Owncloud iOs Client/Login/Login/LoginViewController_iPhone.xib +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Owncloud iOs Client/Login/Login/ServerURLNormalizer.swift b/Owncloud iOs Client/Login/Login/ServerURLNormalizer.swift new file mode 100644 index 0000000000..1388d513fd --- /dev/null +++ b/Owncloud iOs Client/Login/Login/ServerURLNormalizer.swift @@ -0,0 +1,131 @@ +// +// ServerURLNormalizer.swift +// Owncloud iOs Client +// +// Created by David A. Velasco on 19/7/17. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +import Foundation + + +class ServerURLNormalizer { + + let k_http_prefix : String = "http://" + let k_https_prefix : String = "https://" + let k_remove_to_suffix : String = "/index.php" + let k_remove_to_contained_path : String = "/index.php/apps/" + + var normalizedURL = "" + var user: String? + var password: String? + var scheme: String? //TODO store scheme + + func normalize(serverURL: String) { + + self.normalizedURL = serverURL; + + self.normalizedURL = stripAccidentalWhiteSpaces(inputURL: normalizedURL) + + self.normalizedURL = stripUsernameAndPassword(inputURL: normalizedURL) + + self.normalizedURL = stripIndexPhpOrAppsFilesFromUrl(inputURL: normalizedURL); + + self.normalizedURL = grantFinalSlash(inputURL: normalizedURL) + } + + // Strip accidental white spaces at the end and beginning of the received URL. + // + func stripAccidentalWhiteSpaces(inputURL: String) -> String { + + var workURL: String = inputURL; + + while(workURL.hasSuffix(" ")) { // final blanks + workURL = workURL.substring(to: workURL.index(before: workURL.endIndex)) + } + + while(workURL.hasPrefix(" ")) { // initial blanks + workURL = workURL.substring(from: workURL.index(after: workURL.startIndex)) + } + + return workURL + } + + + // Strip username and password inserted in the received URL, if any. + // + // Stores both values in 'user' and 'password' properties. + // + func stripUsernameAndPassword(inputURL: String) -> String { + + var workURL: String = inputURL; + + // inputURL without scheme prefix is accepted, but NSURLComponents will parse all the string as the scheme + var forcedPrefix = false; + if !(workURL.hasPrefix(k_https_prefix) || workURL.hasPrefix(k_http_prefix)) { + // add HTTPS as prefix to trick NSURLComponents + workURL = "\(k_https_prefix)\(workURL)" + forcedPrefix = true; + } + if let components = NSURLComponents(string: workURL) { + // save parsed user and password + self.user = components.user + self.password = components.password + + // generate the URL as string again, without user and password + components.user = nil; + components.password = nil; + workURL = components.string! + + // remove scheme if was not in inputURL + if forcedPrefix { + workURL = workURL.substring(from: workURL.range(of: k_https_prefix)!.upperBound) + } + + return workURL + + } else { + return inputURL + } + } + + + // Strip accepted paths for URLs copied directly from web browser + // + func stripIndexPhpOrAppsFilesFromUrl(inputURL: String) -> String { + + var returnURL: String = inputURL + + if inputURL.hasSuffix(k_remove_to_suffix) { + + returnURL = inputURL.substring(to: inputURL.range(of: k_remove_to_suffix, options: NSString.CompareOptions.backwards)!.lowerBound) + + } else if let rangeOfContainedPathToRemove = inputURL.range(of: k_remove_to_contained_path) { + + returnURL = inputURL.substring(to: rangeOfContainedPathToRemove.lowerBound); + } + + return returnURL + } + + + // Grant last character is / + // + func grantFinalSlash(inputURL: String) -> String { + + if !inputURL.hasSuffix("/") { + return "\(inputURL)/" + } + + return inputURL + } + +} diff --git a/Owncloud iOs Client/Login/Login/UniversalLoginViewController.swift b/Owncloud iOs Client/Login/Login/UniversalLoginViewController.swift new file mode 100644 index 0000000000..cf7c92131a --- /dev/null +++ b/Owncloud iOs Client/Login/Login/UniversalLoginViewController.swift @@ -0,0 +1,953 @@ +// +// UniversalLoginViewController.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 21/06/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +import Foundation + +struct K { + struct segueId { + static let segueToWebLoginView = "segueToWebLoginView" + } + + struct unwindId { + static let unwindToMainLoginView = "unwindToMainLoginView" + } + + struct vcId { + static let vcIdWebViewLogin = "WebViewLoginViewController" + } +} + +public enum TextfieldType: String { + case url = "url" + case username = "username" + case password = "password" +} + +@objc public enum StateCheckedURL: Int { + case None + case TestingConnection + case ConnectionEstablishedSecure + case ConnectionEstablishedNonSecure + case Error +} + + +@objc public class UniversalLoginViewController: UIViewController, UITextFieldDelegate, SSODelegate { + +// MARK: IBOutlets + @IBOutlet var scrollView: UIScrollView! + + @IBOutlet var imageViewLogo: UIImageView! + + @IBOutlet weak var viewTopLogo: UIView! + @IBOutlet var imageViewTopInfo: UIImageView! + @IBOutlet var labelTopInfo: UILabel! + + @IBOutlet var imageViewLeftURL: UIImageView! + @IBOutlet var textFieldURL: UITextField! + @IBOutlet var buttonReconnection: UIButton! + + @IBOutlet weak var buttonReconnectionURL: UIButton! + @IBOutlet var imageViewURLFooter: UIImageView! + @IBOutlet var labelURLFooter: UILabel! + @IBOutlet var activityIndicatorURLFooter: UIActivityIndicatorView! + + //For Basic and edit account + @IBOutlet var imageViewUsername: UIImageView! + @IBOutlet var textFieldUsername: UITextField! + + @IBOutlet var imageViewLeftPassword: UIImageView! + @IBOutlet var textFieldPassword: UITextField! + @IBOutlet var revealPasswordButton: UIButton! + + @IBOutlet var imageViewPasswordFooter: UIImageView! + @IBOutlet var labelPasswordFooter: UILabel! + + @IBOutlet var buttonConnect: UIButton! + @IBOutlet var buttonHelpLink: UIButton! + + + //StackViews + @IBOutlet weak var topInfoStackView: UIStackView! + @IBOutlet weak var urlStackView: UIStackView! + @IBOutlet weak var urlInfoStackView: UIStackView! + @IBOutlet weak var usernameStackView: UIStackView! + @IBOutlet weak var passwordStackView: UIStackView! + @IBOutlet weak var basicAuthInfoStackView: UIStackView! + @IBOutlet weak var connectButtonStackView: UIStackView! + @IBOutlet weak var helpButtonStackView: UIStackView! + + + var validatedServerURL: String! + var allAvailableAuthMethods = [AuthenticationMethod]() + var authMethodToLogin: AuthenticationMethod! = .UNKNOWN + var authCodeReceived = "" + var manageNetworkErrors: ManageNetworkErrors! + private var loginMode: LoginMode! + private var user: UserDto? + var activeField: UITextField! + var nextErrorShouldBeShownAfterPasswordField = false; + + let serverURLNormalizer: ServerURLNormalizer = ServerURLNormalizer() + let getPublicInfoFromServerJob: GetPublicInfoFromServerJob = GetPublicInfoFromServerJob() + var statusBarTintSubview: UIView! + var topTwentiConstraint: NSLayoutConstraint! + + private let oAuth2Manager: OCOAuth2Manager = OCOAuth2Manager() + + + public override func viewDidLoad() { + super.viewDidLoad() + + topTwentiConstraint = self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 0) + + topTwentiConstraint.isActive = true + + viewDidLayoutSubviews() + + self.listenNotificationsAboutKeyboard() + self.manageNetworkErrors = ManageNetworkErrors() + // using ManageNetworkErrors() without delegate; UniversalLoginViewController will call + // ManageNetworkErrors.returnErrorMessageWithHttpStatusCode when appropriate, and will show + // the message without a callback to a delegate method + + textFieldURL.delegate = self + textFieldUsername.delegate = self + textFieldPassword.delegate = self + + + self.showInitMessageCredentialsErrorIfNeeded() + + let enabledEditUrlUsernamePassword : Bool = (self.loginMode == .create || self.loginMode == .migrate) + self.textFieldURL.isEnabled = enabledEditUrlUsernamePassword + self.textFieldURL.isUserInteractionEnabled = enabledEditUrlUsernamePassword + self.textFieldUsername.isEnabled = enabledEditUrlUsernamePassword + self.textFieldUsername.isUserInteractionEnabled = enabledEditUrlUsernamePassword + + + self.setBrandingStyle() + + self.initUI() + + self.oAuth2Manager.trustedCertificatesStore = SSLCertificateManager() + if self.loginMode == .update { + self.buttonReconnectionURL.isHidden = true + self.labelURLFooter.text = nil + self.imageViewURLFooter.image = nil + self.checkCurrentUrl() + } + + UtilsCookies.clear() // network requests from log-in view need to be independent of existing sessions + + print("Init login with loginMode: \(loginMode.rawValue) (0=Create,1=Update,2=Expire,3=Migrate)") + } + + public override func viewWillDisappear(_ animated: Bool) { + super.viewWillDisappear(animated) + + self.removeNotificationsAboutKeyboard() + if self.loginMode == .update || self.loginMode == .migrate { + UtilsCookies.restoreTheCookiesOfActiveUser() + + } + } + + public override func viewDidLayoutSubviews() { + if self.navigationController == nil { + if !UIApplication.shared.isStatusBarHidden { + topTwentiConstraint.constant = 0 + } else { + topTwentiConstraint.constant = -64 + } + } else { + topTwentiConstraint.constant = -10 + } + } + + + public override var preferredStatusBarStyle: UIStatusBarStyle { + if Customization.kIsTextLoginStatusBarWhite() { + return .lightContent + } + return .default + } + + + //MARK: Set up credentials error + + func showInitMessageCredentialsErrorIfNeeded() { + + if self.loginMode == .migrate { + + self.setTopInfo(message: "error_updating_predefined_url") + + } else if self.loginMode == .expire{ + + self.setTopInfo(message: "session_expired") + + } + } + + //MARK: Set up image and label with error/info + + func setTopInfo(message: String) { + + self.labelTopInfo.text = NSLocalizedString(message, comment: ""); + + self.imageViewTopInfo.image = UIImage(named: "CredentialsError.png")! + } + + func setActivityIndicator(isVisible: Bool) { + self.imageViewURLFooter.isHidden = isVisible + if isVisible { + self.activityIndicatorURLFooter.startAnimating() + } else { + self.activityIndicatorURLFooter.stopAnimating() + } + } + + private func showURLError(_ message: String!) { + DispatchQueue.main.async { + self.setURLFooter(isType: .Error, errorMessage: message) + } + } + + private func showURLSuccess(_ serverIsSecure: Bool) { + DispatchQueue.main.async { + if serverIsSecure { + self.setURLFooter(isType: .ConnectionEstablishedSecure) + } else { + self.setURLFooter(isType: .ConnectionEstablishedNonSecure) + } + } + } + + private func showCredentialsError(_ message: String!) { + DispatchQueue.main.async { + if (self.basicAuthInfoStackView.isHidden) { + self.setURLFooter(isType: .Error, errorMessage: message) + } else { + self.setPasswordFooterError(errorMessage: message) + } + self.setConnectButton(status: true) + } + } + + private func setURLFooter(isType type: StateCheckedURL, errorMessage: String = "") { + + var footerMessage = "" + self.setActivityIndicator(isVisible: false) + + switch type { + + case .Error: + self.imageViewURLFooter.image = UIImage(named: "CredentialsError.png")! + self.labelURLFooter.text = errorMessage + self.setReconnectionButtons(hiddenStatus: false) + return // beware: return here, break in the rest + + case .TestingConnection: + footerMessage = "testing_connection" + self.setActivityIndicator(isVisible: true) + break + + case .ConnectionEstablishedNonSecure: + self.imageViewURLFooter.image = UIImage(named: "NonSecureConnectionIcon.png")! + footerMessage = "connection_established" + break + + case .ConnectionEstablishedSecure: + self.imageViewURLFooter.image = UIImage(named: "SecureConnectionIcon.png")! + footerMessage = "secure_connection_established" + break + + case .None: + self.imageViewURLFooter.image = nil + footerMessage = "" + break + } + + self.labelURLFooter.text = NSLocalizedString(footerMessage, comment: "") + } + + + func setPasswordFooterError(errorMessage: String) { + + self.labelPasswordFooter.text = errorMessage; + + self.imageViewPasswordFooter.image = UIImage(named: "CredentialsError.png")! + } + + + //MARK: Set style + + func setBrandingStyle() { + + //labels messages + self.labelTopInfo.backgroundColor = UIColor.clear + self.labelTopInfo.textColor = UIColor.ofLoginErrorText() + + self.labelURLFooter.backgroundColor = UIColor.clear + self.labelURLFooter.textColor = UIColor.ofLoginErrorText() + + self.labelPasswordFooter.backgroundColor = UIColor.clear + self.labelPasswordFooter.textColor = UIColor.ofLoginErrorText() + + //text in text fields + textFieldURL.textColor = UIColor.ofURLUserPassword() + textFieldUsername.textColor = UIColor.ofURLUserPassword() + textFieldPassword.textColor = UIColor.ofURLUserPassword() + + //background + self.scrollView.backgroundColor = UIColor.ofLoginBackground() + self.imageViewLogo.backgroundColor = UIColor.ofLoginTopBackground() + self.viewTopLogo.backgroundColor = UIColor.ofLoginTopBackground() + + } + + func setConnectButton(status: Bool) { + self.buttonConnect.isEnabled = status + self.setConnectButtonStyle(isEnabled: status) + } + + private func setConnectButtonStyle(isEnabled: Bool) { + self.buttonConnect.layer.cornerRadius = self.buttonConnect.layer.bounds.height / 2 + self.buttonConnect.setTitleColor(UIColor.ofLoginButtonText(), for: .normal) + + if isEnabled { + self.buttonConnect.backgroundColor = UIColor.ofLoginButtonBackground() + } else { + self.buttonConnect.backgroundColor = UIColor.ofLoginButtonBackground().withAlphaComponent(0.6) + } + + } + + + //MARK: UI set up + func initUI() { + + let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) + + self.hideKeyboardWhenTappedAround() + + + //set cancel button in navigation bar + if ( self.loginMode == .update + || (self.loginMode == .create && (app.activeUser != nil)) + || (Customization.kMultiaccountAvailable() && (self.loginMode == .migrate || self.loginMode == .expire)) + ) { + + self.setCancelBarButtonSystemItem() + } + + //set URL status + if Customization.kHideUrlServer() { + self.setURLStackView(hiddenStatus: true) + } + + //set user&pass visibility + self.updateInputFieldsFromCurrentAuthMethodToLogin() + + //set login button status + self.setConnectButton(status: false) + + //init help link button status + self.buttonHelpLink.isHidden = Customization.kIsShownHelpLinkOnLogin() ? false : true + let buttonHelpTitleWithoutAppName = NSLocalizedString("help_link_login", comment: "") + let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String + let buttonHelpTitle = buttonHelpTitleWithoutAppName.replacingOccurrences(of: "$appname", with: appName) + self.buttonHelpLink.setTitle(buttonHelpTitle, for: .normal) + + + //Placeholders for the login textfields + self.textFieldURL.placeholder = NSLocalizedString("url_sample", comment: "") + self.textFieldUsername.placeholder = NSLocalizedString("username", comment: "") + self.textFieldPassword.placeholder = NSLocalizedString("password", comment: "") + + //init textField values + self.textFieldURL.text = k_default_url_server + + if self.loginMode != .create { + + if self.loginMode != .migrate { + self.textFieldURL.text = UtilsUrls.getFullRemoteServerPath(self.user) + } + + self.textFieldUsername.text = self.user?.username + self.textFieldPassword.text = "" + } + + //auto launch check of URL + if self.textFieldURL.text != nil && self.textFieldURL.text != "" { + self.checkCurrentUrl() + } + + } + + func setCancelBarButtonSystemItem() { + + let cancelButton = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.cancel, + target:self, + action:#selector(closeLoginView)) + + self.navigationItem.leftBarButtonItem = cancelButton + } + + func updateInputFieldsFromCurrentAuthMethodToLogin() { + let shouldBehiddenUserPassFields = (self.authMethodToLogin == nil || self.authMethodToLogin != AuthenticationMethod.BASIC_HTTP_AUTH); + self.setBasicAuthLoginStackViews(hiddenStatus: shouldBehiddenUserPassFields) + } + + func setBasicAuthLoginStackViews(hiddenStatus: Bool) { + + self.revealPasswordButton.setBackgroundImage(UIImage(named: "RevealPasswordIcon.png"), for: .normal) + + UIView.animate(withDuration: 0.5, animations: { + self.usernameStackView.isHidden = hiddenStatus + self.passwordStackView.isHidden = hiddenStatus + self.basicAuthInfoStackView.isHidden = hiddenStatus + }, completion: {(_) in + self.usernameStackView.isHidden = hiddenStatus + self.passwordStackView.isHidden = hiddenStatus + self.basicAuthInfoStackView.isHidden = hiddenStatus + }) + } + + func updateUIWithNormalizedData(_ oNormalized: ServerURLNormalizer) { + self.textFieldURL.text = self.validatedServerURL + if (oNormalized.user != nil) && !(oNormalized.user?.isEmpty)! { + self.textFieldUsername.text = oNormalized.user + } + if (oNormalized.password != nil) && !(oNormalized.password?.isEmpty)! { + self.textFieldPassword.text = oNormalized.password + self.textFieldPassword.becomeFirstResponder() + self.setConnectButton(status: true) + } + } + + func setURLStackView(hiddenStatus: Bool) { + self.urlStackView.isHidden = hiddenStatus + } + + func setReconnectionButtonOnURLInfoStackView(hiddenStatus: Bool) { + UIView.animate(withDuration: 0.5, animations: { + self.buttonReconnection.isHidden = hiddenStatus + }, completion: {(_) in }) + } + + func setReconnectionButtonOnURLStackView(hiddenStatus: Bool) { + UIView.animate(withDuration: 0.5, animations: { + self.buttonReconnectionURL.isHidden = hiddenStatus + }, completion: { (_) in + self.buttonReconnectionURL.isHidden = hiddenStatus + }) + } + + func setPasswordEyeOnPasswordStackView(hiddenStatus: Bool) { + UIView.animate(withDuration: 0.5, animations: { + self.revealPasswordButton.isHidden = hiddenStatus + }, completion: {(_) in }) + } + + func setReconnectionButtons(hiddenStatus: Bool) { + if Customization.kHideUrlServer() { + self.setReconnectionButtonOnURLInfoStackView(hiddenStatus: hiddenStatus) + } else { + self.setReconnectionButtonOnURLStackView(hiddenStatus: hiddenStatus) + } + } + + func setNetworkActivityIndicator(status: Bool) { + UIApplication.shared.isNetworkActivityIndicatorVisible = status + } + + func resetPasswordFooterMessage() { + self.imageViewPasswordFooter.image = nil + self.labelPasswordFooter.text = "" + } + + // MARK: dismiss + func closeLoginView() { + self.setNetworkActivityIndicator(status: false) + self.dismiss(animated: true, completion: nil) + } + + +// MARK: checkUrl + func checkCurrentUrl() { + self.setConnectButton(status: false) + self.setURLFooter(isType: .TestingConnection) + + if let inputURL = textFieldURL.text { + self.serverURLNormalizer.normalize(serverURL: inputURL) + self.setNetworkActivityIndicator(status: true) + // get public infor from server + getPublicInfoFromServerJob.start(serverURL: self.serverURLNormalizer.normalizedURL, withCompletion: { (validatedURL: String?, _ serverAuthenticationMethods: Array?, _ error: Error?, _ httpStatusCode: NSInteger) in + + self.setNetworkActivityIndicator(status: false) + if (error != nil || validatedURL == nil) { + + self.setConnectButton(status: false) + self.showURLError( + self.manageNetworkErrors.returnErrorMessage( + withHttpStatusCode: httpStatusCode, andError: error + ) + ) + print ("error getting information from URL") + + } else if validatedURL != nil { + + self.setURLFooter(isType: .None) + + self.validatedServerURL = validatedURL; + self.allAvailableAuthMethods = serverAuthenticationMethods as! [AuthenticationMethod] + + self.authMethodToLogin = DetectAuthenticationMethod.getAuthMethodToLoginFrom(availableAuthMethods: self.allAvailableAuthMethods) + + if (self.authMethodToLogin != .NONE) { + self.setReconnectionButtons(hiddenStatus: true) + + if (self.authMethodToLogin == .BASIC_HTTP_AUTH) { + self.textFieldURL.resignFirstResponder() + self.textFieldUsername.becomeFirstResponder() + + if self.loginMode == .update { + self.textFieldUsername.text = self.user?.username + self.textFieldPassword.text = "" + } + } else { + self.setConnectButton(status: false) + self.startAuthenticationWith(authMethod: self.authMethodToLogin) + } + + self.showURLSuccess(self.validatedServerURL.hasPrefix("https://")) + + } else { + self.setConnectButton(status: false) + self.showURLError(NSLocalizedString("authentification_not_valid", comment: "")) + } + self.updateUIWithNormalizedData(self.serverURLNormalizer) + } + + self.updateInputFieldsFromCurrentAuthMethodToLogin() + }) + } + } + + +// MARK: start log in auth + func startAuthenticationWith(authMethod: AuthenticationMethod) { + switch authMethod { + + case .SAML_WEB_SSO: + navigateToSAMLLoginView(); + self.setConnectButton(status: true) // work of the buttong was already done + break + + case .BEARER_TOKEN: + navigateToOAuthLoginView(); + self.setConnectButton(status: true) // work of the buttong was already done + break + + case .BASIC_HTTP_AUTH: + self.resetPasswordFooterMessage() + let userCredDto: OCCredentialsDto = OCCredentialsDto() + userCredDto.userName = self.textFieldUsername.text + userCredDto.accessToken = self.textFieldPassword.text + userCredDto.authenticationMethod = authMethod + nextErrorShouldBeShownAfterPasswordField = true + + self.detectUserDataAndValidate(credentials: userCredDto, serverPath: self.validatedServerURL) + + break + + default: + showURLError(NSLocalizedString("authentification_not_valid", comment: "")) + + } + + } + + func navigateToSAMLLoginView() { + + //Grant main thread + DispatchQueue.main.async { + print("_showSSOLoginScreen_ url: %@", self.validatedServerURL) + + //New SSO WebView controller + let ssoViewController: SSOViewController = SSOViewController(nibName: "SSOViewController", bundle: nil) + ssoViewController.urlString = self.validatedServerURL + ssoViewController.delegate = self + + //present it + ssoViewController.navigate(from: self) + } + } + + func navigateToOAuthLoginView() { + performSegue(withIdentifier: K.segueId.segueToWebLoginView, sender: self) + } + +// MARK: SSODelegate implementation + + /** + * This delegate method is called from SSOViewController when the user successfully logs-in. + * + * @param cookieString -> NSString Cookies in last state of the SSO WebView , including SSO cookie & OC session cookie. + * + */ + + public func setCookieForSSO(_ cookieString: String?, serverPath: String?) { + + self.setNetworkActivityIndicator(status: false) + if self.loginMode == .update { + ManageCookiesStorageDB.deleteCookies(byUser: self.user) + UtilsCookies.eraseCredentials(withURL: UtilsUrls.getFullRemoteServerPath(withWebDav: self.user)) + UtilsCookies.eraseURLCache() + } + + let userCredDto :OCCredentialsDto = OCCredentialsDto() + userCredDto.accessToken = cookieString; + userCredDto.authenticationMethod = .SAML_WEB_SSO; + + + if cookieString == nil || cookieString == "" { + self.showCredentialsError(NSLocalizedString("authentification_not_valid", comment: "") ) + + return; + } + + self.detectUserDataAndValidate(credentials: userCredDto, serverPath: serverPath!) + + } + + +// MARK: textField delegate + public func textFieldDidEndEditing(_ textField: UITextField) { + + self.activeField = nil + switch textField.restorationIdentifier! { + case TextfieldType.password.rawValue: + if textField.text == "" { + self.setPasswordEyeOnPasswordStackView(hiddenStatus: true) + } + break + case TextfieldType.url.rawValue: + if textField.text != "" { + self.checkCurrentUrl() + } + break + default: + break + } + } + + public func textFieldDidBeginEditing(_ textField: UITextField) { + self.activeField = textField + if textField.restorationIdentifier! == TextfieldType.password.rawValue { + self.setPasswordEyeOnPasswordStackView(hiddenStatus: false) + } + } + + public func textFieldShouldReturn(_ textField: UITextField) -> Bool { + + if self.authMethodToLogin != nil && self.authMethodToLogin == .BASIC_HTTP_AUTH { + if (self.textFieldUsername.text!.characters.count > 0) && (self.textFieldPassword.text!.characters.count > 0) { + self.setConnectButton(status: true) + } else { + self.setConnectButton(status: false) + } + } + + self.activeField = nil + switch textField.restorationIdentifier! { + case TextfieldType.url.rawValue: + textField.resignFirstResponder() + return true + case TextfieldType.username.rawValue: + self.textFieldPassword.becomeFirstResponder() + break + case TextfieldType.password.rawValue: + if (self.textFieldUsername.text?.characters.count)! > 0 { + self.setNetworkActivityIndicator(status: true) + self.setConnectButton(status: false) + startAuthenticationWith(authMethod: .BASIC_HTTP_AUTH) + } + textField.resignFirstResponder() + break + default: + break + } + + return false + } + + + public override func touchesBegan(_ touches: Set, with event: UIEvent?) { + self.view.endEditing(true) + } + +// MARK: Keyboard + + func hideKeyboardWhenTappedAround() { + let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UniversalLoginViewController.dismissKeyboard)) + view.addGestureRecognizer(tap) + } + + func dismissKeyboard() { + view.endEditing(true) + } + + + //MARK: Keyboard Notifications + + func listenNotificationsAboutKeyboard () { + NotificationCenter.default.addObserver(self, selector: #selector(UniversalLoginViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(UniversalLoginViewController.keyboardWillBeHidden(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) + } + + func removeNotificationsAboutKeyboard () { + NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil) + NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) + } + + func keyboardDidShow(_ notification: Notification) { + if let activeField = self.activeField, let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue { + let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height + 20, right: 0.0) + self.scrollView.contentInset = contentInsets + self.scrollView.scrollIndicatorInsets = contentInsets + var aRect = self.view.frame + aRect.size.height -= keyboardSize.size.height + if (!aRect.contains(activeField.frame.origin)) { + self.scrollView.scrollRectToVisible(activeField.frame, animated: true) + } + } + } + + func keyboardWillBeHidden(_ notification: Notification) { + let contentInsets = UIEdgeInsets.zero + self.scrollView.contentInset = contentInsets + self.scrollView.scrollIndicatorInsets = contentInsets + } + +// MARK: IBActions + @IBAction func reconnectionButtonTapped(_ sender: Any) { + self.dismissKeyboard() + self.checkCurrentUrl() + } + + @IBAction func connectButtonTapped(_ sender: Any) { + self.view.endEditing(true) + self.setNetworkActivityIndicator(status: true) + self.setConnectButton(status: false) // prevent multiple taps + self.startAuthenticationWith(authMethod: self.authMethodToLogin) + } + + @IBAction func helpLinkButtonTapped(_ sender: Any) { + UIApplication.shared.openURL(NSURL(string: k_url_link_on_login)! as URL) + } + + @IBAction func unwindToMainLoginView(segue:UIStoryboardSegue) { + if let sourceViewController = segue.source as? WebLoginViewController { + /// back from web view getting OAuth2 authorization code + + let webVC: WebLoginViewController = sourceViewController + if !(webVC.authCode).isEmpty { + self.setNetworkActivityIndicator(status: false) + self.authCodeReceived = webVC.authCode + + let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) + + self.oAuth2Manager.authData(by: app.oauth2Configuration, + withBaseURL: self.validatedServerURL, + authCode: self.authCodeReceived , + userAgent: UtilsUrls.getUserAgent(), + withCompletion: { (userCredDto: OCCredentialsDto?, error: Error?) in + + if let userCredentials = userCredDto { + + self.detectUserDataAndValidate(credentials: userCredentials, serverPath: self.validatedServerURL) + + } else { + + self.showURLError( + self.manageNetworkErrors.returnErrorMessage(withHttpStatusCode: -1, andError: error) + ) + } + + }) + } else if let error = webVC.error { + self.showURLError( + self.manageNetworkErrors.returnErrorMessage( + withHttpStatusCode: -1, andError: error + ) + ) + } + } + } + + @IBAction func revealPasswordButtonTapped(_ sender: UIButton) { + + if self.textFieldPassword.isSecureTextEntry { + self.textFieldPassword.isSecureTextEntry = false + self.revealPasswordButton.setBackgroundImage(UIImage(named: "NonRevealPasswordIcon.png"), for: .normal) + } else { + self.textFieldPassword.isSecureTextEntry = true + self.revealPasswordButton.setBackgroundImage(UIImage(named: "RevealPasswordIcon.png"), for: .normal) + } + } + + @IBAction func editingChanged(_ sender: UITextField) { + + if self.textFieldUsername.text != ""{ + self.setConnectButton(status: (sender.text?.characters.count)! > 0) + } + } + +// MARK: segue + override public func prepare(for segue: UIStoryboardSegue, sender: Any?) { + + if(segue.identifier == K.segueId.segueToWebLoginView) { + + let destinationNavigationController = segue.destination as! UINavigationController + let targetController = destinationNavigationController.topViewController as! WebLoginViewController + targetController.serverPath = self.validatedServerURL + } + } + + +// MARK: 'private' methods + + func detectUserDataAndValidate(credentials: OCCredentialsDto, serverPath: String) { + + DetectUserData .getUserDisplayName(ofServer: serverPath, credentials: credentials) { (displayName, error) in + + if (displayName != nil) { + + if credentials.authenticationMethod == .SAML_WEB_SSO { + + credentials.userName = displayName + } + credentials.userDisplayName = displayName + + } + + self.validateCredentialsAndStoreAccount(credentials: credentials) + } + + } + + + func validateCredentialsAndStoreAccount(credentials: OCCredentialsDto) { + //get list of files in root to check session validty, if ok store new account + let urlToGetRootFiles = NSURL (string: UtilsUrls.getFullRemoteServerPathWithWebDav(byNormalizedUrl: validatedServerURL) ) + + DetectListOfFiles().getListOfFiles(url: urlToGetRootFiles!, credentials: credentials, + withCompletion: { (_ errorHttp: NSInteger?,_ error: NSError?, _ listOfFileDtos: [FileDto]? ) in + + self.setNetworkActivityIndicator(status: false) + let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) + + if (listOfFileDtos != nil && !((listOfFileDtos?.isEmpty)!)) { + /// credentials allowed access to root folder: well done + + if ( (self.loginMode == .update || self.loginMode == .expire) && credentials.userName != self.user?.username ) { + self.showCredentialsError(NSLocalizedString("credentials_different_user", comment: "") ) + + } else { + + if self.user == nil { + self.user = UserDto() + } + + self.user?.url = self.validatedServerURL + self.user?.username = credentials.userName + self.user?.ssl = self.validatedServerURL.hasPrefix("https") + self.user?.urlRedirected = app.urlServerRedirected + self.user?.predefinedUrl = k_default_url_server + + credentials.baseURL = UtilsUrls.getFullRemoteServerPath(self.user) + + if self.loginMode == .create { + + if (ManageUsersDB.isExistUser(self.user)) { + self.showURLError(NSLocalizedString("account_not_new", comment: "")) + + } else { + + self.user = ManageAccounts().storeAccountOfUser(self.user!, withCredentials: credentials) + + if self.user != nil { + ManageFiles().storeListOfFiles(listOfFileDtos!, forFileId: 0, andUser: self.user!) + + app.switchActiveUser(to: self.user, inHardMode: true, withCompletionHandler: + { + app.generateAppInterface(fromLoginScreen: true) + }) + } else { + self.showURLError(NSLocalizedString("error_could_not_add_account", comment: "")) + } + } + + } else { + + ManageAccounts().updateAccountOfUser(self.user!, withCredentials: credentials) + if (app.activeUser != nil && app.activeUser.userId == self.user?.userId) { + app.activeUser = self.user; + } + + if self.loginMode == .migrate { + // migration mode needs to start a fresh list of files, so that it is updated with the new URL + app.generateAppInterface(fromLoginScreen: true) + + } else { + self.closeLoginView() + } + } + } + + } else { + if errorHttp == Int(kOCErrorServerUnauthorized) { + self.showCredentialsError( + self.manageNetworkErrors.returnErrorMessage( + withHttpStatusCode: (errorHttp)!, andError: nil + ) + ) + + } else { + self.showURLError( + self.manageNetworkErrors.returnErrorMessage( + withHttpStatusCode: (errorHttp)!, andError: error + ) + ) + } + } + + }) + + } + + override public func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + func setLoginMode(loginMode: LoginMode, user: UserDto) { + self.loginMode = loginMode + self.user = user + } + +} diff --git a/Owncloud iOs Client/Login/Login/UtilsLogin.h b/Owncloud iOs Client/Login/Login/UtilsLogin.h new file mode 100644 index 0000000000..32250441d5 --- /dev/null +++ b/Owncloud iOs Client/Login/Login/UtilsLogin.h @@ -0,0 +1,35 @@ +// +// UtilsLogin.h +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 18/07/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +#import +#import "UserDto.h" + + +@class UniversalLoginViewController; + +typedef NS_ENUM (NSUInteger, LoginMode){ + LoginModeCreate, + LoginModeUpdate, + LoginModeExpire, + LoginModeMigrate, +}; + +@interface UtilsLogin : NSObject + + ++ (UniversalLoginViewController *)getLoginVCWithMode:(LoginMode)loginMode andUser:(UserDto *)user; + +@end diff --git a/Owncloud iOs Client/Login/Login/UtilsLogin.m b/Owncloud iOs Client/Login/Login/UtilsLogin.m new file mode 100644 index 0000000000..4b7865177d --- /dev/null +++ b/Owncloud iOs Client/Login/Login/UtilsLogin.m @@ -0,0 +1,40 @@ +// +// UtilsLogin.m +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 18/07/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +#import "UtilsLogin.h" + +#ifdef CONTAINER_APP +#import "Owncloud_iOs_Client-Swift.h" +#elif FILE_PICKER +#import "ownCloudExtApp-Swift.h" +#elif SHARE_IN +#import "OC_Share_Sheet-Swift.h" +#else +#import "ownCloudExtAppFileProvider-Swift.h" +#endif + +@implementation UtilsLogin + ++ (UniversalLoginViewController *)getLoginVCWithMode:(LoginMode)loginMode andUser:(UserDto *)user { + UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; + UniversalLoginViewController *universalLoginVC = (UniversalLoginViewController*)[storyboard instantiateViewControllerWithIdentifier:@"universalLoginViewController"]; + [universalLoginVC setLoginModeWithLoginMode:loginMode user:user]; + //[]; + + return universalLoginVC; +} + +@end diff --git a/Owncloud iOs Client/Login/Login/WebLoginViewController.swift b/Owncloud iOs Client/Login/Login/WebLoginViewController.swift new file mode 100644 index 0000000000..c4b8d16f70 --- /dev/null +++ b/Owncloud iOs Client/Login/Login/WebLoginViewController.swift @@ -0,0 +1,199 @@ +// +// WebLoginViewController.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 23/06/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + + +import Foundation + + +@objc class WebLoginViewController: UIViewController, UIWebViewDelegate, UITextFieldDelegate, NSURLConnectionDelegate { + + + var authCode = "" + var error: Error? = nil + + private let sslCertificateManager: SSLCertificateManager = SSLCertificateManager(); + + private var currentRequest: URLRequest? = nil; + + private var loadInterrupted: Bool = false; + + private let oAuth2Manager: OCOAuth2Manager = OCOAuth2Manager() + + // MARK: IBOutlets + @IBOutlet var webViewLogin: UIWebView! + @IBOutlet var cancelButton: UIBarButtonItem! + + @IBAction func cancelButtonTapped(_ sender: Any) { + self.closeLoginViewController() + + } + + func closeLoginViewController() { + self.performSegue(withIdentifier: K.unwindId.unwindToMainLoginView, sender: self) + } + + var serverPath: String! + + override func viewDidLoad() { + super.viewDidLoad() + self.webViewLogin.delegate = self + self.webViewLogin.backgroundColor = UIColor.ofWebViewBackground() + + // Do any additional setup after loading the view. + + //load login url in web view + let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) + self.oAuth2Manager.trustedCertificatesStore = self.sslCertificateManager + let urlToGetAuthCode = self.oAuth2Manager.getOAuth2URLToGetAuthCode(by: app.oauth2Configuration, withServerPath: serverPath) + self.loadWebViewWith(url: urlToGetAuthCode!) + + self.loadInterrupted = false; + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + func loadWebViewWith (url : URL) { + + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: TimeInterval(k_timeout_upload)) + request.addValue(UtilsUrls.getUserAgent(), forHTTPHeaderField: "User-Agent") + + self.webViewLogin.loadRequest(request) + } + + + // MARK: webView delegates + + func webViewDidStartLoad(_ webView: UIWebView) { + + print("Loading login in webView with url:\(String(describing: webView.request?.mainDocumentURL))") + } + + func webViewDidFinishLoad(_ webView: UIWebView) { + + print("Loaded url:\(String(describing: webView.request?.mainDocumentURL))") + } + + func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { + print("An error happened during load: \(error)"); + + if sslCertificateManager.isUntrustedServerCertificate(error) { + self.retryIfCertificateInCurrentRequestWasAcceptedByUser() + return; + + } else if !self.loadInterrupted { + self.error = error + + } //else, let the error set in webView(webView, shouldStartLoadWith, navigationType), if any + + self.closeLoginViewController() + } + + func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { + + let urlToFollow: String = (request.url?.absoluteString)! + + // We store the request to inspect the server certificate and retry it in case of SSL error + self.currentRequest = request; + + if urlToFollow.hasPrefix(k_oauth2_redirect_uri){ + processFinalRedirect(urlToFollow); + self.loadInterrupted = true; + return false; // will trigger webView(webView, didFailLoadWithError), with error due to cancellation + + } else if urlToFollow.hasPrefix(serverPath + k_url_path_list_of_files_in_web) { + self.error = UtilsFramework.getErrorByCodeId(Int32(OCErrorOAuth2Error.rawValue)) + self.loadInterrupted = true; + // for some reason, this time "return false" will NOT trigger webView(webView, didFailLoadWithError), with error due to cancellation + // so, let's solve it here: + self.closeLoginViewController() + return false; + } + + return true; + } + + func processFinalRedirect(_ urlToFollow: String) -> Void { + if let code = getQueryStringParameter(url: urlToFollow, param: "code") { + self.authCode = code + self.error = nil; + print("contains url and code auth \(self.authCode)") + + } else if let errorString = getQueryStringParameter(url: urlToFollow, param: "error") { + if errorString == "access_denied" { + self.error = UtilsFramework.getErrorByCodeId(Int32(OCErrorOAuth2ErrorAccessDenied.rawValue)) + } else { + self.error = UtilsFramework.getErrorByCodeId(Int32(OCErrorOAuth2Error.rawValue)) + } + + } + } + + func getQueryStringParameter(url: String, param: String) -> String? { + guard let url = URLComponents(string: url) else { return nil } + return url.queryItems?.first(where: { $0.name == param })?.value + } + + + // MARK - HACK on UIWebView to allow access to servers with insecure certificates that were already accepted by the user + + func retryIfCertificateInCurrentRequestWasAcceptedByUser() -> Void { + // Start an NSURLConnection with the current request to receive an authentication challenge that we can accept or not + NSURLConnection.init(request: currentRequest!, delegate: self) + // TODO - check if hack works also with NSURLSession + } + + // MARK NSURLConnection Delegate Method, part of the HACK on UIWebView + + public func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge) { + var trusted: Bool = false + if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) { + if sslCertificateManager.isTrustedServerCertificate(in: challenge) { + print("trusting connection to host %@", challenge.protectionSpace.host) + + trusted = true; + + challenge.sender?.use(URLCredential.init(trust: challenge.protectionSpace.serverTrust!), for: challenge) + + } else { + print("Not trusting connection to host %@", challenge.protectionSpace.host); + } + + } else { + print("WARNING: expecting NSURLAuthenticationMethodServerTrust, received %@ instead, will continue without credentials", challenge); + } + + if (!trusted) { + challenge.sender?.continueWithoutCredential(for: challenge) + } + + connection.cancel() + // nothing else is needed from the connection once that challenge.sender is "instructed"; + // ir will cache the response for future uses, what allows to load the request again in the webview successfully + + if (trusted) { + // retry it; should work now! + self.webViewLogin.loadRequest(currentRequest!) + + } else { + // TODO askToAcceptCertificate() + print("TODO: askToAcceptCertificate() or direct error"); + } + } + +} diff --git a/Owncloud iOs Client/Login/SSO/SSOViewController.h b/Owncloud iOs Client/Login/SSO/SSOViewController.h index fcc64e0b67..d6fe805fb7 100644 --- a/Owncloud iOs Client/Login/SSO/SSOViewController.h +++ b/Owncloud iOs Client/Login/SSO/SSOViewController.h @@ -24,7 +24,7 @@ @protocol SSODelegate @optional -- (void)setCookieForSSO:(NSString *) cookieString andSamlUserName:(NSString*)samlUserName; +- (void)setCookieForSSO:(NSString *) cookieString serverPath:(NSString*)serverPath; @end @interface SSOViewController : UIViewController @@ -63,4 +63,8 @@ - (IBAction)cancel:(id)sender; +//Navigate to this instance +- (void) navigateFrom:(UIViewController *)currentVC; + + @end diff --git a/Owncloud iOs Client/Login/SSO/SSOViewController.m b/Owncloud iOs Client/Login/SSO/SSOViewController.m index a941e8d094..641bf79a3c 100644 --- a/Owncloud iOs Client/Login/SSO/SSOViewController.m +++ b/Owncloud iOs Client/Login/SSO/SSOViewController.m @@ -17,7 +17,6 @@ */ - #import "AppDelegate.h" #import "SSOViewController.h" #import "UserDto.h" @@ -34,21 +33,19 @@ #import "UIAlertView+Blocks.h" #import "UtilsUrls.h" #import "ManageAppSettingsDB.h" +#import "OCNavigationController.h" //Cookie #define k_cookie_user_value_name @"oc_username" -//JSON structure values -#define k_json_ocs @"ocs" -#define k_json_ocs_data @"data" -#define k_json_ocs_data_display_name @"display-name" - static NSString *const tmpFileName = @"tmp.der"; @interface SSOViewController () +@property SSLCertificateManager* sslCertificateManager; + @end @implementation SSOViewController @@ -72,6 +69,9 @@ - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil } //2- Delete the current cookies because we delete the current active user [UtilsFramework deleteAllCookies]; + + //3- Init SSLCertificateManager instance to access user-accepted server certificates + self.sslCertificateManager = [SSLCertificateManager new]; } return self; @@ -101,7 +101,6 @@ - (void)viewDidLoad //Set Background color [_webView setBackgroundColor:[UIColor colorOfWebViewBackground]]; - } @@ -173,7 +172,6 @@ - (void)clearAllCookies { DLog(@"Delete cookie"); [storage deleteCookie:cookie]; } - } #pragma mark UIWebView Delegate methods @@ -211,7 +209,7 @@ - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { error.code == kCFURLErrorServerCertificateNotYetValid) { - if (![[CheckAccessToServer sharedManager] isTemporalCertificateTrusted]) { + if (![self.sslCertificateManager isCurrentCertificateTrusted]) { [self askToAcceptCertificate]; } @@ -257,7 +255,6 @@ -(void)webViewDidFinishLoad:(UIWebView *)webView { if ([currentURL isEqualToString:_ownCloudServerUrlString]) { //Login is success with the third part server - //Catch the cookie storage NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage]; @@ -267,33 +264,17 @@ -(void)webViewDidFinishLoad:(UIWebView *)webView { NSMutableString * cookieString = nil; cookieString = [NSMutableString new]; - NSString *samlNameUser=nil; - - //DLog(@" %d cookies", cookiesArray.count); - //Loop for the cookies for (NSHTTPCookie * cookie in cookiesArray) { - if ([cookie.name isEqualToString:k_cookie_user_value_name]) { - samlNameUser = cookie.value; - } + [cookie.name isEqualToString:k_cookie_user_value_name]; // DLog(@"url: %@", webView.request.URL.absoluteString); - //DLog(@"cookie: %@", cookie); [cookieString appendFormat:@"%@=%@;", cookie.name, cookie.value]; } - samlNameUser = [self requestForUserNameByCookie: cookieString]; - - if (samlNameUser) { - DLog(@"samlNameUser: %@", samlNameUser); - DLog(@"currentURL: %@", currentURL); - - //Send to the delegate class the cookie receive from the server - [_delegate setCookieForSSO:cookieString andSamlUserName:samlNameUser]; - } - - + //Send to the delegate class the cookie receive from the server + [_delegate setCookieForSSO:cookieString serverPath:_urlString]; //Close this view [self cancel:nil]; @@ -394,7 +375,7 @@ - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)er error.code == kCFURLErrorServerCertificateNotYetValid) { - if (![[CheckAccessToServer sharedManager] isTemporalCertificateTrusted]) { + if (![self.sslCertificateManager isCurrentCertificateTrusted]) { [self initParemetersAndRetryOpenLink]; } } @@ -412,17 +393,6 @@ - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSUR DLog(@"Request: %@", request.URL.absoluteString); DLog(@"redirectResponse: %@", redirectResponse.URL.absoluteString); - if (redirectResponse) - { - NSMutableURLRequest *newRequest = [request mutableCopy]; // original request - - [newRequest setURL: [request URL]]; - - NSLog (@"redirected"); - self.authRequest = newRequest; - return newRequest; - } - return request; } @@ -470,77 +440,6 @@ - (void) initParemetersAndRetryOpenLink { [self retryOpenLink:self.urlStringToRetryTheWholeProcess]; } -///----------------------------------- -/// @name Request For User Name -///----------------------------------- - -/** - * This method gets the user display name for the ownCloud api and - * then return this. - * - * @param cookieString --> saml cookie - * - * @return userName - * - */ -- (NSString *) requestForUserNameByCookie:(NSString *) cookieString { - DLog(@"_requestForUserNameByCookie:_ %@", cookieString); - __block NSString *userName = @""; - - //We create a semaphore to wait until we recive the responses from Async calls - dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); - - - //Set the right credentials - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:cookieString]; - - [[AppDelegate sharedOCCommunication] getUserNameByCookie:cookieString ofServerPath:_urlString onCommunication:[AppDelegate sharedOCCommunication] success:^(NSHTTPURLResponse *response, NSData *responseData, NSString *redirectedServer) { - - //NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; - //DLog(@"Response: %@", responseString); - NSError *jsonError = nil; - //Get the json dictionary object - NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&jsonError]; - - if (!jsonDict) { - //Error - DLog(@"json error: %@", jsonError); - } else { - - //Get the ocs dictionary object - NSDictionary *ocsDict = [jsonDict objectForKey:k_json_ocs]; - - //Get the data dictionary object - NSDictionary *userDataDict = [ocsDict objectForKey:k_json_ocs_data]; - - //Display Name - userName = [userDataDict objectForKey:k_json_ocs_data_display_name]; - // DLog(@"UserName is: %@", userName); - } - - dispatch_semaphore_signal(semaphore); - - } failure:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) { - - DLog(@"Error: %@", error); - - userName = nil; - - [self.manageNetworkErrors returnErrorMessageWithHttpStatusCode:response.statusCode andError:error]; - - //Error we do not have user - dispatch_semaphore_signal(semaphore); - - }]; - - // Run loop - while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) { - [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode - beforeDate:[NSDate dateWithTimeIntervalSinceNow:k_timeout_upload]]; - } - - return userName; -} #pragma mark - Credentials interface @@ -608,35 +507,8 @@ -(void) connection:(NSURLConnection *)connection willSendRequestForAuthenticatio NSLog(@"willSendRequestForAuthenticationChallenge"); - BOOL trusted = NO; - SecTrustRef trust; - NSURLProtectionSpace *protectionSpace; - - protectionSpace = [challenge protectionSpace]; - trust = [protectionSpace serverTrust]; - - [[CheckAccessToServer sharedManager] createFolderToSaveCertificates]; - - if(trust != nil) { - [[CheckAccessToServer sharedManager] saveCertificate:trust withName:tmpFileName]; + BOOL trusted = [self.sslCertificateManager isTrustedServerCertificateIn:challenge]; - NSString *localCertificatesFolder = [UtilsUrls getLocalCertificatesPath]; - - NSMutableArray *listCertificateLocation = [ManageAppSettingsDB getAllCertificatesLocation]; - - for (int i = 0 ; i < [listCertificateLocation count] ; i++) { - - NSString *currentLocalCertLocation = [listCertificateLocation objectAtIndex:i]; - NSFileManager *fileManager = [ NSFileManager defaultManager]; - if([fileManager contentsEqualAtPath:[NSString stringWithFormat:@"%@%@",localCertificatesFolder,tmpFileName] andPath:[NSString stringWithFormat:@"%@",currentLocalCertLocation]]) { - NSLog(@"Is the same certificate!!!"); - trusted = YES; - } - } - } else { - trusted = NO; - } - if (trusted) { self.authenticated = YES; @@ -654,7 +526,8 @@ - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)butto if (alertView.tag == 2) { if (buttonIndex == 1) { - [[CheckAccessToServer sharedManager] acceptCertificate]; + DLog(@"user pressed YES"); + [self.sslCertificateManager trustCurrentCertificate]; } else { NSLog(@"user pressed CANCEL"); [self dismissThisView]; @@ -676,6 +549,22 @@ - (void) askToAcceptCertificate { +#pragma mark - navigation + +- (void) navigateFrom:(UIViewController *)currentVC { + + OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:self]; + + //Check if is iPhone or iPad + if (!IS_IPHONE) { + //iPad + navController.modalTransitionStyle=UIModalTransitionStyleCoverVertical; + navController.modalPresentationStyle = UIModalPresentationFormSheet; + } + [currentVC presentViewController:navController animated:YES completion:nil]; + +} + diff --git a/Owncloud iOs Client/Main.storyboard b/Owncloud iOs Client/Main.storyboard new file mode 100644 index 0000000000..45a5e69380 --- /dev/null +++ b/Owncloud iOs Client/Main.storyboard @@ -0,0 +1,453 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Owncloud iOs Client/ManageAccounts.swift b/Owncloud iOs Client/ManageAccounts.swift new file mode 100644 index 0000000000..4b7d3c2108 --- /dev/null +++ b/Owncloud iOs Client/ManageAccounts.swift @@ -0,0 +1,9 @@ +// +// ManageAccounts.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 13/07/2017. +// +// + +import Foundation diff --git a/Owncloud iOs Client/Network/Authentication/DetectAuthenticationMethod.swift b/Owncloud iOs Client/Network/Authentication/DetectAuthenticationMethod.swift new file mode 100644 index 0000000000..9f809791d0 --- /dev/null +++ b/Owncloud iOs Client/Network/Authentication/DetectAuthenticationMethod.swift @@ -0,0 +1,224 @@ +// +// DetectAuthenticationMethod.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 13/06/17. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +import Foundation + + +/** + * Operation to find out what authentication method requires + * the server to access files. + * + * Basically, tries to access to the root folder without authorization + * and analyzes the response. + * + * When successful, returns array of AuthenticationMethod available. + */ + +@objc class DetectAuthenticationMethod: NSObject, URLSessionDelegate, URLSessionTaskDelegate { + + @objc func auth_request(_ url: URL, withCompletion completion: @escaping (_ httpResponse: HTTPURLResponse?, _ error: Error?) -> Void) { + + var request = URLRequest(url: url) + request.httpMethod = "PROPFIND" + request.setValue("0", forHTTPHeaderField: "Depth") + request.setValue(UtilsUrls.getUserAgent(), forHTTPHeaderField: "User-Agent") + request.setValue("application/xml", forHTTPHeaderField: "Content-Type") + let body = "" + request.httpBody = body.data(using: String.Encoding.utf8) + + let configuration = URLSessionConfiguration.ephemeral + configuration.urlCredentialStorage = nil; // enforce that no credential is proposed for the auhtentication challenge + let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main) + + let task = session.dataTask(with: request as URLRequest, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) -> Void in + + if let error = error { + print(error.localizedDescription) + completion(nil, error) + + } else if let httpResponse = response as? HTTPURLResponse { + completion(httpResponse, error) + } + }) + task.resume() + + } + + + // Analyze server response and return all authentication methods accepted by it. + // + // Returns {AuthenticationMethod.UNKNOWN} if no method known by the client is supported, + // or if an HTTP error was returned. + func analyzeResponse(httpResponse: HTTPURLResponse) -> Array { + + var allAvailableAuthMethods = [AuthenticationMethod]() + + let isSAML: Bool = FileNameUtils.isURL(withSamlFragment: httpResponse) + + + if httpResponse.statusCode == NSInteger(kOCErrorServerUnauthorized) { + + let wwwAuthenticate = httpResponse.allHeaderFields["Www-Authenticate"] as? String + + if let allAuthMethodsResponse = wwwAuthenticate?.components(separatedBy: ",") { + + for wAuth in allAuthMethodsResponse { + + if wAuth.lowercased().range(of:"basic") != nil { + allAvailableAuthMethods.append(AuthenticationMethod.BASIC_HTTP_AUTH) + + } else if wAuth.lowercased().range(of:"bearer") != nil { + + allAvailableAuthMethods.append(AuthenticationMethod.BEARER_TOKEN) + } + + } + } + } else { + + if isSAML { + + allAvailableAuthMethods.append(AuthenticationMethod.SAML_WEB_SSO) + + } else if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300){ + + allAvailableAuthMethods.append(AuthenticationMethod.NONE) + } + + } + + + if allAvailableAuthMethods.isEmpty { + print("Authentication method not found") + allAvailableAuthMethods.append(AuthenticationMethod.UNKNOWN) + + } else { + print("Authentication methods found:") + for element in allAvailableAuthMethods { + print(" \(element.rawValue)" ) + } + print("0=UNKNOWN, 1=NONE, 2=BASIC_HTTP_AUTH, 3=BEARER_TOKEN, 4=SAML_WEB_SSO"); + } + + return allAvailableAuthMethods + } + + + func getAuthenticationMethodsAvailableBy(url: URL, withCompletion completion: @escaping (_ authMethods: Array? ,_ error: Error?) -> Void) { + + self.auth_request(url, withCompletion: { (httpResponse: HTTPURLResponse?,error: Error?) in + + if (httpResponse != nil) { + completion(self.analyzeResponse(httpResponse: httpResponse!) , nil ) + } else { + completion(nil, error) + } + + }) + + } + + + static func getAuthMethodToLoginFrom(availableAuthMethods: [AuthenticationMethod]) -> AuthenticationMethod { + + var authMethod: AuthenticationMethod? = .NONE + + if Customization.kIsSsoActive() { + + if availableAuthMethods.contains(.SAML_WEB_SSO) { + authMethod = .SAML_WEB_SSO + } + + } else if availableAuthMethods.contains(.BEARER_TOKEN){ + authMethod = .BEARER_TOKEN + + } else if availableAuthMethods.contains(.BASIC_HTTP_AUTH) { + authMethod = .BASIC_HTTP_AUTH + } + + return authMethod! + } + + +// MARK: UrlSession delegates + + // Delegate method called when the server responded with an authentication challenge. + // Since iOS is so great, it is also called when the server certificate is not trusted, so that the client + // can decide what to do about it. + // + // In this case an authentication challenge from the server is an expected response, since we made an + // unauthenticated request to analyse the authentication challenge. + // + func urlSession(_ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void){ + + // For the case that the call is due to server certificate not trusted, first we compare it with the server that + // could have been trusted by CheckAccessToServer in a previous call. Please, notice that DetectAuthenticationMethod is + // only used in the app as part of GetPublicInfoFromServerJob, and a successful call to CheckAccessToServer must have been + // finished before. That successful call could include the acceptance by the user of self-signed server certificates, and + // those are cached in CheckAccessToServer and considered in the call to CheckAccessToServer.isTrustedServer + let sslCertificateManager: SSLCertificateManager = SSLCertificateManager(); + let trusted: Bool = sslCertificateManager.isTrustedServerCertificate(in: challenge) + if (trusted) { + let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) + completionHandler(.useCredential,credential); + + } else if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust ){ + // If this method was called due to an unstrusted server certificate and this was not accepted by the user in + // CheckAccessToServer, .performDefaultHandling should be good enought to make the request fail due to the untrusted + // certificate. + completionHandler(.performDefaultHandling, nil); + + } else { + // If this method was called due to a real authentication challenge from the server, .performDefaultHandling with nil + // will repeat again the network request, wich is pretty unconvenient, but allows to handle the HTTP status code and + // response in the analyzeResponse(...) as part of the request completion handler. + + // The only way to prevent that the request was repeated would be using .cancelAuthenticationChallenge instead of + // .performDefaultHandling, but in that case I see no way to get the status code and the response headers in the completion + // handler, and since this callback itself cannot recognize Bearer authentication challenges, we cannot use it either to + // determine the list of authentication methods supported in the server. + + // "Deal with it" -- somebody in Apple. + // + completionHandler(.performDefaultHandling, nil); + } + } + + func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Swift.Void) { + + print("DetectAuthenticationMethod: redirect detected in URLSessionTaskDelegate implementation") + let newRequest = request + + let isSAML: Bool = FileNameUtils.isURL(withSamlFragment:response) + + if (isSAML) { + //stop + completionHandler(nil) + + } else { + //follow + completionHandler(newRequest) + } + } + + +} + + + diff --git a/Owncloud iOs Client/Network/Downloads/Download.m b/Owncloud iOs Client/Network/Downloads/Download.m index b4ce6d4ac1..75a8970933 100644 --- a/Owncloud iOs Client/Network/Downloads/Download.m +++ b/Owncloud iOs Client/Network/Downloads/Download.m @@ -94,17 +94,17 @@ - (void) processToDownloadTheFile { NSArray *splitedUrl = [[UtilsUrls getFullRemoteServerPath:app.activeUser] componentsSeparatedByString:@"/"]; NSString *serverUrl = [NSString stringWithFormat:@"%@%@%@",[NSString stringWithFormat:@"%@/%@/%@",[splitedUrl objectAtIndex:0],[splitedUrl objectAtIndex:1],[splitedUrl objectAtIndex:2]], _fileDto.filePath, _fileDto.fileName]; - serverUrl = [serverUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + serverUrl = [serverUrl stringByRemovingPercentEncoding]; //get local path of server __block NSString *localPath; if (_fileDto.isNecessaryUpdate) { //Change the local name for a temporal one - _temporalFileName = [NSString stringWithFormat:@"%@-%@", [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]], [_fileDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + _temporalFileName = [NSString stringWithFormat:@"%@-%@", [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]], [_fileDto.fileName stringByRemovingPercentEncoding]]; localPath = [NSString stringWithFormat:@"%@%@", _currentLocalFolder, _temporalFileName]; } else { - localPath = [NSString stringWithFormat:@"%@%@", _currentLocalFolder, [_fileDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + localPath = [NSString stringWithFormat:@"%@%@", _currentLocalFolder, [_fileDto.fileName stringByRemovingPercentEncoding]]; } _deviceLocalPath = localPath; @@ -121,17 +121,9 @@ - (void) processToDownloadTheFile { } [self reloadFileListForDataBase]; - - - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - + + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; __weak typeof(self) weakSelf = self; @@ -539,22 +531,15 @@ - (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error co - (void) updateThisEtagWithTheLast { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; //FileName full path NSString *serverPath = [UtilsUrls getFullRemoteServerPathWithWebDav:app.activeUser]; NSString *path = [NSString stringWithFormat:@"%@%@%@",serverPath, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:_fileDto.filePath andUser:app.activeUser], _fileDto.fileName]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; __weak typeof(self) weakSelf = self; diff --git a/Owncloud iOs Client/Network/Downloads/DownloadFolder/DownloadFileSyncFolder.m b/Owncloud iOs Client/Network/Downloads/DownloadFolder/DownloadFileSyncFolder.m index 394243530b..4ff08c60a2 100644 --- a/Owncloud iOs Client/Network/Downloads/DownloadFolder/DownloadFileSyncFolder.m +++ b/Owncloud iOs Client/Network/Downloads/DownloadFolder/DownloadFileSyncFolder.m @@ -45,28 +45,21 @@ - (void) addFileToDownload:(FileDto *) file { } AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; + NSString *serverUrl = [UtilsUrls getFullRemoteServerFilePathByFile:file andUser:app.activeUser]; - serverUrl = [serverUrl stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunicationDownloadFolder] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunicationDownloadFolder] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunicationDownloadFolder] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + serverUrl = [serverUrl stringByRemovingPercentEncoding]; + DLog(@"serverUrl: %@", serverUrl); + [[AppDelegate sharedOCCommunicationDownloadFolder] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunicationDownloadFolder] setUserAgent:[UtilsUrls getUserAgent]]; - DLog(@"serverUrl: %@", serverUrl); - //get local path of server __block NSString *localPath = file.localFolder; if (file.isNecessaryUpdate) { //Change the local name for a temporal one - NSString *tmpUpdateFileName = [NSString stringWithFormat:@"%@-%@", [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]], [file.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *tmpUpdateFileName = [NSString stringWithFormat:@"%@-%@", [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]], [file.fileName stringByRemovingPercentEncoding]]; localPath = [localPath substringToIndex:[localPath length] - file.fileName.length]; localPath = [localPath stringByAppendingString: tmpUpdateFileName]; @@ -89,7 +82,7 @@ - (void) addFileToDownload:(FileDto *) file { } } failureRequest:^(NSURLResponse *response, NSError *error) { DLog(@"Error: %@", error); - DLog(@"error.code: %ld", (long)error.code); + DLog(@"download error.code: %ld", (long)error.code); if (error.code != kCFURLErrorCancelled) { [weakSelf failureDownloadProcess]; diff --git a/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.h b/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.h index f66fd95884..e80c03e44f 100644 --- a/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.h +++ b/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.h @@ -21,8 +21,6 @@ @class IndexedForest; @protocol SyncFolderManagerDelegate - -@optional - (void) releaseSemaphoreToContinueChangingUser; @end diff --git a/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.m b/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.m index be671a4623..40815c11c5 100644 --- a/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.m +++ b/Owncloud iOs Client/Network/Downloads/DownloadFolder/SyncFolderManager.m @@ -149,7 +149,7 @@ - (void) checkFolderByIdKey:(id) idKey { //Add the file to the indexed forest of files downloading //We check if the user is the same that when we started to check - if (currentUser.idUser == app.activeUser.idUser) { + if (currentUser.userId == app.activeUser.userId) { [self.forestOfFilesAndFoldersToBeDownloaded addFileToTheForest:currentFile]; [self downloadTheFile:currentFile andNewEtag:currentFile .etag]; } @@ -174,19 +174,12 @@ - (void) checkFolderByIdKey:(id) idKey { } else { - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - + NSString *path = [UtilsUrls getFullRemoteServerFilePathByFile:currentFolder andUser:app.activeUser]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; DLog(@"PathRquest: %@", path); @@ -397,7 +390,7 @@ - (void) cancelAllDownloads { for (DownloadFileSyncFolder *current in listOfFilesToBeDownloadedCopy) { if (!user) { - user = [ManageUsersDB getUserByIdUser:current.file.userId]; + user = [ManageUsersDB getUserByUserId:current.file.userId]; } current.user = user; diff --git a/Owncloud iOs Client/Network/Downloads/ManageDownloads.m b/Owncloud iOs Client/Network/Downloads/ManageDownloads.m index fa518d2e26..d50128f6a3 100644 --- a/Owncloud iOs Client/Network/Downloads/ManageDownloads.m +++ b/Owncloud iOs Client/Network/Downloads/ManageDownloads.m @@ -83,7 +83,7 @@ - (void)cancelDownloads { for (Download *download in temp) { if (!user) { - user = [ManageUsersDB getUserByIdUser:download.fileDto.userId]; + user = [ManageUsersDB getUserByUserId:download.fileDto.userId]; } download.user = user; [download cancelDownload]; diff --git a/Owncloud iOs Client/Network/Favorites/ManageFavorites.m b/Owncloud iOs Client/Network/Favorites/ManageFavorites.m index 73239f1334..76e48ffb86 100644 --- a/Owncloud iOs Client/Network/Favorites/ManageFavorites.m +++ b/Owncloud iOs Client/Network/Favorites/ManageFavorites.m @@ -138,7 +138,7 @@ - (void) syncFavoritesOfFolder:(FileDto *)folder withUser:(NSInteger)userId { */ - (void) syncFavoritesOfList:(NSArray*)favoritesFilesAndFolders ofThisUser:(NSInteger)userId{ - UserDto *user = [ManageUsersDB getUserByIdUser:userId]; + UserDto *user = [ManageUsersDB getUserByUserId:userId]; //Loop for favorites for (FileDto *file in favoritesFilesAndFolders) { @@ -147,7 +147,7 @@ - (void) syncFavoritesOfList:(NSArray*)favoritesFilesAndFolders ofThisUser:(NSIn NSString *serverPath = [UtilsUrls getFullRemoteServerPathWithWebDav:user]; NSString *path = [NSString stringWithFormat:@"%@%@%@",serverPath, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:file.filePath andUser:user], file.fileName]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; //Check if the file is including in the sync files if (![self isOnAnUpdatingProcessThisFavoriteFile:file]) { @@ -208,8 +208,8 @@ - (void) syncFavoritesOfList:(NSArray*)favoritesFilesAndFolders ofThisUser:(NSIn //Data to download //Get the current local folder AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - NSString *currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)user.idUser, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:updatedFile.filePath andUser:user]]; - currentLocalFolder = [currentLocalFolder stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *currentLocalFolder = [NSString stringWithFormat:@"%@%ld/%@", [UtilsUrls getOwnCloudFilePath],(long)user.userId, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:updatedFile.filePath andUser:user]]; + currentLocalFolder = [currentLocalFolder stringByRemovingPercentEncoding]; Download *download = [Download new]; download.delegate =self; @@ -315,14 +315,7 @@ - (FileDto *)getFileEqualTo:(FileDto*)file{ - (void) thereIsANewVersionAvailableOfThisFile: (FileDto *)favoriteFile { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; @@ -330,7 +323,7 @@ - (void) thereIsANewVersionAvailableOfThisFile: (FileDto *)favoriteFile { NSString *serverPath = [UtilsUrls getFullRemoteServerPathWithWebDav:app.activeUser]; NSString *path = [NSString stringWithFormat:@"%@%@%@",serverPath, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:favoriteFile.filePath andUser:app.activeUser], favoriteFile.fileName]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; [[AppDelegate sharedOCCommunication] readFile:path onCommunication:[AppDelegate sharedOCCommunication] successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) { @@ -476,22 +469,15 @@ - (void)updateOrCancelTheDownload:(id)download{ - (void) downloadSingleFavoriteFileSonOfFavoriteFolder:(FileDto *) file { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; //FileName full path NSString *serverPath = [UtilsUrls getFullRemoteServerPathWithWebDav:app.activeUser]; NSString *path = [NSString stringWithFormat:@"%@%@%@",serverPath, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:file.filePath andUser:app.activeUser], file.fileName]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; [[AppDelegate sharedOCCommunication] readFile:path onCommunication:[AppDelegate sharedOCCommunication] successRequest:^(NSHTTPURLResponse *response, NSArray *items, NSString *redirectedServer) { diff --git a/Owncloud iOs Client/Network/ReadFolder/DetectListOfFiles.swift b/Owncloud iOs Client/Network/ReadFolder/DetectListOfFiles.swift new file mode 100644 index 0000000000..f687645cd7 --- /dev/null +++ b/Owncloud iOs Client/Network/ReadFolder/DetectListOfFiles.swift @@ -0,0 +1,88 @@ +// +// DetectListOfFiles.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 07/07/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + + +import Foundation + +@objc class DetectListOfFiles: NSObject { + + func readFolderOfURL(_ url: NSURL, credentials: OCCredentialsDto, + success: ( @escaping (_ listOfFiles: [Any]) -> Void ), + failure: (@escaping (_ errorHttp: NSInteger?,_ error: NSError?) -> Void) ) { + + + AppDelegate.sharedOCCommunication().setCredentials(credentials) + AppDelegate.sharedOCCommunication().setValueOfUserAgent(UtilsUrls.getUserAgent()) + + AppDelegate.sharedOCCommunication().readFolder(url.absoluteString, withUserSessionToken: credentials.accessToken, on: AppDelegate.sharedOCCommunication(), + + successRequest: { (response: HTTPURLResponse?, items: [Any]?, redirectedServer: String?, token: String? ) in + + if (response != nil) { + print("Operation success response code:\(String(describing: response?.statusCode))") + } + + var isSamlCredentialsError: Bool = false + + if Customization.kIsSsoActive() { + isSamlCredentialsError = FileNameUtils.isURL(withSamlFragment: response) + if isSamlCredentialsError { + + //Fail as credentials error + failure(Int(kOCErrorServerUnauthorized), + UtilsFramework.getErrorWithCode(Int(kOCErrorServerUnauthorized), andCustomMessageFromTheServer: "")! as NSError) + return; + } + } + //TODO: chec redirectedserver in status + + if ( items != nil && !(items!.isEmpty) ) { + success(items!) + } else { + let statusCode: NSInteger = (response?.statusCode == nil) ? 0: (response?.statusCode)! + failure(statusCode, UtilsFramework.getErrorWithCode(Int(kOCErrorServerUnauthorized), andCustomMessageFromTheServer: "")! as NSError) + } + + }, failureRequest: { (response:HTTPURLResponse?, error: Error?, token: String?, redirectedServer: String?) in + + let statusCode: NSInteger = (response?.statusCode == nil) ? 0: (response?.statusCode)! + + failure(statusCode, error! as NSError) + + }) + } + + + func getListOfFiles(url:NSURL, credentials: OCCredentialsDto, withCompletion completion: @escaping (_ errorHttp: NSInteger?,_ error: NSError?, _ listOfFileDtos: [FileDto]? ) -> Void) { + + self.readFolderOfURL(url, credentials: credentials, success: { (_ listOfFiles: [Any]) in + var listOfFileDtos: [FileDto]? = nil + + print("\(String(describing: listOfFiles)) files found in this folder") + + //Pass the listOfFiles with OCFileDto to FileDto Array + listOfFileDtos = UtilsDtos.pass(toFileDtoArrayThisOCFileDtoArray: listOfFiles) as? [FileDto] + + completion(nil, nil, listOfFileDtos) + + }) { (_ errorHttp: NSInteger?,_ error: NSError?) in + + completion(errorHttp, error, nil) + } + + } + +} diff --git a/Owncloud iOs Client/Network/Server Version Checks/CheckCapabilities.m b/Owncloud iOs Client/Network/Server Version Checks/CheckCapabilities.m index c084d29f14..8e026927f5 100644 --- a/Owncloud iOs Client/Network/Server Version Checks/CheckCapabilities.m +++ b/Owncloud iOs Client/Network/Server Version Checks/CheckCapabilities.m @@ -36,17 +36,10 @@ + (void) getServerCapabilitiesOfActiveAccount:(void(^)(OCCapabilities *capabilit if (app.activeUser) { - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - - [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setValueOfUserAgent:[UtilsUrls getUserAgent]]; + [[AppDelegate sharedOCCommunication] getCapabilitiesOfServer:app.activeUser.url onCommunication:[AppDelegate sharedOCCommunication] successRequest:^(NSHTTPURLResponse *response, OCCapabilities *capabilities, NSString *redirectedServer) { BOOL isSamlCredentialsError=NO; @@ -77,12 +70,12 @@ + (void) updateServerCapabilitiesOfActiveAccountInDB:(OCCapabilities *)capabilit AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; - OCCapabilities *capDB = [ManageCapabilitiesDB getCapabilitiesOfUserId: app.activeUser.idUser]; + OCCapabilities *capDB = [ManageCapabilitiesDB getCapabilitiesOfUserId: app.activeUser.userId]; if (capDB == nil) { - [ManageCapabilitiesDB insertCapabilities:capabilities ofUserId: app.activeUser.idUser]; + [ManageCapabilitiesDB insertCapabilities:capabilities ofUserId: app.activeUser.userId]; }else{ - [ManageCapabilitiesDB updateCapabilitiesWith:capabilities ofUserId: app.activeUser.idUser]; + [ManageCapabilitiesDB updateCapabilitiesWith:capabilities ofUserId: app.activeUser.userId]; } } diff --git a/Owncloud iOs Client/Network/Server Version Checks/CheckFeaturesSupported.m b/Owncloud iOs Client/Network/Server Version Checks/CheckFeaturesSupported.m index d2587268de..13323b6aa7 100644 --- a/Owncloud iOs Client/Network/Server Version Checks/CheckFeaturesSupported.m +++ b/Owncloud iOs Client/Network/Server Version Checks/CheckFeaturesSupported.m @@ -60,7 +60,7 @@ + (void) updateServerFeaturesAndCapabilitiesOfActiveUser{ } failure:^(NSError *error) { DLog(@"error getting capabilities from server, we use previous capabilities from DB to update active user"); - app.activeUser.capabilitiesDto = [ManageCapabilitiesDB getCapabilitiesOfUserId:app.activeUser.idUser]; + app.activeUser.capabilitiesDto = [ManageCapabilitiesDB getCapabilitiesOfUserId:app.activeUser.userId]; }]; } }); diff --git a/Owncloud iOs Client/Network/URLSession Subclasses/OCURLSessionManager.m b/Owncloud iOs Client/Network/URLSession Subclasses/OCURLSessionManager.m index 4b92e2f765..20e5c0a4f3 100644 --- a/Owncloud iOs Client/Network/URLSession Subclasses/OCURLSessionManager.m +++ b/Owncloud iOs Client/Network/URLSession Subclasses/OCURLSessionManager.m @@ -32,37 +32,11 @@ - (void)URLSession:(NSURLSession *)session completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler { - DLog(@"willSendRequestForAuthenticationChallenge"); - - BOOL trusted = NO; - SecTrustRef trust; - NSURLProtectionSpace *protectionSpace; - - protectionSpace = [challenge protectionSpace]; - trust = [protectionSpace serverTrust]; - - [[CheckAccessToServer sharedManager] createFolderToSaveCertificates]; - - if(trust != nil) { - [[CheckAccessToServer sharedManager] saveCertificate:trust withName:tmpFileName]; - - NSString *localCertificatesFolder = [UtilsUrls getLocalCertificatesPath]; - - NSMutableArray *listCertificateLocation = [ManageAppSettingsDB getAllCertificatesLocation]; - - for (int i = 0 ; i < [listCertificateLocation count] ; i++) { - - NSString *currentLocalCertLocation = [listCertificateLocation objectAtIndex:i]; - NSFileManager *fileManager = [ NSFileManager defaultManager]; - if([fileManager contentsEqualAtPath:[NSString stringWithFormat:@"%@%@",localCertificatesFolder,tmpFileName] andPath:[NSString stringWithFormat:@"%@",currentLocalCertLocation]]) { - DLog(@"Is the same certificate!!!"); - trusted = YES; - } - } - } else { - trusted = NO; - } + DLog(@"didReceiveChallenge"); + SSLCertificateManager* sslCertificateManager = [SSLCertificateManager new]; + BOOL trusted = [sslCertificateManager isTrustedServerCertificateIn:challenge]; + __block NSURLCredential *credential = nil; credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]; diff --git a/Owncloud iOs Client/Network/Uploads/ManageUploadRequest.m b/Owncloud iOs Client/Network/Uploads/ManageUploadRequest.m index e3cd970e6a..6a4f01dfa6 100644 --- a/Owncloud iOs Client/Network/Uploads/ManageUploadRequest.m +++ b/Owncloud iOs Client/Network/Uploads/ManageUploadRequest.m @@ -66,15 +66,13 @@ - (void)addFileToUpload:(UploadsOfflineDto*) currentUpload { [self updateRecentsTab]; - self.userUploading = [ManageUsersDB getUserByIdUser:_currentUpload.userId]; + self.userUploading = [ManageUsersDB getUserByUserId:_currentUpload.userId]; [self checkIfExistOnserverAndBeginUpload]; } -(void) checkIfExistOnserverAndBeginUpload { - - _userUploading = [ManageUsersDB getUserByIdUser:_currentUpload.userId]; - + if (_currentUpload.isNotNecessaryCheckIfExist) { [self performSelectorInBackground:@selector(startUploadFile) withObject:nil]; } else { @@ -165,18 +163,10 @@ -(void) newFolder:(NSString*) pathRemoteFolder { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - [[AppDelegate sharedOCCommunication] createFolder:pathRemoteFolder onCommunication:[AppDelegate sharedOCCommunication] withForbiddenCharactersSupported:[ManageUsersDB hasTheServerOfTheActiveUserForbiddenCharactersSupport] successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) { @@ -226,30 +216,25 @@ -(void) newFolder:(NSString*) pathRemoteFolder { - (void) startUploadFile { - _isFromBackground = NO; + self.isFromBackground = NO; - DLog(@"self.currentUpload: %@", _currentUpload.uploadFileName); + DLog(@"self.currentUpload: %@", self.currentUpload.uploadFileName); - if (_currentUpload.isNotNecessaryCheckIfExist) { + if (self.currentUpload.isNotNecessaryCheckIfExist) { //Upload ready, continue with next [ManageUploadsDB setStatus:waitingForUpload andKindOfError:notAnError byUploadOffline:self.currentUpload]; - _currentUpload.status=waitingForUpload; + self.currentUpload.status=waitingForUpload; } - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:_userUploading.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:_userUploading.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:_userUploading.username andPassword:_userUploading.password]; - } + self.userUploading = [ManageUsersDB getUserByUserId:self.currentUpload.userId]; + + [[AppDelegate sharedOCCommunication] setCredentials:self.userUploading.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - - NSString *urlClean = [NSString stringWithFormat:@"%@%@", _currentUpload.destinyFolder, _currentUpload.uploadFileName]; - urlClean = [urlClean stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *urlClean = [NSString stringWithFormat:@"%@%@", self.currentUpload.destinyFolder, self.currentUpload.uploadFileName]; + urlClean = [urlClean stringByRemovingPercentEncoding]; __block BOOL firstTime = YES; __weak typeof(self) weakSelf = self; @@ -730,22 +715,17 @@ - (void)updateRecentsTab{ - (void) updateTheEtagOfTheFile: (FileDto *) overwrittenFile { - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:self.userUploading.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:self.userUploading.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:self.userUploading.username andPassword:self.userUploading.password]; - } + self.userUploading = [ManageUsersDB getUserByUserId:self.currentUpload.userId]; + [[AppDelegate sharedOCCommunication] setCredentials:self.userUploading.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; //FileName full path NSString *serverPath = [UtilsUrls getFullRemoteServerPathWithWebDav:self.userUploading]; NSString *path = [NSString stringWithFormat:@"%@%@%@",serverPath, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:overwrittenFile.filePath andUser:self.userUploading], overwrittenFile.fileName]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; __weak typeof(self) weakSelf = self; @@ -809,22 +789,17 @@ - (void) updateTheEtagOfTheFile: (FileDto *) overwrittenFile { - (void) checkTheEtagInTheServerOfTheFile:(FileDto *) overwrittenFile { - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:self.userUploading.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:self.userUploading.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:self.userUploading.username andPassword:self.userUploading.password]; - } + self.userUploading = [ManageUsersDB getUserByUserId:self.userUploading.userId]; + [[AppDelegate sharedOCCommunication] setCredentials:self.userUploading.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; //FileName full path NSString *serverPath = [UtilsUrls getFullRemoteServerPathWithWebDav:self.userUploading]; NSString *path = [NSString stringWithFormat:@"%@%@%@",serverPath, [UtilsUrls getFilePathOnDBByFilePathOnFileDto:overwrittenFile.filePath andUser:self.userUploading], overwrittenFile.fileName]; - path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + path = [path stringByRemovingPercentEncoding]; __weak typeof(self) weakSelf = self; diff --git a/Owncloud iOs Client/Network/Uploads/PrepareFilesToUpload.m b/Owncloud iOs Client/Network/Uploads/PrepareFilesToUpload.m index d60d289839..bf06e8b4a6 100644 --- a/Owncloud iOs Client/Network/Uploads/PrepareFilesToUpload.m +++ b/Owncloud iOs Client/Network/Uploads/PrepareFilesToUpload.m @@ -22,7 +22,6 @@ #import "UserDto.h" #import "constants.h" -#import "EditAccountViewController.h" #import "UtilsDtos.h" #import "ManageUploadsDB.h" #import "FileNameUtils.h" @@ -157,7 +156,7 @@ - (void) uploadAssetFromGallery:(PHAsset *) assetToUpload andRemoteFolder:(NSStr currentUpload.destinyFolder = remoteFolder; currentUpload.uploadFileName = fileName; currentUpload.estimateLength = imageData.length;; - currentUpload.userId = currentUser.idUser; + currentUpload.userId = currentUser.userId; currentUpload.isLastUploadFileOfThisArray = isLastUploadFileOfThisArray; currentUpload.status = waitingAddToUploadList; currentUpload.chunksLength = k_lenght_chunk; @@ -214,7 +213,7 @@ - (void) uploadAssetFromGallery:(PHAsset *) assetToUpload andRemoteFolder:(NSStr currentUpload.destinyFolder = remoteFolder; currentUpload.uploadFileName = fileName; currentUpload.estimateLength = videoData.length;; - currentUpload.userId = currentUser.idUser; + currentUpload.userId = currentUser.userId; currentUpload.isLastUploadFileOfThisArray = isLastUploadFileOfThisArray; currentUpload.status = waitingAddToUploadList; currentUpload.chunksLength = k_lenght_chunk; diff --git a/Owncloud iOs Client/DataBase/DTOs/CredentialsDto.h b/Owncloud iOs Client/Network/UserData/DetectUserData.h similarity index 53% rename from Owncloud iOs Client/DataBase/DTOs/CredentialsDto.h rename to Owncloud iOs Client/Network/UserData/DetectUserData.h index 65011ec705..260d112a7f 100644 --- a/Owncloud iOs Client/DataBase/DTOs/CredentialsDto.h +++ b/Owncloud iOs Client/Network/UserData/DetectUserData.h @@ -1,12 +1,13 @@ // -// CredentialsDto.h +// DetectUserData.h // Owncloud iOs Client // -// Created by Noelia Alvarez on 27/10/14. +// Created by Noelia Alvarez on 18/10/2017. +// // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -15,10 +16,9 @@ #import -@interface CredentialsDto : NSObject - -@property (nonatomic, copy) NSString *userName; -@property (nonatomic, copy) NSString *password; +@interface DetectUserData : NSObject ++ (void) getUserDisplayNameOfServer:(NSString*)path credentials:(OCCredentialsDto *)credentials + withCompletion:(void(^)(NSString *displayName, NSError *error))completion; @end diff --git a/Owncloud iOs Client/Network/UserData/DetectUserData.m b/Owncloud iOs Client/Network/UserData/DetectUserData.m new file mode 100644 index 0000000000..df87747110 --- /dev/null +++ b/Owncloud iOs Client/Network/UserData/DetectUserData.m @@ -0,0 +1,52 @@ +// +// DetectUserData.m +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 18/10/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + +#import "DetectUserData.h" +#import "OCCommunication.h" +#import "UtilsUrls.h" +#import "UtilsFramework.h" +#import "OCErrorMsg.h" +#import "AppDelegate.h" + +@implementation DetectUserData + + ++ (void) getUserDisplayNameOfServer:(NSString*)path credentials:(OCCredentialsDto *)credentials + withCompletion:(void(^)(NSString *displayName, NSError *error))completion { + OCCommunication *sharedCommunication; + + sharedCommunication = [AppDelegate sharedOCCommunication]; + + + [sharedCommunication setCredentials:credentials]; + + [sharedCommunication setValueOfUserAgent:[UtilsUrls getUserAgent]]; + + [sharedCommunication getUserDisplayNameOfServer:path onCommunication:sharedCommunication + success:^(NSHTTPURLResponse *response, NSString *displayName, NSString *redirectedServer) { + if (displayName && ![displayName isEqualToString:@""]) { + completion(displayName, nil); + } else { + completion(nil, [UtilsFramework getErrorWithCode:0 andCustomMessageFromTheServer:NSLocalizedString(@"server_does_not_give_user_id", nil)]); + } + } failure:^(NSHTTPURLResponse *response, NSError *error, NSString *redirectedServer) { + DLog(@"error when try to get server displayName: %@", error); + completion(nil, error); + }]; +} + + +@end diff --git a/Owncloud iOs Client/OCExtensions-Bridging-Header.h b/Owncloud iOs Client/OCExtensions-Bridging-Header.h index ec771e78d5..362f0f6728 100644 --- a/Owncloud iOs Client/OCExtensions-Bridging-Header.h +++ b/Owncloud iOs Client/OCExtensions-Bridging-Header.h @@ -3,7 +3,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -32,3 +32,6 @@ #import "InitializeDatabase.h" #import "ManageTouchID.h" #import "OCErrorMsg.h" +#import "UtilsLogin.h" +#import "OCCredentialsStorage.h" + diff --git a/Owncloud iOs Client/Owncloud iOs Client-Bridging-Header.h b/Owncloud iOs Client/Owncloud iOs Client-Bridging-Header.h index 81350f3b0c..ce123712bc 100644 --- a/Owncloud iOs Client/Owncloud iOs Client-Bridging-Header.h +++ b/Owncloud iOs Client/Owncloud iOs Client-Bridging-Header.h @@ -3,7 +3,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -33,4 +33,23 @@ #import "MBProgressHUD.h" #import "AppDelegate.h" #import "ManageFilesDB.h" +#import "OCErrorMsg.h" +#import "CheckAccessToServer.h" +#import "SSLCertificateManager.h" +#import "Customization.h" +#import "UtilsFramework.h" +#import "OCKeychain.h" +#import "SSOViewController.h" +#import "UtilsLogin.h" +#import "UtilsCookies.h" +#import "CheckFeaturesSupported.h" +#import "InstantUpload.h" +#import "ManageCookiesStorageDB.h" +#import "OCCredentialsStorage.h" +#import "OCFrameworkConstants.h" +#import "OCOAuth2Manager.h" +#import "OCOAuth2Configuration.h" +#import "DetectUserData.h" +#import "UtilsNotifications.h" + diff --git a/Owncloud iOs Client/Owncloud iOs Client-Info.plist b/Owncloud iOs Client/Owncloud iOs Client-Info.plist index 6f8e3116bd..1cc62c444f 100644 --- a/Owncloud iOs Client/Owncloud iOs Client-Info.plist +++ b/Owncloud iOs Client/Owncloud iOs Client-Info.plist @@ -61,7 +61,7 @@ CFBundlePackageType APPL CFBundleShortVersionString - 3.6.2 + 3.7.0 CFBundleSignature ???? CFBundleURLTypes @@ -78,7 +78,7 @@ CFBundleVersion - 1.0 + 1.0.5 ITSAppUsesNonExemptEncryption LSApplicationCategoryType diff --git a/Owncloud iOs Client/Owncloud iOs Client-Prefix.pch b/Owncloud iOs Client/Owncloud iOs Client-Prefix.pch index f99b25506c..aa1f9c8b0c 100644 --- a/Owncloud iOs Client/Owncloud iOs Client-Prefix.pch +++ b/Owncloud iOs Client/Owncloud iOs Client-Prefix.pch @@ -3,7 +3,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -23,6 +23,7 @@ #import #import #import "SystemConstants.h" + #import "OCFrameworkConstants.h" #endif #ifdef DEBUG_MODE diff --git a/Owncloud iOs Client/SupportingFiles/Languages/en.lproj/Localizable.strings b/Owncloud iOs Client/SupportingFiles/Languages/en.lproj/Localizable.strings index fafef60a82..df7c4bc281 100644 Binary files a/Owncloud iOs Client/SupportingFiles/Languages/en.lproj/Localizable.strings and b/Owncloud iOs Client/SupportingFiles/Languages/en.lproj/Localizable.strings differ diff --git a/Owncloud iOs Client/Tabs/FileTab/DeleteFile/DeleteFile.m b/Owncloud iOs Client/Tabs/FileTab/DeleteFile/DeleteFile.m index a7994bb3e3..752c2a0fb0 100644 --- a/Owncloud iOs Client/Tabs/FileTab/DeleteFile/DeleteFile.m +++ b/Owncloud iOs Client/Tabs/FileTab/DeleteFile/DeleteFile.m @@ -264,7 +264,7 @@ - (void) deleteItemFromServerAndDeviceByFileDto:(FileDto *) file { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; NSString *pathToDelete = [UtilsUrls getFullRemoteServerFilePathByFile:file andUser:app.activeUser]; - pathToDelete = [pathToDelete stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + pathToDelete = [pathToDelete stringByRemovingPercentEncoding]; DLog(@"Path for delete: %@", pathToDelete); @@ -279,14 +279,7 @@ - (void) deleteItemFromServerAndDeviceByFileDto:(FileDto *) file { app.isLoadingVisible = YES; } - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; @@ -379,7 +372,7 @@ - (void)removePreviewOniPadIfIsTheSameFile{ //Check if the id file is in the files into this folder DLog(@"path folder: %@", pathFolder); - if ([ManageFilesDB isThisFile:app.detailViewController.file.idFile ofThisUserId:app.activeUser.idUser intoThisFolder:pathFolder]) { + if ([ManageFilesDB isThisFile:app.detailViewController.file.idFile ofThisUserId:app.activeUser.userId intoThisFolder:pathFolder]) { [app.detailViewController unselectCurrentFile]; } } diff --git a/Owncloud iOs Client/Tabs/FileTab/FileListDBOperations.m b/Owncloud iOs Client/Tabs/FileTab/FileListDBOperations.m index 183c03d92f..403e324eb0 100644 --- a/Owncloud iOs Client/Tabs/FileTab/FileListDBOperations.m +++ b/Owncloud iOs Client/Tabs/FileTab/FileListDBOperations.m @@ -18,6 +18,7 @@ #import "ManageFilesDB.h" #import "UserDto.h" +#import "ManageUsersDB.h" @implementation FileListDBOperations @@ -37,7 +38,7 @@ + (void) createAllFoldersByArrayOfFilesDto: (NSArray *) listOfFiles andLocalFold DLog(@"Current folder to create: %@%@",currentFile.filePath, currentFile.fileName); - NSString *currentLocalFileToCreateFolder = [NSString stringWithFormat:@"%@%@",localFolder,[currentFile.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *currentLocalFileToCreateFolder = [NSString stringWithFormat:@"%@%@",localFolder,[currentFile.fileName stringByRemovingPercentEncoding]]; DLog(@"currentLocalFileToCreateFolder: %@", currentLocalFileToCreateFolder); @@ -67,7 +68,7 @@ + (FileDto*)createRootFolderAndGetFileDtoByUser:(UserDto *) user { initialRootFolder.ocId = @""; initialRootFolder.filePath = @""; initialRootFolder.fileName = @""; - initialRootFolder.userId = user.idUser; + initialRootFolder.userId = user.userId; initialRootFolder.isDirectory = YES; initialRootFolder.isDownload = notDownload; initialRootFolder.fileId = -1; @@ -115,7 +116,16 @@ + (void)makeTheRefreshProcessWith:(NSMutableArray*)arrayFromServer inThisFolder: DLog(@"name: %@", currentFolder.fileName); // NSMutableArray *directoryList = [[req getDirectoryList] mutableCopy]; - [ManageFilesDB insertManyFiles:arrayFromServer andFileId:currentFolder.idFile]; + + UserDto *user; +#ifdef CONTAINER_APP + AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; + user = app.activeUser; +#else + user = [ManageUsersDB getActiveUser]; +#endif + + [ManageFilesDB insertManyFiles:arrayFromServer ofFileId:currentFolder.idFile andUser:user]; //Read all backups folders and update on the old files related with the new ids [ManageFilesDB updateRelatedFilesFromBackup]; @@ -139,7 +149,7 @@ + (void) createAFolder: (NSString *)folderName inLocalFolder:(NSString *)localFo DLog(@"Current folder to create: %@", folderName); - NSString *currentLocalFileToCreateFolder = [NSString stringWithFormat:@"%@%@",localFolder,[folderName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *currentLocalFileToCreateFolder = [NSString stringWithFormat:@"%@%@",localFolder,[folderName stringByRemovingPercentEncoding]]; DLog(@"currentLocalFileToCreateFolder: %@", currentLocalFileToCreateFolder); diff --git a/Owncloud iOs Client/Tabs/FileTab/FilesViewController.h b/Owncloud iOs Client/Tabs/FileTab/FilesViewController.h index 07a30b05d8..c64f81e4bd 100644 --- a/Owncloud iOs Client/Tabs/FileTab/FilesViewController.h +++ b/Owncloud iOs Client/Tabs/FileTab/FilesViewController.h @@ -40,13 +40,27 @@ #import "PrepareFilesToUpload.h" #import "RenameFile.h" #import "MoveFile.h" -#import "EditAccountViewController.h" #import "SWTableViewCell.h" #import "OverwriteFileOptions.h" #import "ManageNetworkErrors.h" #import "SelectFolderViewController.h" #import "SelectFolderNavigation.h" #import "ManageFavorites.h" +#import "DetectUserData.h" + +#ifdef CONTAINER_APP +#import "Owncloud_iOs_Client-Swift.h" +#elif FILE_PICKER +#import "ownCloudExtApp-Swift.h" +#elif SHARE_IN +#import "OC_Share_Sheet-Swift.h" +#else +#import "ownCloudExtAppFileProvider-Swift.h" +#endif + + +@class UniversalViewController; +@class ManageAccounts; @interface FilesViewController : UIViewController 0){ @@ -1267,11 +1196,7 @@ - (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker { if (IS_IPHONE){ [self dismissViewControllerAnimated:YES completion:nil]; } else { - if (IS_IOS8 || IS_IOS9) { - [app.detailViewController dismissViewControllerAnimated:YES completion:nil]; - } else { - [app.splitViewController dismissViewControllerAnimated:YES completion:nil]; - } + [app.detailViewController dismissViewControllerAnimated:YES completion:nil]; } app.isUploadViewVisible = NO; @@ -1663,7 +1588,7 @@ -(void)prepareForNavigationWithData:(NSArray *) requestArray { // DLog(@"The directory List have: %d elements", directoryList.count); // DLog(@"Directoy list: %@", directoryList); - [ManageFilesDB insertManyFiles:directoryList andFileId:_selectedFileDto.idFile]; + [ManageFilesDB insertManyFiles:directoryList ofFileId:_selectedFileDto.idFile andUser:app.activeUser]; [self navigateToUrl:_nextRemoteFolder andFileId:_selectedFileDto.idFile]; } @@ -1773,24 +1698,16 @@ - (void) goToFolder:(FileDto *) selectedFile { */ -(void) goToFolderWithoutCheck { - _isLoadingForNavigate = YES; + self.isLoadingForNavigate = YES; AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - - [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - - NSString *path = _nextRemoteFolder; + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - path = [path stringByRemovingPercentEncoding]; + NSString *path = self.nextRemoteFolder; + path = [path stringByRemovingPercentEncoding]; if (!app.userSessionCurrentToken) { app.userSessionCurrentToken = [UtilsFramework getUserSessionToken]; @@ -1990,7 +1907,7 @@ - (void) syncFavoritesByFolder:(FileDto *) folder { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ //Launch the method to sync the favorites files with specific path AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - [[AppDelegate sharedManageFavorites] syncFavoritesOfFolder:folder withUser:app.activeUser.idUser]; + [[AppDelegate sharedManageFavorites] syncFavoritesOfFolder:folder withUser:app.activeUser.userId]; }); @@ -2019,19 +1936,11 @@ - (void)sendRequestToReloadTableView { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - NSString *path = _currentRemoteFolder; - + NSString *path = self.currentRemoteFolder; path = [path stringByRemovingPercentEncoding]; if (!app.userSessionCurrentToken) { @@ -2233,18 +2142,12 @@ - (void) refreshSharedPath{ AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; //Check if the server has share support - if ((app.activeUser.hasShareApiSupport == serverFunctionalitySupported) && (app.activeUser.idUser == _mUser.idUser)) { - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + if ((app.activeUser.hasShareApiSupport == serverFunctionalitySupported) && (app.activeUser.userId == _mUser.userId)) { + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; - + NSString *path = [UtilsUrls getFilePathOnDBByFilePathOnFileDto:_fileIdToShowFiles.filePath andUser:app.activeUser]; path = [path stringByAppendingString:_fileIdToShowFiles.fileName]; path = [path stringByRemovingPercentEncoding]; @@ -2291,7 +2194,7 @@ - (void) refreshSharedPath{ //4. We add the new shared on the share list [ManageSharesDB insertSharedList:items]; //5. Update the files with shared info of this folder - [ManageFilesDB updateFilesAndSetSharedOfUser:app.activeUser.idUser]; + [ManageFilesDB updateFilesAndSetSharedOfUser:app.activeUser.userId]; dispatch_async(dispatch_get_main_queue(), ^{ //Make operations in main thread @@ -2341,11 +2244,7 @@ - (void)showSortingOptions{ AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - if (IS_IOS8 || IS_IOS9) { - [self.sortingActionSheet showInView:app.splitViewController.view]; - } else { - [self.sortingActionSheet showInView:app.detailViewController.view]; - } + [self.sortingActionSheet showInView:app.splitViewController.view]; } } @@ -2779,7 +2678,7 @@ - (void)didSelectMoveOption { //We get the current folder to create the local tree AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - NSString *localRootUrlString = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath], (long)_mUser.idUser]; + NSString *localRootUrlString = [NSString stringWithFormat:@"%@%ld/", [UtilsUrls getOwnCloudFilePath], (long)_mUser.userId]; self.selectFolderViewController.currentLocalFolder = localRootUrlString; self.selectFolderNavigation.delegate=self; @@ -2821,19 +2720,11 @@ - (void) didSelectDownloadFolder { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; NSString *path = _nextRemoteFolder; - path = [path stringByRemovingPercentEncoding]; if (!app.userSessionCurrentToken) { @@ -3194,14 +3085,7 @@ - (void) downloadTheFile { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; @@ -3209,6 +3093,7 @@ - (void) downloadTheFile { app.userSessionCurrentToken = [UtilsFramework getUserSessionToken]; } + //TODO:check this rootFolder URL, it should be using utilsURL : getFullRemoteServerPathWithWebDav NSString *rootFolder =[NSString stringWithFormat:@"%@%@",app.activeUser.url,k_url_webdav_server]; [[AppDelegate sharedOCCommunication] checkServer:rootFolder onCommunication:[AppDelegate sharedOCCommunication] successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) { @@ -3430,29 +3315,28 @@ - (void) showEditAccount { AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - //Edit Account + UniversalLoginViewController *loginViewController = nil; + BOOL requiredUpdateUrl = [UtilsUrls isNecessaryUpdateToPredefinedUrlByPreviousUrl:[ManageUsersDB getActiveUser].predefinedUrl]; - if (requiredUpdateUrl) { - self.resolvedCredentialError = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:app.activeUser andLoginMode:LoginModeMigrate]; - } else { - self.resolvedCredentialError = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:app.activeUser andLoginMode:LoginModeExpire]; - } + + LoginMode loginMode = (requiredUpdateUrl) ? LoginModeMigrate : LoginModeExpire; + loginViewController = [UtilsLogin getLoginVCWithMode:loginMode andUser:app.activeUser]; if (IS_IPHONE) { - OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:_resolvedCredentialError]; + OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:loginViewController]; [self.navigationController presentViewController:navController animated:YES completion:nil]; } else { OCNavigationController *navController = nil; - navController = [[OCNavigationController alloc] initWithRootViewController:_resolvedCredentialError]; + navController = [[OCNavigationController alloc] initWithRootViewController:loginViewController]; navController.modalPresentationStyle = UIModalPresentationFormSheet; [app.splitViewController presentViewController:navController animated:YES completion:nil]; } } #pragma mark - CheckAccessToServer --(void)connectionToTheServer:(BOOL)isConnection { - if(isConnection) { +-(void)connectionToTheServerWasChecked:(BOOL)isConnected withHttpStatusCode:(NSInteger)statusCode andError:(NSError *)error { + if(isConnected) { DLog(@"Ok, we have connection to the server"); } else { //Error msg @@ -3468,7 +3352,7 @@ -(void)repeatTheCheckToTheServer { [[CheckAccessToServer sharedManager]isConnectionToTheServerByUrl:APP_DELEGATE.activeUser.url]; } --(void)badCertificateNoAcceptedByUser { +-(void)badCertificateNotAcceptedByUser { DLog(@"Certificate refushed by user"); } @@ -3683,11 +3567,7 @@ - (void) didSelectMoreOptions { [self.moreActionSheet showInView:self.tabBarController.view]; }else { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - if (IS_IOS8 || IS_IOS9) { - [self.moreActionSheet showInView:app.splitViewController.view]; - } else { - [self.moreActionSheet showInView:app.detailViewController.view]; - } + [self.moreActionSheet showInView:app.splitViewController.view]; } } else { @@ -3720,11 +3600,7 @@ - (void) didSelectMoreOptions { [self.moreActionSheet showInView:self.tabBarController.view]; }else { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - if (IS_IOS8 || IS_IOS9) { - [self.moreActionSheet showInView:app.splitViewController.view]; - } else { - [self.moreActionSheet showInView:app.detailViewController.view]; - } + [self.moreActionSheet showInView:app.splitViewController.view]; } } } diff --git a/Owncloud iOs Client/Tabs/FileTab/ManageFiles.swift b/Owncloud iOs Client/Tabs/FileTab/ManageFiles.swift new file mode 100644 index 0000000000..1035239e44 --- /dev/null +++ b/Owncloud iOs Client/Tabs/FileTab/ManageFiles.swift @@ -0,0 +1,38 @@ +// +// ManageFiles.swift +// Owncloud iOs Client +// +// Created by Noelia Alvarez on 13/07/2017. +// +// + +/* + Copyright (C) 2017, ownCloud GmbH. + This code is covered by the GNU Public License Version 3. + For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ + You should have received a copy of this license + along with this program. If not, see . + */ + + +import Foundation + +@objc class ManageFiles: NSObject { + + + + func storeListOfFiles(_ listOfFiles: [FileDto] , forFileId fileId: Int, andUser user: UserDto) { + + //Change the filePath from the library to our db format + + for currentFile:FileDto in listOfFiles { + + currentFile.filePath = UtilsUrls.getFilePathOnDBByFilePath(onFileDto: currentFile.filePath, andUser:user) + } + + + ManageFilesDB.insertManyFiles(listOfFiles as! NSMutableArray, ofFileId: fileId, andUser: user) + + } + +} diff --git a/Owncloud iOs Client/Tabs/FileTab/MoveFile/MoveFile.m b/Owncloud iOs Client/Tabs/FileTab/MoveFile/MoveFile.m index 6ae3f4dcd5..5b422b7663 100644 --- a/Owncloud iOs Client/Tabs/FileTab/MoveFile/MoveFile.m +++ b/Owncloud iOs Client/Tabs/FileTab/MoveFile/MoveFile.m @@ -121,8 +121,8 @@ -(void)moveItem { NSString *destinyFile = [NSString stringWithFormat:@"%@%@",self.destinationFolder, self.destinyFilename]; //We remove the URL Encoding - originFile = [originFile stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - destinyFile = [destinyFile stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + originFile = [originFile stringByRemovingPercentEncoding]; + destinyFile = [destinyFile stringByRemovingPercentEncoding]; //In iPad set the global variable if (!IS_IPHONE) { @@ -130,14 +130,7 @@ -(void)moveItem { app.isLoadingVisible = YES; } - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; @@ -455,11 +448,11 @@ - (NSString *)getDestinyLocalFolder { //Delete files os user in the system AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - //NSString *newLocalFolder= [[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", currentUser.idUser]]; - NSString *newLocalFolder= [[UtilsUrls getOwnCloudFilePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld", (long)app.activeUser.idUser]]; + //NSString *newLocalFolder= [[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d", userId]]; + NSString *newLocalFolder= [[UtilsUrls getOwnCloudFilePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"%ld", (long)app.activeUser.userId]]; NSString *newStr = [UtilsUrls getFilePathOnDBByFullPath:self.destinationFolder andUser:app.activeUser]; - newLocalFolder = [NSString stringWithFormat:@"%@/%@%@", newLocalFolder,[newStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding],[_destinyFilename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + newLocalFolder = [NSString stringWithFormat:@"%@/%@%@", newLocalFolder,[newStr stringByRemovingPercentEncoding],[_destinyFilename stringByRemovingPercentEncoding]]; return newLocalFolder; } diff --git a/Owncloud iOs Client/Tabs/FileTab/RenameFile/RenameFile.m b/Owncloud iOs Client/Tabs/FileTab/RenameFile/RenameFile.m index 91c81346e9..ab3d9e4117 100644 --- a/Owncloud iOs Client/Tabs/FileTab/RenameFile/RenameFile.m +++ b/Owncloud iOs Client/Tabs/FileTab/RenameFile/RenameFile.m @@ -67,10 +67,10 @@ - (void)showRenameFile: (FileDto *) file { if(self.selectedFileDto.isDirectory) { if ( [self.selectedFileDto.fileName length] > 0) { - [_renameAlertView textFieldAtIndex:0].text = [[self.selectedFileDto.fileName substringToIndex:[self.selectedFileDto.fileName length] - 1]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [_renameAlertView textFieldAtIndex:0].text = [[self.selectedFileDto.fileName substringToIndex:[self.selectedFileDto.fileName length] - 1]stringByRemovingPercentEncoding]; } } else { - [_renameAlertView textFieldAtIndex:0].text = [self.selectedFileDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [_renameAlertView textFieldAtIndex:0].text = [self.selectedFileDto.fileName stringByRemovingPercentEncoding]; } [_renameAlertView show]; @@ -243,8 +243,8 @@ -(void) renameFile { NSString *newURLString = [NSString stringWithFormat:@"%@%@", [UtilsUrls getFullRemoteServerPathWithWebDav:app.activeUser], self.destinationFile]; NSString *originalURLString = [UtilsUrls getFullRemoteServerFilePathByFile:self.selectedFileDto andUser:app.activeUser]; - originalURLString = [originalURLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; - newURLString = [newURLString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + originalURLString = [originalURLString stringByRemovingPercentEncoding]; + newURLString = [newURLString stringByRemovingPercentEncoding]; if ([originalURLString hasSuffix:@"/"]) { originalURLString = [originalURLString substringToIndex:[originalURLString length] - 1]; @@ -255,15 +255,8 @@ -(void) renameFile { DLog(@"After checking the original and destiny path Move request"); - //Set the right credentials - if (k_is_sso_active) { - [[AppDelegate sharedOCCommunication] setCredentialsWithCookie:app.activeUser.password]; - } else if (k_is_oauth_active) { - [[AppDelegate sharedOCCommunication] setCredentialsOauthWithToken:app.activeUser.password]; - } else { - [[AppDelegate sharedOCCommunication] setCredentialsWithUser:app.activeUser.username andPassword:app.activeUser.password]; - } - + [[AppDelegate sharedOCCommunication] setCredentials:app.activeUser.credDto]; + [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; [[AppDelegate sharedOCCommunication] moveFileOrFolder:originalURLString toDestiny:newURLString onCommunication:[AppDelegate sharedOCCommunication] withForbiddenCharactersSupported:[ManageUsersDB hasTheServerOfTheActiveUserForbiddenCharactersSupport] successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) { @@ -431,9 +424,9 @@ -(void) moveTheFileOrFolderOnTheDBAndFileSystem { NSError *error; - NSString *localUrl = [NSString stringWithFormat:@"%@%@", self.currentLocalFolder, [originalName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *localUrl = [NSString stringWithFormat:@"%@%@", self.currentLocalFolder, [originalName stringByRemovingPercentEncoding]]; - NSString *newFile = [NSString stringWithFormat:@"%@%@", self.currentLocalFolder, [self.mNewName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *newFile = [NSString stringWithFormat:@"%@%@", self.currentLocalFolder, [self.mNewName stringByRemovingPercentEncoding]]; NSString *documentPath= [UtilsUrls getOwnCloudFilePath]; @@ -472,7 +465,7 @@ -(void) moveTheFileOrFolderOnTheDBAndFileSystem { // Create file manager NSFileManager *fileMgr = [[NSFileManager alloc] init]; - NSString *fileNameWithoutPercents = [self.selectedFileDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + NSString *fileNameWithoutPercents = [self.selectedFileDto.fileName stringByRemovingPercentEncoding]; DLog(@"FileName: %@", fileNameWithoutPercents); DLog(@"Delete: %@", self.selectedFileDto.localFolder); @@ -504,13 +497,13 @@ -(void) moveTheFileOrFolderOnTheDBAndFileSystem { if (!IS_IPHONE) { if (app.detailViewController.file.idFile == _selectedFileDto.idFile) { app.detailViewController.file = [ManageFilesDB getFileDtoByFileName:[_mNewName encodeString:NSUTF8StringEncoding] andFilePath:[UtilsUrls getFilePathOnDBByFilePathOnFileDto:_selectedFileDto.filePath andUser:app.activeUser] andUser:app.activeUser]; - app.detailViewController.titleLabel.text = [app.detailViewController.file.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + app.detailViewController.titleLabel.text = [app.detailViewController.file.fileName stringByRemovingPercentEncoding]; } } //To update the audio player - NSString *oldPath = [NSString stringWithFormat:@"%@%@",_currentLocalFolder, [self.selectedFileDto.fileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; + NSString *oldPath = [NSString stringWithFormat:@"%@%@",_currentLocalFolder, [self.selectedFileDto.fileName stringByRemovingPercentEncoding]]; if ([app isMediaPlayerRunningWithThisFilePath: oldPath]) { NSString *pathOfNewFile = [NSString stringWithFormat:@"%@%@",_currentLocalFolder, _mNewName]; diff --git a/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.h b/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.h index 0e7e4cc519..c1549b1d61 100644 --- a/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.h +++ b/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.h @@ -22,7 +22,7 @@ #import "SimpleFileListTableViewController.h" -@interface SelectFolderViewController : SimpleFileListTableViewController { +@interface SelectFolderViewController : SimpleFileListTableViewController { __weak id parent; } diff --git a/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.m b/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.m index f80834d01a..b4f9fd1937 100644 --- a/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.m +++ b/Owncloud iOs Client/Tabs/FileTab/SelectFolder/SelectFolderViewController.m @@ -36,7 +36,6 @@ #import "FileListDBOperations.h" #import "UtilsDtos.h" #import "ManageFilesDB.h" -#import "EditAccountViewController.h" #import "DetailViewController.h" #import "OCNavigationController.h" #import "OCCommunication.h" @@ -311,7 +310,7 @@ - (IBAction)showCreateFolder{ -(BOOL)checkForSameName:(NSString *)string { string = [string stringByAppendingString:@"/"]; - string = [string stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]; + string = [string stringByRemovingPercentEncoding]; DLog(@"string: %@",string); NSString *dicName; FileDto *fileDto=nil; @@ -321,7 +320,7 @@ -(BOOL)checkForSameName:(NSString *)string fileDto = [self.currentDirectoryArray objectAtIndex:i]; //DLog(@"%@", fileDto.fileName); - dicName=[fileDto.fileName stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]; + dicName=[fileDto.fileName stringByRemovingPercentEncoding]; if([string isEqualToString:dicName]) { @@ -342,33 +341,25 @@ -(void) newFolderSaveClicked:(NSString*)name { //Check if exist a folder with the same name if ([self checkForSameName:name] == NO) { - OCCommunication *communication = nil; + OCCommunication *sharedCommunication = nil; #ifdef SHARE_IN - communication = Managers.sharedOCCommunication; + sharedCommunication = Managers.sharedOCCommunication; [[Managers sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; #else - communication = [AppDelegate sharedOCCommunication]; + sharedCommunication = [AppDelegate sharedOCCommunication]; [[AppDelegate sharedOCCommunication] setUserAgent:[UtilsUrls getUserAgent]]; #endif NSString *remotePath = [UtilsUrls getFullRemoteServerFilePathByFile:self.currentFolder andUser:self.user]; NSString *newURL = [NSString stringWithFormat:@"%@%@",remotePath,[name encodeString:NSUTF8StringEncoding]]; - NSString *rootPath = [UtilsUrls getFilePathOnDBByFullPath:newURL andUser:self.user]; - //Set the right credentials - if (k_is_sso_active) { - [communication setCredentialsWithCookie:self.user.password]; - } else if (k_is_oauth_active) { - [communication setCredentialsOauthWithToken:self.user.password]; - } else { - [communication setCredentialsWithUser:self.user.username andPassword:self.user.password]; - } - - NSString *pathOfNewFolder = [newURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + [sharedCommunication setCredentials:self.user.credDto]; + + NSString *pathOfNewFolder = [newURL stringByRemovingPercentEncoding]; - [communication createFolder:pathOfNewFolder onCommunication:communication withForbiddenCharactersSupported:[ManageUsersDB hasTheServerOfTheActiveUserForbiddenCharactersSupport] successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) { + [sharedCommunication createFolder:pathOfNewFolder onCommunication:sharedCommunication withForbiddenCharactersSupported:[ManageUsersDB hasTheServerOfTheActiveUserForbiddenCharactersSupport] successRequest:^(NSHTTPURLResponse *response, NSString *redirectedServer) { DLog(@"Folder created"); BOOL isSamlCredentialsError=NO; @@ -560,7 +551,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N fileCell.labelTitle.font = fileFont; //Is directory - NSString *folderName = [file.fileName stringByReplacingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; + NSString *folderName = [file.fileName stringByRemovingPercentEncoding]; //Quit the last character folderName = [folderName substringToIndex:[folderName length]-1]; diff --git a/Owncloud iOs Client/Tabs/FileTab/Share/Cells/SharePrivilegeCell.swift b/Owncloud iOs Client/Tabs/FileTab/Share/Cells/SharePrivilegeCell.swift index b140342d21..c155358b90 100644 --- a/Owncloud iOs Client/Tabs/FileTab/Share/Cells/SharePrivilegeCell.swift +++ b/Owncloud iOs Client/Tabs/FileTab/Share/Cells/SharePrivilegeCell.swift @@ -16,7 +16,7 @@ along with this program. If not, see . */ +#import #import #import "MBProgressHUD.h" #import "CheckAccessToServer.h" #import "ManageNetworkErrors.h" -#import "EditAccountViewController.h" +#import "UtilsLogin.h" + @class UserDto; @class FileDto; - @class SimpleFileListTableViewController; @interface SimpleFileListTableViewController : UIViewController @@ -113,7 +114,7 @@ //Next List of files to navigate @property (nonatomic, strong) SimpleFileListTableViewController *simpleFilesViewController; -@property (nonatomic, strong) EditAccountViewController *resolveCredentialErrorViewController; +@property (nonatomic, strong) UniversalLoginViewController *resolveCredentialErrorViewController; //View for loading screen @property(nonatomic, strong) MBProgressHUD *HUD; diff --git a/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.m b/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.m index b384abd8c1..b29c3bfcd6 100644 --- a/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.m +++ b/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.m @@ -14,6 +14,8 @@ along with this program. If not, see . */ +#import +#import #import "SimpleFileListTableViewController.h" #import "ManageUsersDB.h" #import "ManageFilesDB.h" @@ -36,14 +38,20 @@ #ifdef CONTAINER_APP #import "AppDelegate.h" -#import "EditAccountViewController.h" #import "OCNavigationController.h" +#import "Owncloud_iOs_Client-Swift.h" +#elif FILE_PICKER +#import "DocumentPickerViewController.h" +#import "ownCloudExtApp-Swift.h" #elif SHARE_IN #import "OC_Share_Sheet-Swift.h" #else #import "DocumentPickerViewController.h" +#import "ownCloudExtAppFileProvider-Swift.h" #endif +@class UniversalLoginViewController; + @interface SimpleFileListTableViewController () @end @@ -367,14 +375,7 @@ - (void) loadRemote:(FileDto *) file andNavigateIfIsNecessary:(BOOL) isNecessary sharedCommunication = [DocumentPickerViewController sharedOCCommunication]; #endif - //Set the right credentials - if (k_is_sso_active) { - [sharedCommunication setCredentialsWithCookie:self.user.password]; - } else if (k_is_oauth_active) { - [sharedCommunication setCredentialsOauthWithToken:self.user.password]; - } else { - [sharedCommunication setCredentialsWithUser:self.user.username andPassword:self.user.password]; - } + [sharedCommunication setCredentials:self.user.credDto]; [sharedCommunication setUserAgent:[UtilsUrls getUserAgent]]; @@ -553,11 +554,8 @@ - (void)showError:(NSString *) message { }]; [alert addAction:ok]; - if ([self.navigationController isViewLoaded] && self.navigationController.view.window && self.resolveCredentialErrorViewController != nil) { - [self.resolveCredentialErrorViewController presentViewController:alert animated:YES completion:nil]; - } else { - [self presentViewController:alert animated:YES completion:nil]; - } + [self presentViewController:alert animated:YES completion:nil]; + }); } @@ -566,8 +564,8 @@ - (void) showEditAccount { #ifdef CONTAINER_APP //Edit Account - self.resolveCredentialErrorViewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:[ManageUsersDB getActiveUser] andLoginMode:LoginModeExpire]; - + self.resolveCredentialErrorViewController = [UtilsLogin getLoginVCWithMode:LoginModeExpire andUser: self.user]; + if (IS_IPHONE) { OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:self.resolveCredentialErrorViewController]; [self.navigationController presentViewController:navController animated:YES completion:nil]; @@ -664,16 +662,7 @@ - (void) reloadFolderByEtag { #endif if (!self.isRefreshInProgress) { - //Set the right credentials - if (k_is_sso_active) { - [sharedCommunication setCredentialsWithCookie:self.user.password]; - } else if (k_is_oauth_active) { - [sharedCommunication setCredentialsOauthWithToken:self.user.password]; - } else { - [sharedCommunication setCredentialsWithUser:self.user.username andPassword:self.user.password]; - } - - [sharedCommunication setUserAgent:[UtilsUrls getUserAgent]]; + [sharedCommunication setCredentials:self.user.credDto]; NSString *remotePath = [UtilsUrls getFullRemoteServerFilePathByFile:self.currentFolder andUser:self.user]; remotePath = [remotePath stringByRemovingPercentEncoding]; @@ -729,7 +718,7 @@ - (void) reloadFolderByEtag { #pragma mark - CheckAccessToServerDelegate --(void)connectionToTheServer:(BOOL)isConnection { +-(void)connectionToTheServerWasChecked:(BOOL)isConnected withHttpStatusCode:(NSInteger)statusCode andError:(NSError *)error { } @@ -740,7 +729,7 @@ -(void)repeatTheCheckToTheServer { [[CheckAccessToServer sharedManager] isConnectionToTheServerByUrl:self.user.url]; } --(void)badCertificateNoAcceptedByUser { +-(void)badCertificateNotAcceptedByUser { DLog(@"Certificate refushed by user"); } diff --git a/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.xib b/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.xib index 17aecd2000..5382db9d4b 100644 --- a/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.xib +++ b/Owncloud iOs Client/Tabs/FileTab/SimpleFileList/SimpleFileListTableViewController.xib @@ -1,7 +1,11 @@ - - + + + + + - + + @@ -12,19 +16,19 @@ - + - - + + - + diff --git a/Owncloud iOs Client/Tabs/RecentTab/RecentViewController.m b/Owncloud iOs Client/Tabs/RecentTab/RecentViewController.m index 02b88d780b..112cd3b437 100644 --- a/Owncloud iOs Client/Tabs/RecentTab/RecentViewController.m +++ b/Owncloud iOs Client/Tabs/RecentTab/RecentViewController.m @@ -22,7 +22,6 @@ #import "UIColor+Constants.h" #import "NSString+Encoding.h" #import "constants.h" -#import "EditAccountViewController.h" #import "ManageUsersDB.h" #import "ManageUploadsDB.h" #import "ManageFilesDB.h" @@ -298,7 +297,7 @@ - (void)updateRecents{ if ([[uploadsOfflineDict allKeys] containsObject:[NSNumber numberWithInteger:currentManageUploadRequest.currentUpload.idUploadsOffline]]) { //Update the upload offline data currentManageUploadRequest.currentUpload = [uploadsOfflineDict objectForKey:[NSNumber numberWithInteger:currentManageUploadRequest.currentUpload.idUploadsOffline]]; - currentManageUploadRequest.userUploading = [ManageUsersDB getUserByIdUser:currentManageUploadRequest.currentUpload.userId]; + currentManageUploadRequest.userUploading = [ManageUsersDB getUserByUserId:currentManageUploadRequest.currentUpload.userId]; } //Depends of kind of error we assings the upload to appropiate array @@ -489,7 +488,7 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N uploadCell.cancelButton.tag=indexPath.row; [uploadCell.cancelButton addTarget:self action:@selector(cancelUploadTapped:) forControlEvents:UIControlEventTouchUpInside]; - uploadCell.labelTitle.text=[currentManageUploadRequest.currentUpload.uploadFileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + uploadCell.labelTitle.text=[currentManageUploadRequest.currentUpload.uploadFileName stringByRemovingPercentEncoding]; uploadCell.progressView.progress=currentManageUploadRequest.transferProgress; currentManageUploadRequest.progressTag=uploadCell.progressView.tag; @@ -623,12 +622,12 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N NSString *lengthAndError = [NSString stringWithFormat:@"%@, %@", length, msgError]; - failedCell.labelTitle.text=[currentManageUploadRequest.currentUpload.uploadFileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + failedCell.labelTitle.text=[currentManageUploadRequest.currentUpload.uploadFileName stringByRemovingPercentEncoding]; failedCell.labelLengthAndError.text=lengthAndError; - failedCell.labelUserName.text=[UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUsername:currentManageUploadRequest.userUploading]; + failedCell.labelUserName.text=[UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:currentManageUploadRequest.userUploading]; //If there are SAML replacind the percents escapes with UTF8 coding if (k_is_sso_active) { - failedCell.labelUserName.text = [failedCell.labelUserName.text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + failedCell.labelUserName.text = [failedCell.labelUserName.text stringByRemovingPercentEncoding]; } failedCell.labelPath.text=currentManageUploadRequest.pathOfUpload; @@ -677,13 +676,14 @@ - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N NSString *labelLengthAndDateString = [NSString stringWithFormat:@"%@, %@", length, timeAgo]; - uploadRecentCell.labelTitle.text=[currentManageUploadRequest.currentUpload.uploadFileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + uploadRecentCell.labelTitle.text=[currentManageUploadRequest.currentUpload.uploadFileName stringByRemovingPercentEncoding]; uploadRecentCell.labelLengthAndDate.text=labelLengthAndDateString; uploadRecentCell.labelPath.text=currentManageUploadRequest.pathOfUpload; - uploadRecentCell.labelUserName.text=[NSString stringWithFormat:@"%@@%@", currentManageUploadRequest.userUploading.username, [UtilsUrls getUrlServerWithoutHttpOrHttps:currentManageUploadRequest.userUploading.url]]; + uploadRecentCell.labelUserName.text = [UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:currentManageUploadRequest.userUploading]; + //If there are SAML replacind the percents escapes with UTF8 coding if (k_is_sso_active) { - uploadRecentCell.labelUserName.text = [uploadRecentCell.labelUserName.text stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + uploadRecentCell.labelUserName.text = [uploadRecentCell.labelUserName.text stringByRemovingPercentEncoding]; } } else { @@ -850,11 +850,11 @@ - (void) resolveFolderNotFoundError:(UploadsOfflineDto *) selectedUpload { AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - DLog(@"user: %ld", (long)app.activeUser.idUser); + DLog(@"user: %ld", (long)app.activeUser.userId); DLog(@"user: %ld", (long)selectedUpload.userId); - if(selectedUpload.userId == app.activeUser.idUser){ + if(selectedUpload.userId == app.activeUser.userId){ _selectedUploadToResolveTheConflict=selectedUpload; SelectFolderViewController *sf = [[SelectFolderViewController alloc] initWithNibName:@"SelectFolderViewController" onFolder:[ManageFilesDB getRootFileDtoByUser:app.activeUser]]; @@ -881,13 +881,13 @@ - (void) resolveFolderNotFoundError:(UploadsOfflineDto *) selectedUpload { } } else { - UserDto *userSelected = [ManageUsersDB getUserByIdUser:selectedUpload.userId]; - NSString *userName = userSelected.username; + UserDto *userSelected = [ManageUsersDB getUserByUserId:selectedUpload.userId]; + NSString *userDisplayAccountName = [UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:userSelected]; //if SAML is enabled replace the percent of the samlusername by utf8 if (k_is_sso_active) { - userName= [userName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + userDisplayAccountName = [userDisplayAccountName stringByRemovingPercentEncoding]; } - NSString* temp=[NSString stringWithFormat:@"%@ %@@%@", NSLocalizedString(@"change_active_user", nil), userName, [UtilsUrls getUrlServerWithoutHttpOrHttps:userSelected.url]]; + NSString* temp=[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"change_active_user", nil), userDisplayAccountName]; UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:temp delegate:nil @@ -905,7 +905,7 @@ - (void) resolveFolderNotFoundError:(UploadsOfflineDto *) selectedUpload { /** * This method is called when the user tap to resolve a error in a file and * the error is an "credential error" - * This method prepare and show the EditAccount Screen + * This method prepare and show the Login View in Edit Mode * * @param selectedUpload -> UploadsOfflineDto of the selected file by the user * @@ -916,15 +916,15 @@ - (void) resolveCredentialError:(UploadsOfflineDto *) selectedUpload { _selectedUploadToResolveTheConflict=selectedUpload; AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; //Get the update of the user - UserDto *userSelected = [ManageUsersDB getUserByIdUser:selectedUpload.userId]; + UserDto *userSelected = [ManageUsersDB getUserByUserId:selectedUpload.userId]; - if (selectedUpload.userId != (app.activeUser.idUser)) { - NSString *userName = userSelected.username; + if (selectedUpload.userId != (app.activeUser.userId)) { + NSString *userDisplayAccountName = [UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:userSelected]; //if SAML is enabled replace the percent of the samlusername by utf8 if (k_is_sso_active) { - userName= [userName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + userDisplayAccountName= [userDisplayAccountName stringByRemovingPercentEncoding]; } - NSString* temp=[NSString stringWithFormat:@"%@ %@@%@", NSLocalizedString(@"change_active_user", nil), userName, [UtilsUrls getUrlServerWithoutHttpOrHttps:userSelected.url]]; + NSString* temp=[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"change_active_user", nil),userDisplayAccountName]; UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:temp delegate:nil @@ -932,11 +932,11 @@ - (void) resolveCredentialError:(UploadsOfflineDto *) selectedUpload { otherButtonTitles:NSLocalizedString(@"ok",nil), nil]; [alertView show]; } else { - //Show the Edit Account Screen - EditAccountViewController *viewController = [[EditAccountViewController alloc]initWithNibName:@"EditAccountViewController_iPhone" bundle:nil andUser:userSelected andLoginMode:LoginModeExpire]; + //Show the Login View in Edit Mode + + UniversalLoginViewController *viewController = [UtilsLogin getLoginVCWithMode:LoginModeExpire andUser:app.activeUser]; if (IS_IPHONE) { - viewController.hidesBottomBarWhenPushed = YES; OCNavigationController *navController = [[OCNavigationController alloc] initWithRootViewController:viewController]; [self.navigationController presentViewController:navController animated:YES completion:nil]; } else { @@ -973,12 +973,12 @@ - (void) resolveFileExistError:(UploadsOfflineDto *) selectedUpload { AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - if(selectedUpload.userId == app.activeUser.idUser){ + if(selectedUpload.userId == app.activeUser.userId){ _selectedUploadToResolveTheConflict = selectedUpload; FileDto *file = [[FileDto alloc] init]; - file.fileName = [_selectedUploadToResolveTheConflict.uploadFileName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + file.fileName = [_selectedUploadToResolveTheConflict.uploadFileName stringByRemovingPercentEncoding]; file.isDirectory = NO; if (!self.overWritteOption) { @@ -995,14 +995,14 @@ - (void) resolveFileExistError:(UploadsOfflineDto *) selectedUpload { [_overWritteOption showOverWriteOptionActionSheet]; } else { - UserDto *userSelected = [ManageUsersDB getUserByIdUser:selectedUpload.userId]; - NSString *userName=userSelected.username; + UserDto *userSelected = [ManageUsersDB getUserByUserId:selectedUpload.userId]; + NSString *userDisplayAccountName = [UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:userSelected]; //if SAML is enabled replace the percent of the samlusername by utf8 if (k_is_sso_active) { - userName= [userName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + userDisplayAccountName= [userDisplayAccountName stringByRemovingPercentEncoding]; } - NSString* temp=[NSString stringWithFormat:@"%@ %@@%@", NSLocalizedString(@"change_active_user", nil), userName, [UtilsUrls getUrlServerWithoutHttpOrHttps:userSelected.url]]; + NSString* temp=[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"change_active_user", nil), userDisplayAccountName]; UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:temp delegate:nil @@ -1026,22 +1026,22 @@ - (void) resolveNotHavePermission:(UploadsOfflineDto *) selectedUpload { AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - DLog(@"user: %ld", (long)app.activeUser.idUser); + DLog(@"user: %ld", (long)app.activeUser.userId); DLog(@"user: %ld", (long)selectedUpload.userId); - if(selectedUpload.userId == app.activeUser.idUser){ + if(selectedUpload.userId == app.activeUser.userId){ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error_permission_alert_message", nil) message:@"" delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", nil) otherButtonTitles:NSLocalizedString(@"choose_folder", nil), nil]; [alertView show]; }else{ - UserDto *userSelected = [ManageUsersDB getUserByIdUser:selectedUpload.userId]; - NSString *userName = userSelected.username; + UserDto *userSelected = [ManageUsersDB getUserByUserId:selectedUpload.userId]; + NSString *userDisplayAccountName = [UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:userSelected]; //if SAML is enabled replace the percent of the samlusername by utf8 if (k_is_sso_active) { - userName= [userName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + userDisplayAccountName= [userDisplayAccountName stringByRemovingPercentEncoding]; } - NSString* temp=[NSString stringWithFormat:@"%@ %@@%@", NSLocalizedString(@"change_active_user", nil), userName, [UtilsUrls getUrlServerWithoutHttpOrHttps:userSelected.url]]; + NSString* temp=[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"change_active_user", nil), userDisplayAccountName]; UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:temp delegate:nil @@ -1066,16 +1066,16 @@ - (void) resolveNotHavePermission:(UploadsOfflineDto *) selectedUpload { - (void) resolveInsufficientStorage:(UploadsOfflineDto *) selectedUpload { AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - if(selectedUpload.userId == app.activeUser.idUser){ + if(selectedUpload.userId == app.activeUser.userId){ [ManageUploadsDB updateErrorOfAllUploadsOfUser:selectedUpload.userId withCurrentError:errorInsufficientStorage toNewError:notAnError]; } else { - UserDto *userSelected = [ManageUsersDB getUserByIdUser:selectedUpload.userId]; - NSString *userName = userSelected.username; + UserDto *userSelected = [ManageUsersDB getUserByUserId:selectedUpload.userId]; + NSString *userDisplayAccountName = [UtilsUrls getFullRemoteServerPathWithoutProtocolBeginningWithUserDisplayName:userSelected]; //if SAML is enabled replace the percent of the samlusername by utf8 if (k_is_sso_active) { - userName= [userName stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; + userDisplayAccountName= [userDisplayAccountName stringByRemovingPercentEncoding]; } - NSString* temp=[NSString stringWithFormat:@"%@ %@@%@", NSLocalizedString(@"change_active_user", nil), userName, [UtilsUrls getUrlServerWithoutHttpOrHttps:userSelected.url]]; + NSString* temp=[NSString stringWithFormat:@"%@ %@", NSLocalizedString(@"change_active_user", nil), userDisplayAccountName]; UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:temp delegate:nil @@ -1165,7 +1165,7 @@ - (void)folderSelected:(NSString*)folder{ if (self.selectedFileDtoToResolveNotPermission) { //If exist file related with the select upload put in downloaded state - //UserDto *user = [ManageUsersDB getUserByIdUser:self.selectedFileDtoToResolveNotPermission.userId]; + //UserDto *user = [ManageUsersDB getUserByUserId:self.selectedFileDtoToResolveNotPermission.userId]; // NSString *parentFolder = [UtilsUrls getFilePathOnDBByFullPath:self.selectedFileDtoToResolveNotPermission.destinyFolder andUser:user]; @@ -1253,7 +1253,7 @@ - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEd * This method addObservers for notifications to this class */ -(void)setNotificationForCommunicationBetweenViews{ - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relaunchErrorCredentialFiles:) name:relaunchErrorCredentialFilesNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(relaunchErrorCredentialFiles:) name:RelaunchErrorCredentialFilesNotification object:nil]; } @@ -1279,7 +1279,7 @@ -(void)relaunchErrorCredentialFiles:(NSNotification*)notification{ UserDto *userDto = (UserDto*)[notification object]; //Change the status of the Credencial files error on a specific user - [app changeTheStatusOfCredentialsFilesErrorOfAnUserId:userDto.idUser]; + [app changeTheStatusOfCredentialsFilesErrorOfAnUserId:userDto.userId]; //Update the uploads table view [self updateRecents]; diff --git a/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController.h b/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController.h deleted file mode 100644 index b50c6ba76f..0000000000 --- a/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController.h +++ /dev/null @@ -1,31 +0,0 @@ -// -// AddAccountViewController.h -// Owncloud iOs Client -// -// Created by Javier Gonzalez on 10/2/12. -// - -/* - Copyright (C) 2016, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ - -#import -#import "LoginViewController.h" - -@protocol AddAccountDelegate - -@optional -- (void)refreshTable; -@end - -@interface AddAccountViewController : LoginViewController - -@property(nonatomic,weak) __weak id delegate; - -- (IBAction)cancelClicked:(id)sender; - -@end diff --git a/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController.m b/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController.m deleted file mode 100644 index eb04acc1fd..0000000000 --- a/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController.m +++ /dev/null @@ -1,203 +0,0 @@ -// -// AddAccountViewController.m -// Owncloud iOs Client -// -// Created by Javier Gonzalez on 10/2/12. -// - -/* - Copyright (C) 2016, ownCloud GmbH. - This code is covered by the GNU Public License Version 3. - For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ - You should have received a copy of this license - along with this program. If not, see . - */ - -#import "AddAccountViewController.h" -#import "UserDto.h" - -#import "UIColor+Constants.h" -#import "constants.h" -#import "Customization.h" -#import "ManageUsersDB.h" -#import "UtilsCookies.h" -#import "UtilsFramework.h" -#import "AppDelegate.h" -#import "ManageCookiesStorageDB.h" -#import "ManageAppSettingsDB.h" - -@interface AddAccountViewController () - -@end - -@implementation AddAccountViewController - - -- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil -{ - self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil andLoginMode:LoginModeCreate]; - if (self) { - // Custom initialization - if (!IS_IPHONE) { - UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelClicked:)]; - self.navigationItem.leftBarButtonItem = cancelButton; - } - - } - return self; -} - -- (void) viewWillAppear:(BOOL)animated { - - AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate]; - - //Clear the cookies before to try to do login - //1- Storage the new cookies on the Database - [UtilsCookies setOnDBStorageCookiesByUser:app.activeUser]; - //2- Clean the cookies storage - [UtilsFramework deleteAllCookies]; - - [super viewWillAppear:animated]; - -} - - -- (void)viewDidLoad -{ - [super viewDidLoad]; - // Do any additional setup after loading the view from its nib. - - self.edgesForExtendedLayout = UIRectEdgeNone; - - -} - -- (void)viewDidUnload -{ - [super viewDidUnload]; - // Release any retained subviews of the main view. - // e.g. self.myOutlet = nil; -} - -- (void)viewWillDisappear:(BOOL)animated { - [super viewWillDisappear:animated]; - - [self restoreTheCookiesOfActiveUser]; - - ((CheckAccessToServer *)[CheckAccessToServer sharedManager]).delegate = nil; -} - - --(void)potraitViewiPad{ - - DLog(@"Vertical iPad"); - - [self addEditAccountsViewiPad]; -} - --(void)landscapeViewiPad{ - - DLog(@"Horizontal iPad"); - - [self addEditAccountsViewiPad]; -} - - -///----------------------------------- -/// @name Create data with server data -///----------------------------------- - -/** - * This method is called when the app receive the data of the login proffind - * - * @param items -> items of the proffind - * @param requestCode -> webdav server response - * - * @warning This method is overwrite of the parent class (LoginViewController) and it's present also in EditViewController - */ --(void)createUserAndDataInTheSystemWithRequest:(NSArray *)items andCode:(int) requestCode{ - - //DLog(@"Request Did Fetch Directory Listing And Test Authetification"); - - if(requestCode >= 400) { - [self.manageNetworkErrors returnErrorMessageWithHttpStatusCode:requestCode - andError:nil]; - } else { - - UserDto *userDto = [[UserDto alloc] init]; - - //We check if start with http or https to concat it - if([self.urlTextField.text hasPrefix:@"http://"] || [self.urlTextField.text hasPrefix:@"https://"]) { - userDto.url = [self getUrlChecked: self.urlTextField.text]; - - } else { - if(isHttps) { - userDto.url = [NSString stringWithFormat:@"%@%@",@"https://", [self getUrlChecked: self.urlTextField.text]]; - } else { - userDto.url = [NSString stringWithFormat:@"%@%@",@"http://", [self getUrlChecked: self.urlTextField.text]]; - } - } - - //DLog(@"URL FINAL: %@", userDto.url); - - NSString *userNameUTF8=self.usernameTextField.text; - NSString *passwordUTF8=self.passwordTextField.text; - //TODO with UTF8 the % crash on password... - //userNameUTF8 = [userNameUTF8 stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]; - //passwordUTF8 = [passwordUTF8 stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)NSUTF8StringEncoding]; - - userDto.username = userNameUTF8; - userDto.password = passwordUTF8; - userDto.ssl = isHttps; - userDto.activeaccount = NO; - AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; - userDto.urlRedirected = app.urlServerRedirected; - userDto.predefinedUrl = k_default_url_server; - - [self hideTryingToLogin]; - - if([ManageUsersDB isExistUser:userDto]) { - - [self showError:NSLocalizedString(@"user_exist", nil)]; - - //1- Clean the cookies after login or not before go with the active user - [UtilsFramework deleteAllCookies]; - - //2- Storage the active account cookies on the Cookies System Storage - [UtilsCookies setOnSystemStorageCookiesByUser:app.activeUser]; - //3- We delete the cookies of the active user on the databse because it could change and it is not necessary keep them there - [ManageCookiesStorageDB deleteCookiesByUser:app.activeUser]; - - } else { - [ManageUsersDB insertUser:userDto]; - - [ManageAppSettingsDB updateInstantUploadAllUser]; - - //Return the cookies to the previous user - userDto = [ManageUsersDB getLastUserInserted]; - - //Storage the new cookies on the Database - [UtilsCookies setOnDBStorageCookiesByUser:userDto]; - [self restoreTheCookiesOfActiveUser]; - - if (!IS_IPHONE) { - [_delegate refreshTable]; - [self cancelClicked:nil]; - } else { - [[self navigationController] popViewControllerAnimated:YES]; - } - } - } -} - - - -#pragma mark - Buttons -/* - * This method close the view - */ -- (IBAction)cancelClicked:(id)sender { - [self dismissViewControllerAnimated:YES completion:nil]; -} - -@end diff --git a/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController_iPhone.xib b/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController_iPhone.xib deleted file mode 100644 index b990da5b02..0000000000 --- a/Owncloud iOs Client/Tabs/SettingTab/Account/AddAccount/AddAccountViewController_iPhone.xib +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.h b/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.h index 764f0c8b86..0050110855 100644 --- a/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.h +++ b/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.h @@ -6,7 +6,7 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license @@ -15,23 +15,14 @@ #import -@protocol AccountCellDelegate - -@optional -- (void)activeAccountByPosition:(NSInteger) position; -@end - @interface AccountCell : UITableViewCell - @property(nonatomic, weak) IBOutlet UILabel *userName; @property(nonatomic, weak) IBOutlet UILabel *urlServer; @property(nonatomic, weak) IBOutlet UIButton *activeButton; @property (weak, nonatomic) IBOutlet UIButton *menuButton; -@property(nonatomic, weak) __weak id delegate; -- (IBAction)activeAccount:(id)sender; diff --git a/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.m b/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.m index a067c9fe11..578e426067 100644 --- a/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.m +++ b/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.m @@ -6,21 +6,14 @@ // /* - Copyright (C) 2016, ownCloud GmbH. + Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license along with this program. If not, see . */ -#import "AppDelegate.h" #import "AccountCell.h" -#import "CheckAccessToServer.h" -#import "UtilsFramework.h" -#import "ManageUsersDB.h" -#import "Customization.h" -#import "OCKeychain.h" -#import "UtilsCookies.h" @implementation AccountCell @@ -40,16 +33,6 @@ - (void)setSelected:(BOOL)selected animated:(BOOL)animated // Configure the view for the selected state } --(IBAction)activeAccount:(id)sender { - - //We delete the cookies on SAML - if (k_is_sso_active) { - [UtilsCookies eraseCredentialsAndUrlCacheOfActiveUser]; - } - - [self.delegate activeAccountByPosition:self.activeButton.tag]; - -} @end diff --git a/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.xib b/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.xib index bebf6529fa..d70d1c590b 100644 --- a/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.xib +++ b/Owncloud iOs Client/Tabs/SettingTab/Account/Cell/AccountCell.xib @@ -1,9 +1,12 @@ - - + + + + + - - + + @@ -21,7 +24,7 @@ - +