DashboardData.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 convertDataToImage(data: Data?, size: CGSize, fileNameToWrite: String?) -> UIImage? {
  77. guard let data = data else { return nil }
  78. var imageData: UIImage?
  79. if let image = UIImage(data: data), let image = image.resizeImage(size: size) {
  80. imageData = image
  81. } else if let image = SVGKImage(data: data) {
  82. image.size = size
  83. imageData = image.uiImage
  84. } else {
  85. print("error")
  86. }
  87. if let fileName = fileNameToWrite, let image = imageData {
  88. do {
  89. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  90. try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  91. } catch { }
  92. }
  93. return imageData
  94. }
  95. func getDashboardDataEntry(configuration: DashboardIntent?, isPreview: Bool, displaySize: CGSize, completion: @escaping (_ entry: DashboardDataEntry) -> Void) {
  96. let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: false)
  97. let datasPlaceholder = Array(dashboardDatasTest[0...dashboardItems - 1])
  98. var account: tableAccount?
  99. if isPreview {
  100. 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"))
  101. }
  102. let accountIdentifier: String = configuration?.accounts?.identifier ?? "active"
  103. if accountIdentifier == "active" {
  104. account = NCManageDatabase.shared.getActiveAccount()
  105. } else {
  106. account = NCManageDatabase.shared.getAccount(predicate: NSPredicate(format: "account == %@", accountIdentifier))
  107. }
  108. guard let account = 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: "")))
  110. }
  111. // Default widget
  112. let result = NCManageDatabase.shared.getDashboardWidgetApplications(account: account.account).first
  113. let id: String = configuration?.applications?.identifier ?? (result?.id ?? "recommendations")
  114. // Capabilities
  115. NCManageDatabase.shared.setCapabilities(account: account.account)
  116. guard NCGlobal.shared.capabilityServerVersionMajor >= NCGlobal.shared.nextcloudVersion25 else {
  117. 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: "")))
  118. }
  119. // NETWORKING
  120. let password = CCUtility.getPassword(account.account)!
  121. NextcloudKit.shared.setup(
  122. account: account.account,
  123. user: account.user,
  124. userId: account.userId,
  125. password: password,
  126. urlBase: account.urlBase,
  127. userAgent: userAgent,
  128. nextcloudVersion: 0,
  129. delegate: NCNetworking.shared)
  130. // LOG
  131. let levelLog = CCUtility.getLogLevel()
  132. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  133. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  134. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  135. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  136. NextcloudKit.shared.nkCommonInstance.pathLog = pathDirectoryGroup
  137. }
  138. if isSimulatorOrTestFlight {
  139. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) dashboard widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  140. } else {
  141. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) dashboard widget session with level \(levelLog) " + versionNextcloudiOS)
  142. }
  143. let (tableDashboard, tableButton) = NCManageDatabase.shared.getDashboardWidget(account: account.account, id: id)
  144. let existsButton = (tableButton?.isEmpty ?? true) ? false : true
  145. let title = tableDashboard?.title ?? id
  146. var imagetmp = UIImage(named: "widget")!
  147. if let fileName = tableDashboard?.iconClass {
  148. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  149. if let image = UIImage(contentsOfFile: fileNamePath) {
  150. imagetmp = image.withTintColor(.label, renderingMode: .alwaysOriginal)
  151. }
  152. }
  153. let titleImage = imagetmp
  154. let options = NKRequestOptions(timeout: 90, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  155. NextcloudKit.shared.getDashboardWidgetsApplication(id, options: options) { _, results, data, error in
  156. Task {
  157. var datas = [DashboardData]()
  158. var numberItems = 0
  159. if let results = results {
  160. for result in results {
  161. if let items = result.items {
  162. numberItems = result.items?.count ?? 0
  163. var counter: Int = 0
  164. let dashboardItems = getDashboardItems(displaySize: displaySize, withButton: existsButton)
  165. for item in items {
  166. counter += 1
  167. let title = item.title ?? ""
  168. let subtitle = item.subtitle ?? ""
  169. var link = URL(string: "https://")!
  170. if let entryLink = item.link, let url = URL(string: entryLink) { link = url }
  171. var icon = UIImage(named: "file")!
  172. var iconFileName: String?
  173. var imageTemplate: Bool = false
  174. var imageAvatar: Bool = false
  175. var imageColorized: Bool = false
  176. var imageColor: UIColor?
  177. if let iconUrl = item.iconUrl, let url = URL(string: iconUrl) {
  178. if let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  179. let path = (urlComponents.path as NSString)
  180. let pathComponents = path.components(separatedBy: "/")
  181. let queryItems = urlComponents.queryItems
  182. if (pathComponents.last as? NSString)?.pathExtension.lowercased() == "svg" {
  183. imageTemplate = true
  184. }
  185. if let item = CCUtility.value(forKey: "fileId", fromQueryItems: queryItems) {
  186. iconFileName = item
  187. } else if pathComponents.contains("avatar") {
  188. iconFileName = pathComponents[pathComponents.count - 2]
  189. imageAvatar = true
  190. } else if pathComponents.contains("getCalendarDotSvg") {
  191. imageColorized = true
  192. } else {
  193. iconFileName = ((path.lastPathComponent) as NSString).deletingPathExtension
  194. }
  195. }
  196. // Color
  197. if imageColorized, let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) {
  198. let path = (urlComponents.path as NSString)
  199. let colorString = ((path.lastPathComponent) as NSString).deletingPathExtension
  200. imageColor = UIColor(hex: colorString)
  201. icon = UIImage(systemName: "circle.fill")!
  202. } else if let fileName = iconFileName {
  203. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  204. if FileManager().fileExists(atPath: fileNamePath), let image = UIImage(contentsOfFile: fileNamePath) {
  205. icon = image
  206. } else {
  207. let (_, data, _) = await NextcloudKit.shared.getPreview(url: url)
  208. if let image = convertDataToImage(data: data, size: CGSize(width: 256, height: 256), fileNameToWrite: fileName) {
  209. icon = image
  210. }
  211. }
  212. }
  213. }
  214. let data = DashboardData(id: counter, title: title, subTitle: subtitle, link: link, icon: icon, template: imageTemplate, avatar: imageAvatar, imageColor: imageColor)
  215. datas.append(data)
  216. if datas.count == dashboardItems { break }
  217. }
  218. }
  219. }
  220. }
  221. var buttons = tableButton
  222. if numberItems == datas.count, let tableButton = tableButton, tableButton.contains(where: { $0.type == "more"}) {
  223. buttons = tableButton.filter(({ $0.type != "more" }))
  224. }
  225. let alias = (account.alias.isEmpty) ? "" : (" (" + account.alias + ")")
  226. let footerText = "Dashboard " + NSLocalizedString("_of_", comment: "") + " " + account.displayName + alias
  227. if error != .success {
  228. completion(DashboardDataEntry(date: Date(), datas: datasPlaceholder, dashboard: tableDashboard, buttons: buttons, isPlaceholder: true, isEmpty: false, titleImage: titleImage, title: title, footerImage: "xmark.icloud", footerText: error.errorDescription))
  229. } else {
  230. completion(DashboardDataEntry(date: Date(), datas: datas, dashboard: tableDashboard, buttons: buttons, isPlaceholder: false, isEmpty: datas.isEmpty, titleImage: titleImage, title: title, footerImage: "checkmark.icloud", footerText: footerText))
  231. }
  232. }
  233. }
  234. }