NCUtility.swift 23 KB

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