NCService.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. let appDelegate = (UIApplication.shared.delegate as? AppDelegate)!
  29. let utilityFileSystem = NCUtilityFileSystem()
  30. // MARK: -
  31. @objc public func startRequestServicesServer() {
  32. guard !appDelegate.account.isEmpty, UIApplication.shared.applicationState != .background else {
  33. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Service not start request service server with the application in background")
  34. return
  35. }
  36. let account = appDelegate.account
  37. NCManageDatabase.shared.clearAllAvatarLoaded()
  38. NCPushNotification.shared().pushNotification()
  39. Task {
  40. addInternalTypeIdentifier()
  41. let result = await requestServerStatus()
  42. if result {
  43. requestServerCapabilities()
  44. getAvatar()
  45. requestDashboardWidget()
  46. NCNetworkingE2EE().unlockAll(account: account)
  47. sendClientDiagnosticsRemoteOperation(account: account)
  48. synchronize()
  49. }
  50. }
  51. }
  52. // MARK: -
  53. func addInternalTypeIdentifier() {
  54. // txt
  55. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/plain", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  56. // html
  57. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/html", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  58. // markdown
  59. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "net.daringfireball.markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  60. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: "text/x-markdown", classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorText, iconName: NKCommon.TypeIconFile.document.rawValue, name: "markdown")
  61. // document: text
  62. 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")
  63. 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")
  64. 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")
  65. 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")
  66. // document: sheet
  67. 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")
  68. 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")
  69. 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")
  70. 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")
  71. // document: presentation
  72. 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")
  73. 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")
  74. 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")
  75. 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")
  76. }
  77. // MARK: -
  78. private func requestServerStatus() async -> Bool {
  79. switch await NextcloudKit.shared.getServerStatus(serverUrl: appDelegate.urlBase, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) {
  80. case .success(let serverInfo):
  81. if serverInfo.maintenance {
  82. let error = NKError(errorCode: NCGlobal.shared.errorInternalError, errorDescription: "_maintenance_mode_")
  83. NCContentPresenter().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().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().showWarning(error: error, priority: .max)
  92. }
  93. case .failure:
  94. return false
  95. }
  96. let resultUserProfile = await NextcloudKit.shared.getUserProfile(options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue))
  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().showError(error: resultUserProfile.error, priority: .max)
  111. return false
  112. }
  113. }
  114. func synchronize() {
  115. NextcloudKit.shared.listingFavorites(showHiddenFiles: NCKeychain().showHiddenFiles,
  116. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, files, _, error in
  117. guard error == .success else { return }
  118. NCManageDatabase.shared.convertFilesToMetadatas(files, useFirstAsMetadataFolder: false) { _, metadatas in
  119. NCManageDatabase.shared.updateMetadatasFavorite(account: account, metadatas: metadatas)
  120. }
  121. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Synchronize Favorite")
  122. self.synchronizeOffline(account: account)
  123. }
  124. }
  125. func getAvatar() {
  126. let fileName = appDelegate.userBaseUrl + "-" + self.appDelegate.user + ".png"
  127. let fileNameLocalPath = utilityFileSystem.directoryUserData + "/" + fileName
  128. let etag = NCManageDatabase.shared.getTableAvatar(fileName: fileName)?.etag
  129. NextcloudKit.shared.downloadAvatar(user: appDelegate.userId,
  130. fileNameLocalPath: fileNameLocalPath,
  131. sizeImage: NCGlobal.shared.avatarSize,
  132. avatarSizeRounded: NCGlobal.shared.avatarSizeRounded,
  133. etag: etag,
  134. options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, _, _, etag, error in
  135. if let etag = etag, error == .success {
  136. NCManageDatabase.shared.addAvatar(fileName: fileName, etag: etag)
  137. } else if error.errorCode == NCGlobal.shared.errorNotModified {
  138. NCManageDatabase.shared.setAvatarLoaded(fileName: fileName)
  139. }
  140. NotificationCenter.default.postOnMainThread(name: NCGlobal.shared.notificationCenterReloadAvatar, userInfo: ["error": error])
  141. }
  142. }
  143. private func requestServerCapabilities() {
  144. guard !appDelegate.account.isEmpty else { return }
  145. NextcloudKit.shared.getCapabilities(options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, data, error in
  146. guard error == .success, let data = data else {
  147. NCBrandColor.shared.settingThemingColor(account: account)
  148. NCImageCache.shared.createImagesBrandCache()
  149. return
  150. }
  151. data.printJson()
  152. NCManageDatabase.shared.addCapabilitiesJSon(data, account: account)
  153. NCManageDatabase.shared.setCapabilities(account: account, data: data)
  154. // Theming
  155. if NCGlobal.shared.capabilityThemingColor != NCBrandColor.shared.themingColor || NCGlobal.shared.capabilityThemingColorElement != NCBrandColor.shared.themingColorElement || NCGlobal.shared.capabilityThemingColorText != NCBrandColor.shared.themingColorText {
  156. NCBrandColor.shared.settingThemingColor(account: account)
  157. NCImageCache.shared.createImagesBrandCache()
  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, _, 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: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, externalSites, _, 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. if NCGlobal.shared.capabilityUserStatusEnabled {
  183. NextcloudKit.shared.getUserStatus(options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, clearAt, icon, message, messageId, messageIsPredefined, status, statusIsUserDefined, userId, _, error in
  184. if error == .success && account == self.appDelegate.account && userId == self.appDelegate.userId {
  185. NCManageDatabase.shared.setAccountUserStatus(userStatusClearAt: clearAt, userStatusIcon: icon, userStatusMessage: message, userStatusMessageId: messageId, userStatusMessageIsPredefined: messageIsPredefined, userStatusStatus: status, userStatusStatusIsUserDefined: statusIsUserDefined, account: account)
  186. }
  187. }
  188. }
  189. // Added UTI for Collabora
  190. NCGlobal.shared.capabilityRichDocumentsMimetypes.forEach { mimeType in
  191. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: mimeType, classFile: NKCommon.TypeClassFile.document.rawValue, editor: NCGlobal.shared.editorCollabora, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  192. }
  193. // Added UTI for ONLYOFFICE & Text
  194. if let directEditingCreators = NCManageDatabase.shared.getDirectEditingCreators(account: account) {
  195. for directEditing in directEditingCreators {
  196. NextcloudKit.shared.nkCommonInstance.addInternalTypeIdentifier(typeIdentifier: directEditing.mimetype, classFile: NKCommon.TypeClassFile.document.rawValue, editor: directEditing.editor, iconName: NKCommon.TypeIconFile.document.rawValue, name: "document")
  197. }
  198. }
  199. }
  200. }
  201. // MARK: -
  202. private func requestDashboardWidget() {
  203. @Sendable func convertDataToImage(data: Data?, size: CGSize, fileNameToWrite: String?) {
  204. guard let data = data else { return }
  205. var imageData: UIImage?
  206. if let image = UIImage(data: data), let image = image.resizeImage(size: size) {
  207. imageData = image
  208. } else if let image = SVGKImage(data: data) {
  209. image.size = size
  210. imageData = image.uiImage
  211. } else {
  212. print("error")
  213. }
  214. if let fileName = fileNameToWrite, let image = imageData {
  215. do {
  216. let fileNamePath = utilityFileSystem.directoryUserData + "/" + fileName + ".png"
  217. try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  218. } catch { }
  219. }
  220. }
  221. NextcloudKit.shared.getDashboardWidget(options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { account, dashboardWidgets, data, error in
  222. Task {
  223. if error == .success, let dashboardWidgets = dashboardWidgets {
  224. NCManageDatabase.shared.addDashboardWidget(account: account, dashboardWidgets: dashboardWidgets)
  225. for widget in dashboardWidgets {
  226. if let url = URL(string: widget.iconUrl), let fileName = widget.iconClass {
  227. let (_, data, error) = await NextcloudKit.shared.getPreview(url: url)
  228. if error == .success {
  229. convertDataToImage(data: data, size: CGSize(width: 256, height: 256), fileNameToWrite: fileName)
  230. }
  231. }
  232. }
  233. }
  234. }
  235. }
  236. }
  237. // MARK: -
  238. @objc func synchronizeOffline(account: String) {
  239. // Synchronize Directory
  240. Task {
  241. if let directories = NCManageDatabase.shared.getTablesDirectory(predicate: NSPredicate(format: "account == %@ AND offline == true", account), sorted: "serverUrl", ascending: true) {
  242. for directory: tableDirectory in directories {
  243. await NCNetworking.shared.synchronization(account: account, serverUrl: directory.serverUrl, add: false)
  244. }
  245. }
  246. }
  247. // Synchronize 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 { continue }
  251. if NCNetworking.shared.isSynchronizable(ocId: metadata.ocId, fileName: metadata.fileName, etag: metadata.etag) {
  252. NCManageDatabase.shared.setMetadatasSessionInWaitDownload(metadatas: [metadata],
  253. session: NCNetworking.shared.sessionDownloadBackground,
  254. selector: NCGlobal.shared.selectorSynchronizationOffline)
  255. }
  256. }
  257. }
  258. // MARK: -
  259. func sendClientDiagnosticsRemoteOperation(account: String) {
  260. guard NCGlobal.shared.capabilitySecurityGuardDiagnostics,
  261. NCManageDatabase.shared.existsDiagnostics(account: account) else { return }
  262. struct Issues: Codable {
  263. struct SyncConflicts: Codable {
  264. var count: Int?
  265. var oldest: TimeInterval?
  266. }
  267. struct VirusDetected: Codable {
  268. var count: Int?
  269. var oldest: TimeInterval?
  270. }
  271. struct E2EError: Codable {
  272. var count: Int?
  273. var oldest: TimeInterval?
  274. }
  275. struct Problem: Codable {
  276. struct Error: Codable {
  277. var count: Int
  278. var oldest: TimeInterval
  279. }
  280. var forbidden: Error? // NCGlobal.shared.diagnosticProblemsForbidden
  281. var badResponse: Error? // NCGlobal.shared.diagnosticProblemsBadResponse
  282. var uploadServerError: Error? // NCGlobal.shared.diagnosticProblemsUploadServerError
  283. }
  284. var syncConflicts: SyncConflicts
  285. var virusDetected: VirusDetected
  286. var e2eeErrors: E2EError
  287. var problems: Problem?
  288. enum CodingKeys: String, CodingKey {
  289. case syncConflicts = "sync_conflicts"
  290. case virusDetected = "virus_detected"
  291. case e2eeErrors = "e2ee_errors"
  292. case problems
  293. }
  294. }
  295. var ids: [ObjectId] = []
  296. var syncConflicts: Issues.SyncConflicts = Issues.SyncConflicts()
  297. var virusDetected: Issues.VirusDetected = Issues.VirusDetected()
  298. var e2eeErrors: Issues.E2EError = Issues.E2EError()
  299. var problems: Issues.Problem? = Issues.Problem()
  300. var problemForbidden: Issues.Problem.Error?
  301. var problemBadResponse: Issues.Problem.Error?
  302. var problemUploadServerError: Issues.Problem.Error?
  303. if let result = NCManageDatabase.shared.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueSyncConflicts)?.first {
  304. syncConflicts = Issues.SyncConflicts(count: result.counter, oldest: result.oldest)
  305. ids.append(result.id)
  306. }
  307. if let result = NCManageDatabase.shared.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueVirusDetected)?.first {
  308. virusDetected = Issues.VirusDetected(count: result.counter, oldest: result.oldest)
  309. ids.append(result.id)
  310. }
  311. if let result = NCManageDatabase.shared.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueE2eeErrors)?.first {
  312. e2eeErrors = Issues.E2EError(count: result.counter, oldest: result.oldest)
  313. ids.append(result.id)
  314. }
  315. if let results = NCManageDatabase.shared.getDiagnostics(account: account, issue: NCGlobal.shared.diagnosticIssueProblems) {
  316. for result in results {
  317. switch result.error {
  318. case NCGlobal.shared.diagnosticProblemsForbidden:
  319. if result.counter >= 1 {
  320. problemForbidden = Issues.Problem.Error(count: result.counter, oldest: result.oldest)
  321. ids.append(result.id)
  322. }
  323. case NCGlobal.shared.diagnosticProblemsBadResponse:
  324. if result.counter >= 2 {
  325. problemBadResponse = Issues.Problem.Error(count: result.counter, oldest: result.oldest)
  326. ids.append(result.id)
  327. }
  328. case NCGlobal.shared.diagnosticProblemsUploadServerError:
  329. if result.counter >= 1 {
  330. problemUploadServerError = Issues.Problem.Error(count: result.counter, oldest: result.oldest)
  331. ids.append(result.id)
  332. }
  333. default:
  334. break
  335. }
  336. }
  337. problems = Issues.Problem(forbidden: problemForbidden, badResponse: problemBadResponse, uploadServerError: problemUploadServerError)
  338. }
  339. do {
  340. let issues = Issues(syncConflicts: syncConflicts, virusDetected: virusDetected, e2eeErrors: e2eeErrors, problems: problems)
  341. let data = try JSONEncoder().encode(issues)
  342. data.printJson()
  343. NextcloudKit.shared.sendClientDiagnosticsRemoteOperation(data: data, options: NKRequestOptions(queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)) { _, error in
  344. if error == .success {
  345. NCManageDatabase.shared.deleteDiagnostics(account: account, ids: ids)
  346. }
  347. }
  348. } catch {
  349. print("Error: \(error.localizedDescription)")
  350. }
  351. }
  352. }