FilesData.swift 13 KB

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