NCService.swift 16 KB

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