NCUtility.swift 20 KB

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