DashboardData.swift 13 KB

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