NextcloudData.swift 12 KB

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