DashboardData.swift 13 KB

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