NCUtility.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. //
  2. // NCUtility.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 25/06/18.
  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 SVGKit
  25. class NCUtility: NSObject {
  26. @objc static let sharedInstance: NCUtility = {
  27. let instance = NCUtility()
  28. return instance
  29. }()
  30. let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
  31. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  32. var resultFileName = fileName
  33. var exitLoop = false
  34. while exitLoop == false {
  35. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  36. var name = NSString(string: resultFileName).deletingPathExtension
  37. let ext = NSString(string: resultFileName).pathExtension
  38. let characters = Array(name)
  39. if characters.count < 2 {
  40. resultFileName = name + " " + "1" + "." + ext
  41. } else {
  42. let space = characters[characters.count-2]
  43. let numChar = characters[characters.count-1]
  44. var num = Int(String(numChar))
  45. if (space == " " && num != nil) {
  46. name = String(name.dropLast())
  47. num = num! + 1
  48. resultFileName = name + "\(num!)" + "." + ext
  49. } else {
  50. resultFileName = name + " " + "1" + "." + ext
  51. }
  52. }
  53. } else {
  54. exitLoop = true
  55. }
  56. }
  57. return resultFileName
  58. }
  59. @objc func isEncryptedMetadata(_ metadata: tableMetadata) -> Bool {
  60. if metadata.fileName != metadata.fileNameView && metadata.fileName.count == 32 && metadata.fileName.contains(".") == false {
  61. return true
  62. }
  63. return false
  64. }
  65. @objc func getFileSize(asset: PHAsset) -> Int64 {
  66. let resources = PHAssetResource.assetResources(for: asset)
  67. if let resource = resources.first {
  68. if resource.responds(to: #selector(NSDictionary.fileSize)) {
  69. let unsignedInt64 = resource.value(forKey: "fileSize") as! CLong
  70. return Int64(bitPattern: UInt64(unsignedInt64))
  71. }
  72. }
  73. return 0
  74. }
  75. @objc func getScreenWidthForPreview() -> CGFloat {
  76. let screenSize = UIScreen.main.bounds
  77. let screenWidth = screenSize.width * 0.75
  78. return screenWidth
  79. }
  80. @objc func getScreenHeightForPreview() -> CGFloat {
  81. let screenSize = UIScreen.main.bounds
  82. let screenWidth = screenSize.height * 0.75
  83. return screenWidth
  84. }
  85. @objc func convertFileIDClientToFileIDServer(_ fileID: NSString) -> String {
  86. let split = fileID.components(separatedBy: "oc")
  87. if split.count == 2 {
  88. let fileIDServerInt = CLongLong(split[0])
  89. return String(describing: fileIDServerInt ?? 0)
  90. }
  91. return fileID as String
  92. }
  93. @objc func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
  94. let scale = newWidth / image.size.width
  95. let newHeight = image.size.height * scale
  96. UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
  97. image.draw(in: (CGRect(x: 0, y: 0, width: newWidth, height: newHeight)))
  98. let newImage = UIGraphicsGetImageFromCurrentImageContext()!
  99. UIGraphicsEndImageContext()
  100. return newImage
  101. }
  102. func cellBlurEffect(with frame: CGRect) -> UIView {
  103. let blurEffect = UIBlurEffect(style: .extraLight)
  104. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  105. blurEffectView.frame = frame
  106. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  107. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  108. return blurEffectView
  109. }
  110. func setLayoutForView(key: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool) {
  111. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)"
  112. UICKeyChainStore.setString(string, forKey: key, service: k_serviceShareKeyChain)
  113. }
  114. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool) {
  115. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  116. return (k_layout_list, "fileName", true, "none", true)
  117. }
  118. let array = string.components(separatedBy: "|")
  119. if array.count == 5 {
  120. let sort = NSString(string: array[2])
  121. let directoryOnTop = NSString(string: array[4])
  122. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue)
  123. }
  124. return (k_layout_list, "fileName", true, "none", true)
  125. }
  126. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, closure: @escaping (String?) -> ()) {
  127. var fileNamePNG = ""
  128. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  129. return closure(nil)
  130. }
  131. guard let iconURL = URL(string: svgUrlString) else {
  132. return closure(nil)
  133. }
  134. if fileName == nil {
  135. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  136. } else {
  137. fileNamePNG = fileName!
  138. }
  139. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  140. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  141. guard let imageData = try? Data(contentsOf:iconURL) else {
  142. return closure(nil)
  143. }
  144. if let image = UIImage.init(data: imageData) {
  145. var newImage: UIImage = image
  146. if width != nil {
  147. let ratio = image.size.height / image.size.width
  148. let newSize = CGSize(width: width!, height: width! * ratio)
  149. let renderFormat = UIGraphicsImageRendererFormat.default()
  150. renderFormat.opaque = false
  151. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  152. newImage = renderer.image {
  153. (context) in
  154. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  155. }
  156. }
  157. guard let pngImageData = newImage.pngData() else {
  158. return closure(nil)
  159. }
  160. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  161. } else {
  162. let task = URLSession(configuration: .default).dataTask(with: iconURL) { (data, response, error) in
  163. guard error == nil, response != nil, data != nil else {
  164. return closure(nil)
  165. }
  166. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  167. return closure(nil)
  168. }
  169. if width != nil {
  170. let scale = svgImage.size.height / svgImage.size.width
  171. svgImage.size = CGSize(width: width!, height: width! * scale)
  172. }
  173. guard let image: UIImage = svgImage.uiImage else {
  174. return closure(nil)
  175. }
  176. guard let pngImageData = image.pngData() else {
  177. return closure(nil)
  178. }
  179. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  180. DispatchQueue.main.async {
  181. return closure(imageNamePath)
  182. }
  183. }
  184. task.resume()
  185. }
  186. }
  187. return closure(imageNamePath)
  188. }
  189. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool) -> String? {
  190. var fileNamePNG = ""
  191. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  192. return nil
  193. }
  194. guard let iconURL = URL(string: svgUrlString) else {
  195. return nil
  196. }
  197. if fileName == nil {
  198. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  199. } else {
  200. fileNamePNG = fileName!
  201. }
  202. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  203. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  204. guard let imageData = try? Data(contentsOf:iconURL) else {
  205. return nil
  206. }
  207. if let image = UIImage.init(data: imageData) {
  208. var newImage: UIImage = image
  209. if width != nil {
  210. let ratio = image.size.height / image.size.width
  211. let newSize = CGSize(width: width!, height: width! * ratio)
  212. let renderFormat = UIGraphicsImageRendererFormat.default()
  213. renderFormat.opaque = false
  214. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  215. newImage = renderer.image {
  216. (context) in
  217. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  218. }
  219. }
  220. guard let pngImageData = newImage.pngData() else {
  221. return nil
  222. }
  223. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  224. } else {
  225. guard let svgImage: SVGKImage = SVGKImage(contentsOf: iconURL) else {
  226. return nil
  227. }
  228. if width != nil {
  229. let scale = svgImage.size.height / svgImage.size.width
  230. svgImage.size = CGSize(width: width!, height: width! * scale)
  231. }
  232. guard let image: UIImage = svgImage.uiImage else {
  233. return nil
  234. }
  235. guard let pngImageData = image.pngData() else {
  236. return nil
  237. }
  238. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  239. return imageNamePath
  240. }
  241. }
  242. return imageNamePath
  243. }
  244. @objc func startActivityIndicator(view: UIView, bottom: CGFloat) {
  245. activityIndicator.color = NCBrandColor.sharedInstance.brand
  246. activityIndicator.hidesWhenStopped = true
  247. view.addSubview(activityIndicator)
  248. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  249. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  250. view.addConstraint(horizontalConstraint)
  251. var verticalConstant: CGFloat = 0
  252. if bottom > 0 {
  253. verticalConstant = (view.frame.size.height / 2) - bottom
  254. }
  255. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  256. view.addConstraint(verticalConstraint)
  257. activityIndicator.startAnimating()
  258. }
  259. @objc func stopActivityIndicator() {
  260. activityIndicator.stopAnimating()
  261. activityIndicator.removeFromSuperview()
  262. }
  263. @objc func isSimulatorOrTestFlight() -> Bool {
  264. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  265. return false
  266. }
  267. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  268. }
  269. @objc func isEditImage(_ fileName: NSString) -> String? {
  270. switch fileName.pathExtension.uppercased() {
  271. case "PNG":
  272. return "PNG";
  273. case "JPG":
  274. return "JPG";
  275. case "JPEG":
  276. return "JPG"
  277. default:
  278. return nil
  279. }
  280. }
  281. }