NCService.swift 18 KB

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