NCCommunication.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //
  2. // NCCommunication.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 12/10/19.
  6. // Copyright © 2018 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 Foundation
  24. import Alamofire
  25. import SwiftyXMLParser
  26. class NCCommunication: NSObject {
  27. @objc static let sharedInstance: NCCommunication = {
  28. let instance = NCCommunication()
  29. return instance
  30. }()
  31. var username = ""
  32. var password = ""
  33. var userAgent: String?
  34. //MARK: - Settings
  35. @objc func settingAccount(username: String, password: String, userAgent: String?) {
  36. self.username = username
  37. self.password = password
  38. self.userAgent = userAgent
  39. }
  40. //MARK: - webDAV
  41. @objc func createFolder(serverUrl: String, fileName: String, completionHandler: @escaping (_ error: Error?) -> Void) {
  42. // url
  43. var serverUrl = serverUrl
  44. var url: URLConvertible
  45. do {
  46. if serverUrl.last == "/" {
  47. serverUrl = serverUrl + fileName
  48. } else {
  49. serverUrl = serverUrl + "/" + fileName
  50. }
  51. try url = serverUrl.asURL()
  52. } catch let error {
  53. completionHandler(error)
  54. return
  55. }
  56. // headers
  57. var headers: HTTPHeaders = [.authorization(username: self.username, password: self.password)]
  58. if let userAgent = self.userAgent { headers.update(.userAgent(userAgent)) }
  59. headers.update(.contentType("application/xml"))
  60. // method
  61. let method = HTTPMethod(rawValue: "MKCOL")
  62. AF.request(url, method: method, parameters:nil, encoding: URLEncoding.default, headers: headers, interceptor: nil).validate(statusCode: 200..<300).response { (response) in
  63. switch response.result {
  64. case.failure(let error):
  65. completionHandler(error)
  66. case .success( _):
  67. completionHandler(nil)
  68. }
  69. }
  70. }
  71. @objc func readFolder(serverUrl: String, depth: String, completionHandler: @escaping (_ result: [NCFile], _ error: Error?) -> Void) {
  72. var files = [NCFile]()
  73. let dataFile =
  74. """
  75. <?xml version=\"1.0\" encoding=\"UTF-8\"?>
  76. <d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\">
  77. <d:prop>"
  78. <d:displayname/>
  79. <d:getcontenttype/>
  80. <d:resourcetype/>
  81. <d:getcontentlength/>
  82. <d:getlastmodified/>
  83. <d:creationdate/>
  84. <d:getetag/>
  85. <d:quota-used-bytes/>
  86. <d:quota-available-bytes/>
  87. <permissions xmlns=\"http://owncloud.org/ns\"/>
  88. <id xmlns=\"http://owncloud.org/ns\"/>
  89. <fileid xmlns=\"http://owncloud.org/ns\"/>
  90. <size xmlns=\"http://owncloud.org/ns\"/>
  91. <favorite xmlns=\"http://owncloud.org/ns\"/>
  92. <is-encrypted xmlns=\"http://nextcloud.org/ns\"/>
  93. <mount-type xmlns=\"http://nextcloud.org/ns\"/>
  94. <owner-id xmlns=\"http://owncloud.org/ns\"/>
  95. <owner-display-name xmlns=\"http://owncloud.org/ns\"/>
  96. <comments-unread xmlns=\"http://owncloud.org/ns\"/>
  97. <has-preview xmlns=\"http://nextcloud.org/ns\"/>
  98. <trashbin-filename xmlns=\"http://nextcloud.org/ns\"/>
  99. <trashbin-original-location xmlns=\"http://nextcloud.org/ns\"/>
  100. <trashbin-deletion-time xmlns=\"http://nextcloud.org/ns\"/>"
  101. </d:prop>
  102. </d:propfind>
  103. """
  104. // url
  105. var url: URLConvertible
  106. do {
  107. try url = serverUrl.asURL()
  108. } catch let error {
  109. completionHandler(files, error)
  110. return
  111. }
  112. // headers
  113. var headers: HTTPHeaders = [.authorization(username: self.username, password: self.password)]
  114. if let userAgent = self.userAgent { headers.update(.userAgent(userAgent)) }
  115. headers.update(.contentType("application/xml"))
  116. headers.update(name: "Depth", value: depth)
  117. // Parameters
  118. //let parameters: Parameters = ["":"<?xml version=\"1.0\" encoding=\"UTF-8\"?><d:propfind xmlns:d=\"DAV:\" xmlns:oc=\"http://owncloud.org/ns\" xmlns:nc=\"http://nextcloud.org/ns\"><d:prop>" + NCResourceList + "</d:prop></d:propfind>"]
  119. // method
  120. let method = HTTPMethod(rawValue: "PROPFIND")
  121. AF.request(url, method: method, parameters:[:], encoding: URLEncoding.httpBody, headers: headers, interceptor: nil).validate(statusCode: 200..<300).responseData { (response) in
  122. switch response.result {
  123. case.failure(let error):
  124. completionHandler(files, error)
  125. case .success( _):
  126. if let data = response.data {
  127. let xml = XML.parse(data)
  128. let elements = xml["d:multistatus", "d:response"]
  129. for element in elements {
  130. let file = NCFile()
  131. if let href = element["d:href"].text {
  132. file.path = href.removingPercentEncoding ?? ""
  133. }
  134. let propstat = element["d:propstat"][0]
  135. if let getetag = propstat["d:prop", "d:getetag"].text {
  136. file.etag = getetag.replacingOccurrences(of: "\"", with: "")
  137. }
  138. if let getlastmodified = propstat["d:prop", "d:getlastmodified"].text {
  139. if let date = NCCommunicationCommon.sharedInstance.convertDate(getlastmodified, format: "EEE, dd MMM y HH:mm:ss zzz") {
  140. file.date = date
  141. }
  142. }
  143. if let quotaavailablebytes = propstat["d:prop", "d:quota-available-bytes"].text {
  144. file.quotaAvailableBytes = Double(quotaavailablebytes) ?? 0
  145. }
  146. if let quotausedbytes = propstat["d:prop", "d:quota-used-bytes"].text {
  147. file.quotaUsedBytes = Double(quotausedbytes) ?? 0
  148. }
  149. files.append(file)
  150. }
  151. }
  152. completionHandler(files, nil)
  153. }
  154. }
  155. }
  156. //MARK: - Download
  157. @objc func download(serverUrl: String, fileName: String, fileNamePathDestination: String, completionHandler: @escaping (_ error: Error?) -> Void) {
  158. // url
  159. var serverUrl = serverUrl
  160. var url: URLConvertible
  161. do {
  162. if serverUrl.last == "/" {
  163. serverUrl = serverUrl + fileName
  164. } else {
  165. serverUrl = serverUrl + "/" + fileName
  166. }
  167. try url = serverUrl.asURL()
  168. } catch let error {
  169. completionHandler(error)
  170. return
  171. }
  172. // destination
  173. var destination: Alamofire.DownloadRequest.Destination?
  174. if let fileNamePathDestinationURL = URL(string: fileNamePathDestination) {
  175. let destinationFile: DownloadRequest.Destination = { _, _ in
  176. return (fileNamePathDestinationURL, [.removePreviousFile, .createIntermediateDirectories])
  177. }
  178. destination = destinationFile
  179. }
  180. // headers
  181. var headers: HTTPHeaders = [.authorization(username: self.username, password: self.password)]
  182. if let userAgent = self.userAgent { headers.update(.userAgent(userAgent)) }
  183. AF.download(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers, interceptor: nil, to: destination).downloadProgress { progress in
  184. //self.postProgress(progress: progress)
  185. }.responseData { response in
  186. switch response.result {
  187. case.failure(let error):
  188. completionHandler(error)
  189. case .success( _):
  190. completionHandler(nil)
  191. }
  192. }
  193. }
  194. }