FilesData.swift 12 KB

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