NCService.swift 19 KB

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