NextcloudData.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. struct NextcloudDataEntry: TimelineEntry {
  26. let date: Date
  27. let recentDatas: [RecentData]
  28. let uploadDatas: [UploadData]
  29. let isPlaceholder: Bool
  30. let footerText: String
  31. }
  32. struct RecentData: Identifiable, Hashable {
  33. var id: String
  34. var image: UIImage
  35. var title: String
  36. var subTitle: String
  37. var url: URL
  38. }
  39. struct UploadData: Identifiable, Hashable {
  40. var id: String
  41. var image: UIImage
  42. }
  43. let recentDatasTest: [RecentData] = [
  44. .init(id: "1", image: UIImage(named: "nextcloud")!, title: "title1", subTitle: "subTitle-description1", url: URL(string: "https://nextcloud.com/")!),
  45. .init(id: "2", image: UIImage(named: "nextcloud")!, title: "title2", subTitle: "subTitle-description2", url: URL(string: "https://nextcloud.com/")!),
  46. .init(id: "3", image: UIImage(named: "nextcloud")!, title: "title3", subTitle: "subTitle-description3", url: URL(string: "https://nextcloud.com/")!),
  47. .init(id: "4", image: UIImage(named: "nextcloud")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  48. .init(id: "5", image: UIImage(named: "nextcloud")!, title: "title5", subTitle: "subTitle-description5", url: URL(string: "https://nextcloud.com/")!)
  49. ]
  50. let uploadDatasTest: [UploadData] = [
  51. .init(id: "1", image: UIImage(named: "nextcloud")!),
  52. .init(id: "2", image: UIImage(named: "nextcloud")!),
  53. .init(id: "3", image: UIImage(named: "nextcloud")!),
  54. .init(id: "4", image: UIImage(named: "nextcloud")!),
  55. .init(id: "5", image: UIImage(named: "nextcloud")!),
  56. .init(id: "6", image: UIImage(named: "nextcloud")!),
  57. .init(id: "7", image: UIImage(named: "nextcloud")!),
  58. .init(id: "8", image: UIImage(named: "nextcloud")!)
  59. ]
  60. func getDataEntry(completion: @escaping (_ entry: NextcloudDataEntry) -> Void) {
  61. guard let account = NCManageDatabase.shared.getActiveAccount() else {
  62. return completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest,isPlaceholder: true, footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: "")))
  63. }
  64. func isLive(file: NCCommunicationFile, files: [NCCommunicationFile]) -> Bool {
  65. if file.ext.lowercased() != "mov" { return false }
  66. if files.filter({ ($0.fileNameWithoutExt == file.fileNameWithoutExt) && ($0.ext.lowercased() == "jpg") }).first != nil {
  67. return true
  68. }
  69. return false
  70. }
  71. // NETWORKING
  72. let password = CCUtility.getPassword(account.account)!
  73. NCCommunicationCommon.shared.setup(
  74. account: account.account,
  75. user: account.user,
  76. userId: account.userId,
  77. password: password,
  78. urlBase: account.urlBase,
  79. userAgent: CCUtility.getUserAgent(),
  80. webDav: NCUtilityFileSystem.shared.getWebDAV(account: account.account),
  81. nextcloudVersion: 0,
  82. delegate: NCNetworking.shared)
  83. let requestBodyRecent =
  84. """
  85. <?xml version=\"1.0\"?>
  86. <d:searchrequest xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  87. <d:basicsearch>
  88. <d:select>
  89. <d:prop>
  90. <d:displayname/>
  91. <d:getcontenttype/>
  92. <d:resourcetype/>
  93. <d:getcontentlength/>
  94. <d:getlastmodified/>
  95. <d:getetag/>
  96. <d:quota-used-bytes/>
  97. <d:quota-available-bytes/>
  98. <permissions xmlns=\"http://owncloud.org/ns\"/>
  99. <id xmlns=\"http://owncloud.org/ns\"/>
  100. <fileid xmlns=\"http://owncloud.org/ns\"/>
  101. <size xmlns=\"http://owncloud.org/ns\"/>
  102. <favorite xmlns=\"http://owncloud.org/ns\"/>
  103. <creation_time xmlns=\"http://nextcloud.org/ns\"/>
  104. <upload_time xmlns=\"http://nextcloud.org/ns\"/>
  105. <is-encrypted xmlns=\"http://nextcloud.org/ns\"/>
  106. <mount-type xmlns=\"http://nextcloud.org/ns\"/>
  107. <owner-id xmlns=\"http://owncloud.org/ns\"/>
  108. <owner-display-name xmlns=\"http://owncloud.org/ns\"/>
  109. <comments-unread xmlns=\"http://owncloud.org/ns\"/>
  110. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  111. <trashbin-filename xmlns=\"http://nextcloud.org/ns\"/>
  112. <trashbin-original-location xmlns=\"http://nextcloud.org/ns\"/>
  113. <trashbin-deletion-time xmlns=\"http://nextcloud.org/ns\"/>
  114. </d:prop>
  115. </d:select>
  116. <d:from>
  117. <d:scope>
  118. <d:href>%@</d:href>
  119. <d:depth>infinity</d:depth>
  120. </d:scope>
  121. </d:from>
  122. <d:where>
  123. <d:lt>
  124. <d:prop>
  125. <d:getlastmodified/>
  126. </d:prop>
  127. <d:literal>%@</d:literal>
  128. </d:lt>
  129. </d:where>
  130. <d:orderby>
  131. <d:order>
  132. <d:prop>
  133. <d:getlastmodified/>
  134. </d:prop>
  135. <d:descending/>
  136. </d:order>
  137. </d:orderby>
  138. <d:limit>
  139. <d:nresults>50</d:nresults>
  140. </d:limit>
  141. </d:basicsearch>
  142. </d:searchrequest>
  143. """
  144. let dateFormatter = DateFormatter()
  145. dateFormatter.locale = Locale(identifier: "en_US_POSIX")
  146. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
  147. let lessDateString = dateFormatter.string(from: Date())
  148. let requestBody = String(format: requestBodyRecent, "/files/" + account.userId, lessDateString)
  149. // LOG
  150. let levelLog = CCUtility.getLogLevel()
  151. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  152. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  153. NCCommunicationCommon.shared.levelLog = levelLog
  154. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  155. NCCommunicationCommon.shared.pathLog = pathDirectoryGroup
  156. }
  157. if isSimulatorOrTestFlight {
  158. NCCommunicationCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  159. } else {
  160. NCCommunicationCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS)
  161. }
  162. NCCommunicationCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget [Auto upload]")
  163. NCAutoUpload.shared.initAutoUpload(viewController: nil) { items in
  164. NCCommunicationCommon.shared.writeLog("Completition \(NCBrandOptions.shared.brand) widget [Auto upload]")
  165. NCCommunication.shared.searchBodyRequest(serverUrl: account.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles()) { _, files, errorCode, errorDescription in
  166. // Get recent files
  167. var recentDatas: [RecentData] = []
  168. for file in files {
  169. guard !file.directory else { continue }
  170. guard !isLive(file: file, files: files) else { continue }
  171. let subTitle = CCUtility.dateDiff(file.date as Date) + " · " + CCUtility.transformedSize(file.size)
  172. let imagePath = CCUtility.getDirectoryProviderStorageIconOcId(file.ocId, etag: file.etag)!
  173. let image = UIImage(contentsOfFile: imagePath) ?? UIImage(named: "file")!
  174. // Example: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  175. guard var path = NCUtilityFileSystem.shared.getPath(path: file.path, user: file.user, fileName: file.fileName).urlEncoded else { continue }
  176. if path.first == "/" { path = String(path.dropFirst())}
  177. guard let user = file.user.urlEncoded else { continue }
  178. let link = file.urlBase + "/f/" + file.fileId
  179. let urlString = "nextcloud://open-file?path=\(path)&user=\(user)&link=\(link)"
  180. guard let url = URL(string: urlString) else { continue }
  181. let recentData = RecentData.init(id: file.ocId, image: image, title: file.fileName, subTitle: subTitle, url: url)
  182. recentDatas.append(recentData)
  183. if recentDatas.count == 5 { break}
  184. }
  185. // Get upload files
  186. var uploadDatas: [UploadData] = []
  187. 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: 10, sorted: "sessionTaskIdentifier", ascending: false)
  188. for metadata in metadatas {
  189. let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(metadata.ocId, etag: metadata.etag)!
  190. let filePath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  191. var imagePath = ""
  192. if FileManager().fileExists(atPath: iconImagePath) {
  193. imagePath = iconImagePath
  194. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.image.rawValue, FileManager().fileExists(atPath: filePath) {
  195. if let image = UIImage(contentsOfFile: filePath), let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon), isAspectRation: true), let data = image.jpegData(compressionQuality: 0.5) {
  196. do {
  197. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  198. imagePath = iconImagePath
  199. } catch { }
  200. }
  201. } else if metadata.classFile == NCCommunicationCommon.typeClassFile.video.rawValue, FileManager().fileExists(atPath: filePath) {
  202. if let image = NCUtility.shared.imageFromVideo(url: URL(fileURLWithPath: filePath), at: 0), let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon), isAspectRation: true), let data = image.jpegData(compressionQuality: 0.5) {
  203. do {
  204. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  205. imagePath = iconImagePath
  206. } catch { }
  207. }
  208. } else {
  209. continue
  210. }
  211. let image = UIImage(contentsOfFile: imagePath) ?? UIImage(named: "file")!
  212. uploadDatas.append(UploadData(id: metadata.ocId, image: image))
  213. if uploadDatas.count == 5 { break}
  214. }
  215. // Completion
  216. if errorCode != 0 {
  217. completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest, isPlaceholder: true, footerText: errorDescription))
  218. } else if recentDatas.isEmpty {
  219. completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatasTest, uploadDatas: uploadDatasTest, isPlaceholder: true, footerText: "Auto upoload: \(0), \(Date().formatted())"))
  220. } else {
  221. completion(NextcloudDataEntry(date: Date(), recentDatas: recentDatas, uploadDatas: uploadDatas, isPlaceholder: false, footerText: "Auto upoload: \(0), \(Date().formatted())"))
  222. }
  223. }
  224. }
  225. }