NCUtility.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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 NCCommunication
  27. import PDFKit
  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. @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. if ext == "" {
  44. resultFileName = name + " " + "1"
  45. } else {
  46. resultFileName = name + " " + "1" + "." + ext
  47. }
  48. } else {
  49. let space = characters[characters.count-2]
  50. let numChar = characters[characters.count-1]
  51. var num = Int(String(numChar))
  52. if (space == " " && num != nil) {
  53. name = String(name.dropLast())
  54. num = num! + 1
  55. if ext == "" {
  56. resultFileName = name + "\(num!)"
  57. } else {
  58. resultFileName = name + "\(num!)" + "." + ext
  59. }
  60. } else {
  61. if ext == "" {
  62. resultFileName = name + " " + "1"
  63. } else {
  64. resultFileName = name + " " + "1" + "." + ext
  65. }
  66. }
  67. }
  68. } else {
  69. exitLoop = true
  70. }
  71. }
  72. return resultFileName
  73. }
  74. @objc func isEncryptedMetadata(_ metadata: tableMetadata) -> Bool {
  75. if metadata.fileName != metadata.fileNameView && metadata.fileName.count == 32 && metadata.fileName.contains(".") == false {
  76. return true
  77. }
  78. return false
  79. }
  80. @objc func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
  81. let scale = newWidth / image.size.width
  82. let newHeight = image.size.height * scale
  83. UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
  84. image.draw(in: (CGRect(x: 0, y: 0, width: newWidth, height: newHeight)))
  85. let newImage = UIGraphicsGetImageFromCurrentImageContext()!
  86. UIGraphicsEndImageContext()
  87. return newImage
  88. }
  89. func cellBlurEffect(with frame: CGRect) -> UIView {
  90. let blurEffect = UIBlurEffect(style: .extraLight)
  91. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  92. blurEffectView.frame = frame
  93. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  94. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  95. return blurEffectView
  96. }
  97. func setLayoutForView(key: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool) {
  98. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)"
  99. UICKeyChainStore.setString(string, forKey: key, service: k_serviceShareKeyChain)
  100. }
  101. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool) {
  102. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  103. return (k_layout_list, "fileName", true, "none", true)
  104. }
  105. let array = string.components(separatedBy: "|")
  106. if array.count == 5 {
  107. let sort = NSString(string: array[2])
  108. let directoryOnTop = NSString(string: array[4])
  109. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue)
  110. }
  111. return (k_layout_list, "fileName", true, "none", true)
  112. }
  113. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, account: String, closure: @escaping (String?) -> ()) {
  114. var fileNamePNG = ""
  115. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  116. return closure(nil)
  117. }
  118. guard let iconURL = URL(string: svgUrlString) else {
  119. return closure(nil)
  120. }
  121. if fileName == nil {
  122. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  123. } else {
  124. fileNamePNG = fileName!
  125. }
  126. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  127. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  128. NCCommunication.shared.downloadContent(serverUrl: iconURL.absoluteString) { (account, data, errorCode, errorMessage) in
  129. if errorCode == 0 && data != nil {
  130. if let image = UIImage.init(data: data!) {
  131. var newImage: UIImage = image
  132. if width != nil {
  133. let ratio = image.size.height / image.size.width
  134. let newSize = CGSize(width: width!, height: width! * ratio)
  135. let renderFormat = UIGraphicsImageRendererFormat.default()
  136. renderFormat.opaque = false
  137. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  138. newImage = renderer.image {
  139. (context) in
  140. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  141. }
  142. }
  143. guard let pngImageData = newImage.pngData() else {
  144. return closure(nil)
  145. }
  146. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  147. return closure(imageNamePath)
  148. } else {
  149. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  150. return closure(nil)
  151. }
  152. if width != nil {
  153. let scale = svgImage.size.height / svgImage.size.width
  154. svgImage.size = CGSize(width: width!, height: width! * scale)
  155. }
  156. guard let image: UIImage = svgImage.uiImage else {
  157. return closure(nil)
  158. }
  159. guard let pngImageData = image.pngData() else {
  160. return closure(nil)
  161. }
  162. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  163. return closure(imageNamePath)
  164. }
  165. } else {
  166. return closure(nil)
  167. }
  168. }
  169. } else {
  170. return closure(imageNamePath)
  171. }
  172. }
  173. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat) {
  174. guard let view = view else { return }
  175. activityIndicator.color = NCBrandColor.sharedInstance.brand
  176. activityIndicator.hidesWhenStopped = true
  177. view.addSubview(activityIndicator)
  178. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  179. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  180. view.addConstraint(horizontalConstraint)
  181. var verticalConstant: CGFloat = 0
  182. if bottom > 0 {
  183. verticalConstant = (view.frame.size.height / 2) - bottom
  184. }
  185. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  186. view.addConstraint(verticalConstraint)
  187. activityIndicator.startAnimating()
  188. }
  189. @objc func stopActivityIndicator() {
  190. activityIndicator.stopAnimating()
  191. activityIndicator.removeFromSuperview()
  192. }
  193. @objc func isSimulatorOrTestFlight() -> Bool {
  194. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  195. return false
  196. }
  197. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  198. }
  199. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  200. if seconds.isNaN {
  201. return "00:00:00"
  202. }
  203. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  204. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  205. let hour = Int(seconds / 3600)
  206. return String(format: "%02d:%02d:%02d", hour, min, sec)
  207. }
  208. @objc func blink(cell: AnyObject?) {
  209. DispatchQueue.main.async {
  210. if let cell = cell as? UITableViewCell {
  211. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  212. UIView.animate(withDuration: 2) {
  213. cell.backgroundColor = .clear
  214. }
  215. } else if let cell = cell as? UICollectionViewCell {
  216. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  217. UIView.animate(withDuration: 2) {
  218. cell.backgroundColor = .clear
  219. }
  220. }
  221. }
  222. }
  223. @objc func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor) -> UIFont {
  224. let constrainingDimension = min(bounds.width, bounds.height)
  225. let properBounds = CGRect(origin: .zero, size: bounds.size)
  226. var attributes = [NSAttributedString.Key: Any]()
  227. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  228. var bestFontSize: CGFloat = constrainingDimension
  229. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  230. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  231. attributes[.font] = newFont
  232. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  233. if properBounds.contains(currentFrame) {
  234. bestFontSize = fontSize
  235. break
  236. }
  237. }
  238. return UIFont(descriptor: fontDescriptor, size: bestFontSize)
  239. }
  240. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  241. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  242. return false
  243. }
  244. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  245. return false
  246. }
  247. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  248. let mimeTypeArray = mimeType.components(separatedBy: ".")
  249. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  250. for richdocumentMimetype: String in richdocumentsMimetypes {
  251. if richdocumentMimetype.contains(mimeType) {
  252. return true
  253. }
  254. }
  255. }
  256. return false
  257. }
  258. @objc func isDirectEditing(_ metadata: tableMetadata) -> String? {
  259. guard let results = NCManageDatabase.sharedInstance.getDirectEditingEditors(account: metadata.account) else {
  260. return nil
  261. }
  262. for result: tableDirectEditingEditors in results {
  263. for mimetype in result.mimetypes {
  264. if mimetype == metadata.contentType {
  265. return result.editor
  266. }
  267. }
  268. for mimetype in result.optionalMimetypes {
  269. if mimetype == metadata.contentType {
  270. return result.editor
  271. }
  272. }
  273. }
  274. return nil
  275. }
  276. @objc func removeAllSettings() {
  277. URLCache.shared.memoryCapacity = 0
  278. URLCache.shared.diskCapacity = 0
  279. KTVHTTPCache.cacheDeleteAllCaches()
  280. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeAccount: true)
  281. CCUtility.removeGroupDirectoryProviderStorage()
  282. CCUtility.removeGroupLibraryDirectory()
  283. CCUtility.removeDocumentsDirectory()
  284. CCUtility.removeTemporaryDirectory()
  285. CCUtility.createDirectoryStandard()
  286. CCUtility.deleteAllChainStore()
  287. }
  288. #if !EXTENSION
  289. @objc func createAvatar(fileNameSource: String, fileNameSourceAvatar: String) -> UIImage? {
  290. guard let imageSource = UIImage(contentsOfFile: fileNameSource) else { return nil }
  291. let size = Int(k_avatar_size)
  292. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, UIScreen.main.scale)
  293. imageSource.draw(in: CGRect(x: 0, y: 0, width: size, height: size))
  294. let image = UIGraphicsGetImageFromCurrentImageContext()
  295. UIGraphicsEndImageContext()
  296. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, UIScreen.main.scale)
  297. let avatarImageView = CCAvatar.init(image: image, borderColor: .lightGray, borderWidth: Float(1 * UIScreen.main.scale))
  298. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  299. avatarImageView?.layer.render(in: context)
  300. guard let imageAvatar = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
  301. UIGraphicsEndImageContext()
  302. guard let data = imageAvatar.pngData() else {
  303. return nil
  304. }
  305. do {
  306. try data.write(to: NSURL(fileURLWithPath: fileNameSourceAvatar) as URL, options: .atomic)
  307. } catch { }
  308. return imageAvatar
  309. }
  310. #endif
  311. @objc func UIColorFromRGB(rgbValue: UInt32) -> UIColor {
  312. return UIColor(
  313. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  314. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  315. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  316. alpha: CGFloat(1.0)
  317. )
  318. }
  319. @objc func RGBFromUIColor(uicolorValue: UIColor) -> UInt32 {
  320. var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
  321. if uicolorValue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
  322. var colorAsUInt : UInt32 = 0
  323. colorAsUInt += UInt32(red * 255.0) << 16 +
  324. UInt32(green * 255.0) << 8 +
  325. UInt32(blue * 255.0)
  326. return colorAsUInt
  327. }
  328. return 0
  329. }
  330. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  331. for char in permissions {
  332. if metadataPermissions.contains(char) == false {
  333. return false
  334. }
  335. }
  336. return true
  337. }
  338. @objc func getCustomUserAgentOnlyOffice() -> String {
  339. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  340. if UIDevice.current.userInterfaceIdiom == .pad {
  341. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  342. }else{
  343. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  344. }
  345. }
  346. @objc func isLivePhoto(metadata: tableMetadata) -> tableMetadata? {
  347. if metadata.typeFile != k_metadataTypeFile_image && metadata.typeFile != k_metadataTypeFile_video { return nil }
  348. if !CCUtility.getLivePhoto() {return nil }
  349. let ext = (metadata.fileNameView as NSString).pathExtension.lowercased()
  350. if ext == "mov" {
  351. let fileNameJPG = (metadata.fileNameView as NSString).deletingPathExtension + ".jpg"
  352. let fileNameHEIC = (metadata.fileNameView as NSString).deletingPathExtension + ".heic"
  353. return NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND (fileNameView LIKE[c] %@ OR fileNameView LIKE[c] %@)", metadata.account, metadata.serverUrl, fileNameJPG, fileNameHEIC))
  354. } else {
  355. let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".mov"
  356. return NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView LIKE[c] %@", metadata.account, metadata.serverUrl, fileName))
  357. }
  358. }
  359. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  360. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  361. return nil
  362. }
  363. let pageSize = page.bounds(for: .mediaBox)
  364. let pdfScale = width / pageSize.width
  365. // Apply if you're displaying the thumbnail on screen
  366. let scale = UIScreen.main.scale * pdfScale
  367. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  368. return page.thumbnail(of: screenSize, for: .mediaBox)
  369. }
  370. @objc func getMetadataConflict(account: String, serverUrl: String, fileName: String) -> tableMetadata? {
  371. // verify exists conflict
  372. let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
  373. let fileNameWithoutExtension = (fileName as NSString).deletingPathExtension
  374. var fileNameConflict = fileName
  375. if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() {
  376. fileNameConflict = fileNameWithoutExtension + ".jpg"
  377. }
  378. return NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
  379. }
  380. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  381. return true
  382. }
  383. @objc func fromColor(color: UIColor) -> UIImage {
  384. let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
  385. UIGraphicsBeginImageContext(rect.size)
  386. let context: CGContext? = UIGraphicsGetCurrentContext()
  387. context?.setFillColor(color.cgColor)
  388. context?.fill(rect)
  389. let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
  390. UIGraphicsEndImageContext()
  391. return image ?? UIImage()
  392. }
  393. @objc func deleteAssetLocalIdentifiers(account: String, sessionSelector: String) {
  394. if UIApplication.shared.applicationState != .active { return }
  395. let metadatasSessionUpload = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"), sorted: nil, ascending: true)
  396. if metadatasSessionUpload?.count ?? 0 > 0 { return }
  397. let localIdentifiers = NCManageDatabase.sharedInstance.getAssetLocalIdentifiersUploaded(account: account, sessionSelector: sessionSelector)
  398. if localIdentifiers.count == 0 { return }
  399. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  400. PHPhotoLibrary.shared().performChanges({
  401. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  402. }, completionHandler: { success, error in
  403. DispatchQueue.main.async {
  404. NCManageDatabase.sharedInstance.clearAssetLocalIdentifiers(localIdentifiers, account: account)
  405. }
  406. })
  407. }
  408. }