NCUtility.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. import Accelerate
  29. class NCUtility: NSObject {
  30. @objc static let shared: NCUtility = {
  31. let instance = NCUtility()
  32. return instance
  33. }()
  34. let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
  35. func setLayoutForView(key: String, serverUrl: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool, titleButton: String, itemForLine: Int) {
  36. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)" + "|" + titleButton + "|" + "\(itemForLine)"
  37. var keyStore = key
  38. if serverUrl != "" {
  39. keyStore = serverUrl
  40. }
  41. UICKeyChainStore.setString(string, forKey: keyStore, service: NCBrandGlobal.shared.serviceShareKeyChain)
  42. }
  43. func setLayoutForView(key: String, serverUrl: String, layout: String) {
  44. var sort: String
  45. var ascending: Bool
  46. var groupBy: String
  47. var directoryOnTop: Bool
  48. var titleButton: String
  49. var itemForLine: Int
  50. (_, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: NCBrandGlobal.shared.layoutViewFavorite, serverUrl: serverUrl)
  51. setLayoutForView(key: key, serverUrl: serverUrl, layout: layout, sort: sort, ascending: ascending, groupBy: groupBy, directoryOnTop: directoryOnTop, titleButton: titleButton, itemForLine: itemForLine)
  52. }
  53. @objc func getLayoutForView(key: String, serverUrl: String) -> (String) {
  54. var layout: String
  55. (layout, _, _, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  56. return layout
  57. }
  58. @objc func getSortedForView(key: String, serverUrl: String) -> (String) {
  59. var sort: String
  60. (_, sort, _, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  61. return sort
  62. }
  63. @objc func getAscendingForView(key: String, serverUrl: String) -> (Bool) {
  64. var ascending: Bool
  65. (_, _, ascending, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  66. return ascending
  67. }
  68. func getLayoutForView(key: String, serverUrl: String) -> (layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool, titleButton: String, itemForLine: Int) {
  69. var keyStore = key
  70. if serverUrl != "" {
  71. keyStore = serverUrl
  72. }
  73. guard let string = UICKeyChainStore.string(forKey: keyStore, service: NCBrandGlobal.shared.serviceShareKeyChain) else {
  74. setLayoutForView(key: key, serverUrl: serverUrl, layout: NCBrandGlobal.shared.layoutList, sort: "fileName", ascending: true, groupBy: "none", directoryOnTop: true, titleButton: "_sorted_by_name_a_z_", itemForLine: 3)
  75. return (NCBrandGlobal.shared.layoutList, "fileName", true, "none", true, "_sorted_by_name_a_z_", 3)
  76. }
  77. let array = string.components(separatedBy: "|")
  78. if array.count == 7 {
  79. let sort = NSString(string: array[2])
  80. let directoryOnTop = NSString(string: array[4])
  81. let itemForLine = NSString(string: array[6])
  82. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue, array[5], Int(itemForLine.intValue))
  83. }
  84. setLayoutForView(key: key, serverUrl: serverUrl, layout: NCBrandGlobal.shared.layoutList, sort: "fileName", ascending: true, groupBy: "none", directoryOnTop: true, titleButton: "_sorted_by_name_a_z_", itemForLine: 3)
  85. return (NCBrandGlobal.shared.layoutList, "fileName", true, "none", true, "_sorted_by_name_a_z_", 3)
  86. }
  87. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, account: String, closure: @escaping (String?) -> ()) {
  88. var fileNamePNG = ""
  89. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  90. return closure(nil)
  91. }
  92. guard let iconURL = URL(string: svgUrlString) else {
  93. return closure(nil)
  94. }
  95. if fileName == nil {
  96. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  97. } else {
  98. fileNamePNG = fileName!
  99. }
  100. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  101. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  102. NCCommunication.shared.downloadContent(serverUrl: iconURL.absoluteString) { (account, data, errorCode, errorMessage) in
  103. if errorCode == 0 && data != nil {
  104. if let image = UIImage.init(data: data!) {
  105. var newImage: UIImage = image
  106. if width != nil {
  107. let ratio = image.size.height / image.size.width
  108. let newSize = CGSize(width: width!, height: width! * ratio)
  109. let renderFormat = UIGraphicsImageRendererFormat.default()
  110. renderFormat.opaque = false
  111. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  112. newImage = renderer.image {
  113. (context) in
  114. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  115. }
  116. }
  117. guard let pngImageData = newImage.pngData() else {
  118. return closure(nil)
  119. }
  120. try? pngImageData.write(to: URL(fileURLWithPath:imageNamePath))
  121. return closure(imageNamePath)
  122. } else {
  123. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  124. return closure(nil)
  125. }
  126. if width != nil {
  127. let scale = svgImage.size.height / svgImage.size.width
  128. svgImage.size = CGSize(width: width!, height: width! * scale)
  129. }
  130. guard let image: UIImage = svgImage.uiImage else {
  131. return closure(nil)
  132. }
  133. guard let pngImageData = image.pngData() else {
  134. return closure(nil)
  135. }
  136. try? pngImageData.write(to: URL(fileURLWithPath:imageNamePath))
  137. return closure(imageNamePath)
  138. }
  139. } else {
  140. return closure(nil)
  141. }
  142. }
  143. } else {
  144. return closure(imageNamePath)
  145. }
  146. }
  147. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat = 0) {
  148. guard let view = view else { return }
  149. activityIndicator.color = .gray
  150. activityIndicator.hidesWhenStopped = true
  151. view.addSubview(activityIndicator)
  152. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  153. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  154. view.addConstraint(horizontalConstraint)
  155. var verticalConstant: CGFloat = 0
  156. if bottom > 0 {
  157. verticalConstant = (view.frame.size.height / 2) - bottom
  158. }
  159. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  160. view.addConstraint(verticalConstraint)
  161. activityIndicator.startAnimating()
  162. }
  163. @objc func stopActivityIndicator() {
  164. activityIndicator.stopAnimating()
  165. activityIndicator.removeFromSuperview()
  166. }
  167. @objc func isSimulatorOrTestFlight() -> Bool {
  168. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  169. return false
  170. }
  171. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  172. }
  173. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  174. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  175. return false
  176. }
  177. guard let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  178. return false
  179. }
  180. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  181. let mimeTypeArray = mimeType.components(separatedBy: ".")
  182. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  183. for richdocumentMimetype: String in richdocumentsMimetypes {
  184. if richdocumentMimetype.contains(mimeType) {
  185. return true
  186. }
  187. }
  188. }
  189. return false
  190. }
  191. @objc func isDirectEditing(account: String, contentType: String) -> String? {
  192. var editor: String?
  193. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else {
  194. return editor
  195. }
  196. for result: tableDirectEditingEditors in results {
  197. for mimetype in result.mimetypes {
  198. if mimetype == contentType {
  199. editor = result.editor
  200. }
  201. // HARDCODE
  202. // https://github.com/nextcloud/text/issues/913
  203. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  204. editor = result.editor
  205. }
  206. }
  207. for mimetype in result.optionalMimetypes {
  208. if mimetype == contentType {
  209. editor = result.editor
  210. }
  211. }
  212. }
  213. // HARDCODE
  214. if editor == "" {
  215. editor = NCBrandGlobal.shared.editorText
  216. }
  217. return editor
  218. }
  219. @objc func removeAllSettings() {
  220. URLCache.shared.memoryCapacity = 0
  221. URLCache.shared.diskCapacity = 0
  222. KTVHTTPCache.cacheDeleteAllCaches()
  223. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  224. CCUtility.removeGroupDirectoryProviderStorage()
  225. CCUtility.removeGroupLibraryDirectory()
  226. CCUtility.removeDocumentsDirectory()
  227. CCUtility.removeTemporaryDirectory()
  228. CCUtility.createDirectoryStandard()
  229. CCUtility.deleteAllChainStore()
  230. }
  231. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  232. for char in permissions {
  233. if metadataPermissions.contains(char) == false {
  234. return false
  235. }
  236. }
  237. return true
  238. }
  239. @objc func getCustomUserAgentOnlyOffice() -> String {
  240. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  241. if UIDevice.current.userInterfaceIdiom == .pad {
  242. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  243. }else{
  244. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  245. }
  246. }
  247. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  248. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  249. return nil
  250. }
  251. let pageSize = page.bounds(for: .mediaBox)
  252. let pdfScale = width / pageSize.width
  253. // Apply if you're displaying the thumbnail on screen
  254. let scale = UIScreen.main.scale * pdfScale
  255. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  256. return page.thumbnail(of: screenSize, for: .mediaBox)
  257. }
  258. @objc func getMetadataConflict(account: String, serverUrl: String, fileName: String) -> tableMetadata? {
  259. // verify exists conflict
  260. let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
  261. let fileNameWithoutExtension = (fileName as NSString).deletingPathExtension
  262. var fileNameConflict = fileName
  263. if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() {
  264. fileNameConflict = fileNameWithoutExtension + ".jpg"
  265. }
  266. return NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
  267. }
  268. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  269. return true
  270. }
  271. @objc func fromColor(color: UIColor) -> UIImage {
  272. let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
  273. UIGraphicsBeginImageContext(rect.size)
  274. let context: CGContext? = UIGraphicsGetCurrentContext()
  275. context?.setFillColor(color.cgColor)
  276. context?.fill(rect)
  277. let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
  278. UIGraphicsEndImageContext()
  279. return image ?? UIImage()
  280. }
  281. // Delete Asset on Photos album
  282. @objc func deleteAssetLocalIdentifiers(account: String, sessionSelector: String, completition: @escaping () -> ()) {
  283. if UIApplication.shared.applicationState != .active {
  284. completition()
  285. return
  286. }
  287. let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
  288. if metadatasSessionUpload.count > 0 {
  289. completition()
  290. return
  291. }
  292. let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account, sessionSelector: sessionSelector)
  293. if localIdentifiers.count == 0 {
  294. completition()
  295. return
  296. }
  297. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  298. PHPhotoLibrary.shared().performChanges({
  299. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  300. }, completionHandler: { success, error in
  301. DispatchQueue.main.async {
  302. NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: account)
  303. completition()
  304. }
  305. })
  306. }
  307. @objc func ocIdToFileId(ocId: String?) -> String? {
  308. guard let ocId = ocId else { return nil }
  309. let items = ocId.components(separatedBy: "oc")
  310. if items.count < 2 { return nil }
  311. guard let intFileId = Int(items[0]) else { return nil }
  312. return String(intFileId)
  313. }
  314. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String) {
  315. var onlineStatus: UIImage?
  316. var statusMessage: String = ""
  317. var messageUserDefined: String = ""
  318. if userStatus?.lowercased() == "online" {
  319. onlineStatus = UIImage.init(named: "userStatusOnline")!.image(color: UIColor(red: 103.0/255.0, green: 176.0/255.0, blue: 134.0/255.0, alpha: 1.0), size: 50)
  320. messageUserDefined = NSLocalizedString("_online_", comment: "")
  321. }
  322. if userStatus?.lowercased() == "away" {
  323. onlineStatus = UIImage.init(named: "userStatusAway")!.image(color: UIColor(red: 233.0/255.0, green: 166.0/255.0, blue: 75.0/255.0, alpha: 1.0), size: 50)
  324. messageUserDefined = NSLocalizedString("_away_", comment: "")
  325. }
  326. if userStatus?.lowercased() == "dnd" {
  327. onlineStatus = UIImage.init(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  328. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  329. }
  330. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  331. onlineStatus = UIImage.init(named: "userStatusOffline")!.image(color: .black, size: 50)
  332. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  333. }
  334. if let userIcon = userIcon {
  335. statusMessage = userIcon + " "
  336. }
  337. if let userMessage = userMessage {
  338. statusMessage = statusMessage + userMessage
  339. }
  340. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  341. if statusMessage == "" {
  342. statusMessage = messageUserDefined
  343. }
  344. return(onlineStatus, statusMessage)
  345. }
  346. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  347. let asset = AVURLAsset(url: url)
  348. let assetIG = AVAssetImageGenerator(asset: asset)
  349. assetIG.appliesPreferredTrackTransform = true
  350. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  351. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  352. let thumbnailImageRef: CGImage
  353. do {
  354. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  355. } catch let error {
  356. print("Error: \(error)")
  357. return nil
  358. }
  359. return UIImage(cgImage: thumbnailImageRef)
  360. }
  361. func createImageFrom(fileName: String, ocId: String, etag: String, typeFile: String) {
  362. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  363. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  364. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  365. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  366. if FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  367. if !CCUtility.fileProviderStorageExists(ocId, fileNameView: fileName) { return }
  368. if typeFile != NCBrandGlobal.shared.metadataTypeFileImage && typeFile != NCBrandGlobal.shared.metadataTypeFileVideo { return }
  369. if typeFile == NCBrandGlobal.shared.metadataTypeFileImage {
  370. originalImage = UIImage.init(contentsOfFile: fileNamePath)
  371. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCBrandGlobal.shared.sizePreview, height: NCBrandGlobal.shared.sizePreview), isAspectRation: false)
  372. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCBrandGlobal.shared.sizeIcon, height: NCBrandGlobal.shared.sizeIcon), isAspectRation: false)
  373. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  374. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  375. } else if typeFile == NCBrandGlobal.shared.metadataTypeFileVideo {
  376. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  377. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  378. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  379. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  380. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  381. }
  382. }
  383. }