NCUtility.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
  87. let scale = newWidth / image.size.width
  88. let newHeight = image.size.height * scale
  89. UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
  90. image.draw(in: (CGRect(x: 0, y: 0, width: newWidth, height: newHeight)))
  91. let newImage = UIGraphicsGetImageFromCurrentImageContext()!
  92. UIGraphicsEndImageContext()
  93. return newImage
  94. }
  95. func cellBlurEffect(with frame: CGRect) -> UIView {
  96. let blurEffect = UIBlurEffect(style: .extraLight)
  97. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  98. blurEffectView.frame = frame
  99. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  100. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  101. return blurEffectView
  102. }
  103. func setLayoutForView(key: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool) {
  104. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)"
  105. UICKeyChainStore.setString(string, forKey: key, service: k_serviceShareKeyChain)
  106. }
  107. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool) {
  108. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  109. return (k_layout_list, "fileName", true, "none", true)
  110. }
  111. let array = string.components(separatedBy: "|")
  112. if array.count == 5 {
  113. let sort = NSString(string: array[2])
  114. let directoryOnTop = NSString(string: array[4])
  115. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue)
  116. }
  117. return (k_layout_list, "fileName", true, "none", true)
  118. }
  119. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, closure: @escaping (String?) -> ()) {
  120. var fileNamePNG = ""
  121. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  122. return closure(nil)
  123. }
  124. guard let iconURL = URL(string: svgUrlString) else {
  125. return closure(nil)
  126. }
  127. if fileName == nil {
  128. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  129. } else {
  130. fileNamePNG = fileName!
  131. }
  132. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  133. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  134. OCNetworking.sharedManager()?.downloadContents(ofUrl: iconURL.absoluteString, completion: { (data, message, errorCode) in
  135. if errorCode == 0 && data != nil {
  136. if let image = UIImage.init(data: data!) {
  137. var newImage: UIImage = image
  138. if width != nil {
  139. let ratio = image.size.height / image.size.width
  140. let newSize = CGSize(width: width!, height: width! * ratio)
  141. let renderFormat = UIGraphicsImageRendererFormat.default()
  142. renderFormat.opaque = false
  143. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  144. newImage = renderer.image {
  145. (context) in
  146. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  147. }
  148. }
  149. guard let pngImageData = newImage.pngData() else {
  150. return closure(nil)
  151. }
  152. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  153. return closure(imageNamePath)
  154. } else {
  155. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  156. return closure(nil)
  157. }
  158. if width != nil {
  159. let scale = svgImage.size.height / svgImage.size.width
  160. svgImage.size = CGSize(width: width!, height: width! * scale)
  161. }
  162. guard let image: UIImage = svgImage.uiImage else {
  163. return closure(nil)
  164. }
  165. guard let pngImageData = image.pngData() else {
  166. return closure(nil)
  167. }
  168. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  169. return closure(imageNamePath)
  170. }
  171. } else {
  172. return closure(nil)
  173. }
  174. })
  175. } else {
  176. return closure(imageNamePath)
  177. }
  178. }
  179. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat) {
  180. guard let view = view else { return }
  181. activityIndicator.color = NCBrandColor.sharedInstance.brand
  182. activityIndicator.hidesWhenStopped = true
  183. view.addSubview(activityIndicator)
  184. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  185. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  186. view.addConstraint(horizontalConstraint)
  187. var verticalConstant: CGFloat = 0
  188. if bottom > 0 {
  189. verticalConstant = (view.frame.size.height / 2) - bottom
  190. }
  191. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  192. view.addConstraint(verticalConstraint)
  193. activityIndicator.startAnimating()
  194. }
  195. @objc func stopActivityIndicator() {
  196. activityIndicator.stopAnimating()
  197. activityIndicator.removeFromSuperview()
  198. }
  199. @objc func isSimulatorOrTestFlight() -> Bool {
  200. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  201. return false
  202. }
  203. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  204. }
  205. @objc func isEditImage(_ fileName: NSString) -> String? {
  206. switch fileName.pathExtension.uppercased() {
  207. case "PNG":
  208. return "PNG";
  209. case "JPG":
  210. return "JPG";
  211. case "JPEG":
  212. return "JPG"
  213. default:
  214. return nil
  215. }
  216. }
  217. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  218. if seconds.isNaN {
  219. return "00:00:00"
  220. }
  221. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  222. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  223. let hour = Int(seconds / 3600)
  224. return String(format: "%02d:%02d:%02d", hour, min, sec)
  225. }
  226. @objc func blink(cell: AnyObject?) {
  227. DispatchQueue.main.async {
  228. if let cell = cell as? UITableViewCell {
  229. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  230. UIView.animate(withDuration: 2) {
  231. cell.backgroundColor = .clear
  232. }
  233. } else if let cell = cell as? UICollectionViewCell {
  234. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  235. UIView.animate(withDuration: 2) {
  236. cell.backgroundColor = .clear
  237. }
  238. }
  239. }
  240. }
  241. @objc func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor) -> UIFont {
  242. let constrainingDimension = min(bounds.width, bounds.height)
  243. let properBounds = CGRect(origin: .zero, size: bounds.size)
  244. var attributes = [NSAttributedString.Key: Any]()
  245. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  246. var bestFontSize: CGFloat = constrainingDimension
  247. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  248. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  249. attributes[.font] = newFont
  250. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  251. if properBounds.contains(currentFrame) {
  252. bestFontSize = fontSize
  253. break
  254. }
  255. }
  256. return UIFont(descriptor: fontDescriptor, size: bestFontSize)
  257. }
  258. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  259. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  260. return false
  261. }
  262. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: metadata.account) else {
  263. return false
  264. }
  265. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  266. let mimeTypeArray = mimeType.components(separatedBy: ".")
  267. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  268. for richdocumentMimetype: String in richdocumentsMimetypes {
  269. if richdocumentMimetype.contains(mimeType) {
  270. return true
  271. }
  272. }
  273. }
  274. return false
  275. }
  276. @objc func removeAllSettings() {
  277. URLCache.shared.memoryCapacity = 0
  278. URLCache.shared.diskCapacity = 0
  279. KTVHTTPCache.cacheDeleteAllCaches()
  280. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeUser: true)
  281. CCUtility.emptyGroupDirectoryProviderStorage()
  282. CCUtility.emptyGroupLibraryDirectory()
  283. CCUtility.emptyDocumentsDirectory()
  284. CCUtility.emptyTemporaryDirectory()
  285. CCUtility.createDirectoryStandard()
  286. CCUtility.deleteAllChainStore()
  287. }
  288. @objc func createAvatar(fileNameSource: String, fileNameSourceAvatar: String) -> UIImage? {
  289. guard let imageSource = UIImage(contentsOfFile: fileNameSource) else { return nil }
  290. let size = Int(k_avatar_size) ?? 128
  291. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  292. imageSource.draw(in: CGRect(x: 0, y: 0, width: size, height: size))
  293. let image = UIGraphicsGetImageFromCurrentImageContext()
  294. UIGraphicsEndImageContext()
  295. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  296. let avatarImageView = CCAvatar.init(image: image, borderColor: .lightGray, borderWidth: 0.5)
  297. //avatarImageView?.alpha = alpha
  298. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  299. avatarImageView?.layer.render(in: context)
  300. guard let imageAvatar = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
  301. UIGraphicsEndImageContext()
  302. guard let data = imageAvatar.pngData() else {
  303. return nil
  304. }
  305. do {
  306. try data.write(to: NSURL(fileURLWithPath: fileNameSourceAvatar) as URL, options: .atomic)
  307. } catch { }
  308. return imageAvatar
  309. }
  310. }