NCUtility.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. guard let results = NCManageDatabase.sharedInstance.getDirectEditingEditors(account: metadata.account) else {
  298. return nil
  299. }
  300. for result: tableDirectEditingEditors in results {
  301. for mimetype in result.mimetypes {
  302. if mimetype == metadata.contentType {
  303. return result.name
  304. }
  305. }
  306. for mimetype in result.optionalMimetypes {
  307. if mimetype == metadata.contentType {
  308. return result.name
  309. }
  310. }
  311. }
  312. return nil
  313. }
  314. @objc func removeAllSettings() {
  315. URLCache.shared.memoryCapacity = 0
  316. URLCache.shared.diskCapacity = 0
  317. KTVHTTPCache.cacheDeleteAllCaches()
  318. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeAccount: true)
  319. CCUtility.emptyGroupDirectoryProviderStorage()
  320. CCUtility.emptyGroupLibraryDirectory()
  321. CCUtility.emptyDocumentsDirectory()
  322. CCUtility.emptyTemporaryDirectory()
  323. CCUtility.createDirectoryStandard()
  324. CCUtility.deleteAllChainStore()
  325. }
  326. @objc func createAvatar(fileNameSource: String, fileNameSourceAvatar: String) -> UIImage? {
  327. guard let imageSource = UIImage(contentsOfFile: fileNameSource) else { return nil }
  328. let size = Int(k_avatar_size) ?? 128
  329. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  330. imageSource.draw(in: CGRect(x: 0, y: 0, width: size, height: size))
  331. let image = UIGraphicsGetImageFromCurrentImageContext()
  332. UIGraphicsEndImageContext()
  333. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  334. let avatarImageView = CCAvatar.init(image: image, borderColor: .lightGray, borderWidth: 0.5)
  335. //avatarImageView?.alpha = alpha
  336. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  337. avatarImageView?.layer.render(in: context)
  338. guard let imageAvatar = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
  339. UIGraphicsEndImageContext()
  340. guard let data = imageAvatar.pngData() else {
  341. return nil
  342. }
  343. do {
  344. try data.write(to: NSURL(fileURLWithPath: fileNameSourceAvatar) as URL, options: .atomic)
  345. } catch { }
  346. return imageAvatar
  347. }
  348. func loadImage(ocId: String, fileNameView: String, completion: @escaping (UIImage?) -> Void) {
  349. if let image = cache.object(forKey: ocId as NSString) {
  350. completion(image)
  351. return
  352. }
  353. DispatchQueue.global(qos: .background).async { [weak self] in
  354. let loadedImage = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(ocId, fileNameView: fileNameView))
  355. DispatchQueue.main.async {
  356. if let loadedImage = loadedImage {
  357. self?.cache.setObject(loadedImage, forKey: ocId as NSString)
  358. }
  359. completion(loadedImage)
  360. }
  361. }
  362. }
  363. func UIColorFromRGB(rgbValue: UInt32) -> UIColor {
  364. return UIColor(
  365. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  366. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  367. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  368. alpha: CGFloat(1.0)
  369. )
  370. }
  371. func RGBFromUIColor(uicolorValue: UIColor) -> UInt32 {
  372. var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
  373. if uicolorValue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
  374. var colorAsUInt : UInt32 = 0
  375. colorAsUInt += UInt32(red * 255.0) << 16 +
  376. UInt32(green * 255.0) << 8 +
  377. UInt32(blue * 255.0)
  378. return colorAsUInt
  379. }
  380. return 0
  381. }
  382. func IMUnzip(metadata: tableMetadata) -> Bool {
  383. // bak
  384. let atPathBak = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView
  385. let toPathBak = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension + ".bak"
  386. CCUtility.copyFile(atPath: atPathBak, toPath: toPathBak)
  387. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  388. let destination = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  389. let removeAtPath = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension
  390. try? FileManager.default.removeItem(atPath: removeAtPath)
  391. try? FileManager().unzipItem(at: source, to: destination)
  392. let bundleDirectory = NCUtility.sharedInstance.IMGetBundleDirectory(metadata: metadata)
  393. if bundleDirectory.error {
  394. return false
  395. }
  396. if let fileHandle = FileHandle(forReadingAtPath: bundleDirectory.immPath) {
  397. // let dataFormat = fileHandle.readData(ofLength: 1)
  398. // if dataFormat.starts(with: [0x01]) {
  399. // appDelegate.messageNotification("_error_", description: "File format binary error, library imagemeter not present. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  400. // return;
  401. // }
  402. let dataZip = fileHandle.readData(ofLength: 4)
  403. if dataZip.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
  404. try? FileManager().unzipItem(at: NSURL(fileURLWithPath: bundleDirectory.immPath) as URL, to: NSURL(fileURLWithPath: bundleDirectory.bundleDirectory) as URL)
  405. }
  406. fileHandle.closeFile()
  407. }
  408. return true
  409. }
  410. func IMGetBundleDirectory(metadata: tableMetadata) -> bundleDirectoryType {
  411. var error = true
  412. var bundleDirectory = ""
  413. var immPath = ""
  414. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  415. if let archive = Archive(url: source, accessMode: .read) {
  416. archive.forEach({ (entry) in
  417. let pathComponents = (entry.path as NSString).pathComponents
  418. if pathComponents.count == 2 && (pathComponents.last! as NSString).pathExtension.lowercased() == "imm" {
  419. error = false
  420. bundleDirectory = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + pathComponents.first!
  421. immPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + entry.path
  422. }
  423. })
  424. }
  425. return bundleDirectoryType(error: error, bundleDirectory: bundleDirectory, immPath: immPath)
  426. }
  427. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  428. for char in permissions {
  429. if metadataPermissions.contains(char) == false {
  430. return false
  431. }
  432. }
  433. return true
  434. }
  435. }