NCService.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 {
  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 public func startRequestServicesServer() {
  33. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  34. return
  35. }
  36. self.requestUserProfile()
  37. self.requestServerCapabilities()
  38. self.requestActivityServer()
  39. self.requestServerStatus()
  40. }
  41. //MARK: -
  42. //MARK: Internal request Service API NC
  43. private func requestServerCapabilities() {
  44. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  45. return
  46. }
  47. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  48. return
  49. }
  50. metadataNet.action = actionGetCapabilities
  51. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  52. }
  53. private func requestUserProfile() {
  54. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  55. return
  56. }
  57. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  58. return
  59. }
  60. metadataNet.action = actionGetUserProfile
  61. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  62. }
  63. private func requestActivityServer() {
  64. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  65. return
  66. }
  67. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  68. return
  69. }
  70. metadataNet.action = actionGetActivityServer
  71. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  72. }
  73. @objc public func middlewarePing() {
  74. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  75. return
  76. }
  77. guard let metadataNet = CCMetadataNet.init(account: appDelegate.activeAccount) else {
  78. return
  79. }
  80. metadataNet.action = actionMiddlewarePing
  81. metadataNet.serverUrl = NCBrandOptions.sharedInstance.middlewarePingUrl
  82. //appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  83. }
  84. private func requestServerStatus() {
  85. let ocNetworking = OCnetworking.init(delegate: self, metadataNet: nil, withUser: appDelegate.activeUser, withUserID: appDelegate.activeUserID, withPassword: appDelegate.activePassword, withUrl: appDelegate.activeUrl)
  86. ocNetworking?.serverStatus(appDelegate.activeUrl, success: { (serverProductName, versionMajor, versionMicro, versionMinor) in
  87. if serverProductName == "owncloud" {
  88. self.appDelegate.messageNotification("_warning_", description: "_warning_owncloud_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: Int(k_CCErrorInternalError))
  89. } else if versionMajor <= k_nextcloud_unsupported {
  90. self.appDelegate.messageNotification("_warning_", description: "_warning_unsupported_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: Int(k_CCErrorInternalError))
  91. }
  92. }, failure: { (message, errorCode) in
  93. //
  94. })
  95. }
  96. //MARK: -
  97. //MARK: Delegate Service API NC
  98. func getCapabilitiesOfServerSuccessFailure(_ metadataNet: CCMetadataNet!, capabilities: OCCapabilities?, message: String?, errorCode: Int) {
  99. // Check Active Account
  100. if (metadataNet.account != appDelegate.activeAccount) {
  101. return
  102. }
  103. if (errorCode == 0) {
  104. // Update capabilities db
  105. NCManageDatabase.sharedInstance.addCapabilities(capabilities!)
  106. // ------ THEMING -----------------------------------------------------------------------
  107. if (NCBrandOptions.sharedInstance.use_themingBackground && capabilities!.themingBackground != "") {
  108. // Download Theming Background & Change Theming color
  109. DispatchQueue.global().async {
  110. let address = capabilities!.themingBackground!.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  111. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(self.appDelegate.activeUser, activeUrl: self.appDelegate.activeUrl) + "-themingBackground.png"
  112. guard let imageData = try? Data(contentsOf: URL(string: address)!) else {
  113. DispatchQueue.main.async {
  114. self.appDelegate.settingThemingColorBrand()
  115. }
  116. return
  117. }
  118. DispatchQueue.main.async {
  119. guard let image = UIImage(data: imageData) else {
  120. try? FileManager.default.removeItem(atPath: fileNamePath)
  121. self.appDelegate.settingThemingColorBrand()
  122. return
  123. }
  124. if let data = image.pngData() {
  125. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  126. }
  127. self.appDelegate.settingThemingColorBrand()
  128. }
  129. }
  130. } else {
  131. self.appDelegate.settingThemingColorBrand()
  132. }
  133. // ------ SEARCH ------------------------------------------------------------------------
  134. if (NCManageDatabase.sharedInstance.getServerVersion() != capabilities!.versionMajor && appDelegate.activeMain != nil) {
  135. appDelegate.activeMain.cancelSearchBar()
  136. }
  137. // ------ GET OTHER SERVICE -------------------------------------------------------------
  138. // Read Notification
  139. if (capabilities!.isNotificationServerEnabled) {
  140. metadataNet.action = actionGetNotificationServer
  141. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  142. } else {
  143. // Remove all Notification
  144. self.appDelegate.listOfNotifications.removeAllObjects()
  145. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  146. // Update Main NavigationBar
  147. if (appDelegate.activeMain != nil && self.appDelegate.activeMain.isSelectedMode == false) {
  148. self.appDelegate.activeMain.setUINavigationBarDefault()
  149. }
  150. }
  151. // Read External Sites
  152. if (capabilities!.isExternalSitesServerEnabled) {
  153. metadataNet.action = actionGetExternalSitesServer
  154. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  155. } else {
  156. NCManageDatabase.sharedInstance.deleteExternalSites()
  157. }
  158. // Read Share
  159. if (capabilities!.isFilesSharingAPIEnabled && appDelegate.activeMain != nil) {
  160. appDelegate.sharesID.removeAllObjects()
  161. metadataNet.action = actionReadShareServer
  162. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: appDelegate.activeMain, metadataNet: metadataNet)
  163. }
  164. } else {
  165. // Change Theming color
  166. appDelegate.settingThemingColorBrand()
  167. var error = ""
  168. if let message = message {
  169. error = "Get Capabilities failure error \(errorCode) \(message)"
  170. } else {
  171. error = "Get Capabilities failure error \(errorCode)"
  172. }
  173. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Capabilities of Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  174. }
  175. }
  176. func getUserProfileSuccessFailure(_ metadataNet: CCMetadataNet!, userProfile: OCUserProfile?, message: String?, errorCode: Int) {
  177. // Check Active Account
  178. if (metadataNet.account != appDelegate.activeAccount) {
  179. return
  180. }
  181. if (errorCode == 0) {
  182. // Update User (+ userProfile.id) & active account & account network
  183. guard let tableAccount = NCManageDatabase.sharedInstance.setAccountUserProfile(userProfile!) else {
  184. appDelegate.messageNotification("Accopunt", description: "Internal error : account not found on DB", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  185. return
  186. }
  187. let user = tableAccount.user
  188. let url = tableAccount.url
  189. CCNetworking.shared().settingAccount()
  190. appDelegate.settingActiveAccount(tableAccount.account, activeUrl: tableAccount.url, activeUser: tableAccount.user, activeUserID: tableAccount.userID, activePassword: tableAccount.password)
  191. // Call func thath required the userdID
  192. appDelegate.activeFavorites.listingFavorites()
  193. appDelegate.activeMedia.searchPhotoVideo()
  194. DispatchQueue.global(qos: .default).async {
  195. let address = "\(self.appDelegate.activeUrl!)/index.php/avatar/\(self.appDelegate.activeUser!)/128".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  196. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(user, activeUrl: url) + "-avatar.png"
  197. guard let imageData = try? Data(contentsOf: URL(string: address)!) else {
  198. DispatchQueue.main.async {
  199. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  200. }
  201. return
  202. }
  203. DispatchQueue.main.async {
  204. guard let image = UIImage(data: imageData) else {
  205. try? FileManager.default.removeItem(atPath: fileNamePath)
  206. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  207. return
  208. }
  209. if let data = image.pngData() {
  210. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  211. }
  212. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  213. }
  214. }
  215. } else {
  216. var error = ""
  217. if let message = message {
  218. error = "Get user profile failure error \(errorCode) \(message)"
  219. } else {
  220. error = "Get user profile failure error \(errorCode)"
  221. }
  222. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get user profile Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  223. }
  224. }
  225. func getExternalSitesServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfExternalSites: [Any]?, message: String?, errorCode: Int) {
  226. // Check Active Account
  227. if (metadataNet.account != appDelegate.activeAccount) {
  228. return
  229. }
  230. if (errorCode == 0) {
  231. NCManageDatabase.sharedInstance.deleteExternalSites()
  232. for externalSites in listOfExternalSites! {
  233. NCManageDatabase.sharedInstance.addExternalSites(externalSites as! OCExternalSites)
  234. }
  235. } else {
  236. var error = ""
  237. if let message = message {
  238. error = "Get external site failure error \(errorCode) \(message)"
  239. } else {
  240. error = "Get external site failure error \(errorCode)"
  241. }
  242. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get external site Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  243. }
  244. }
  245. func getActivityServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfActivity: [Any]?, message: String?, errorCode: Int) {
  246. // Check Active Account
  247. if (metadataNet.account != appDelegate.activeAccount) {
  248. return
  249. }
  250. if (errorCode == 0) {
  251. NCManageDatabase.sharedInstance.addActivityServer(listOfActivity as! [OCActivity])
  252. if (appDelegate.activeActivity != nil) {
  253. appDelegate.activeActivity.reloadDatasource()
  254. }
  255. } else {
  256. var error = ""
  257. if let message = message {
  258. error = "Get Activity Server failure error \(errorCode) \(message)"
  259. } else {
  260. error = "Get Activity Server failure error \(errorCode)"
  261. }
  262. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Activity Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  263. }
  264. }
  265. func getNotificationServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfNotifications: [Any]?, message: String?, errorCode: Int) {
  266. // Check Active Account
  267. if (metadataNet.account != appDelegate.activeAccount) {
  268. return
  269. }
  270. if (errorCode == 0) {
  271. DispatchQueue.global(qos: .default).async {
  272. let sortedListOfNotifications = (listOfNotifications! as NSArray).sortedArray(using: [
  273. NSSortDescriptor(key: "date", ascending: false)
  274. ])
  275. var old = ""
  276. var new = ""
  277. for notification in listOfNotifications! {
  278. let id = (notification as AnyObject).idNotification!
  279. new = new + String(describing: id)
  280. }
  281. for notification in self.appDelegate.listOfNotifications! {
  282. let id = (notification as AnyObject).idNotification!
  283. old = old + String(describing: id)
  284. }
  285. DispatchQueue.main.async {
  286. if (new != old) {
  287. self.appDelegate.listOfNotifications = NSMutableArray.init(array: sortedListOfNotifications)
  288. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  289. // Update Main NavigationBar
  290. if (self.appDelegate.activeMain.isSelectedMode == false && self.appDelegate.activeMain != nil) {
  291. self.appDelegate.activeMain.setUINavigationBarDefault()
  292. }
  293. }
  294. }
  295. }
  296. } else {
  297. var error = ""
  298. if let message = message {
  299. error = "Get Notification Server failure error \(errorCode) \(message)"
  300. } else {
  301. error = "Get Notification Server failure error \(errorCode)"
  302. }
  303. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Notification Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  304. // Update Main NavigationBar
  305. if (appDelegate.activeMain.isSelectedMode == false && self.appDelegate.activeMain != nil) {
  306. appDelegate.activeMain.setUINavigationBarDefault()
  307. }
  308. }
  309. }
  310. }