NCUtility.swift 18 KB

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