FilesData.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. //
  2. // FilesData.swift
  3. // Widget
  4. //
  5. // Created by Marino Faggiana on 25/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. struct FilesDataEntry: TimelineEntry {
  28. let date: Date
  29. let datas: [FilesData]
  30. let isPlaceholder: Bool
  31. let isEmpty: Bool
  32. let userId: String
  33. let url: String
  34. let account: String
  35. let tile: String
  36. let footerImage: String
  37. let footerText: String
  38. }
  39. struct FilesData: Identifiable, Hashable {
  40. var id: String
  41. var image: UIImage
  42. var title: String
  43. var subTitle: String
  44. var url: URL
  45. var useTypeIconFile: Bool = false
  46. }
  47. let filesDatasTest: [FilesData] = [
  48. .init(id: "0", image: UIImage(named: "widget")!, title: "title1", subTitle: "subTitle-description1", url: URL(string: "https://nextcloud.com/")!),
  49. .init(id: "1", image: UIImage(named: "widget")!, title: "title2", subTitle: "subTitle-description2", url: URL(string: "https://nextcloud.com/")!),
  50. .init(id: "2", image: UIImage(named: "widget")!, title: "title3", subTitle: "subTitle-description3", url: URL(string: "https://nextcloud.com/")!),
  51. .init(id: "3", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  52. .init(id: "4", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  53. .init(id: "5", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  54. .init(id: "6", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  55. .init(id: "7", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  56. .init(id: "8", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  57. .init(id: "9", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!)
  58. ]
  59. func getTitleFilesWidget(tableAccount: tableAccount?) -> String {
  60. let hour = Calendar.current.component(.hour, from: Date())
  61. var good = ""
  62. switch hour {
  63. case 6..<12: good = NSLocalizedString("_good_morning_", value: "Good morning", comment: "")
  64. case 12: good = NSLocalizedString("_good_day_", value: "Good day", comment: "")
  65. case 13..<17: good = NSLocalizedString("_good_afternoon_", value: "Good afternoon", comment: "")
  66. case 17..<22: good = NSLocalizedString("_good_evening_", value: "Good evening", comment: "")
  67. default: good = NSLocalizedString("_good_night_", value: "Good night", comment: "")
  68. }
  69. if let tableAccount {
  70. return good + ", " + tableAccount.displayName
  71. } else {
  72. return good
  73. }
  74. }
  75. func getFilesItems(displaySize: CGSize) -> Int {
  76. let items = Int((displaySize.height - 90) / 55)
  77. return items
  78. }
  79. func getFilesDataEntry(configuration: AccountIntent?, isPreview: Bool, displaySize: CGSize, completion: @escaping (_ entry: FilesDataEntry) -> Void) {
  80. let utilityFileSystem = NCUtilityFileSystem()
  81. let utility = NCUtility()
  82. let filesItems = getFilesItems(displaySize: displaySize)
  83. let datasPlaceholder = Array(filesDatasTest[0...filesItems - 1])
  84. var activeTableAccount: tableAccount?
  85. if isPreview {
  86. return completion(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " files"))
  87. }
  88. let accountIdentifier: String = configuration?.accounts?.identifier ?? "active"
  89. if accountIdentifier == "active" {
  90. activeTableAccount = NCManageDatabase.shared.getActiveTableAccount()
  91. } else {
  92. activeTableAccount = NCManageDatabase.shared.getTableAccount(predicate: NSPredicate(format: "account == %@", accountIdentifier))
  93. }
  94. guard let activeTableAccount else {
  95. return completion(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: "", url: "", account: "", tile: getTitleFilesWidget(tableAccount: nil), footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: "")))
  96. }
  97. // NETWORKING
  98. let password = NCKeychain().getPassword(account: activeTableAccount.account)
  99. NextcloudKit.shared.setup(delegate: NCNetworking.shared)
  100. NextcloudKit.shared.appendSession(account: activeTableAccount.account,
  101. urlBase: activeTableAccount.urlBase,
  102. user: activeTableAccount.user,
  103. userId: activeTableAccount.userId,
  104. password: password,
  105. userAgent: userAgent,
  106. nextcloudVersion: NCCapabilities.shared.getCapabilities(account: activeTableAccount.account).capabilityServerVersionMajor,
  107. groupIdentifier: NCBrandOptions.shared.capabilitiesGroup)
  108. let requestBodyRecent =
  109. """
  110. <?xml version=\"1.0\"?>
  111. <d:searchrequest xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  112. <d:basicsearch>
  113. <d:select>
  114. <d:prop>
  115. <d:displayname/>
  116. <d:getcontenttype/>
  117. <d:resourcetype/>
  118. <d:getcontentlength/>
  119. <d:getlastmodified/>
  120. <d:getetag/>
  121. <id xmlns=\"http://owncloud.org/ns\"/>
  122. <fileid xmlns=\"http://owncloud.org/ns\"/>
  123. <size xmlns=\"http://owncloud.org/ns\"/>
  124. <creation_time xmlns=\"http://nextcloud.org/ns\"/>
  125. <upload_time xmlns=\"http://nextcloud.org/ns\"/>
  126. <is-encrypted xmlns=\"http://nextcloud.org/ns\"/>
  127. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  128. </d:prop>
  129. </d:select>
  130. <d:from>
  131. <d:scope>
  132. <d:href>%@</d:href>
  133. <d:depth>infinity</d:depth>
  134. </d:scope>
  135. </d:from>
  136. <d:where>
  137. <d:lt>
  138. <d:prop>
  139. <d:getlastmodified/>
  140. </d:prop>
  141. <d:literal>%@</d:literal>
  142. </d:lt>
  143. </d:where>
  144. <d:orderby>
  145. <d:order>
  146. <d:prop>
  147. <d:getlastmodified/>
  148. </d:prop>
  149. <d:descending/>
  150. </d:order>
  151. </d:orderby>
  152. <d:limit>
  153. <d:nresults>50</d:nresults>
  154. </d:limit>
  155. </d:basicsearch>
  156. </d:searchrequest>
  157. """
  158. let dateFormatter = DateFormatter()
  159. dateFormatter.locale = Locale(identifier: "en_US_POSIX")
  160. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
  161. let lessDateString = dateFormatter.string(from: Date())
  162. let requestBody = String(format: requestBodyRecent, "/files/" + activeTableAccount.userId, lessDateString)
  163. // LOG
  164. let levelLog = NCKeychain().logLevel
  165. let isSimulatorOrTestFlight = utility.isSimulatorOrTestFlight()
  166. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionApp())
  167. NextcloudKit.shared.nkCommonInstance.levelLog = levelLog
  168. NextcloudKit.shared.nkCommonInstance.pathLog = utilityFileSystem.directoryGroup
  169. if isSimulatorOrTestFlight {
  170. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  171. } else {
  172. NextcloudKit.shared.nkCommonInstance.writeLog("[INFO] Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS)
  173. }
  174. let options = NKRequestOptions(timeout: 30, queue: NextcloudKit.shared.nkCommonInstance.backgroundQueue)
  175. NextcloudKit.shared.searchBodyRequest(serverUrl: activeTableAccount.urlBase, requestBody: requestBody, showHiddenFiles: NCKeychain().showHiddenFiles, account: activeTableAccount.account, options: options) { _, files, data, error in
  176. Task {
  177. var datas: [FilesData] = []
  178. let title = getTitleFilesWidget(tableAccount: activeTableAccount)
  179. let files = files?.sorted(by: { ($0.date as Date) > ($1.date as Date) }) ?? []
  180. for file in files {
  181. var useTypeIconFile = false
  182. var image: UIImage?
  183. if file.directory || (!file.livePhotoFile.isEmpty && file.classFile == NKCommon.TypeClassFile.video.rawValue) {
  184. continue
  185. }
  186. // SUBTITLE
  187. let subTitle = utility.dateDiff(file.date as Date) + " · " + utilityFileSystem.transformedSize(file.size)
  188. // URL: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  189. guard var path = utilityFileSystem.getPath(path: file.path, user: file.user, fileName: file.fileName).urlEncoded else { continue }
  190. if path.first == "/" { path = String(path.dropFirst())}
  191. guard let user = file.user.urlEncoded else { continue }
  192. let link = file.urlBase + "/f/" + file.fileId
  193. let urlString = "nextcloud://open-file?path=\(path)&user=\(user)&link=\(link)"
  194. guard let url = URL(string: urlString) else { continue }
  195. // IMAGE
  196. image = utility.getImage(ocId: file.ocId, etag: file.etag, ext: NCGlobal.shared.previewExt512)
  197. if image == nil, file.hasPreview {
  198. let result = await NCNetworking.shared.downloadPreview(fileId: file.fileId,
  199. account: activeTableAccount.account,
  200. options: options)
  201. if result.error == .success, let data = result.responseData?.data {
  202. utility.createImageFileFrom(data: data, ocId: file.ocId, etag: file.etag)
  203. image = utility.getImage(ocId: file.ocId, etag: file.etag, ext: NCGlobal.shared.previewExt256)
  204. }
  205. }
  206. if image == nil {
  207. image = utility.loadImage(named: file.iconName, useTypeIconFile: true, account: file.account)
  208. useTypeIconFile = true
  209. }
  210. let isDirectoryE2EE = utilityFileSystem.isDirectoryE2EE(file: file)
  211. let metadata = NCManageDatabase.shared.convertFileToMetadata(file, isDirectoryE2EE: isDirectoryE2EE)
  212. // DATA
  213. let data = FilesData(id: metadata.ocId, image: image ?? UIImage(), title: metadata.fileNameView, subTitle: subTitle, url: url, useTypeIconFile: useTypeIconFile)
  214. datas.append(data)
  215. if datas.count == filesItems { break}
  216. }
  217. let alias = (activeTableAccount.alias.isEmpty) ? "" : (" (" + activeTableAccount.alias + ")")
  218. let footerText = "Files " + NSLocalizedString("_of_", comment: "") + " " + activeTableAccount.displayName + alias
  219. if error != .success {
  220. completion(FilesDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, isEmpty: false, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "xmark.icloud", footerText: error.errorDescription))
  221. } else {
  222. completion(FilesDataEntry(date: Date(), datas: datas, isPlaceholder: false, isEmpty: datas.isEmpty, userId: activeTableAccount.userId, url: activeTableAccount.urlBase, account: activeTableAccount.account, tile: title, footerImage: "checkmark.icloud", footerText: footerText))
  223. }
  224. }
  225. }
  226. }