NCUtility.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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 = NCViewActivityIndicator(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. if viewActivityIndicator is NCViewActivityIndicator {
  178. viewActivityIndicator?.removeFromSuperview()
  179. }
  180. }
  181. @objc func isSimulatorOrTestFlight() -> Bool {
  182. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  183. return false
  184. }
  185. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  186. }
  187. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  188. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  189. return false
  190. }
  191. guard let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  192. return false
  193. }
  194. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  195. let mimeTypeArray = mimeType.components(separatedBy: ".")
  196. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  197. for richdocumentMimetype: String in richdocumentsMimetypes {
  198. if richdocumentMimetype.contains(mimeType) {
  199. return true
  200. }
  201. }
  202. }
  203. return false
  204. }
  205. @objc func isDirectEditing(account: String, contentType: String) -> String? {
  206. var editor: String?
  207. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else {
  208. return editor
  209. }
  210. for result: tableDirectEditingEditors in results {
  211. for mimetype in result.mimetypes {
  212. if mimetype == contentType {
  213. editor = result.editor
  214. }
  215. // HARDCODE
  216. // https://github.com/nextcloud/text/issues/913
  217. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  218. editor = result.editor
  219. }
  220. }
  221. for mimetype in result.optionalMimetypes {
  222. if mimetype == contentType {
  223. editor = result.editor
  224. }
  225. }
  226. }
  227. // HARDCODE
  228. if editor == "" {
  229. editor = NCGlobal.shared.editorText
  230. }
  231. return editor
  232. }
  233. @objc func removeAllSettings() {
  234. URLCache.shared.memoryCapacity = 0
  235. URLCache.shared.diskCapacity = 0
  236. KTVHTTPCache.cacheDeleteAllCaches()
  237. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  238. CCUtility.removeGroupDirectoryProviderStorage()
  239. CCUtility.removeGroupLibraryDirectory()
  240. CCUtility.removeDocumentsDirectory()
  241. CCUtility.removeTemporaryDirectory()
  242. CCUtility.createDirectoryStandard()
  243. CCUtility.deleteAllChainStore()
  244. }
  245. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  246. for char in permissions {
  247. if metadataPermissions.contains(char) == false {
  248. return false
  249. }
  250. }
  251. return true
  252. }
  253. @objc func getCustomUserAgentOnlyOffice() -> String {
  254. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  255. if UIDevice.current.userInterfaceIdiom == .pad {
  256. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  257. }else{
  258. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  259. }
  260. }
  261. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  262. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  263. return nil
  264. }
  265. let pageSize = page.bounds(for: .mediaBox)
  266. let pdfScale = width / pageSize.width
  267. // Apply if you're displaying the thumbnail on screen
  268. let scale = UIScreen.main.scale * pdfScale
  269. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  270. return page.thumbnail(of: screenSize, for: .mediaBox)
  271. }
  272. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  273. return true
  274. }
  275. @objc func ocIdToFileId(ocId: String?) -> String? {
  276. guard let ocId = ocId else { return nil }
  277. let items = ocId.components(separatedBy: "oc")
  278. if items.count < 2 { return nil }
  279. guard let intFileId = Int(items[0]) else { return nil }
  280. return String(intFileId)
  281. }
  282. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String) {
  283. var onlineStatus: UIImage?
  284. var statusMessage: String = ""
  285. var messageUserDefined: String = ""
  286. if userStatus?.lowercased() == "online" {
  287. 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)
  288. messageUserDefined = NSLocalizedString("_online_", comment: "")
  289. }
  290. if userStatus?.lowercased() == "away" {
  291. 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)
  292. messageUserDefined = NSLocalizedString("_away_", comment: "")
  293. }
  294. if userStatus?.lowercased() == "dnd" {
  295. onlineStatus = UIImage.init(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  296. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  297. }
  298. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  299. onlineStatus = UIImage.init(named: "userStatusOffline")!.image(color: .black, size: 50)
  300. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  301. }
  302. if let userIcon = userIcon {
  303. statusMessage = userIcon + " "
  304. }
  305. if let userMessage = userMessage {
  306. statusMessage = statusMessage + userMessage
  307. }
  308. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  309. if statusMessage == "" {
  310. statusMessage = messageUserDefined
  311. }
  312. return(onlineStatus, statusMessage)
  313. }
  314. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  315. let asset = AVURLAsset(url: url)
  316. let assetIG = AVAssetImageGenerator(asset: asset)
  317. assetIG.appliesPreferredTrackTransform = true
  318. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  319. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  320. let thumbnailImageRef: CGImage
  321. do {
  322. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  323. } catch let error {
  324. print("Error: \(error)")
  325. return nil
  326. }
  327. return UIImage(cgImage: thumbnailImageRef)
  328. }
  329. func createImageFrom(fileName: String, ocId: String, etag: String, typeFile: String) {
  330. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  331. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  332. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  333. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  334. if FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  335. if !CCUtility.fileProviderStorageExists(ocId, fileNameView: fileName) { return }
  336. if typeFile != NCGlobal.shared.metadataTypeFileImage && typeFile != NCGlobal.shared.metadataTypeFileVideo { return }
  337. if typeFile == NCGlobal.shared.metadataTypeFileImage {
  338. originalImage = UIImage.init(contentsOfFile: fileNamePath)
  339. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview), isAspectRation: false)
  340. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon), isAspectRation: false)
  341. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  342. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  343. } else if typeFile == NCGlobal.shared.metadataTypeFileVideo {
  344. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  345. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  346. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  347. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  348. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  349. }
  350. }
  351. @objc func getVersionApp() -> String {
  352. if let dictionary = Bundle.main.infoDictionary {
  353. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  354. return "\(version).\(build)"
  355. }
  356. }
  357. return ""
  358. }
  359. }
  360. // MARK: -
  361. class NCViewActivityIndicator: UIView {
  362. override init(frame: CGRect) {
  363. super.init(frame: frame)
  364. }
  365. required init?(coder: NSCoder) {
  366. fatalError("init(coder:) has not been implemented")
  367. }
  368. }