NCUtility.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. } else {
  183. return closure(imageNamePath)
  184. }
  185. }
  186. @objc func startActivityIndicator(view: UIView, bottom: CGFloat) {
  187. activityIndicator.color = NCBrandColor.sharedInstance.brand
  188. activityIndicator.hidesWhenStopped = true
  189. view.addSubview(activityIndicator)
  190. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  191. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  192. view.addConstraint(horizontalConstraint)
  193. var verticalConstant: CGFloat = 0
  194. if bottom > 0 {
  195. verticalConstant = (view.frame.size.height / 2) - bottom
  196. }
  197. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  198. view.addConstraint(verticalConstraint)
  199. activityIndicator.startAnimating()
  200. }
  201. @objc func stopActivityIndicator() {
  202. activityIndicator.stopAnimating()
  203. activityIndicator.removeFromSuperview()
  204. }
  205. @objc func isSimulatorOrTestFlight() -> Bool {
  206. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  207. return false
  208. }
  209. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  210. }
  211. @objc func isEditImage(_ fileName: NSString) -> String? {
  212. switch fileName.pathExtension.uppercased() {
  213. case "PNG":
  214. return "PNG";
  215. case "JPG":
  216. return "JPG";
  217. case "JPEG":
  218. return "JPG"
  219. default:
  220. return nil
  221. }
  222. }
  223. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  224. if seconds.isNaN {
  225. return "00:00:00"
  226. }
  227. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  228. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  229. let hour = Int(seconds / 3600)
  230. return String(format: "%02d:%02d:%02d", hour, min, sec)
  231. }
  232. @objc func blink(cell: AnyObject?) {
  233. if let cell = cell as? UITableViewCell {
  234. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  235. UIView.animate(withDuration: 2) {
  236. cell.backgroundColor = .clear
  237. }
  238. } else if let cell = cell as? UICollectionViewCell {
  239. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  240. UIView.animate(withDuration: 2) {
  241. cell.backgroundColor = .clear
  242. }
  243. }
  244. }
  245. }