NCUtility.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. struct bundleDirectoryType {
  36. var error: Bool = false
  37. var bundleDirectory: String = ""
  38. var immPath: String = ""
  39. }
  40. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  41. var resultFileName = fileName
  42. var exitLoop = false
  43. while exitLoop == false {
  44. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  45. var name = NSString(string: resultFileName).deletingPathExtension
  46. let ext = NSString(string: resultFileName).pathExtension
  47. let characters = Array(name)
  48. if characters.count < 2 {
  49. if ext == "" {
  50. resultFileName = name + " " + "1"
  51. } else {
  52. resultFileName = name + " " + "1" + "." + ext
  53. }
  54. } else {
  55. let space = characters[characters.count-2]
  56. let numChar = characters[characters.count-1]
  57. var num = Int(String(numChar))
  58. if (space == " " && num != nil) {
  59. name = String(name.dropLast())
  60. num = num! + 1
  61. if ext == "" {
  62. resultFileName = name + "\(num!)"
  63. } else {
  64. resultFileName = name + "\(num!)" + "." + ext
  65. }
  66. } else {
  67. if ext == "" {
  68. resultFileName = name + " " + "1"
  69. } else {
  70. resultFileName = name + " " + "1" + "." + ext
  71. }
  72. }
  73. }
  74. } else {
  75. exitLoop = true
  76. }
  77. }
  78. return resultFileName
  79. }
  80. @objc func isEncryptedMetadata(_ metadata: tableMetadata) -> Bool {
  81. if metadata.fileName != metadata.fileNameView && metadata.fileName.count == 32 && metadata.fileName.contains(".") == false {
  82. return true
  83. }
  84. return false
  85. }
  86. @objc func getFileSize(asset: PHAsset) -> Int64 {
  87. let resources = PHAssetResource.assetResources(for: asset)
  88. if let resource = resources.first {
  89. if resource.responds(to: #selector(NSDictionary.fileSize)) {
  90. let unsignedInt64 = resource.value(forKey: "fileSize") as! CLong
  91. return Int64(bitPattern: UInt64(unsignedInt64))
  92. }
  93. }
  94. return 0
  95. }
  96. @objc func getScreenWidthForPreview() -> CGFloat {
  97. let screenSize = UIScreen.main.bounds
  98. let screenWidth = screenSize.width * 0.75
  99. return screenWidth
  100. }
  101. @objc func getScreenHeightForPreview() -> CGFloat {
  102. let screenSize = UIScreen.main.bounds
  103. let screenWidth = screenSize.height * 0.75
  104. return screenWidth
  105. }
  106. @objc func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
  107. let scale = newWidth / image.size.width
  108. let newHeight = image.size.height * scale
  109. UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
  110. image.draw(in: (CGRect(x: 0, y: 0, width: newWidth, height: newHeight)))
  111. let newImage = UIGraphicsGetImageFromCurrentImageContext()!
  112. UIGraphicsEndImageContext()
  113. return newImage
  114. }
  115. func cellBlurEffect(with frame: CGRect) -> UIView {
  116. let blurEffect = UIBlurEffect(style: .extraLight)
  117. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  118. blurEffectView.frame = frame
  119. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  120. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  121. return blurEffectView
  122. }
  123. func setLayoutForView(key: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool) {
  124. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)"
  125. UICKeyChainStore.setString(string, forKey: key, service: k_serviceShareKeyChain)
  126. }
  127. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool) {
  128. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  129. return (k_layout_list, "fileName", true, "none", true)
  130. }
  131. let array = string.components(separatedBy: "|")
  132. if array.count == 5 {
  133. let sort = NSString(string: array[2])
  134. let directoryOnTop = NSString(string: array[4])
  135. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue)
  136. }
  137. return (k_layout_list, "fileName", true, "none", true)
  138. }
  139. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, closure: @escaping (String?) -> ()) {
  140. var fileNamePNG = ""
  141. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  142. return closure(nil)
  143. }
  144. guard let iconURL = URL(string: svgUrlString) else {
  145. return closure(nil)
  146. }
  147. if fileName == nil {
  148. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  149. } else {
  150. fileNamePNG = fileName!
  151. }
  152. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  153. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  154. OCNetworking.sharedManager()?.downloadContents(ofUrl: iconURL.absoluteString, completion: { (data, message, errorCode) in
  155. if errorCode == 0 && data != nil {
  156. if let image = UIImage.init(data: data!) {
  157. var newImage: UIImage = image
  158. if width != nil {
  159. let ratio = image.size.height / image.size.width
  160. let newSize = CGSize(width: width!, height: width! * ratio)
  161. let renderFormat = UIGraphicsImageRendererFormat.default()
  162. renderFormat.opaque = false
  163. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  164. newImage = renderer.image {
  165. (context) in
  166. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  167. }
  168. }
  169. guard let pngImageData = newImage.pngData() else {
  170. return closure(nil)
  171. }
  172. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  173. return closure(imageNamePath)
  174. } else {
  175. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  176. return closure(nil)
  177. }
  178. if width != nil {
  179. let scale = svgImage.size.height / svgImage.size.width
  180. svgImage.size = CGSize(width: width!, height: width! * scale)
  181. }
  182. guard let image: UIImage = svgImage.uiImage else {
  183. return closure(nil)
  184. }
  185. guard let pngImageData = image.pngData() else {
  186. return closure(nil)
  187. }
  188. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  189. return closure(imageNamePath)
  190. }
  191. } else {
  192. return closure(nil)
  193. }
  194. })
  195. } else {
  196. return closure(imageNamePath)
  197. }
  198. }
  199. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat) {
  200. guard let view = view else { return }
  201. activityIndicator.color = NCBrandColor.sharedInstance.brand
  202. activityIndicator.hidesWhenStopped = true
  203. view.addSubview(activityIndicator)
  204. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  205. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  206. view.addConstraint(horizontalConstraint)
  207. var verticalConstant: CGFloat = 0
  208. if bottom > 0 {
  209. verticalConstant = (view.frame.size.height / 2) - bottom
  210. }
  211. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  212. view.addConstraint(verticalConstraint)
  213. activityIndicator.startAnimating()
  214. }
  215. @objc func stopActivityIndicator() {
  216. activityIndicator.stopAnimating()
  217. activityIndicator.removeFromSuperview()
  218. }
  219. @objc func isSimulatorOrTestFlight() -> Bool {
  220. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  221. return false
  222. }
  223. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  224. }
  225. @objc func isEditImage(_ fileName: NSString) -> String? {
  226. switch fileName.pathExtension.uppercased() {
  227. case "PNG":
  228. return "PNG";
  229. case "JPG":
  230. return "JPG";
  231. case "JPEG":
  232. return "JPG"
  233. default:
  234. return nil
  235. }
  236. }
  237. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  238. if seconds.isNaN {
  239. return "00:00:00"
  240. }
  241. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  242. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  243. let hour = Int(seconds / 3600)
  244. return String(format: "%02d:%02d:%02d", hour, min, sec)
  245. }
  246. @objc func blink(cell: AnyObject?) {
  247. DispatchQueue.main.async {
  248. if let cell = cell as? UITableViewCell {
  249. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  250. UIView.animate(withDuration: 2) {
  251. cell.backgroundColor = .clear
  252. }
  253. } else if let cell = cell as? UICollectionViewCell {
  254. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  255. UIView.animate(withDuration: 2) {
  256. cell.backgroundColor = .clear
  257. }
  258. }
  259. }
  260. }
  261. @objc func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor) -> UIFont {
  262. let constrainingDimension = min(bounds.width, bounds.height)
  263. let properBounds = CGRect(origin: .zero, size: bounds.size)
  264. var attributes = [NSAttributedString.Key: Any]()
  265. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  266. var bestFontSize: CGFloat = constrainingDimension
  267. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  268. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  269. attributes[.font] = newFont
  270. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  271. if properBounds.contains(currentFrame) {
  272. bestFontSize = fontSize
  273. break
  274. }
  275. }
  276. return UIFont(descriptor: fontDescriptor, size: bestFontSize)
  277. }
  278. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  279. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  280. return false
  281. }
  282. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: metadata.account) else {
  283. return false
  284. }
  285. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  286. let mimeTypeArray = mimeType.components(separatedBy: ".")
  287. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  288. for richdocumentMimetype: String in richdocumentsMimetypes {
  289. if richdocumentMimetype.contains(mimeType) {
  290. return true
  291. }
  292. }
  293. }
  294. return false
  295. }
  296. @objc func isDirectEditing(_ metadata: tableMetadata) -> String? {
  297. if NCBrandBeta.shared.directEditing == false {
  298. return nil
  299. }
  300. guard let results = NCManageDatabase.sharedInstance.getDirectEditingEditors(account: metadata.account) else {
  301. return nil
  302. }
  303. for result: tableDirectEditingEditors in results {
  304. for mimetype in result.mimetypes {
  305. if mimetype == metadata.contentType {
  306. return result.name
  307. }
  308. }
  309. for mimetype in result.optionalMimetypes {
  310. if mimetype == metadata.contentType {
  311. return result.name
  312. }
  313. }
  314. }
  315. return nil
  316. }
  317. @objc func removeAllSettings() {
  318. URLCache.shared.memoryCapacity = 0
  319. URLCache.shared.diskCapacity = 0
  320. KTVHTTPCache.cacheDeleteAllCaches()
  321. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeAccount: true)
  322. CCUtility.emptyGroupDirectoryProviderStorage()
  323. CCUtility.emptyGroupLibraryDirectory()
  324. CCUtility.emptyDocumentsDirectory()
  325. CCUtility.emptyTemporaryDirectory()
  326. CCUtility.createDirectoryStandard()
  327. CCUtility.deleteAllChainStore()
  328. }
  329. @objc func createAvatar(fileNameSource: String, fileNameSourceAvatar: String) -> UIImage? {
  330. guard let imageSource = UIImage(contentsOfFile: fileNameSource) else { return nil }
  331. let size = Int(k_avatar_size) ?? 128
  332. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  333. imageSource.draw(in: CGRect(x: 0, y: 0, width: size, height: size))
  334. let image = UIGraphicsGetImageFromCurrentImageContext()
  335. UIGraphicsEndImageContext()
  336. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  337. let avatarImageView = CCAvatar.init(image: image, borderColor: .lightGray, borderWidth: 0.5)
  338. //avatarImageView?.alpha = alpha
  339. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  340. avatarImageView?.layer.render(in: context)
  341. guard let imageAvatar = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
  342. UIGraphicsEndImageContext()
  343. guard let data = imageAvatar.pngData() else {
  344. return nil
  345. }
  346. do {
  347. try data.write(to: NSURL(fileURLWithPath: fileNameSourceAvatar) as URL, options: .atomic)
  348. } catch { }
  349. return imageAvatar
  350. }
  351. func loadImage(ocId: String, fileNameView: String, completion: @escaping (UIImage?) -> Void) {
  352. if let image = cache.object(forKey: ocId as NSString) {
  353. completion(image)
  354. return
  355. }
  356. DispatchQueue.global(qos: .background).async { [weak self] in
  357. let loadedImage = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(ocId, fileNameView: fileNameView))
  358. DispatchQueue.main.async {
  359. if let loadedImage = loadedImage {
  360. self?.cache.setObject(loadedImage, forKey: ocId as NSString)
  361. }
  362. completion(loadedImage)
  363. }
  364. }
  365. }
  366. func UIColorFromRGB(rgbValue: UInt32) -> UIColor {
  367. return UIColor(
  368. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  369. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  370. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  371. alpha: CGFloat(1.0)
  372. )
  373. }
  374. func RGBFromUIColor(uicolorValue: UIColor) -> UInt32 {
  375. var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
  376. if uicolorValue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
  377. var colorAsUInt : UInt32 = 0
  378. colorAsUInt += UInt32(red * 255.0) << 16 +
  379. UInt32(green * 255.0) << 8 +
  380. UInt32(blue * 255.0)
  381. return colorAsUInt
  382. }
  383. return 0
  384. }
  385. func IMUnzip(metadata: tableMetadata) -> Bool {
  386. // bak
  387. let atPathBak = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView
  388. let toPathBak = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension + ".bak"
  389. CCUtility.copyFile(atPath: atPathBak, toPath: toPathBak)
  390. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  391. let destination = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  392. let removeAtPath = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension
  393. try? FileManager.default.removeItem(atPath: removeAtPath)
  394. try? FileManager().unzipItem(at: source, to: destination)
  395. let bundleDirectory = NCUtility.sharedInstance.IMGetBundleDirectory(metadata: metadata)
  396. if bundleDirectory.error {
  397. return false
  398. }
  399. if let fileHandle = FileHandle(forReadingAtPath: bundleDirectory.immPath) {
  400. // let dataFormat = fileHandle.readData(ofLength: 1)
  401. // if dataFormat.starts(with: [0x01]) {
  402. // appDelegate.messageNotification("_error_", description: "File format binary error, library imagemeter not present. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  403. // return;
  404. // }
  405. let dataZip = fileHandle.readData(ofLength: 4)
  406. if dataZip.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
  407. try? FileManager().unzipItem(at: NSURL(fileURLWithPath: bundleDirectory.immPath) as URL, to: NSURL(fileURLWithPath: bundleDirectory.bundleDirectory) as URL)
  408. }
  409. fileHandle.closeFile()
  410. }
  411. return true
  412. }
  413. func IMGetBundleDirectory(metadata: tableMetadata) -> bundleDirectoryType {
  414. var error = true
  415. var bundleDirectory = ""
  416. var immPath = ""
  417. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  418. if let archive = Archive(url: source, accessMode: .read) {
  419. archive.forEach({ (entry) in
  420. let pathComponents = (entry.path as NSString).pathComponents
  421. if pathComponents.count == 2 && (pathComponents.last! as NSString).pathExtension.lowercased() == "imm" {
  422. error = false
  423. bundleDirectory = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + pathComponents.first!
  424. immPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + entry.path
  425. }
  426. })
  427. }
  428. return bundleDirectoryType(error: error, bundleDirectory: bundleDirectory, immPath: immPath)
  429. }
  430. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  431. for char in permissions {
  432. if metadataPermissions.contains(char) == false {
  433. return false
  434. }
  435. }
  436. return true
  437. }
  438. }