NextcloudData.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. //
  2. // NextcloudData.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 NCCommunication
  25. let imageSize:CGFloat = 30
  26. let spacingImageUpload:CGFloat = 10
  27. struct NextcloudDataEntry: TimelineEntry {
  28. let date: Date
  29. let recentDatas: [RecentData]
  30. let uploadDatas: [UploadData]
  31. let isPlaceholder: Bool
  32. let footerText: String
  33. }
  34. struct RecentData: Identifiable, Hashable {
  35. var id: String
  36. var image: UIImage
  37. var title: String
  38. var subTitle: String
  39. var url: URL
  40. }
  41. struct UploadData: Identifiable, Hashable {
  42. var id: String
  43. var image: UIImage
  44. var task: Int
  45. var num: Int
  46. }
  47. let recentDatasTest: [RecentData] = [
  48. .init(id: "1", image: UIImage(named: "nextcloud")!, title: "title1", subTitle: "subTitle-description1", url: URL(string: "https://nextcloud.com/")!),
  49. .init(id: "2", image: UIImage(named: "nextcloud")!, title: "title2", subTitle: "subTitle-description2", url: URL(string: "https://nextcloud.com/")!),
  50. .init(id: "3", image: UIImage(named: "nextcloud")!, title: "title3", subTitle: "subTitle-description3", url: URL(string: "https://nextcloud.com/")!),
  51. .init(id: "4", image: UIImage(named: "nextcloud")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  52. .init(id: "5", image: UIImage(named: "nextcloud")!, title: "title5", subTitle: "subTitle-description5", url: URL(string: "https://nextcloud.com/")!)
  53. ]
  54. let uploadDatasTest: [UploadData] = [
  55. .init(id: "1", image: UIImage(named: "nextcloud")!, task: 0, num: 0),
  56. .init(id: "2", image: UIImage(named: "nextcloud")!, task: 0, num: 1),
  57. .init(id: "3", image: UIImage(named: "nextcloud")!, task: 0, num: 2),
  58. .init(id: "4", image: UIImage(named: "nextcloud")!, task: 0, num: 3),
  59. .init(id: "5", image: UIImage(named: "nextcloud")!, task: 0, num: 4),
  60. .init(id: "6", image: UIImage(named: "nextcloud")!, task: 0, num: 5),
  61. .init(id: "7", image: UIImage(named: "nextcloud")!, task: 0, num: 6),
  62. .init(id: "8", image: UIImage(named: "nextcloud")!, task: 0, num: 7),
  63. .init(id: "9", image: UIImage(named: "nextcloud")!, task: 0, num: 8),
  64. .init(id: "0", image: UIImage(named: "nextcloud")!, task: 0, num: 9)
  65. ]
  66. func getDataEntry(isPreview: Bool, displaySize: CGSize, completion: @escaping (_ entry: NextcloudDataEntry) -> Void) {
  67. let limitUpload = Int(displaySize.width / (imageSize + spacingImageUpload))
  68. let uploadDatasTest = uploadDatasTest.filter({ $0.num < limitUpload})
  69. if isPreview {
  70. return completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest, isPlaceholder: true, footerText: ""))
  71. }
  72. guard let account = NCManageDatabase.shared.getActiveAccount() else {
  73. return completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest,isPlaceholder: true, footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: "")))
  74. }
  75. func isLive(file: NCCommunicationFile, files: [NCCommunicationFile]) -> Bool {
  76. if file.ext.lowercased() != "mov" { return false }
  77. if files.filter({ ($0.fileNameWithoutExt == file.fileNameWithoutExt) && ($0.ext.lowercased() == "jpg") }).first != nil {
  78. return true
  79. }
  80. return false
  81. }
  82. // NETWORKING
  83. let password = CCUtility.getPassword(account.account)!
  84. NCCommunicationCommon.shared.setup(
  85. account: account.account,
  86. user: account.user,
  87. userId: account.userId,
  88. password: password,
  89. urlBase: account.urlBase,
  90. userAgent: CCUtility.getUserAgent(),
  91. webDav: NCUtilityFileSystem.shared.getWebDAV(account: account.account),
  92. nextcloudVersion: 0,
  93. delegate: NCNetworking.shared)
  94. let requestBodyRecent =
  95. """
  96. <?xml version=\"1.0\"?>
  97. <d:searchrequest xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  98. <d:basicsearch>
  99. <d:select>
  100. <d:prop>
  101. <d:displayname/>
  102. <d:getcontenttype/>
  103. <d:resourcetype/>
  104. <d:getcontentlength/>
  105. <d:getlastmodified/>
  106. <d:getetag/>
  107. <d:quota-used-bytes/>
  108. <d:quota-available-bytes/>
  109. <permissions xmlns=\"http://owncloud.org/ns\"/>
  110. <id xmlns=\"http://owncloud.org/ns\"/>
  111. <fileid xmlns=\"http://owncloud.org/ns\"/>
  112. <size xmlns=\"http://owncloud.org/ns\"/>
  113. <favorite xmlns=\"http://owncloud.org/ns\"/>
  114. <creation_time xmlns=\"http://nextcloud.org/ns\"/>
  115. <upload_time xmlns=\"http://nextcloud.org/ns\"/>
  116. <is-encrypted xmlns=\"http://nextcloud.org/ns\"/>
  117. <mount-type xmlns=\"http://nextcloud.org/ns\"/>
  118. <owner-id xmlns=\"http://owncloud.org/ns\"/>
  119. <owner-display-name xmlns=\"http://owncloud.org/ns\"/>
  120. <comments-unread xmlns=\"http://owncloud.org/ns\"/>
  121. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  122. <trashbin-filename xmlns=\"http://nextcloud.org/ns\"/>
  123. <trashbin-original-location xmlns=\"http://nextcloud.org/ns\"/>
  124. <trashbin-deletion-time 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>50</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 = CCUtility.getLogLevel()
  162. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  163. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  164. NCCommunicationCommon.shared.levelLog = levelLog
  165. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  166. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  167. }
  168. if isSimulatorOrTestFlight {
  169. NCCommunicationCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  170. } else {
  171. NCCommunicationCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS)
  172. }
  173. NCCommunicationCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget [Auto upload]")
  174. NCAutoUpload.shared.initAutoUpload(viewController: nil) { _ in
  175. NCCommunicationCommon.shared.writeLog("Completition \(NCBrandOptions.shared.brand) widget [Auto upload]")
  176. NCCommunication.shared.searchBodyRequest(serverUrl: account.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles()) { _, files, errorCode, errorDescription in
  177. // Get recent files
  178. var recentDatas: [RecentData] = []
  179. for file in files {
  180. guard !file.directory else { continue }
  181. guard !isLive(file: file, files: files) else { continue }
  182. let metadata = NCManageDatabase.shared.convertNCFileToMetadata(file, isEncrypted: false, account: account.account)
  183. let subTitle = CCUtility.dateDiff(metadata.date as Date) + " · " + CCUtility.transformedSize(metadata.size)
  184. // url: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  185. guard var path = NCUtilityFileSystem.shared.getPath(path: metadata.path, user: metadata.user, fileName: metadata.fileName).urlEncoded else { continue }
  186. if path.first == "/" { path = String(path.dropFirst())}
  187. guard let user = metadata.user.urlEncoded else { continue }
  188. let link = metadata.urlBase + "/f/" + metadata.fileId
  189. let urlString = "nextcloud://open-file?path=\(path)&user=\(user)&link=\(link)"
  190. guard let url = URL(string: urlString) else { continue }
  191. // Recent Data
  192. let image:UIImage = NCUtilityGUI.shared.createFilePreviewImage(metadata: metadata, size: imageSize * 3, createPreview: false) ?? UIImage(named: "file")!
  193. let recentData = RecentData.init(id: metadata.ocId, image: image, title: metadata.fileName, subTitle: subTitle, url: url)
  194. recentDatas.append(recentData)
  195. if recentDatas.count == 5 { break}
  196. }
  197. // Get upload files
  198. var uploadDatas: [UploadData] = []
  199. let metadatas = NCManageDatabase.shared.getAdvancedMetadatas(predicate: NSPredicate(format: "status == %i || status == %i || status == %i", NCGlobal.shared.metadataStatusWaitUpload, NCGlobal.shared.metadataStatusInUpload, NCGlobal.shared.metadataStatusUploading), page: 1, limit: limitUpload, sorted: "sessionTaskIdentifier", ascending: false)
  200. for metadata in metadatas {
  201. // image
  202. let image:UIImage = NCUtilityGUI.shared.createFilePreviewImage(metadata: metadata, size: imageSize * 3, createPreview: false) ?? UIImage(named: "file")!
  203. // Upload Data
  204. uploadDatas.append(UploadData(id: metadata.ocId, image: image, task: metadata.sessionTaskIdentifier, num: 0))
  205. }
  206. // Completion
  207. if errorCode != 0 {
  208. completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest, isPlaceholder: true, footerText: errorDescription))
  209. } else if recentDatas.isEmpty {
  210. completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest, isPlaceholder: true, footerText: "\(Date().formatted())"))
  211. } else {
  212. completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatas, uploadDatas: uploadDatas, isPlaceholder: false, footerText: "\(Date().formatted())"))
  213. }
  214. }
  215. }
  216. }