NCService.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 <marino.faggiana@nextcloud.com>
  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 Logo
  110. let fileNameThemingLogo = CCUtility.getStringUser(self.appDelegate.activeUser, activeUrl: self.appDelegate.activeUrl) + "-themingLogo.png"
  111. NCUtility.sharedInstance.convertSVGtoPNGWriteToUserData(svgUrlString: capabilities!.themingLogo, fileName: fileNameThemingLogo, width: 40, rewrite: true)
  112. // Download Theming Background
  113. DispatchQueue.global().async {
  114. let backgroundURL = capabilities!.themingBackground!.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  115. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(self.appDelegate.activeUser, activeUrl: self.appDelegate.activeUrl) + "-themingBackground.png"
  116. guard let imageData = try? Data(contentsOf: URL(string: backgroundURL)!) else {
  117. DispatchQueue.main.async {
  118. self.appDelegate.settingThemingColorBrand()
  119. }
  120. return
  121. }
  122. DispatchQueue.main.async {
  123. guard let image = UIImage(data: imageData) else {
  124. try? FileManager.default.removeItem(atPath: fileNamePath)
  125. self.appDelegate.settingThemingColorBrand()
  126. return
  127. }
  128. if let data = image.pngData() {
  129. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  130. }
  131. self.appDelegate.settingThemingColorBrand()
  132. }
  133. }
  134. } else {
  135. self.appDelegate.settingThemingColorBrand()
  136. }
  137. // ------ SEARCH ------------------------------------------------------------------------
  138. if (NCManageDatabase.sharedInstance.getServerVersion() != capabilities!.versionMajor && appDelegate.activeMain != nil) {
  139. appDelegate.activeMain.cancelSearchBar()
  140. }
  141. // ------ GET OTHER SERVICE -------------------------------------------------------------
  142. // Read Notification
  143. if (capabilities!.isNotificationServerEnabled) {
  144. metadataNet.action = actionGetNotificationServer
  145. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  146. } else {
  147. // Remove all Notification
  148. self.appDelegate.listOfNotifications.removeAllObjects()
  149. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  150. // Update Main NavigationBar
  151. if (appDelegate.activeMain != nil && self.appDelegate.activeMain.isSelectedMode == false) {
  152. self.appDelegate.activeMain.setUINavigationBarDefault()
  153. }
  154. }
  155. // Read External Sites
  156. if (capabilities!.isExternalSitesServerEnabled) {
  157. metadataNet.action = actionGetExternalSitesServer
  158. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: self, metadataNet: metadataNet)
  159. } else {
  160. NCManageDatabase.sharedInstance.deleteExternalSites()
  161. }
  162. // Read Share
  163. if (capabilities!.isFilesSharingAPIEnabled && appDelegate.activeMain != nil) {
  164. appDelegate.sharesID.removeAllObjects()
  165. metadataNet.action = actionReadShareServer
  166. appDelegate.addNetworkingOperationQueue(appDelegate.netQueue, delegate: appDelegate.activeMain, metadataNet: metadataNet)
  167. }
  168. } else {
  169. // Change Theming color
  170. appDelegate.settingThemingColorBrand()
  171. var error = ""
  172. if let message = message {
  173. error = "Get Capabilities failure error \(errorCode) \(message)"
  174. } else {
  175. error = "Get Capabilities failure error \(errorCode)"
  176. }
  177. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Capabilities of Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  178. }
  179. }
  180. func getUserProfileSuccessFailure(_ metadataNet: CCMetadataNet!, userProfile: OCUserProfile?, message: String?, errorCode: Int) {
  181. // Check Active Account
  182. if (metadataNet.account != appDelegate.activeAccount) {
  183. return
  184. }
  185. if (errorCode == 0) {
  186. // Update User (+ userProfile.id) & active account & account network
  187. guard let tableAccount = NCManageDatabase.sharedInstance.setAccountUserProfile(userProfile!) else {
  188. appDelegate.messageNotification("Accopunt", description: "Internal error : account not found on DB", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  189. return
  190. }
  191. let user = tableAccount.user
  192. let url = tableAccount.url
  193. CCNetworking.shared().settingAccount()
  194. appDelegate.settingActiveAccount(tableAccount.account, activeUrl: tableAccount.url, activeUser: tableAccount.user, activeUserID: tableAccount.userID, activePassword: tableAccount.password)
  195. // Call func thath required the userdID
  196. appDelegate.activeFavorites.listingFavorites()
  197. appDelegate.activeMedia.searchPhotoVideo()
  198. NCFunctionMain.sharedInstance.synchronizeOffline()
  199. DispatchQueue.global(qos: .default).async {
  200. let address = "\(self.appDelegate.activeUrl!)/index.php/avatar/\(self.appDelegate.activeUser!)/128".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  201. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(user, activeUrl: url) + "-avatar.png"
  202. guard let imageData = try? Data(contentsOf: URL(string: address)!) else {
  203. DispatchQueue.main.async {
  204. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  205. }
  206. return
  207. }
  208. DispatchQueue.main.async {
  209. guard let image = UIImage(data: imageData) else {
  210. try? FileManager.default.removeItem(atPath: fileNamePath)
  211. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  212. return
  213. }
  214. if let data = image.pngData() {
  215. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  216. }
  217. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  218. }
  219. }
  220. } else {
  221. var error = ""
  222. if let message = message {
  223. error = "Get user profile failure error \(errorCode) \(message)"
  224. } else {
  225. error = "Get user profile failure error \(errorCode)"
  226. }
  227. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get user profile Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  228. }
  229. }
  230. func getExternalSitesServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfExternalSites: [Any]?, message: String?, errorCode: Int) {
  231. // Check Active Account
  232. if (metadataNet.account != appDelegate.activeAccount) {
  233. return
  234. }
  235. if (errorCode == 0) {
  236. NCManageDatabase.sharedInstance.deleteExternalSites()
  237. for externalSites in listOfExternalSites! {
  238. NCManageDatabase.sharedInstance.addExternalSites(externalSites as! OCExternalSites)
  239. }
  240. } else {
  241. var error = ""
  242. if let message = message {
  243. error = "Get external site failure error \(errorCode) \(message)"
  244. } else {
  245. error = "Get external site failure error \(errorCode)"
  246. }
  247. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get external site Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  248. }
  249. }
  250. func getActivityServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfActivity: [Any]?, message: String?, errorCode: Int) {
  251. // Check Active Account
  252. if (metadataNet.account != appDelegate.activeAccount) {
  253. return
  254. }
  255. if (errorCode == 0) {
  256. NCManageDatabase.sharedInstance.addActivityServer(listOfActivity as! [OCActivity])
  257. if (appDelegate.activeActivity != nil) {
  258. appDelegate.activeActivity.reloadDatasource()
  259. }
  260. } else {
  261. var error = ""
  262. if let message = message {
  263. error = "Get Activity Server failure error \(errorCode) \(message)"
  264. } else {
  265. error = "Get Activity Server failure error \(errorCode)"
  266. }
  267. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Activity Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  268. }
  269. }
  270. func getNotificationServerSuccessFailure(_ metadataNet: CCMetadataNet!, listOfNotifications: [Any]?, message: String?, errorCode: Int) {
  271. // Check Active Account
  272. if (metadataNet.account != appDelegate.activeAccount) {
  273. return
  274. }
  275. if (errorCode == 0) {
  276. DispatchQueue.global(qos: .default).async {
  277. let sortedListOfNotifications = (listOfNotifications! as NSArray).sortedArray(using: [
  278. NSSortDescriptor(key: "date", ascending: false)
  279. ])
  280. var old = ""
  281. var new = ""
  282. for notification in listOfNotifications! {
  283. let id = (notification as! OCNotifications).idNotification
  284. if let icon = (notification as! OCNotifications).icon {
  285. NCUtility.sharedInstance.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false)
  286. }
  287. new = new + String(describing: id)
  288. }
  289. for notification in self.appDelegate.listOfNotifications! {
  290. let id = (notification as! OCNotifications).idNotification
  291. old = old + String(describing: id)
  292. }
  293. DispatchQueue.main.async {
  294. if (new != old) {
  295. self.appDelegate.listOfNotifications = NSMutableArray.init(array: sortedListOfNotifications)
  296. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  297. // Update Main NavigationBar
  298. if (self.appDelegate.activeMain.isSelectedMode == false && self.appDelegate.activeMain != nil) {
  299. self.appDelegate.activeMain.setUINavigationBarDefault()
  300. }
  301. }
  302. }
  303. }
  304. } else {
  305. var error = ""
  306. if let message = message {
  307. error = "Get Notification Server failure error \(errorCode) \(message)"
  308. } else {
  309. error = "Get Notification Server failure error \(errorCode)"
  310. }
  311. NCManageDatabase.sharedInstance.addActivityClient("", fileID: "", action: k_activityDebugActionCapabilities, selector: "Get Notification Server", note: error, type: k_activityTypeFailure, verbose: true, activeUrl: appDelegate.activeUrl)
  312. // Update Main NavigationBar
  313. if (appDelegate.activeMain.isSelectedMode == false && self.appDelegate.activeMain != nil) {
  314. appDelegate.activeMain.setUINavigationBarDefault()
  315. }
  316. }
  317. }
  318. }