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