NCUtility.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. OCNetworking.sharedManager()?.downloadContents(ofUrl: iconURL.absoluteString, completion: { (data, message, errorCode) in
  142. if errorCode == 0 && data != nil {
  143. if let image = UIImage.init(data: data!) {
  144. var newImage: UIImage = image
  145. if width != nil {
  146. let ratio = image.size.height / image.size.width
  147. let newSize = CGSize(width: width!, height: width! * ratio)
  148. let renderFormat = UIGraphicsImageRendererFormat.default()
  149. renderFormat.opaque = false
  150. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  151. newImage = renderer.image {
  152. (context) in
  153. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  154. }
  155. }
  156. guard let pngImageData = newImage.pngData() else {
  157. return closure(nil)
  158. }
  159. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  160. return closure(imageNamePath)
  161. } else {
  162. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  163. return closure(nil)
  164. }
  165. if width != nil {
  166. let scale = svgImage.size.height / svgImage.size.width
  167. svgImage.size = CGSize(width: width!, height: width! * scale)
  168. }
  169. guard let image: UIImage = svgImage.uiImage else {
  170. return closure(nil)
  171. }
  172. guard let pngImageData = image.pngData() else {
  173. return closure(nil)
  174. }
  175. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  176. return closure(imageNamePath)
  177. }
  178. } else {
  179. return closure(nil)
  180. }
  181. })
  182. }
  183. }
  184. @objc func startActivityIndicator(view: UIView, bottom: CGFloat) {
  185. activityIndicator.color = NCBrandColor.sharedInstance.brand
  186. activityIndicator.hidesWhenStopped = true
  187. view.addSubview(activityIndicator)
  188. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  189. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  190. view.addConstraint(horizontalConstraint)
  191. var verticalConstant: CGFloat = 0
  192. if bottom > 0 {
  193. verticalConstant = (view.frame.size.height / 2) - bottom
  194. }
  195. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  196. view.addConstraint(verticalConstraint)
  197. activityIndicator.startAnimating()
  198. }
  199. @objc func stopActivityIndicator() {
  200. activityIndicator.stopAnimating()
  201. activityIndicator.removeFromSuperview()
  202. }
  203. @objc func isSimulatorOrTestFlight() -> Bool {
  204. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  205. return false
  206. }
  207. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  208. }
  209. @objc func isEditImage(_ fileName: NSString) -> String? {
  210. switch fileName.pathExtension.uppercased() {
  211. case "PNG":
  212. return "PNG";
  213. case "JPG":
  214. return "JPG";
  215. case "JPEG":
  216. return "JPG"
  217. default:
  218. return nil
  219. }
  220. }
  221. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  222. if seconds.isNaN {
  223. return "00:00:00"
  224. }
  225. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  226. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  227. let hour = Int(seconds / 3600)
  228. return String(format: "%02d:%02d:%02d", hour, min, sec)
  229. }
  230. }