NCUtility.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. import KTVHTTPCache
  26. class NCUtility: NSObject {
  27. @objc static let sharedInstance: NCUtility = {
  28. let instance = NCUtility()
  29. return instance
  30. }()
  31. let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
  32. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  33. var resultFileName = fileName
  34. var exitLoop = false
  35. while exitLoop == false {
  36. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  37. var name = NSString(string: resultFileName).deletingPathExtension
  38. let ext = NSString(string: resultFileName).pathExtension
  39. let characters = Array(name)
  40. if characters.count < 2 {
  41. resultFileName = name + " " + "1" + "." + ext
  42. } else {
  43. let space = characters[characters.count-2]
  44. let numChar = characters[characters.count-1]
  45. var num = Int(String(numChar))
  46. if (space == " " && num != nil) {
  47. name = String(name.dropLast())
  48. num = num! + 1
  49. resultFileName = name + "\(num!)" + "." + ext
  50. } else {
  51. resultFileName = name + " " + "1" + "." + ext
  52. }
  53. }
  54. } else {
  55. exitLoop = true
  56. }
  57. }
  58. return resultFileName
  59. }
  60. @objc func isEncryptedMetadata(_ metadata: tableMetadata) -> Bool {
  61. if metadata.fileName != metadata.fileNameView && metadata.fileName.count == 32 && metadata.fileName.contains(".") == false {
  62. return true
  63. }
  64. return false
  65. }
  66. @objc func getFileSize(asset: PHAsset) -> Int64 {
  67. let resources = PHAssetResource.assetResources(for: asset)
  68. if let resource = resources.first {
  69. if resource.responds(to: #selector(NSDictionary.fileSize)) {
  70. let unsignedInt64 = resource.value(forKey: "fileSize") as! CLong
  71. return Int64(bitPattern: UInt64(unsignedInt64))
  72. }
  73. }
  74. return 0
  75. }
  76. @objc func getScreenWidthForPreview() -> CGFloat {
  77. let screenSize = UIScreen.main.bounds
  78. let screenWidth = screenSize.width * 0.75
  79. return screenWidth
  80. }
  81. @objc func getScreenHeightForPreview() -> CGFloat {
  82. let screenSize = UIScreen.main.bounds
  83. let screenWidth = screenSize.height * 0.75
  84. return screenWidth
  85. }
  86. @objc func convertFileIDClientToFileIDServer(_ fileID: NSString) -> String {
  87. let split = fileID.components(separatedBy: "oc")
  88. if split.count == 2 {
  89. let fileIDServerInt = CLongLong(split[0])
  90. return String(describing: fileIDServerInt ?? 0)
  91. }
  92. return fileID as String
  93. }
  94. @objc func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
  95. let scale = newWidth / image.size.width
  96. let newHeight = image.size.height * scale
  97. UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
  98. image.draw(in: (CGRect(x: 0, y: 0, width: newWidth, height: newHeight)))
  99. let newImage = UIGraphicsGetImageFromCurrentImageContext()!
  100. UIGraphicsEndImageContext()
  101. return newImage
  102. }
  103. func cellBlurEffect(with frame: CGRect) -> UIView {
  104. let blurEffect = UIBlurEffect(style: .extraLight)
  105. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  106. blurEffectView.frame = frame
  107. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  108. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  109. return blurEffectView
  110. }
  111. func setLayoutForView(key: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool) {
  112. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)"
  113. UICKeyChainStore.setString(string, forKey: key, service: k_serviceShareKeyChain)
  114. }
  115. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool) {
  116. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  117. return (k_layout_list, "fileName", true, "none", true)
  118. }
  119. let array = string.components(separatedBy: "|")
  120. if array.count == 5 {
  121. let sort = NSString(string: array[2])
  122. let directoryOnTop = NSString(string: array[4])
  123. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue)
  124. }
  125. return (k_layout_list, "fileName", true, "none", true)
  126. }
  127. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, closure: @escaping (String?) -> ()) {
  128. var fileNamePNG = ""
  129. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  130. return closure(nil)
  131. }
  132. guard let iconURL = URL(string: svgUrlString) else {
  133. return closure(nil)
  134. }
  135. if fileName == nil {
  136. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  137. } else {
  138. fileNamePNG = fileName!
  139. }
  140. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  141. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  142. OCNetworking.sharedManager()?.downloadContents(ofUrl: iconURL.absoluteString, completion: { (data, message, errorCode) in
  143. if errorCode == 0 && data != nil {
  144. if let image = UIImage.init(data: data!) {
  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. return closure(imageNamePath)
  162. } else {
  163. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  164. return closure(nil)
  165. }
  166. if width != nil {
  167. let scale = svgImage.size.height / svgImage.size.width
  168. svgImage.size = CGSize(width: width!, height: width! * scale)
  169. }
  170. guard let image: UIImage = svgImage.uiImage else {
  171. return closure(nil)
  172. }
  173. guard let pngImageData = image.pngData() else {
  174. return closure(nil)
  175. }
  176. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  177. return closure(imageNamePath)
  178. }
  179. } else {
  180. return closure(nil)
  181. }
  182. })
  183. } else {
  184. return closure(imageNamePath)
  185. }
  186. }
  187. @objc func startActivityIndicator(view: UIView, bottom: CGFloat) {
  188. activityIndicator.color = NCBrandColor.sharedInstance.brand
  189. activityIndicator.hidesWhenStopped = true
  190. view.addSubview(activityIndicator)
  191. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  192. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  193. view.addConstraint(horizontalConstraint)
  194. var verticalConstant: CGFloat = 0
  195. if bottom > 0 {
  196. verticalConstant = (view.frame.size.height / 2) - bottom
  197. }
  198. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  199. view.addConstraint(verticalConstraint)
  200. activityIndicator.startAnimating()
  201. }
  202. @objc func stopActivityIndicator() {
  203. activityIndicator.stopAnimating()
  204. activityIndicator.removeFromSuperview()
  205. }
  206. @objc func isSimulatorOrTestFlight() -> Bool {
  207. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  208. return false
  209. }
  210. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  211. }
  212. @objc func isEditImage(_ fileName: NSString) -> String? {
  213. switch fileName.pathExtension.uppercased() {
  214. case "PNG":
  215. return "PNG";
  216. case "JPG":
  217. return "JPG";
  218. case "JPEG":
  219. return "JPG"
  220. default:
  221. return nil
  222. }
  223. }
  224. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  225. if seconds.isNaN {
  226. return "00:00:00"
  227. }
  228. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  229. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  230. let hour = Int(seconds / 3600)
  231. return String(format: "%02d:%02d:%02d", hour, min, sec)
  232. }
  233. @objc func blink(cell: AnyObject?) {
  234. DispatchQueue.main.async {
  235. if let cell = cell as? UITableViewCell {
  236. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  237. UIView.animate(withDuration: 2) {
  238. cell.backgroundColor = .clear
  239. }
  240. } else if let cell = cell as? UICollectionViewCell {
  241. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  242. UIView.animate(withDuration: 2) {
  243. cell.backgroundColor = .clear
  244. }
  245. }
  246. }
  247. }
  248. @objc func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor) -> UIFont {
  249. let constrainingDimension = min(bounds.width, bounds.height)
  250. let properBounds = CGRect(origin: .zero, size: bounds.size)
  251. var attributes = [NSAttributedString.Key: Any]()
  252. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  253. var bestFontSize: CGFloat = constrainingDimension
  254. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  255. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  256. attributes[.font] = newFont
  257. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  258. if properBounds.contains(currentFrame) {
  259. bestFontSize = fontSize
  260. break
  261. }
  262. }
  263. return UIFont(descriptor: fontDescriptor, size: bestFontSize)
  264. }
  265. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  266. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  267. return false
  268. }
  269. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: metadata.account) else {
  270. return false
  271. }
  272. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  273. let mimeTypeArray = mimeType.components(separatedBy: ".")
  274. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  275. for richdocumentMimetype: String in richdocumentsMimetypes {
  276. if richdocumentMimetype.contains(mimeType) {
  277. return true
  278. }
  279. }
  280. }
  281. return false
  282. }
  283. @objc func removeAllSettings() {
  284. CCNetworking.shared()?.invalidateAndCancelAllSession()
  285. URLCache.shared.memoryCapacity = 0
  286. URLCache.shared.diskCapacity = 0
  287. KTVHTTPCache.cacheDeleteAllCaches()
  288. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeUser: true)
  289. CCUtility.emptyGroupDirectoryProviderStorage()
  290. CCUtility.emptyGroupLibraryDirectory()
  291. CCUtility.emptyGroupCaches()
  292. CCUtility.emptyDocumentsDirectory()
  293. CCUtility.emptyTemporaryDirectory()
  294. CCUtility.emptyLibraryDirectory()
  295. CCUtility.createDirectoryStandard()
  296. CCUtility.deleteAllChainStore()
  297. }
  298. }