NCUtility.swift 23 KB

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