NextcloudData.swift 12 KB

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