NCUtility.swift 22 KB

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