FilesData.swift 13 KB

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