DashboardData.swift 15 KB

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