NCService.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. //
  2. // NCService.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/03/18.
  6. // Copyright © 2018 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import Foundation
  24. class NCService: NSObject, OCNetworkingDelegate, CCLoginDelegate, CCLoginDelegateWeb {
  25. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  26. @objc static let sharedInstance: NCService = {
  27. let instance = NCService()
  28. return instance
  29. }()
  30. //MARK: -
  31. //MARK: Start Services API NC
  32. @objc func startRequestServicesServer() {
  33. self.requestUserProfile()
  34. self.requestServerCapabilities()
  35. self.requestNotificationServer()
  36. self.requestActivityServer()
  37. }
  38. //MARK: -
  39. //MARK: Request Service API NC
  40. @objc func requestServerCapabilities() {
  41. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  42. return
  43. }
  44. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  45. return
  46. }
  47. metadataNet.action = actionGetCapabilities
  48. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  49. }
  50. @objc func requestUserProfile() {
  51. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  52. return
  53. }
  54. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  55. return
  56. }
  57. metadataNet.action = actionGetUserProfile
  58. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  59. }
  60. @objc func requestNotificationServer() {
  61. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  62. return
  63. }
  64. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  65. return
  66. }
  67. metadataNet.action = actionGetNotificationServer
  68. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  69. }
  70. @objc func requestActivityServer() {
  71. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  72. return
  73. }
  74. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  75. return
  76. }
  77. metadataNet.action = actionGetActivityServer
  78. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  79. }
  80. @objc func middlewarePing() {
  81. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  82. return
  83. }
  84. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  85. return
  86. }
  87. metadataNet.action = actionMiddlewarePing
  88. metadataNet.serverUrl = NCBrandOptions.sharedInstance.middlewarePingUrl
  89. //appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  90. }
  91. //MARK: -
  92. //MARK: Delegate Service API NC
  93. func getCapabilitiesOfServerSuccessFailure(_ metadataNet: CCMetadataNet!, capabilities: OCCapabilities?, message: String?, errorCode: Int) {
  94. // Check Active Account
  95. if (metadataNet.account != appDelegate.activeAccount) {
  96. return
  97. }
  98. if (errorCode == 0) {
  99. // Update capabilities db
  100. NCManageDatabase.sharedInstance.addCapabilities(capabilities!)
  101. // ------ THEMING -----------------------------------------------------------------------
  102. // Download Theming Background & Change Theming color
  103. DispatchQueue.global().async {
  104. if (NCBrandOptions.sharedInstance.use_themingBackground) {
  105. let address = capabilities!.themingBackground!.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  106. guard let imageData = try? Data(contentsOf: URL(string: address)!) else {
  107. return
  108. }
  109. guard let image = UIImage(data: imageData) else {
  110. let fileName = "\(self.appDelegate.directoryUser!)/themingBackground.png"
  111. try? FileManager.default.removeItem(atPath: fileName)
  112. return
  113. }
  114. if let data = UIImagePNGRepresentation(image) {
  115. let fileName = "\(self.appDelegate.directoryUser!)/themingBackground.png"
  116. try? data.write(to: URL(fileURLWithPath: fileName))
  117. }
  118. DispatchQueue.main.async {
  119. self.appDelegate.settingThemingColorBrand()
  120. }
  121. }
  122. }
  123. // ------ SEARCH ------------------------------------------------------------------------
  124. if (NCManageDatabase.sharedInstance.getServerVersion() != capabilities!.versionMajor && appDelegate.activeMain != nil) {
  125. appDelegate.activeMain.cancelSearchBar()
  126. }
  127. // ------ GET OTHER SERVICE -------------------------------------------------------------
  128. // Read External Sites
  129. if (capabilities!.isExternalSitesServerEnabled) {
  130. metadataNet.action = actionGetExternalSitesServer
  131. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  132. }
  133. // Read Share
  134. if (capabilities!.isFilesSharingAPIEnabled) {
  135. appDelegate.sharesID.removeAllObjects()
  136. metadataNet.action = actionReadShareServer
  137. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: appDelegate.activeMain, metadataNet: metadataNet)
  138. }
  139. } else {
  140. // Unauthorized
  141. if (errorCode == kOCErrorServerUnauthorized) {
  142. appDelegate.openLoginView(self, loginType: loginModifyPasswordUser)
  143. }
  144. let error = "Get Capabilities failure error \(errorCode) \(message!)"
  145. print("[LOG] \(error)")
  146. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Capabilities of Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  147. // Change Theming color
  148. appDelegate.settingThemingColorBrand()
  149. }
  150. }
  151. @objc func getUserProfileSuccessFailure(_ metadataNet: CCMetadataNet!, userProfile: OCUserProfile?, message: String?, errorCode: Int) {
  152. // Check Active Account
  153. if (metadataNet.account != appDelegate.activeAccount) {
  154. return
  155. }
  156. if (errorCode == 0) {
  157. // Update User (+ userProfile.id) & active account & account network
  158. guard let tableAccount = NCManageDatabase.sharedInstance.setAccountUserProfile(userProfile!) else {
  159. appDelegate.messageNotification("Accopunt", description: "Internal error : account not found on DB", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  160. return
  161. }
  162. CCNetworking.shared().settingAccount()
  163. appDelegate.settingActiveAccount(tableAccount.account, activeUrl: tableAccount.url, activeUser: tableAccount.user, activeUserID: tableAccount.userID, activePassword: tableAccount.password)
  164. // Call func thath required the userdID
  165. appDelegate.activePhotos.readPhotoVideo()
  166. appDelegate.activeFavorites.readListingFavorites()
  167. DispatchQueue.global(qos: .default).async {
  168. let address = "\(self.appDelegate.activeUrl!)/index.php/avatar/\(self.appDelegate.activeUser!)/128".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  169. guard let imageData = try? Data(contentsOf: URL(string: address)!) else {
  170. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  171. return
  172. }
  173. guard let image = UIImage(data: imageData) else {
  174. let fileName = "\(self.appDelegate.directoryUser!)/avatar.png"
  175. try? FileManager.default.removeItem(atPath: fileName)
  176. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  177. return
  178. }
  179. if let data = UIImagePNGRepresentation(image) {
  180. let fileName = "\(self.appDelegate.directoryUser!)/avatar.png"
  181. try? data.write(to: URL(fileURLWithPath: fileName))
  182. }
  183. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  184. }
  185. } else {
  186. let error = "Get user profile failure error \(errorCode) \(message!)"
  187. print("[LOG] \(error)")
  188. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get user profile Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  189. }
  190. }
  191. @objc func getExternalSitesServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfExternalSites: [Any]?, message: String?, errorCode: Int) {
  192. // Check Active Account
  193. if (metadataNet.account != appDelegate.activeAccount) {
  194. return
  195. }
  196. if (errorCode == 0) {
  197. NCManageDatabase.sharedInstance.deleteExternalSites()
  198. for externalSites in listOfExternalSites! {
  199. NCManageDatabase.sharedInstance.addExternalSites(externalSites as! OCExternalSites)
  200. }
  201. } else {
  202. let error = "Get external site failure error \(errorCode) \(message!)"
  203. print("[LOG] \(error)")
  204. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get external site Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  205. }
  206. }
  207. @objc func getActivityServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfActivity: [Any]?, message: String?, errorCode: Int) {
  208. // Check Active Account
  209. if (metadataNet.account != appDelegate.activeAccount) {
  210. return
  211. }
  212. if (errorCode == 0) {
  213. NCManageDatabase.sharedInstance.addActivityServer(listOfActivity as! [OCActivity])
  214. if (appDelegate.activeActivity != nil) {
  215. appDelegate.activeActivity.reloadDatasource()
  216. }
  217. } else {
  218. let error = "Get Activity Server failure error \(errorCode) \(message!)"
  219. print("[LOG] \(error)")
  220. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Activity Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  221. }
  222. }
  223. @objc func getNotificationServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfNotifications: [Any]?, message: String?, errorCode: Int) {
  224. // Check Active Account
  225. if (metadataNet.account != appDelegate.activeAccount) {
  226. return
  227. }
  228. if (errorCode == 0) {
  229. DispatchQueue.global(qos: .default).async {
  230. let sortedListOfNotifications = (listOfNotifications! as NSArray).sortedArray(using: [
  231. NSSortDescriptor(key: "date", ascending: false)
  232. ])
  233. var old = ""
  234. var new = ""
  235. for notification in listOfNotifications! {
  236. let id = (notification as AnyObject).idNotification!
  237. new = new + String(describing: id)
  238. }
  239. for notification in self.appDelegate.listOfNotifications! {
  240. let id = (notification as AnyObject).idNotification!
  241. old = old + String(describing: id)
  242. }
  243. DispatchQueue.main.async {
  244. if (new != old) {
  245. self.appDelegate.listOfNotifications = NSMutableArray.init(array: sortedListOfNotifications)
  246. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  247. // Update Main NavigationBar
  248. if (self.appDelegate.activeMain.isSelectedMode == false) {
  249. self.appDelegate.activeMain.setUINavigationBarDefault()
  250. }
  251. }
  252. }
  253. }
  254. } else {
  255. let error = "Get Notification Server failure error \(errorCode) \(message!)"
  256. print("[LOG] \(error)")
  257. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Notification Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  258. // Update Main NavigationBar
  259. if (appDelegate.activeMain.isSelectedMode == false) {
  260. appDelegate.activeMain.setUINavigationBarDefault()
  261. }
  262. }
  263. }
  264. //MARK: -
  265. //MARK: Delegate Login
  266. func loginSuccess(_ loginType: Int) {
  267. // go to home sweet home
  268. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "initializeMain"), object: nil)
  269. }
  270. func loginClose() {
  271. appDelegate.activeLogin = nil
  272. }
  273. func loginWebClose() {
  274. appDelegate.activeLoginWeb = nil
  275. }
  276. }