NCService.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 {
  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.requestServerStatus()
  39. // Thirt Part
  40. #if HC
  41. self.requestHC()
  42. #endif
  43. }
  44. //MARK: -
  45. //MARK: Internal request Service API NC
  46. private func requestUserProfile() {
  47. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  48. return
  49. }
  50. OCNetworking.sharedManager().getUserProfile(withAccount: appDelegate.activeAccount, completion: { (account, userProfile, message, errorCode) in
  51. if errorCode == 0 && account == self.appDelegate.activeAccount {
  52. // Update User (+ userProfile.id) & active account & account network
  53. guard let tableAccount = NCManageDatabase.sharedInstance.setAccountUserProfile(userProfile!, HCProperties: false) else {
  54. self.appDelegate.messageNotification("Accopunt", description: "Internal error : account not found on DB", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: Int(k_CCErrorInternalError))
  55. return
  56. }
  57. let user = tableAccount.user
  58. let url = tableAccount.url
  59. self.appDelegate.settingActiveAccount(tableAccount.account, activeUrl: tableAccount.url, activeUser: tableAccount.user, activeUserID: tableAccount.userID, activePassword: CCUtility.getPassword(tableAccount.account))
  60. // Call func thath required the userdID
  61. self.appDelegate.activeFavorites.listingFavorites()
  62. self.appDelegate.activeMedia.reloadDataSource(loadNetworkDatasource: true)
  63. NCFunctionMain.sharedInstance.synchronizeOffline()
  64. DispatchQueue.global().async {
  65. let avatarUrl = "\(self.appDelegate.activeUrl!)/index.php/avatar/\(self.appDelegate.activeUser!)/128".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  66. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(user, activeUrl: url) + "-" + self.appDelegate.activeUser + ".png"
  67. OCNetworking.sharedManager()?.downloadContents(ofUrl: avatarUrl, completion: { (data, message, errorCode) in
  68. if errorCode == 0 {
  69. if let image = UIImage(data: data!) {
  70. try? FileManager.default.removeItem(atPath: fileNamePath)
  71. if let data = image.pngData() {
  72. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  73. }
  74. }
  75. }
  76. })
  77. DispatchQueue.main.async {
  78. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeUserProfile"), object: nil)
  79. }
  80. }
  81. // Get Capabilities
  82. self.requestServerCapabilities()
  83. } else if errorCode != 0 {
  84. print("Get user profile failure error")
  85. } else {
  86. print("[LOG] It has been changed user during networking process, error.")
  87. }
  88. })
  89. }
  90. private func requestServerStatus() {
  91. OCNetworking.sharedManager().serverStatusUrl(appDelegate.activeUrl, completion: { (serverProductName, versionMajor, versionMicro, versionMinor, message, errorCode) in
  92. if errorCode == 0 {
  93. if serverProductName == "owncloud" {
  94. self.appDelegate.messageNotification("_warning_", description: "_warning_owncloud_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: Int(k_CCErrorInternalError))
  95. } else if versionMajor <= k_nextcloud_unsupported {
  96. self.appDelegate.messageNotification("_warning_", description: "_warning_unsupported_", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.info, errorCode: Int(k_CCErrorInternalError))
  97. }
  98. }
  99. })
  100. }
  101. private func requestServerCapabilities() {
  102. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  103. return
  104. }
  105. OCNetworking.sharedManager().getCapabilitiesWithAccount(appDelegate.activeAccount, completion: { (account, capabilities, message, errorCode) in
  106. if errorCode == 0 && account == self.appDelegate.activeAccount {
  107. // Update capabilities db
  108. NCManageDatabase.sharedInstance.addCapabilities(capabilities!, account: account!)
  109. // ------ THEMING -----------------------------------------------------------------------
  110. if (NCBrandOptions.sharedInstance.use_themingBackground && capabilities!.themingBackground != "") {
  111. // Download Theming Background
  112. DispatchQueue.global().async {
  113. // Download Logo
  114. let fileNameThemingLogo = CCUtility.getStringUser(self.appDelegate.activeUser, activeUrl: self.appDelegate.activeUrl) + "-themingLogo.png"
  115. NCUtility.sharedInstance.convertSVGtoPNGWriteToUserData(svgUrlString: capabilities!.themingLogo, fileName: fileNameThemingLogo, width: 40, rewrite: true, closure: { (imageNamePath) in })
  116. let backgroundURL = capabilities!.themingBackground!.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)!
  117. let fileNamePath = CCUtility.getDirectoryUserData() + "/" + CCUtility.getStringUser(self.appDelegate.activeUser, activeUrl: self.appDelegate.activeUrl) + "-themingBackground.png"
  118. OCNetworking.sharedManager()?.downloadContents(ofUrl: backgroundURL, completion: { (data, message, errorCode) in
  119. if errorCode == 0 {
  120. if let image = UIImage(data: data!) {
  121. try? FileManager.default.removeItem(atPath: fileNamePath)
  122. if let data = image.pngData() {
  123. try? data.write(to: URL(fileURLWithPath: fileNamePath))
  124. }
  125. }
  126. }
  127. })
  128. DispatchQueue.main.async {
  129. self.appDelegate.settingThemingColorBrand()
  130. }
  131. }
  132. } else {
  133. self.appDelegate.settingThemingColorBrand()
  134. }
  135. // ------ SEARCH ------------------------------------------------------------------------
  136. if (NCManageDatabase.sharedInstance.getServerVersion(account: account!) != capabilities!.versionMajor && self.appDelegate.activeMain != nil) {
  137. self.appDelegate.activeMain.cancelSearchBar()
  138. }
  139. // ------ GET OTHER SERVICE -------------------------------------------------------------
  140. // Get Notification
  141. if (capabilities!.isNotificationServerEnabled) {
  142. OCNetworking.sharedManager().getNotificationWithAccount(account!, completion: { (account, listOfNotifications, message, errorCode) in
  143. if errorCode == 0 && account == self.appDelegate.activeAccount {
  144. DispatchQueue.global().async {
  145. let sortedListOfNotifications = (listOfNotifications! as NSArray).sortedArray(using: [
  146. NSSortDescriptor(key: "date", ascending: false)
  147. ])
  148. var old = ""
  149. var new = ""
  150. for notification in listOfNotifications! {
  151. let id = (notification as! OCNotifications).idNotification
  152. if let icon = (notification as! OCNotifications).icon {
  153. NCUtility.sharedInstance.convertSVGtoPNGWriteToUserData(svgUrlString: icon, fileName: nil, width: 25, rewrite: false, closure: { (imageNamePath) in })
  154. }
  155. new = new + String(describing: id)
  156. }
  157. for notification in self.appDelegate.listOfNotifications! {
  158. let id = (notification as! OCNotifications).idNotification
  159. old = old + String(describing: id)
  160. }
  161. DispatchQueue.main.async {
  162. if (new != old) {
  163. self.appDelegate.listOfNotifications = NSMutableArray.init(array: sortedListOfNotifications)
  164. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  165. }
  166. // Update Main NavigationBar
  167. if (self.appDelegate.activeMain.isSelectedMode == false && self.appDelegate.activeMain != nil) {
  168. self.appDelegate.activeMain.setUINavigationBarDefault()
  169. }
  170. }
  171. }
  172. } else {
  173. // Update Main NavigationBar
  174. if (self.appDelegate.activeMain.isSelectedMode == false && self.appDelegate.activeMain != nil) {
  175. self.appDelegate.activeMain.setUINavigationBarDefault()
  176. }
  177. }
  178. })
  179. } else {
  180. // Remove all Notification
  181. self.appDelegate.listOfNotifications.removeAllObjects()
  182. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationReloadData"), object: nil)
  183. // Update Main NavigationBar
  184. if (self.appDelegate.activeMain != nil && self.appDelegate.activeMain.isSelectedMode == false) {
  185. self.appDelegate.activeMain.setUINavigationBarDefault()
  186. }
  187. }
  188. // Get External Sites
  189. if (capabilities!.isExternalSitesServerEnabled) {
  190. OCNetworking.sharedManager().getExternalSites(withAccount: account!, completion: { (account, listOfExternalSites, message, errorCode) in
  191. if errorCode == 0 && account == self.appDelegate.activeAccount {
  192. NCManageDatabase.sharedInstance.deleteExternalSites(account: account!)
  193. for externalSites in listOfExternalSites! {
  194. NCManageDatabase.sharedInstance.addExternalSites(externalSites as! OCExternalSites, account: account!)
  195. }
  196. }
  197. })
  198. } else {
  199. NCManageDatabase.sharedInstance.deleteExternalSites(account: account!)
  200. }
  201. // Get Share
  202. if (capabilities!.isFilesSharingAPIEnabled && self.appDelegate.activeMain != nil) {
  203. self.appDelegate.activeMain.readShare(withAccount: account, openWindow: false, metadata: nil)
  204. }
  205. // Get Activity
  206. if (capabilities!.isActivityV2Enabled) {
  207. OCNetworking.sharedManager().getActivityWithAccount(account!, since: 0, limit: 100, link: "", completion: { (account, listOfActivity, message, errorCode) in
  208. DispatchQueue.global().async {
  209. if errorCode == 0 && account == self.appDelegate.activeAccount {
  210. NCManageDatabase.sharedInstance.addActivity(listOfActivity as! [OCActivity], account: account!)
  211. }
  212. }
  213. })
  214. }
  215. // Get Trash List
  216. let pathTrash = k_dav + "/trashbin/" + (self.appDelegate.activeUserID as NSString).addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)! + "/trash/"
  217. OCNetworking.sharedManager().listingTrash(withAccount: account, path: pathTrash, serverUrl: self.appDelegate.activeUrl, depth: "infinity", completion: { (account, item, message, errorCode) in
  218. if errorCode == 0 && account == self.appDelegate.activeAccount {
  219. DispatchQueue.global().async {
  220. NCManageDatabase.sharedInstance.deleteTrash(filePath: nil, account: account!)
  221. NCManageDatabase.sharedInstance.addTrashs(item as! [tableTrash])
  222. }
  223. }
  224. })
  225. } else if errorCode != 0 {
  226. self.appDelegate.settingThemingColorBrand()
  227. } else {
  228. print("[LOG] It has been changed user during networking process, error.")
  229. // Change Theming color
  230. self.appDelegate.settingThemingColorBrand()
  231. }
  232. })
  233. }
  234. @objc public func middlewarePing() {
  235. if (appDelegate.activeAccount == nil || appDelegate.activeAccount.count == 0 || appDelegate.maintenanceMode == true) {
  236. return
  237. }
  238. }
  239. //MARK: -
  240. //MARK: Thirt Part
  241. private func requestHC() {
  242. let professions = CCUtility.getHCBusinessType()
  243. if professions != nil && professions!.count > 0 {
  244. OCNetworking.sharedManager()?.putHCUserProfile(withAccount: appDelegate.activeAccount, serverUrl: appDelegate.activeUrl, address: nil, businesssize: nil, businesstype: professions, city: nil, company: nil, country: nil, displayname: nil, email: nil, phone: nil, role_: nil, twitter: nil, website: nil, zip: nil, completion: { (account, message, errorCode) in
  245. if errorCode == 0 && account == self.appDelegate.activeAccount {
  246. CCUtility.setHCBusinessType(nil)
  247. OCNetworking.sharedManager()?.getHCUserProfile(withAccount: self.appDelegate.activeAccount, serverUrl: self.appDelegate.activeUrl, completion: { (account, userProfile, message, errorCode) in
  248. if errorCode == 0 && account == self.appDelegate.activeAccount {
  249. _ = NCManageDatabase.sharedInstance.setAccountUserProfile(userProfile!, HCProperties: true)
  250. }
  251. })
  252. }
  253. })
  254. } else {
  255. OCNetworking.sharedManager()?.getHCUserProfile(withAccount: appDelegate.activeAccount, serverUrl: appDelegate.activeUrl, completion: { (account, userProfile, message, errorCode) in
  256. if errorCode == 0 && account == self.appDelegate.activeAccount {
  257. _ = NCManageDatabase.sharedInstance.setAccountUserProfile(userProfile!, HCProperties: true)
  258. }
  259. })
  260. }
  261. OCNetworking.sharedManager()?.getHCFeatures(withAccount: appDelegate.activeAccount, serverUrl: appDelegate.activeUrl, completion: { (account, features, message, errorCode) in
  262. if errorCode == 0 && account == self.appDelegate.activeAccount {
  263. _ = NCManageDatabase.sharedInstance.setAccountHCFeatures(features!)
  264. }
  265. })
  266. }
  267. }