NCService.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 UIKit
  24. import SVGKit
  25. import NextcloudKit
  26. import SwiftyJSON
  27. class NCService: NSObject {
  28. @objc static let shared: NCService = {
  29. let instance = NCService()
  30. return instance
  31. }()
  32. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  33. // MARK: -
  34. @objc public func startRequestServicesServer() {
  35. NCManageDatabase.shared.clearAllAvatarLoaded()
  36. guard !appDelegate.account.isEmpty else { return }
  37. addInternalTypeIdentifier()
  38. requestServerStatus()
  39. requestUserProfile()
  40. }
  41. // MARK: -
  42. func addInternalTypeIdentifier() {
  43. // txt
  44. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/plain", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  45. // html
  46. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/html", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  47. // markdown
  48. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "net.daringfireball.markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  49. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/x-markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  50. // document: text
  51. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "org.oasis-open.opendocument.text", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  52. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.wordprocessingml.document", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  53. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "com.microsoft.word.doc", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  54. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "com.apple.iwork.pages.pages", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NKCommon.TypeIconFile.document.rawValue, name: "pages")
  55. // document: sheet
  56. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "org.oasis-open.opendocument.spreadsheet", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.xls.rawValue, name: "sheet")
  57. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.spreadsheetml.sheet", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice, iconName: NKCommon.TypeIconFile.xls.rawValue, name: "sheet")
  58. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "com.microsoft.excel.xls", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NKCommon.TypeIconFile.xls.rawValue, name: "sheet")
  59. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "com.apple.iwork.numbers.numbers", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NKCommon.TypeIconFile.xls.rawValue, name: "numbers")
  60. // document: presentation
  61. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "org.oasis-open.opendocument.presentation", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.ppt.rawValue, name: "presentation")
  62. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "org.openxmlformats.presentationml.presentation", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorOnlyoffice, iconName: NKCommon.TypeIconFile.ppt.rawValue, name: "presentation")
  63. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "com.microsoft.powerpoint.ppt", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NKCommon.TypeIconFile.ppt.rawValue, name: "presentation")
  64. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "com.apple.iwork.keynote.key", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorQuickLook, iconName: NKCommon.TypeIconFile.ppt.rawValue, name: "keynote")
  65. }
  66. // MARK: -
  67. private func requestServerStatus() {
  68. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  69. NextcloudKit.shared.getServerStatus(serverUrl: appDelegate.urlBase, options: options) { serverProductName, _, versionMajor, _, _, extendedSupport, data, error in
  70. guard error == .success, extendedSupport == false else {
  71. return
  72. }
  73. if serverProductName == "owncloud" {
  74. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_warning_owncloud_")
  75. NCContentPresenter.shared.showWarning(error: error, priority: .max)
  76. } else if versionMajor <= NCGlobal.shared.nextcloud_unsupported_version {
  77. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_warning_unsupported_")
  78. NCContentPresenter.shared.showWarning(error: error, priority: .max)
  79. }
  80. }
  81. }
  82. // MARK: -
  83. private func requestUserProfile() {
  84. guard !appDelegate.account.isEmpty else { return }
  85. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  86. NextcloudKit.shared.getUserProfile(options: options) { account, userProfile, data, error in
  87. guard error == .success, let userProfile = userProfile else {
  88. // Ops the server has Unauthorized
  89. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] The server has response with Unauthorized \(error.errorCode)")
  90. DispatchQueue.main.async {
  91. if (UIApplication.shared.applicationState == .active) &&
  92. (NCNetworking.shared.networkReachability != NKCommon.TypeReachability.notReachable) &&
  93. (error.errorCode == NCGlobal.shared.errorNCUnauthorized || error.errorCode == NCGlobal.shared.errorUnauthorized || error.errorCode == NCGlobal.shared.errorForbidden) {
  94. NCBrandColor.shared.settingThemingColor(account: account)
  95. NCNetworkingCheckRemoteUser().checkRemoteUser(account: account, error: error)
  96. }
  97. }
  98. return
  99. }
  100. // Update User (+ userProfile.id) & active account & account network
  101. guard let tableAccount = NCManageDatabase.shared.setAccountUserProfile(account: account, userProfile: userProfile) else {
  102. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "Internal error : account not found on DB")
  103. NCContentPresenter.shared.showError(error: error, priority: .max)
  104. return
  105. }
  106. self.appDelegate.settingAccount(tableAccount.account, urlBase: tableAccount.urlBase, user: tableAccount.user, userId: tableAccount.userId, password: CCUtility.getPassword(tableAccount.account))
  107. // Synchronize favorite
  108. NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { _, _, _ in }
  109. // Synchronize Offline
  110. self.synchronizeOffline(account: tableAccount.account)
  111. // Get Avatar
  112. let fileName = tableAccount.userBaseUrl + "-" + self.appDelegate.user + ".png"
  113. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  114. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  115. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  116. NextcloudKit.shared.downloadAvatar(user: tableAccount.userId, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: etag, options: options) { _, _, _, etag, error in
  117. guard let etag = etag, error == .success else {
  118. if error.errorCode == NCGlobal.shared.errorNotModified {
  119. NCManageDatabase.shared.setAvatarLoaded(fileName: fileName)
  120. }
  121. return
  122. }
  123. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  124. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadAvatar, userInfo: nil)
  125. }
  126. self.requestServerCapabilities()
  127. self.requestDashboardWidget()
  128. // Unlock E2EE
  129. NCNetworkingE2EE.shared.unlockAll(account: account)
  130. }
  131. }
  132. // MARK: -
  133. private func requestServerCapabilities() {
  134. guard !appDelegate.account.isEmpty else { return }
  135. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  136. NextcloudKit.shared.getCapabilities(options: options) { account, data, error in
  137. guard error == .success, let data = data else {
  138. NCBrandColor.shared.settingThemingColor(account: account)
  139. return
  140. }
  141. NCManageDatabase.shared.addCapabilitiesJSon(data, account: account)
  142. NCManageDatabase.shared.setCapabilities(account: account, data: data)
  143. // Setup communication
  144. if NCGlobal.shared.capabilityServerVersionMajor > 0 {
  145. NextcloudKit.shared.setup(nextcloudVersion: NCGlobal.shared.capabilityServerVersionMajor)
  146. }
  147. // Theming
  148. if NCGlobal.shared.capabilityThemingColor != NCBrandColor.shared.themingColor || NCGlobal.shared.capabilityThemingColorElement != NCBrandColor.shared.themingColorElement || NCGlobal.shared.capabilityThemingColorText != NCBrandColor.shared.themingColorText {
  149. NCBrandColor.shared.settingThemingColor(account: account)
  150. }
  151. // Sharing & Comments
  152. let comments = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesFilesComments, exists: false)
  153. let activity = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesActivity)
  154. if !NCGlobal.shared.capabilityFileSharingApiEnabled && !comments && activity == nil {
  155. self.appDelegate.disableSharesView = true
  156. } else {
  157. self.appDelegate.disableSharesView = false
  158. }
  159. // Text direct editor detail
  160. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion18 {
  161. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  162. NextcloudKit.shared.NCTextObtainEditorDetails(options: options) { account, editors, creators, data, error in
  163. if error == .success && account == self.appDelegate.account {
  164. NCManageDatabase.shared.addDirectEditing(account: account, editors: editors, creators: creators)
  165. }
  166. }
  167. }
  168. // External file Server
  169. if NCGlobal.shared.capabilityExternalSites {
  170. NextcloudKit.shared.getExternalSite(options: options) { account, externalSites, data, error in
  171. if error == .success && account == self.appDelegate.account {
  172. NCManageDatabase.shared.deleteExternalSites(account: account)
  173. for externalSite in externalSites {
  174. NCManageDatabase.shared.addExternalSites(externalSite, account: account)
  175. }
  176. }
  177. }
  178. } else {
  179. NCManageDatabase.shared.deleteExternalSites(account: account)
  180. }
  181. // User Status
  182. let userStatus = NCManageDatabase.shared.getCapabilitiesServerBool(account: account, elements: NCElementsJSON.shared.capabilitiesUserStatusEnabled, exists: false)
  183. if userStatus {
  184. NextcloudKit.shared.getUserStatus(options: options) { account, clearAt, icon, message, messageId, messageIsPredefined, status, statusIsUserDefined, userId, data, error in
  185. if error == .success && account == self.appDelegate.account && userId == self.appDelegate.userId {
  186. NCManageDatabase.shared.setAccountUserStatus(userStatusClearAt: clearAt, userStatusIcon: icon, userStatusMessage: message, userStatusMessageId: messageId, userStatusMessageIsPredefined: messageIsPredefined, userStatusStatus: status, userStatusStatusIsUserDefined: statusIsUserDefined, account: account)
  187. }
  188. }
  189. }
  190. // Added UTI for Collabora
  191. if let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) {
  192. for mimeType in richdocumentsMimetypes {
  193. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: mimeType, classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  194. }
  195. }
  196. // Added UTI for ONLYOFFICE & Text
  197. if let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account) {
  198. for directEditing in directEditingCreators {
  199. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: directEditing.mimetype, classFile: NKCommon.TypeClassFile.document.rawValue, editor: directEditing.editor, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  200. }
  201. }
  202. }
  203. }
  204. // MARK: -
  205. private func requestDashboardWidget() {
  206. @Sendable func convertDataToImage(data: Data?, size:CGSize, fileNameToWrite: String?) {
  207. guard let data = data else { return }
  208. var imageData: UIImage?
  209. if let image = UIImage(data: data), let image = image.resizeImage(size: size) {
  210. imageData = image
  211. } else if let image = SVGKImage(data: data) {
  212. image.size = size
  213. imageData = image.uiImage
  214. } else {
  215. print("error")
  216. }
  217. if let fileName = fileNameToWrite, let image = imageData {
  218. do {
  219. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  220. try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  221. } catch { }
  222. }
  223. }
  224. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  225. NextcloudKit.shared.getDashboardWidget(options: options) { account, dashboardWidgets, data, error in
  226. Task {
  227. if error == .success, let dashboardWidgets = dashboardWidgets {
  228. NCManageDatabase.shared.addDashboardWidget(account: account, dashboardWidgets: dashboardWidgets)
  229. for widget in dashboardWidgets {
  230. if let url = URL(string: widget.iconUrl), let fileName = widget.iconClass {
  231. let (_, data, error) = await NextcloudKit.shared.getPreview(url: url)
  232. if error == .success {
  233. convertDataToImage(data: data, size: CGSize(width: 256, height: 256), fileNameToWrite: fileName)
  234. }
  235. }
  236. }
  237. }
  238. }
  239. }
  240. }
  241. // MARK: -
  242. @objc func synchronizeOffline(account: String) {
  243. // Synchronize Offline Directory
  244. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "serverUrl", ascending: true) {
  245. for directory: tableDirectory in directories {
  246. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(directory.ocId) else {
  247. continue
  248. }
  249. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadFile)
  250. }
  251. }
  252. // Synchronize Offline Files
  253. let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "fileName", ascending: true)
  254. for file: tableLocalFile in files {
  255. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(file.ocId) else {
  256. continue
  257. }
  258. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadFile)
  259. }
  260. }
  261. }