NCUtility.swift 23 KB

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