NCUtility.swift 20 KB

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