NCUtility.swift 22 KB

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