DashboardData.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. //
  2. // DashboardData.swift
  3. // Widget
  4. //
  5. // Created by Marino Faggiana on 20/08/22.
  6. // Copyright © 2022 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 WidgetKit
  24. import NextcloudKit
  25. import RealmSwift
  26. import SVGKit
  27. struct DashboardDataEntry: TimelineEntry {
  28. let date: Date
  29. let datas: [DashboardData]
  30. let dashboard: tableDashboardWidget?
  31. let buttons: [tableDashboardWidgetButton]?
  32. let isPlaceholder: Bool
  33. let titleImage: UIImage
  34. let title: String
  35. let footerImage: String
  36. let footerText: String
  37. }
  38. struct DashboardData: Identifiable, Hashable {
  39. let id: Int
  40. let title: String
  41. let subTitle: String
  42. let link: URL
  43. let icon: UIImage
  44. let template: Bool
  45. let avatar: Bool
  46. }
  47. struct DashboardDataButton: Hashable {
  48. let type: String
  49. let Text: String
  50. let link: String
  51. }
  52. let dashboardDatasTest: [DashboardData] = [
  53. .init(id: 0, title: "title0", subTitle: "subTitle-description0", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  54. .init(id: 1, title: "title1", subTitle: "subTitle-description1", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  55. .init(id: 2, title: "title2", subTitle: "subTitle-description2", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  56. .init(id: 3, title: "title3", subTitle: "subTitle-description3", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  57. .init(id: 4, title: "title4", subTitle: "subTitle-description4", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  58. .init(id: 5, title: "title5", subTitle: "subTitle-description5", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  59. .init(id: 6, title: "title6", subTitle: "subTitle-description6", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  60. .init(id: 7, title: "title7", subTitle: "subTitle-description7", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  61. .init(id: 8, title: "title8", subTitle: "subTitle-description8", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false),
  62. .init(id: 9, title: "title9", subTitle: "subTitle-description9", link: URL(string: "https://nextcloud.com/")!, icon: UIImage(named: "widget")!, template: true, avatar: false)
  63. ]
  64. func getDashboardItems(displaySize: CGSize, withButton: Bool) -> Int {
  65. if withButton {
  66. let height = Int((displaySize.height - 85) / 50)
  67. return height
  68. } else {
  69. let height = Int((displaySize.height - 60) / 50)
  70. return height
  71. }
  72. }
  73. func getDashboardDataEntry(intent: Applications?, isPreview: Bool, displaySize: CGSize, completion: @escaping (_ entry: DashboardDataEntry) -> Void) {
  74. let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: false)
  75. let datasPlaceholder = Array(dashboardDatasTest[0...dashboardItems - 1])
  76. if isPreview {
  77. return completion(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, titleImage: UIImage(named: "widget")!, title: "Dashboard", footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " dashboard"))
  78. }
  79. guard let account = NCManageDatabase.shared.getActiveAccount() else {
  80. return completion(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, titleImage: UIImage(named: "widget")!, title: "Dashboard", footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", comment: "")))
  81. }
  82. // Default widget
  83. let result = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).first
  84. let id: String = intent?.identifier ?? (result?.id ?? "recommendations")
  85. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  86. guard serverVersionMajor >= NCGlobal.shared.nextcloudVersion25 else {
  87. return completion(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: nil, buttons: nil, isPlaceholder: true, titleImage: UIImage(named: "widget")!, title: "Dashboard", footerImage: "xmark.icloud", footerText: NSLocalizedString("_widget_available_nc25_", comment: "")))
  88. }
  89. // NETWORKING
  90. let password = CCUtility.getPassword(account.account)!
  91. NKCommon.shared.setup(
  92. account: account.account,
  93. user: account.user,
  94. userId: account.userId,
  95. password: password,
  96. urlBase: account.urlBase,
  97. userAgent: CCUtility.getUserAgent(),
  98. nextcloudVersion: 0,
  99. delegate: NCNetworking.shared)
  100. // LOG
  101. let levelLog = CCUtility.getLogLevel()
  102. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  103. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  104. NKCommon.shared.levelLog = levelLog
  105. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  106. NKCommon.shared.pathLog = pathDirectoryGroup
  107. }
  108. if isSimulatorOrTestFlight {
  109. NKCommon.shared.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) dashboard widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  110. } else {
  111. NKCommon.shared.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) dashboard widget session with level \(levelLog) " + versionNextcloudiOS)
  112. }
  113. let (tableDashboard, tableButton) = NCManageDatabase.shared.getDashboardWidget(account: account.account, id: id)
  114. let existsButton = (tableButton?.isEmpty ?? true) ? false : true
  115. let options = NKRequestOptions(timeout: 15, queue: NKCommon.shared.backgroundQueue)
  116. let title = tableDashboard?.title ?? id
  117. var imagetmp = UIImage(named: "widget")!
  118. if let fileName = tableDashboard?.iconClass {
  119. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  120. if let image = UIImage(contentsOfFile: fileNamePath) {
  121. imagetmp = image.withTintColor(.label, renderingMode: .alwaysOriginal)
  122. }
  123. }
  124. let titleImage = imagetmp
  125. NextcloudKit.shared.getDashboardWidgetsApplication(id, options: options) { account, results, data, error in
  126. Task {
  127. var datas = [DashboardData]()
  128. var numberItems = 0
  129. if let results = results {
  130. for result in results {
  131. if let items = result.items {
  132. numberItems = result.items?.count ?? 0
  133. var counter: Int = 0
  134. let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: existsButton)
  135. for item in items {
  136. counter += 1
  137. let title = item.title ?? ""
  138. let subtitle = item.subtitle ?? ""
  139. var link = URL(string: "https://")!
  140. if let entryLink = item.link, let url = URL(string: entryLink) { link = url }
  141. var icon = UIImage(named: "file")!
  142. var iconFileName: String?
  143. var template: Bool = false
  144. var avatar: Bool = false
  145. if let iconUrl = item.iconUrl, let url = URL(string: iconUrl) {
  146. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  147. let path = (urlComponents.path as NSString)
  148. let pathComponents = path.components(separatedBy: "/")
  149. let queryItems = urlComponents.queryItems
  150. if (pathComponents.last as? NSString)?.pathExtension.lowercased() == "svg" {
  151. template = true
  152. }
  153. if let item = CCUtility.value(forKey: "fileId", fromQueryItems: queryItems) {
  154. iconFileName = item
  155. } else if pathComponents.contains("avatar") {
  156. iconFileName = pathComponents[pathComponents.count-2]
  157. avatar = true
  158. } else {
  159. iconFileName = ((path.lastPathComponent) as NSString).deletingPathExtension
  160. }
  161. }
  162. do {
  163. if let fileName = iconFileName {
  164. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  165. if FileManager().fileExists(atPath: fileNamePath), let image = UIImage(contentsOfFile: fileNamePath) {
  166. icon = image
  167. } else {
  168. let (_, data) = try await NextcloudKit.shared.getPreview(url: url)
  169. if let image = NCUtility.shared.convertDataToImage(data: data, size: CGSize(width: 256, height: 256), fileNameToWrite: fileName) {
  170. icon = image
  171. }
  172. }
  173. }
  174. } catch {
  175. print(error)
  176. }
  177. }
  178. let data = DashboardData(id: counter, title: title, subTitle: subtitle, link: link, icon: icon, template: template, avatar: avatar)
  179. datas.append(data)
  180. if datas.count == dashboardItems { break }
  181. }
  182. }
  183. }
  184. }
  185. var buttons = tableButton
  186. if numberItems == datas.count, let tableButton = tableButton, tableButton.contains(where: { $0.type == "more"}) {
  187. buttons = tableButton.filter(({ $0.type != "more" }))
  188. }
  189. if error != .success {
  190. completion(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, titleImage: titleImage, title: title, footerImage: "xmark.icloud", footerText: error.errorDescription))
  191. } else if datas.isEmpty {
  192. completion(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: NSLocalizedString("_no_data_available_", comment: "")))
  193. } else {
  194. completion(DashboardDataEntry(date: Date(), datas: datas, dashboard: tableDashboard, buttons: buttons, isPlaceholder: false, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " dashboard"))
  195. }
  196. }
  197. }
  198. }