NCService.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. class NCService: NSObject {
  27. @objc static let shared: NCService = {
  28. let instance = NCService()
  29. return instance
  30. }()
  31. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  32. // MARK: -
  33. @objc public func startRequestServicesServer() {
  34. NCManageDatabase.shared.clearAllAvatarLoaded()
  35. guard !appDelegate.account.isEmpty else { return }
  36. let account = appDelegate.account
  37. NCPushNotification.shared().pushNotification()
  38. Task {
  39. addInternalTypeIdentifier()
  40. let result = await requestServerStatus()
  41. if result {
  42. synchronize()
  43. getAvatar()
  44. requestServerCapabilities()
  45. requestDashboardWidget()
  46. NCNetworkingE2EE().unlockAll(account: account)
  47. NCNetworkingProcessUpload.shared.verifyUploadZombie()
  48. }
  49. }
  50. }
  51. // MARK: -
  52. func addInternalTypeIdentifier() {
  53. // txt
  54. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/plain", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  55. // html
  56. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/html", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  57. // markdown
  58. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "net.daringfireball.markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  59. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/x-markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  60. // document: text
  61. 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")
  62. 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")
  63. 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")
  64. 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")
  65. // document: sheet
  66. 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")
  67. 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")
  68. 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")
  69. 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")
  70. // document: presentation
  71. 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")
  72. 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")
  73. 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")
  74. 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")
  75. }
  76. // MARK: -
  77. private func requestServerStatus() async -> Bool {
  78. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  79. switch await NextcloudKit.shared.getServerStatus(serverUrl: appDelegate.urlBase, options: options) {
  80. case .success(let serverInfo):
  81. if serverInfo.maintenance {
  82. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_maintenance_mode_")
  83. NCContentPresenter.shared.showWarning(error: error, priority: .max)
  84. return false
  85. } else if serverInfo.productName.lowercased().contains("owncloud") {
  86. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_warning_owncloud_")
  87. NCContentPresenter.shared.showWarning(error: error, priority: .max)
  88. return false
  89. } else if serverInfo.versionMajor <= NCGlobal.shared.nextcloud_unsupported_version {
  90. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_warning_unsupported_")
  91. NCContentPresenter.shared.showWarning(error: error, priority: .max)
  92. }
  93. case .failure:
  94. return false
  95. }
  96. let resultUserProfile = await NextcloudKit.shared.getUserProfile(options: options)
  97. if resultUserProfile.error == .success, let userProfile = resultUserProfile.userProfile {
  98. NCManageDatabase.shared.setAccountUserProfile(account: resultUserProfile.account, userProfile: userProfile)
  99. return true
  100. } else if resultUserProfile.error.errorCode == NCGlobal.shared.errorUnauthorized401 || resultUserProfile.error.errorCode == NCGlobal.shared.errorUnauthorized997 {
  101. // Ops the server has Unauthorized
  102. DispatchQueue.main.async {
  103. if UIApplication.shared.applicationState == .active && NCNetworking.shared.networkReachability != NKCommon.TypeReachability.notReachable {
  104. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] The server has response with Unauthorized go checkRemoteUser \(resultUserProfile.error.errorCode)")
  105. NCNetworkingCheckRemoteUser().checkRemoteUser(account: resultUserProfile.account, error: resultUserProfile.error)
  106. }
  107. }
  108. return false
  109. } else {
  110. NCContentPresenter.shared.showError(error: resultUserProfile.error, priority: .max)
  111. return false
  112. }
  113. }
  114. func synchronize() {
  115. NCNetworking.shared.listingFavoritescompletion(selector: NCGlobal.shared.selectorReadFile) { _, _, _ in }
  116. self.synchronizeOffline(account: appDelegate.account)
  117. }
  118. func getAvatar() {
  119. let fileName = appDelegate.userBaseUrl + "-" + self.appDelegate.user + ".png"
  120. let fileNameLocalPath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  121. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  122. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  123. NextcloudKit.shared.downloadAvatar(user: appDelegate.userId, fileNameLocalPath: fileNameLocalPath, sizeImage: NCGlobal.shared.avatarSize, avatarSizeRounded: NCGlobal.shared.avatarSizeRounded, etag: etag, options: options) { _, _, _, etag, error in
  124. if let etag = etag, error == .success {
  125. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  126. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  127. NCManageDatabase.shared.setAvatarLoaded(fileName: fileName)
  128. }
  129. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadAvatar, userInfo: ["error":error])
  130. }
  131. }
  132. private func requestServerCapabilities() {
  133. guard !appDelegate.account.isEmpty else { return }
  134. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  135. NextcloudKit.shared.getCapabilities(options: options) { account, data, error in
  136. guard error == .success, let data = data else {
  137. NCBrandColor.shared.settingThemingColor(account: account)
  138. return
  139. }
  140. data.printJson()
  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. if !NCGlobal.shared.capabilityFileSharingApiEnabled && !NCGlobal.shared.capabilityFilesComments && NCGlobal.shared.capabilityActivity.isEmpty {
  153. self.appDelegate.disableSharesView = true
  154. } else {
  155. self.appDelegate.disableSharesView = false
  156. }
  157. // Text direct editor detail
  158. if NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion18 {
  159. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  160. NextcloudKit.shared.NCTextObtainEditorDetails(options: options) { account, editors, creators, _, error in
  161. if error == .success && account == self.appDelegate.account {
  162. NCManageDatabase.shared.addDirectEditing(account: account, editors: editors, creators: creators)
  163. }
  164. }
  165. }
  166. // External file Server
  167. if NCGlobal.shared.capabilityExternalSites {
  168. NextcloudKit.shared.getExternalSite(options: options) { account, externalSites, _, error in
  169. if error == .success && account == self.appDelegate.account {
  170. NCManageDatabase.shared.deleteExternalSites(account: account)
  171. for externalSite in externalSites {
  172. NCManageDatabase.shared.addExternalSites(externalSite, account: account)
  173. }
  174. }
  175. }
  176. } else {
  177. NCManageDatabase.shared.deleteExternalSites(account: account)
  178. }
  179. // User Status
  180. if NCGlobal.shared.capabilityUserStatusEnabled {
  181. NextcloudKit.shared.getUserStatus(options: options) { account, clearAt, icon, message, messageId, messageIsPredefined, status, statusIsUserDefined, userId, _, error in
  182. if error == .success && account == self.appDelegate.account && userId == self.appDelegate.userId {
  183. NCManageDatabase.shared.setAccountUserStatus(userStatusClearAt: clearAt, userStatusIcon: icon, userStatusMessage: message, userStatusMessageId: messageId, userStatusMessageIsPredefined: messageIsPredefined, userStatusStatus: status, userStatusStatusIsUserDefined: statusIsUserDefined, account: account)
  184. }
  185. }
  186. }
  187. // Added UTI for Collabora
  188. for mimeType in NCGlobal.shared.capabilityRichdocumentsMimetypes {
  189. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: mimeType, classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  190. }
  191. // Added UTI for ONLYOFFICE & Text
  192. if let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account) {
  193. for directEditing in directEditingCreators {
  194. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: directEditing.mimetype, classFile: NKCommon.TypeClassFile.document.rawValue, editor: directEditing.editor, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  195. }
  196. }
  197. }
  198. }
  199. // MARK: -
  200. private func requestDashboardWidget() {
  201. @Sendable func convertDataToImage(data: Data?, size: CGSize, fileNameToWrite: String?) {
  202. guard let data = data else { return }
  203. var imageData: UIImage?
  204. if let image = UIImage(data: data), let image = image.resizeImage(size: size) {
  205. imageData = image
  206. } else if let image = SVGKImage(data: data) {
  207. image.size = size
  208. imageData = image.uiImage
  209. } else {
  210. print("error")
  211. }
  212. if let fileName = fileNameToWrite, let image = imageData {
  213. do {
  214. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  215. try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  216. } catch { }
  217. }
  218. }
  219. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  220. NextcloudKit.shared.getDashboardWidget(options: options) { account, dashboardWidgets, data, error in
  221. Task {
  222. if error == .success, let dashboardWidgets = dashboardWidgets {
  223. NCManageDatabase.shared.addDashboardWidget(account: account, dashboardWidgets: dashboardWidgets)
  224. for widget in dashboardWidgets {
  225. if let url = URL(string: widget.iconUrl), let fileName = widget.iconClass {
  226. let (_, data, error) = await NextcloudKit.shared.getPreview(url: url)
  227. if error == .success {
  228. convertDataToImage(data: data, size: CGSize(width: 256, height: 256), fileNameToWrite: fileName)
  229. }
  230. }
  231. }
  232. }
  233. }
  234. }
  235. }
  236. // MARK: -
  237. @objc func synchronizeOffline(account: String) {
  238. // Synchronize Offline Directory
  239. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "serverUrl", ascending: true) {
  240. for directory: tableDirectory in directories {
  241. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(directory.ocId) else {
  242. continue
  243. }
  244. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadFile)
  245. }
  246. }
  247. // Synchronize Offline Files
  248. let files = NCManageDatabase.shared.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "fileName", ascending: true)
  249. for file: tableLocalFile in files {
  250. guard let metadata = NCManageDatabase.shared.getMetadataFromOcId(file.ocId) else {
  251. continue
  252. }
  253. NCOperationQueue.shared.synchronizationMetadata(metadata, selector: NCGlobal.shared.selectorDownloadFile)
  254. }
  255. }
  256. }