NCService.swift 21 KB

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