FilesData.swift 14 KB

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