NextcloudData.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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 NextcloudKit
  25. let nextcloudItems = 4
  26. struct NextcloudDataEntry: TimelineEntry {
  27. let date: Date
  28. let datas: [NextcloudRecentData]
  29. let isPlaceholder: Bool
  30. let tile: String
  31. let footerImage: String
  32. let footerText: String
  33. }
  34. struct NextcloudRecentData: 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 recentDatasTest: [NextcloudRecentData] = [
  42. .init(id: "1", image: UIImage(named: "widget")!, title: "title1", subTitle: "subTitle-description1", url: URL(string: "https://nextcloud.com/")!),
  43. .init(id: "2", image: UIImage(named: "widget")!, title: "title2", subTitle: "subTitle-description2", url: URL(string: "https://nextcloud.com/")!),
  44. .init(id: "3", image: UIImage(named: "widget")!, title: "title3", subTitle: "subTitle-description3", url: URL(string: "https://nextcloud.com/")!),
  45. .init(id: "4", image: UIImage(named: "widget")!, title: "title4", subTitle: "subTitle-description4", url: URL(string: "https://nextcloud.com/")!),
  46. .init(id: "5", image: UIImage(named: "widget")!, title: "title5", subTitle: "subTitle-description5", url: URL(string: "https://nextcloud.com/")!),
  47. .init(id: "6", image: UIImage(named: "widget")!, title: "title6", subTitle: "subTitle-description6", url: URL(string: "https://nextcloud.com/")!)
  48. ]
  49. func getTitleNextcloudWidget() -> String {
  50. let hour = Calendar.current.component(.hour, from: Date())
  51. var good = ""
  52. switch hour {
  53. case 6..<12: good = NSLocalizedString("_good_morning_", value: "Good morning", comment: "")
  54. case 12: good = NSLocalizedString("_good_noon_", value: "Good noon", comment: "")
  55. case 13..<17: good = NSLocalizedString("_good_afternoon_", value: "Good afternoon", comment: "")
  56. case 17..<22: good = NSLocalizedString("_good_evening_", value: "Good evening", comment: "")
  57. default: good = NSLocalizedString("_good_night_", value: "Good night", comment: "")
  58. }
  59. if let account = NCManageDatabase.shared.getActiveAccount() {
  60. return good + ", " + account.displayName
  61. } else {
  62. return good
  63. }
  64. }
  65. func getNextcloudDataEntry(isPreview: Bool, displaySize: CGSize, completion: @escaping (_ entry: NextcloudDataEntry) -> Void) {
  66. let datasPlaceholder = Array(recentDatasTest[0...nextcloudItems - 1])
  67. let title = getTitleNextcloudWidget()
  68. if isPreview {
  69. return completion(NextcloudDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, tile: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " widget"))
  70. }
  71. guard let account = NCManageDatabase.shared.getActiveAccount() else {
  72. return completion(NextcloudDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, tile: title, footerImage: "xmark.icloud", footerText: NSLocalizedString("_no_active_account_", value: "No account found", comment: "")))
  73. }
  74. func isLive(file: NKFile, files: [NKFile]) -> Bool {
  75. if file.ext.lowercased() != "mov" { return false }
  76. if files.filter({ ($0.fileNameWithoutExt == file.fileNameWithoutExt) && ($0.ext.lowercased() == "jpg") }).first != nil {
  77. return true
  78. }
  79. return false
  80. }
  81. // NETWORKING
  82. let password = CCUtility.getPassword(account.account)!
  83. NKCommon.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. nextcloudVersion: 0,
  91. delegate: NCNetworking.shared)
  92. let requestBodyRecent =
  93. """
  94. <?xml version=\"1.0\"?>
  95. <d:searchrequest xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  96. <d:basicsearch>
  97. <d:select>
  98. <d:prop>
  99. <d:displayname/>
  100. <d:getcontenttype/>
  101. <d:resourcetype/>
  102. <d:getcontentlength/>
  103. <d:getlastmodified/>
  104. <d:getetag/>
  105. <d:quota-used-bytes/>
  106. <d:quota-available-bytes/>
  107. <permissions xmlns=\"http://owncloud.org/ns\"/>
  108. <id xmlns=\"http://owncloud.org/ns\"/>
  109. <fileid xmlns=\"http://owncloud.org/ns\"/>
  110. <size xmlns=\"http://owncloud.org/ns\"/>
  111. <favorite xmlns=\"http://owncloud.org/ns\"/>
  112. <creation_time xmlns=\"http://nextcloud.org/ns\"/>
  113. <upload_time xmlns=\"http://nextcloud.org/ns\"/>
  114. <is-encrypted xmlns=\"http://nextcloud.org/ns\"/>
  115. <mount-type xmlns=\"http://nextcloud.org/ns\"/>
  116. <owner-id xmlns=\"http://owncloud.org/ns\"/>
  117. <owner-display-name xmlns=\"http://owncloud.org/ns\"/>
  118. <comments-unread xmlns=\"http://owncloud.org/ns\"/>
  119. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  120. <trashbin-filename xmlns=\"http://nextcloud.org/ns\"/>
  121. <trashbin-original-location xmlns=\"http://nextcloud.org/ns\"/>
  122. <trashbin-deletion-time xmlns=\"http://nextcloud.org/ns\"/>
  123. </d:prop>
  124. </d:select>
  125. <d:from>
  126. <d:scope>
  127. <d:href>%@</d:href>
  128. <d:depth>infinity</d:depth>
  129. </d:scope>
  130. </d:from>
  131. <d:where>
  132. <d:lt>
  133. <d:prop>
  134. <d:getlastmodified/>
  135. </d:prop>
  136. <d:literal>%@</d:literal>
  137. </d:lt>
  138. </d:where>
  139. <d:orderby>
  140. <d:order>
  141. <d:prop>
  142. <d:getlastmodified/>
  143. </d:prop>
  144. <d:descending/>
  145. </d:order>
  146. </d:orderby>
  147. <d:limit>
  148. <d:nresults>50</d:nresults>
  149. </d:limit>
  150. </d:basicsearch>
  151. </d:searchrequest>
  152. """
  153. let dateFormatter = DateFormatter()
  154. dateFormatter.locale = Locale(identifier: "en_US_POSIX")
  155. dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
  156. let lessDateString = dateFormatter.string(from: Date())
  157. let requestBody = String(format: requestBodyRecent, "/files/" + account.userId, lessDateString)
  158. // LOG
  159. let levelLog = CCUtility.getLogLevel()
  160. let isSimulatorOrTestFlight = NCUtility.shared.isSimulatorOrTestFlight()
  161. let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, NCUtility.shared.getVersionApp())
  162. NKCommon.shared.levelLog = levelLog
  163. if let pathDirectoryGroup = CCUtility.getDirectoryGroup()?.path {
  164. NKCommon.shared.pathLog = pathDirectoryGroup
  165. }
  166. if isSimulatorOrTestFlight {
  167. NKCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS + " (Simulator / TestFlight)")
  168. } else {
  169. NKCommon.shared.writeLog("Start \(NCBrandOptions.shared.brand) widget session with level \(levelLog) " + versionNextcloudiOS)
  170. }
  171. NextcloudKit.shared.searchBodyRequest(serverUrl: account.urlBase, requestBody: requestBody, showHiddenFiles: CCUtility.getShowHiddenFiles()) { _, files, data, error in
  172. var datas: [NextcloudRecentData] = []
  173. for file in files {
  174. guard !file.directory else { continue }
  175. guard !isLive(file: file, files: files) else { continue }
  176. let subTitle = CCUtility.dateDiff(file.date as Date) + " · " + CCUtility.transformedSize(file.size)
  177. // url: nextcloud://open-file?path=Talk/IMG_0000123.jpg&user=marinofaggiana&link=https://cloud.nextcloud.com/f/123
  178. guard var path = NCUtilityFileSystem.shared.getPath(path: file.path, user: file.user, fileName: file.fileName).urlEncoded else { continue }
  179. if path.first == "/" { path = String(path.dropFirst())}
  180. guard let user = file.user.urlEncoded else { continue }
  181. let link = file.urlBase + "/f/" + file.fileId
  182. let urlString = "nextcloud://open-file?path=\(path)&user=\(user)&link=\(link)"
  183. guard let url = URL(string: urlString) else { continue }
  184. // Build Recent Data
  185. var imageRecent = UIImage()
  186. if let image = NCUtility.shared.createFilePreviewImage(ocId: file.ocId, etag: file.etag, fileNameView: file.fileName, classFile: file.classFile, status: 0, createPreviewMedia: false) {
  187. imageRecent = image
  188. } else if !file.iconName.isEmpty {
  189. imageRecent = UIImage(named: file.iconName)!
  190. } else {
  191. imageRecent = UIImage(named: "file")!
  192. }
  193. let recentData = NextcloudRecentData.init(id: file.ocId, image: imageRecent, title: file.fileName, subTitle: subTitle, url: url)
  194. datas.append(recentData)
  195. if datas.count == nextcloudItems { break}
  196. }
  197. if error != .success {
  198. completion(NextcloudDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, tile: title, footerImage: "xmark.icloud", footerText: error.errorDescription))
  199. } else if datas.isEmpty {
  200. var footerText = NSLocalizedString("_no_data_available_", comment: "")
  201. let serverVersionMajor = NCManageDatabase.shared.getCapabilitiesServerInt(account: account.account, elements: NCElementsJSON.shared.capabilitiesVersionMajor)
  202. if serverVersionMajor < NCGlobal.shared.nextcloudVersion25 {
  203. footerText = NSLocalizedString("_widget_available_nc25_", comment: "")
  204. }
  205. completion(NextcloudDataEntry(date: Date(), datas: datasPlaceholder, isPlaceholder: true, tile: title, footerImage: "checkmark.icloud", footerText: footerText))
  206. } else {
  207. completion(NextcloudDataEntry(date: Date(), datas: datas, isPlaceholder: false, tile: title, footerImage: "checkmark.icloud", footerText: NCBrandOptions.shared.brand + " widget"))
  208. }
  209. }
  210. }