NCService.swift 15 KB

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