NCUtility.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. @objc func getLayoutForView(key: String) -> (String) {
  135. var typeLayout = ""
  136. (typeLayout, _, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key)
  137. return typeLayout
  138. }
  139. @objc func getSortedForView(key: String) -> (String) {
  140. var sorted = ""
  141. (_, sorted, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key)
  142. return sorted
  143. }
  144. @objc func getAscendingForView(key: String) -> (Bool) {
  145. var ascending: Bool
  146. (_, _, ascending, _, _, _) = NCUtility.shared.getLayoutForView(key: key)
  147. return ascending
  148. }
  149. @objc func getGroupByForView(key: String) -> (String) {
  150. var groupBy: String
  151. (_, _, _, groupBy, _, _) = NCUtility.shared.getLayoutForView(key: key)
  152. return groupBy
  153. }
  154. @objc func getDirectoryOnTopForView(key: String) -> (Bool) {
  155. var directoryOnTop: Bool
  156. (_, _, _, _, directoryOnTop, _) = NCUtility.shared.getLayoutForView(key: key)
  157. return directoryOnTop
  158. }
  159. @objc func getTitleButtonForView(key: String) -> (String) {
  160. var title: String
  161. (_, _, _, _, _, title) = NCUtility.shared.getLayoutForView(key: key)
  162. return title
  163. }
  164. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool, String) {
  165. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  166. return (k_layout_list, "fileName", true, "none", true, "_sorted_by_name_a_z_")
  167. }
  168. let array = string.components(separatedBy: "|")
  169. if array.count == 6 {
  170. let sort = NSString(string: array[2])
  171. let directoryOnTop = NSString(string: array[4])
  172. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue, array[5])
  173. }
  174. return (k_layout_list, "fileName", true, "none", true, "_sorted_by_name_a_z_")
  175. }
  176. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, account: String, closure: @escaping (String?) -> ()) {
  177. var fileNamePNG = ""
  178. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  179. return closure(nil)
  180. }
  181. guard let iconURL = URL(string: svgUrlString) else {
  182. return closure(nil)
  183. }
  184. if fileName == nil {
  185. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  186. } else {
  187. fileNamePNG = fileName!
  188. }
  189. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  190. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  191. NCCommunication.shared.downloadContent(serverUrl: iconURL.absoluteString) { (account, data, errorCode, errorMessage) in
  192. if errorCode == 0 && data != nil {
  193. if let image = UIImage.init(data: data!) {
  194. var newImage: UIImage = image
  195. if width != nil {
  196. let ratio = image.size.height / image.size.width
  197. let newSize = CGSize(width: width!, height: width! * ratio)
  198. let renderFormat = UIGraphicsImageRendererFormat.default()
  199. renderFormat.opaque = false
  200. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  201. newImage = renderer.image {
  202. (context) in
  203. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  204. }
  205. }
  206. guard let pngImageData = newImage.pngData() else {
  207. return closure(nil)
  208. }
  209. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  210. return closure(imageNamePath)
  211. } else {
  212. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  213. return closure(nil)
  214. }
  215. if width != nil {
  216. let scale = svgImage.size.height / svgImage.size.width
  217. svgImage.size = CGSize(width: width!, height: width! * scale)
  218. }
  219. guard let image: UIImage = svgImage.uiImage else {
  220. return closure(nil)
  221. }
  222. guard let pngImageData = image.pngData() else {
  223. return closure(nil)
  224. }
  225. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  226. return closure(imageNamePath)
  227. }
  228. } else {
  229. return closure(nil)
  230. }
  231. }
  232. } else {
  233. return closure(imageNamePath)
  234. }
  235. }
  236. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat = 0) {
  237. guard let view = view else { return }
  238. activityIndicator.color = NCBrandColor.sharedInstance.brandElement
  239. activityIndicator.hidesWhenStopped = true
  240. view.addSubview(activityIndicator)
  241. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  242. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  243. view.addConstraint(horizontalConstraint)
  244. var verticalConstant: CGFloat = 0
  245. if bottom > 0 {
  246. verticalConstant = (view.frame.size.height / 2) - bottom
  247. }
  248. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  249. view.addConstraint(verticalConstraint)
  250. activityIndicator.startAnimating()
  251. }
  252. @objc func stopActivityIndicator() {
  253. activityIndicator.stopAnimating()
  254. activityIndicator.removeFromSuperview()
  255. }
  256. @objc func isSimulatorOrTestFlight() -> Bool {
  257. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  258. return false
  259. }
  260. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  261. }
  262. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  263. if seconds.isNaN {
  264. return "00:00:00"
  265. }
  266. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  267. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  268. let hour = Int(seconds / 3600)
  269. return String(format: "%02d:%02d:%02d", hour, min, sec)
  270. }
  271. @objc func blink(cell: AnyObject?) {
  272. DispatchQueue.main.async {
  273. if let cell = cell as? UITableViewCell {
  274. cell.backgroundColor = NCBrandColor.sharedInstance.brandElement.withAlphaComponent(0.3)
  275. UIView.animate(withDuration: 2) {
  276. cell.backgroundColor = .clear
  277. }
  278. } else if let cell = cell as? UICollectionViewCell {
  279. cell.backgroundColor = NCBrandColor.sharedInstance.brandElement.withAlphaComponent(0.3)
  280. UIView.animate(withDuration: 2) {
  281. cell.backgroundColor = .clear
  282. }
  283. }
  284. }
  285. }
  286. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  287. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  288. return false
  289. }
  290. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  291. return false
  292. }
  293. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  294. let mimeTypeArray = mimeType.components(separatedBy: ".")
  295. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  296. for richdocumentMimetype: String in richdocumentsMimetypes {
  297. if richdocumentMimetype.contains(mimeType) {
  298. return true
  299. }
  300. }
  301. }
  302. return false
  303. }
  304. @objc func isDirectEditing(account: String, contentType: String) -> String? {
  305. var editor: String?
  306. guard let results = NCManageDatabase.sharedInstance.getDirectEditingEditors(account: account) else {
  307. return editor
  308. }
  309. for result: tableDirectEditingEditors in results {
  310. for mimetype in result.mimetypes {
  311. if mimetype == contentType {
  312. editor = result.editor
  313. }
  314. // HARDCODE
  315. // https://github.com/nextcloud/text/issues/913
  316. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  317. editor = result.editor
  318. }
  319. }
  320. for mimetype in result.optionalMimetypes {
  321. if mimetype == contentType {
  322. editor = result.editor
  323. }
  324. }
  325. }
  326. // HARDCODE
  327. if editor == "" {
  328. editor = k_editor_text
  329. }
  330. return editor
  331. }
  332. @objc func removeAllSettings() {
  333. URLCache.shared.memoryCapacity = 0
  334. URLCache.shared.diskCapacity = 0
  335. KTVHTTPCache.cacheDeleteAllCaches()
  336. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeAccount: true)
  337. CCUtility.removeGroupDirectoryProviderStorage()
  338. CCUtility.removeGroupLibraryDirectory()
  339. CCUtility.removeDocumentsDirectory()
  340. CCUtility.removeTemporaryDirectory()
  341. CCUtility.createDirectoryStandard()
  342. CCUtility.deleteAllChainStore()
  343. }
  344. #if !EXTENSION
  345. @objc func createAvatar(fileNameSource: String, fileNameSourceAvatar: String) -> UIImage? {
  346. guard let imageSource = UIImage(contentsOfFile: fileNameSource) else { return nil }
  347. let size = Int(k_avatar_size)
  348. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, UIScreen.main.scale)
  349. imageSource.draw(in: CGRect(x: 0, y: 0, width: size, height: size))
  350. let image = UIGraphicsGetImageFromCurrentImageContext()
  351. UIGraphicsEndImageContext()
  352. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, UIScreen.main.scale)
  353. let avatarImageView = CCAvatar.init(image: image, borderColor: .lightGray, borderWidth: Float(1 * UIScreen.main.scale))
  354. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  355. avatarImageView?.layer.render(in: context)
  356. guard let imageAvatar = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
  357. UIGraphicsEndImageContext()
  358. guard let data = imageAvatar.pngData() else {
  359. return nil
  360. }
  361. do {
  362. try data.write(to: NSURL(fileURLWithPath: fileNameSourceAvatar) as URL, options: .atomic)
  363. } catch { }
  364. return imageAvatar
  365. }
  366. #endif
  367. @objc func UIColorFromRGB(rgbValue: UInt32) -> UIColor {
  368. return UIColor(
  369. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  370. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  371. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  372. alpha: CGFloat(1.0)
  373. )
  374. }
  375. @objc func RGBFromUIColor(uicolorValue: UIColor) -> UInt32 {
  376. var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
  377. if uicolorValue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
  378. var colorAsUInt : UInt32 = 0
  379. colorAsUInt += UInt32(red * 255.0) << 16 +
  380. UInt32(green * 255.0) << 8 +
  381. UInt32(blue * 255.0)
  382. return colorAsUInt
  383. }
  384. return 0
  385. }
  386. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  387. for char in permissions {
  388. if metadataPermissions.contains(char) == false {
  389. return false
  390. }
  391. }
  392. return true
  393. }
  394. @objc func getCustomUserAgentOnlyOffice() -> String {
  395. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  396. if UIDevice.current.userInterfaceIdiom == .pad {
  397. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  398. }else{
  399. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  400. }
  401. }
  402. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  403. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  404. return nil
  405. }
  406. let pageSize = page.bounds(for: .mediaBox)
  407. let pdfScale = width / pageSize.width
  408. // Apply if you're displaying the thumbnail on screen
  409. let scale = UIScreen.main.scale * pdfScale
  410. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  411. return page.thumbnail(of: screenSize, for: .mediaBox)
  412. }
  413. @objc func getMetadataConflict(account: String, serverUrl: String, fileName: String) -> tableMetadata? {
  414. // verify exists conflict
  415. let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
  416. let fileNameWithoutExtension = (fileName as NSString).deletingPathExtension
  417. var fileNameConflict = fileName
  418. if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() {
  419. fileNameConflict = fileNameWithoutExtension + ".jpg"
  420. }
  421. return NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
  422. }
  423. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  424. return true
  425. }
  426. @objc func fromColor(color: UIColor) -> UIImage {
  427. let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
  428. UIGraphicsBeginImageContext(rect.size)
  429. let context: CGContext? = UIGraphicsGetCurrentContext()
  430. context?.setFillColor(color.cgColor)
  431. context?.fill(rect)
  432. let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
  433. UIGraphicsEndImageContext()
  434. return image ?? UIImage()
  435. }
  436. // Delete Asset on Photos album
  437. @objc func deleteAssetLocalIdentifiers(account: String, sessionSelector: String, completition: @escaping () -> ()) {
  438. if UIApplication.shared.applicationState != .active {
  439. completition()
  440. return
  441. }
  442. let metadatasSessionUpload = NCManageDatabase.sharedInstance.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
  443. if metadatasSessionUpload.count > 0 {
  444. completition()
  445. return
  446. }
  447. let localIdentifiers = NCManageDatabase.sharedInstance.getAssetLocalIdentifiersUploaded(account: account, sessionSelector: sessionSelector)
  448. if localIdentifiers.count == 0 {
  449. completition()
  450. return
  451. }
  452. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  453. PHPhotoLibrary.shared().performChanges({
  454. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  455. }, completionHandler: { success, error in
  456. DispatchQueue.main.async {
  457. NCManageDatabase.sharedInstance.clearAssetLocalIdentifiers(localIdentifiers, account: account)
  458. completition()
  459. }
  460. })
  461. }
  462. @objc func ocIdToFileId(ocId: String?) -> String? {
  463. guard let ocId = ocId else { return nil }
  464. let items = ocId.components(separatedBy: "oc")
  465. if items.count < 2 { return nil }
  466. guard let intFileId = Int(items[0]) else { return nil }
  467. return String(intFileId)
  468. }
  469. }