NCUtility.swift 17 KB

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