NCService.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 NextcloudKit
  25. import RealmSwift
  26. class NCService: NSObject {
  27. let utilityFileSystem = NCUtilityFileSystem()
  28. let database = NCManageDatabase.shared
  29. // MARK: -
  30. public func startRequestServicesServer(account: String, controller: NCMainTabBarController?) {
  31. guard !account.isEmpty, UIApplication.shared.applicationState == .active else { return }
  32. Task(priority: .background) {
  33. self.database.clearAllAvatarLoaded()
  34. NCPushNotification.shared.pushNotification()
  35. addInternalTypeIdentifier(account: account)
  36. let result = await requestServerStatus(account: account, controller: controller)
  37. if result {
  38. requestServerCapabilities(account: account)
  39. getAvatar(account: account)
  40. NCNetworkingE2EE().unlockAll(account: account)
  41. sendClientDiagnosticsRemoteOperation(account: account)
  42. synchronize(account: account)
  43. }
  44. }
  45. }
  46. // MARK: -
  47. func addInternalTypeIdentifier(account: String) {
  48. NextcloudKit.shared.nkCommonInstance.clearInternalTypeIdentifier(account: account)
  49. // txt
  50. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/plain", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown", account: account)
  51. // html
  52. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/html", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown", account: account)
  53. // markdown
  54. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "net.daringfireball.markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown", account: account)
  55. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/x-markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown", account: account)
  56. // document: text
  57. 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", account: account)
  58. 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", account: account)
  59. 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", account: account)
  60. 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", account: account)
  61. // document: sheet
  62. 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", account: account)
  63. 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", account: account)
  64. 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", account: account)
  65. 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", account: account)
  66. // document: presentation
  67. 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", account: account)
  68. 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", account: account)
  69. 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", account: account)
  70. 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", account: account)
  71. }
  72. // MARK: -
  73. private func requestServerStatus(account: String, controller: NCMainTabBarController?) async -> Bool {
  74. let serverUrl = NCSession.shared.getSession(account: account).urlBase
  75. switch await NCNetworking.shared.getServerStatus(serverUrl: serverUrl, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) {
  76. case .success(let serverInfo):
  77. if serverInfo.maintenance {
  78. return false
  79. } else if serverInfo.productName.lowercased().contains("owncloud") {
  80. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_warning_owncloud_")
  81. NCContentPresenter().showWarning(error: error, priority: .max)
  82. return false
  83. } else if serverInfo.versionMajor <= NCGlobal.shared.nextcloud_unsupported_version {
  84. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_warning_unsupported_")
  85. NCContentPresenter().showWarning(error: error, priority: .max)
  86. }
  87. case .failure:
  88. return false
  89. }
  90. let resultUserProfile = await NCNetworking.shared.getUserProfile(account: account, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue))
  91. if resultUserProfile.error == .success, let userProfile = resultUserProfile.userProfile {
  92. self.database.setAccountUserProfile(account: resultUserProfile.account, userProfile: userProfile)
  93. return true
  94. } else if resultUserProfile.error.errorCode == NCGlobal.shared.errorUnauthorized401 || resultUserProfile.error.errorCode == NCGlobal.shared.errorUnauthorized997 {
  95. /// Ops the server has Unauthorized, cancel allTask and go to in CheckRemoteUser
  96. NCNetworking.shared.cancelAllTask()
  97. ///
  98. DispatchQueue.main.async {
  99. if UIApplication.shared.applicationState == .active && NCNetworking.shared.isOnline {
  100. NextcloudKit.shared.nkCommonInstance.writeLog("[ERROR] The server has response with Unauthorized go checkRemoteUser \(resultUserProfile.error.errorCode)")
  101. NCNetworkingCheckRemoteUser().checkRemoteUser(account: resultUserProfile.account, controller: controller, error: resultUserProfile.error)
  102. }
  103. }
  104. return false
  105. } else {
  106. NCContentPresenter().showError(error: resultUserProfile.error, priority: .max)
  107. return false
  108. }
  109. }
  110. func synchronize(account: String) {
  111. NextcloudKit.shared.listingFavorites(showHiddenFiles: NCKeychain().showHiddenFiles,
  112. account: account,
  113. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in
  114. guard error == .success, let files else { return }
  115. self.database.convertFilesToMetadatas(files, useFirstAsMetadataFolder: false) { _, metadatas in
  116. self.database.updateMetadatasFavorite(account: account, metadatas: metadatas)
  117. }
  118. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Synchronize Favorite")
  119. self.synchronizeOffline(account: account)
  120. }
  121. }
  122. func getAvatar(account: String) {
  123. let session = NCSession.shared.getSession(account: account)
  124. let fileName = NCSession.shared.getFileName(urlBase: session.urlBase, user: session.user)
  125. let etag = self.database.getTableAvatar(fileName: fileName)?.etag
  126. NextcloudKit.shared.downloadAvatar(user: session.userId,
  127. fileNameLocalPath: utilityFileSystem.directoryUserData + "/" + fileName,
  128. sizeImage: NCGlobal.shared.avatarSize,
  129. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  130. etag: etag,
  131. account: account,
  132. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, _, _, etag, _, error in
  133. if let etag = etag, error == .success {
  134. self.database.addAvatar(fileName: fileName, etag: etag)
  135. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  136. self.database.setAvatarLoaded(fileName: fileName)
  137. }
  138. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadAvatar, userInfo: ["error": error])
  139. }
  140. }
  141. private func requestServerCapabilities(account: String) {
  142. NextcloudKit.shared.getCapabilities(account: account, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, presponseData, error in
  143. guard error == .success, let data = presponseData?.data else { return }
  144. data.printJson()
  145. if NCNetworking.shared.isResponseDataChanged(account: account, responseData: presponseData) {
  146. self.database.addCapabilitiesJSon(data, account: account)
  147. }
  148. guard let capability = self.database.setCapabilities(account: account, data: data) else { return }
  149. // Theming
  150. if NCBrandColor.shared.settingThemingColor(account: account) {
  151. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterChangeTheming, userInfo: ["account": account])
  152. }
  153. // Text direct editor detail
  154. if capability.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion18 {
  155. let options = NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  156. NextcloudKit.shared.NCTextObtainEditorDetails(account: account, options: options) { account, editors, creators, _, error in
  157. if error == .success {
  158. self.database.addDirectEditing(account: account, editors: editors, creators: creators)
  159. }
  160. }
  161. }
  162. // External file Server
  163. if capability.capabilityExternalSites {
  164. NextcloudKit.shared.getExternalSite(account: account, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, externalSites, _, error in
  165. if error == .success {
  166. self.database.deleteExternalSites(account: account)
  167. for externalSite in externalSites {
  168. self.database.addExternalSites(externalSite, account: account)
  169. }
  170. }
  171. }
  172. } else {
  173. self.database.deleteExternalSites(account: account)
  174. }
  175. // User Status
  176. if capability.capabilityUserStatusEnabled {
  177. NextcloudKit.shared.getUserStatus(account: account, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, clearAt, icon, message, messageId, messageIsPredefined, status, statusIsUserDefined, _, _, error in
  178. if error == .success {
  179. self.database.setAccountUserStatus(userStatusClearAt: clearAt, userStatusIcon: icon, userStatusMessage: message, userStatusMessageId: messageId, userStatusMessageIsPredefined: messageIsPredefined, userStatusStatus: status, userStatusStatusIsUserDefined: statusIsUserDefined, account: account)
  180. }
  181. }
  182. }
  183. // Added UTI for Collabora
  184. capability.capabilityRichDocumentsMimetypes.forEach { mimeType in
  185. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: mimeType, classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document", account: account)
  186. }
  187. // Added UTI for ONLYOFFICE & Text
  188. if let directEditingCreators = self.database.getDirectEditingCreators(account: account) {
  189. for directEditing in directEditingCreators {
  190. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: directEditing.mimetype, classFile: NKCommon.TypeClassFile.document.rawValue, editor: directEditing.editor, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document", account: account)
  191. }
  192. }
  193. }
  194. }
  195. // MARK: -
  196. @objc func synchronizeOffline(account: String) {
  197. // Synchronize Directory
  198. Task {
  199. if let directories = self.database.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "serverUrl", ascending: true) {
  200. for directory: tableDirectory in directories {
  201. await NCNetworking.shared.synchronization(account: account, serverUrl: directory.serverUrl, add: false)
  202. }
  203. }
  204. }
  205. // Synchronize Files
  206. let files = self.database.getTableLocalFiles(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "fileName", ascending: true)
  207. for file: tableLocalFile in files {
  208. guard let metadata = self.database.getMetadataFromOcId(file.ocId) else { continue }
  209. if NCNetworking.shared.isSynchronizable(ocId: metadata.ocId, fileName: metadata.fileName, etag: metadata.etag) {
  210. self.database.setMetadatasSessionInWaitDownload(metadatas: [metadata],
  211. session: NCNetworking.shared.sessionDownloadBackground,
  212. selector: NCGlobal.shared.selectorSynchronizationOffline)
  213. }
  214. }
  215. }
  216. // MARK: -
  217. func sendClientDiagnosticsRemoteOperation(account: String) {
  218. guard NCCapabilities.shared.getCapabilities(account: account).capabilitySecurityGuardDiagnostics,
  219. self.database.existsDiagnostics(account: account) else {
  220. return
  221. }
  222. struct Issues: Codable {
  223. struct SyncConflicts: Codable {
  224. var count: Int?
  225. var oldest: TimeInterval?
  226. }
  227. struct VirusDetected: Codable {
  228. var count: Int?
  229. var oldest: TimeInterval?
  230. }
  231. struct E2EError: Codable {
  232. var count: Int?
  233. var oldest: TimeInterval?
  234. }
  235. struct Problem: Codable {
  236. struct Error: Codable {
  237. var count: Int
  238. var oldest: TimeInterval
  239. }
  240. var forbidden: Error? // NCGlobal.shared.diagnosticProblemsForbidden
  241. var badResponse: Error? // NCGlobal.shared.diagnosticProblemsBadResponse
  242. var uploadServerError: Error? // NCGlobal.shared.diagnosticProblemsUploadServerError
  243. }
  244. var syncConflicts: SyncConflicts
  245. var virusDetected: VirusDetected
  246. var e2eeErrors: E2EError
  247. var problems: Problem?
  248. enum CodingKeys: String, CodingKey {
  249. case syncConflicts = "sync_conflicts"
  250. case virusDetected = "virus_detected"
  251. case e2eeErrors = "e2ee_errors"
  252. case problems
  253. }
  254. }
  255. var ids: [ObjectId] = []
  256. var syncConflicts: Issues.SyncConflicts = Issues.SyncConflicts()
  257. var virusDetected: Issues.VirusDetected = Issues.VirusDetected()
  258. var e2eeErrors: Issues.E2EError = Issues.E2EError()
  259. var problems: Issues.Problem? = Issues.Problem()
  260. var problemForbidden: Issues.Problem.Error?
  261. var problemBadResponse: Issues.Problem.Error?
  262. var problemUploadServerError: Issues.Problem.Error?
  263. if let result = self.database.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueSyncConflicts)?.first {
  264. syncConflicts = Issues.SyncConflicts(count: result.counter, oldest: result.oldest)
  265. ids.append(result.id)
  266. }
  267. if let result = self.database.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueVirusDetected)?.first {
  268. virusDetected = Issues.VirusDetected(count: result.counter, oldest: result.oldest)
  269. ids.append(result.id)
  270. }
  271. if let result = self.database.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueE2eeErrors)?.first {
  272. e2eeErrors = Issues.E2EError(count: result.counter, oldest: result.oldest)
  273. ids.append(result.id)
  274. }
  275. if let results = self.database.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueProblems) {
  276. for result in results {
  277. switch result.error {
  278. case NCGlobal.shared.diagnosticProblemsForbidden:
  279. if result.counter >= 1 {
  280. problemForbidden = Issues.Problem.Error(count: result.counter, oldest: result.oldest)
  281. ids.append(result.id)
  282. }
  283. case NCGlobal.shared.diagnosticProblemsBadResponse:
  284. if result.counter >= 2 {
  285. problemBadResponse = Issues.Problem.Error(count: result.counter, oldest: result.oldest)
  286. ids.append(result.id)
  287. }
  288. case NCGlobal.shared.diagnosticProblemsUploadServerError:
  289. if result.counter >= 1 {
  290. problemUploadServerError = Issues.Problem.Error(count: result.counter, oldest: result.oldest)
  291. ids.append(result.id)
  292. }
  293. default:
  294. break
  295. }
  296. }
  297. problems = Issues.Problem(forbidden: problemForbidden, badResponse: problemBadResponse, uploadServerError: problemUploadServerError)
  298. }
  299. do {
  300. let issues = Issues(syncConflicts: syncConflicts, virusDetected: virusDetected, e2eeErrors: e2eeErrors, problems: problems)
  301. let data = try JSONEncoder().encode(issues)
  302. data.printJson()
  303. NextcloudKit.shared.sendClientDiagnosticsRemoteOperation(data: data, account: account, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, _, error in
  304. if error == .success {
  305. self.database.deleteDiagnostics(account: account, ids: ids)
  306. }
  307. }
  308. } catch {
  309. print("Error: \(error.localizedDescription)")
  310. }
  311. }
  312. }