NCUtility.swift 18 KB

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