NCUtility.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. @objc func getWebDAV(account: String) -> String {
  36. return NCManageDatabase.shared.getCapabilitiesServerString(account: account, elements: NCElementsJSON.shared.capabilitiesWebDavRoot) ?? "remote.php/webdav"
  37. }
  38. @objc func getDAV() -> String {
  39. return "remote.php/dav"
  40. }
  41. @objc func getHomeServer(urlBase: String, account: String) -> String {
  42. return urlBase + "/" + self.getWebDAV(account: account)
  43. }
  44. @objc func deletingLastPathComponent(serverUrl: String, urlBase: String, account: String) -> String {
  45. if getHomeServer(urlBase: urlBase, account: account) == serverUrl { return serverUrl }
  46. let fileName = (serverUrl as NSString).lastPathComponent
  47. let serverUrl = serverUrl.replacingOccurrences(of: "/"+fileName, with: "", options: String.CompareOptions.backwards, range: nil)
  48. return serverUrl
  49. }
  50. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  51. var resultFileName = fileName
  52. var exitLoop = false
  53. while exitLoop == false {
  54. if NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  55. var name = NSString(string: resultFileName).deletingPathExtension
  56. let ext = NSString(string: resultFileName).pathExtension
  57. let characters = Array(name)
  58. if characters.count < 2 {
  59. if ext == "" {
  60. resultFileName = name + " " + "1"
  61. } else {
  62. resultFileName = name + " " + "1" + "." + ext
  63. }
  64. } else {
  65. let space = characters[characters.count-2]
  66. let numChar = characters[characters.count-1]
  67. var num = Int(String(numChar))
  68. if (space == " " && num != nil) {
  69. name = String(name.dropLast())
  70. num = num! + 1
  71. if ext == "" {
  72. resultFileName = name + "\(num!)"
  73. } else {
  74. resultFileName = name + "\(num!)" + "." + ext
  75. }
  76. } else {
  77. if ext == "" {
  78. resultFileName = name + " " + "1"
  79. } else {
  80. resultFileName = name + " " + "1" + "." + ext
  81. }
  82. }
  83. }
  84. } else {
  85. exitLoop = true
  86. }
  87. }
  88. return resultFileName
  89. }
  90. @objc func isEncryptedMetadata(_ metadata: tableMetadata) -> Bool {
  91. if metadata.fileName != metadata.fileNameView && metadata.fileName.count == 32 && metadata.fileName.contains(".") == false {
  92. return true
  93. }
  94. return false
  95. }
  96. func cellBlurEffect(with frame: CGRect) -> UIView {
  97. let blurEffect = UIBlurEffect(style: .extraLight)
  98. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  99. blurEffectView.frame = frame
  100. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  101. blurEffectView.backgroundColor = NCBrandColor.shared.brandElement.withAlphaComponent(0.2)
  102. return blurEffectView
  103. }
  104. func setLayoutForView(key: String, serverUrl: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool, titleButton: String, itemForLine: Int) {
  105. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)" + "|" + titleButton + "|" + "\(itemForLine)"
  106. var keyStore = key
  107. if serverUrl != "" {
  108. keyStore = serverUrl
  109. }
  110. UICKeyChainStore.setString(string, forKey: keyStore, service: NCBrandGlobal.shared.serviceShareKeyChain)
  111. }
  112. func setLayoutForView(key: String, serverUrl: String, layout: String) {
  113. var sort: String
  114. var ascending: Bool
  115. var groupBy: String
  116. var directoryOnTop: Bool
  117. var titleButton: String
  118. var itemForLine: Int
  119. (_, sort, ascending, groupBy, directoryOnTop, titleButton, itemForLine) = NCUtility.shared.getLayoutForView(key: NCBrandGlobal.shared.layoutViewFavorite, serverUrl: serverUrl)
  120. setLayoutForView(key: key, serverUrl: serverUrl, layout: layout, sort: sort, ascending: ascending, groupBy: groupBy, directoryOnTop: directoryOnTop, titleButton: titleButton, itemForLine: itemForLine)
  121. }
  122. @objc func getLayoutForView(key: String, serverUrl: String) -> (String) {
  123. var layout: String
  124. (layout, _, _, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  125. return layout
  126. }
  127. @objc func getSortedForView(key: String, serverUrl: String) -> (String) {
  128. var sort: String
  129. (_, sort, _, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  130. return sort
  131. }
  132. @objc func getAscendingForView(key: String, serverUrl: String) -> (Bool) {
  133. var ascending: Bool
  134. (_, _, ascending, _, _, _, _) = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  135. return ascending
  136. }
  137. func getLayoutForView(key: String, serverUrl: String) -> (layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool, titleButton: String, itemForLine: Int) {
  138. var keyStore = key
  139. if serverUrl != "" {
  140. keyStore = serverUrl
  141. }
  142. guard let string = UICKeyChainStore.string(forKey: keyStore, service: NCBrandGlobal.shared.serviceShareKeyChain) else {
  143. 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)
  144. return (NCBrandGlobal.shared.layoutList, "fileName", true, "none", true, "_sorted_by_name_a_z_", 3)
  145. }
  146. let array = string.components(separatedBy: "|")
  147. if array.count == 7 {
  148. let sort = NSString(string: array[2])
  149. let directoryOnTop = NSString(string: array[4])
  150. let itemForLine = NSString(string: array[6])
  151. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue, array[5], Int(itemForLine.intValue))
  152. }
  153. 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)
  154. return (NCBrandGlobal.shared.layoutList, "fileName", true, "none", true, "_sorted_by_name_a_z_", 3)
  155. }
  156. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, account: String, closure: @escaping (String?) -> ()) {
  157. var fileNamePNG = ""
  158. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  159. return closure(nil)
  160. }
  161. guard let iconURL = URL(string: svgUrlString) else {
  162. return closure(nil)
  163. }
  164. if fileName == nil {
  165. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  166. } else {
  167. fileNamePNG = fileName!
  168. }
  169. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  170. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  171. NCCommunication.shared.downloadContent(serverUrl: iconURL.absoluteString) { (account, data, errorCode, errorMessage) in
  172. if errorCode == 0 && data != nil {
  173. if let image = UIImage.init(data: data!) {
  174. var newImage: UIImage = image
  175. if width != nil {
  176. let ratio = image.size.height / image.size.width
  177. let newSize = CGSize(width: width!, height: width! * ratio)
  178. let renderFormat = UIGraphicsImageRendererFormat.default()
  179. renderFormat.opaque = false
  180. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  181. newImage = renderer.image {
  182. (context) in
  183. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  184. }
  185. }
  186. guard let pngImageData = newImage.pngData() else {
  187. return closure(nil)
  188. }
  189. try? pngImageData.write(to: URL(fileURLWithPath:imageNamePath))
  190. return closure(imageNamePath)
  191. } else {
  192. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  193. return closure(nil)
  194. }
  195. if width != nil {
  196. let scale = svgImage.size.height / svgImage.size.width
  197. svgImage.size = CGSize(width: width!, height: width! * scale)
  198. }
  199. guard let image: UIImage = svgImage.uiImage else {
  200. return closure(nil)
  201. }
  202. guard let pngImageData = image.pngData() else {
  203. return closure(nil)
  204. }
  205. try? pngImageData.write(to: URL(fileURLWithPath:imageNamePath))
  206. return closure(imageNamePath)
  207. }
  208. } else {
  209. return closure(nil)
  210. }
  211. }
  212. } else {
  213. return closure(imageNamePath)
  214. }
  215. }
  216. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat = 0) {
  217. guard let view = view else { return }
  218. activityIndicator.color = .gray
  219. activityIndicator.hidesWhenStopped = true
  220. view.addSubview(activityIndicator)
  221. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  222. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  223. view.addConstraint(horizontalConstraint)
  224. var verticalConstant: CGFloat = 0
  225. if bottom > 0 {
  226. verticalConstant = (view.frame.size.height / 2) - bottom
  227. }
  228. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  229. view.addConstraint(verticalConstraint)
  230. activityIndicator.startAnimating()
  231. }
  232. @objc func stopActivityIndicator() {
  233. activityIndicator.stopAnimating()
  234. activityIndicator.removeFromSuperview()
  235. }
  236. @objc func isSimulatorOrTestFlight() -> Bool {
  237. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  238. return false
  239. }
  240. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  241. }
  242. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  243. if seconds.isNaN {
  244. return "00:00:00"
  245. }
  246. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  247. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  248. let hour = Int(seconds / 3600)
  249. return String(format: "%02d:%02d:%02d", hour, min, sec)
  250. }
  251. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  252. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  253. return false
  254. }
  255. guard let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  256. return false
  257. }
  258. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  259. let mimeTypeArray = mimeType.components(separatedBy: ".")
  260. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  261. for richdocumentMimetype: String in richdocumentsMimetypes {
  262. if richdocumentMimetype.contains(mimeType) {
  263. return true
  264. }
  265. }
  266. }
  267. return false
  268. }
  269. @objc func isDirectEditing(account: String, contentType: String) -> String? {
  270. var editor: String?
  271. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else {
  272. return editor
  273. }
  274. for result: tableDirectEditingEditors in results {
  275. for mimetype in result.mimetypes {
  276. if mimetype == contentType {
  277. editor = result.editor
  278. }
  279. // HARDCODE
  280. // https://github.com/nextcloud/text/issues/913
  281. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  282. editor = result.editor
  283. }
  284. }
  285. for mimetype in result.optionalMimetypes {
  286. if mimetype == contentType {
  287. editor = result.editor
  288. }
  289. }
  290. }
  291. // HARDCODE
  292. if editor == "" {
  293. editor = NCBrandGlobal.shared.editorText
  294. }
  295. return editor
  296. }
  297. @objc func removeAllSettings() {
  298. URLCache.shared.memoryCapacity = 0
  299. URLCache.shared.diskCapacity = 0
  300. KTVHTTPCache.cacheDeleteAllCaches()
  301. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  302. CCUtility.removeGroupDirectoryProviderStorage()
  303. CCUtility.removeGroupLibraryDirectory()
  304. CCUtility.removeDocumentsDirectory()
  305. CCUtility.removeTemporaryDirectory()
  306. CCUtility.createDirectoryStandard()
  307. CCUtility.deleteAllChainStore()
  308. }
  309. @objc func UIColorFromRGB(rgbValue: UInt32) -> UIColor {
  310. return UIColor(
  311. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  312. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  313. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  314. alpha: CGFloat(1.0)
  315. )
  316. }
  317. @objc func RGBFromUIColor(uicolorValue: UIColor) -> UInt32 {
  318. var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
  319. if uicolorValue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
  320. var colorAsUInt : UInt32 = 0
  321. colorAsUInt += UInt32(red * 255.0) << 16 +
  322. UInt32(green * 255.0) << 8 +
  323. UInt32(blue * 255.0)
  324. return colorAsUInt
  325. }
  326. return 0
  327. }
  328. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  329. for char in permissions {
  330. if metadataPermissions.contains(char) == false {
  331. return false
  332. }
  333. }
  334. return true
  335. }
  336. @objc func getCustomUserAgentOnlyOffice() -> String {
  337. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  338. if UIDevice.current.userInterfaceIdiom == .pad {
  339. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  340. }else{
  341. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  342. }
  343. }
  344. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  345. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  346. return nil
  347. }
  348. let pageSize = page.bounds(for: .mediaBox)
  349. let pdfScale = width / pageSize.width
  350. // Apply if you're displaying the thumbnail on screen
  351. let scale = UIScreen.main.scale * pdfScale
  352. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  353. return page.thumbnail(of: screenSize, for: .mediaBox)
  354. }
  355. @objc func getMetadataConflict(account: String, serverUrl: String, fileName: String) -> tableMetadata? {
  356. // verify exists conflict
  357. let fileNameExtension = (fileName as NSString).pathExtension.lowercased()
  358. let fileNameWithoutExtension = (fileName as NSString).deletingPathExtension
  359. var fileNameConflict = fileName
  360. if fileNameExtension == "heic" && CCUtility.getFormatCompatibility() {
  361. fileNameConflict = fileNameWithoutExtension + ".jpg"
  362. }
  363. return NCManageDatabase.shared.getMetadata(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@ AND fileNameView == %@", account, serverUrl, fileNameConflict))
  364. }
  365. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  366. return true
  367. }
  368. @objc func fromColor(color: UIColor) -> UIImage {
  369. let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
  370. UIGraphicsBeginImageContext(rect.size)
  371. let context: CGContext? = UIGraphicsGetCurrentContext()
  372. context?.setFillColor(color.cgColor)
  373. context?.fill(rect)
  374. let image: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
  375. UIGraphicsEndImageContext()
  376. return image ?? UIImage()
  377. }
  378. // Delete Asset on Photos album
  379. @objc func deleteAssetLocalIdentifiers(account: String, sessionSelector: String, completition: @escaping () -> ()) {
  380. if UIApplication.shared.applicationState != .active {
  381. completition()
  382. return
  383. }
  384. let metadatasSessionUpload = NCManageDatabase.shared.getMetadatas(predicate: NSPredicate(format: "account == %@ AND session CONTAINS[cd] %@", account, "upload"))
  385. if metadatasSessionUpload.count > 0 {
  386. completition()
  387. return
  388. }
  389. let localIdentifiers = NCManageDatabase.shared.getAssetLocalIdentifiersUploaded(account: account, sessionSelector: sessionSelector)
  390. if localIdentifiers.count == 0 {
  391. completition()
  392. return
  393. }
  394. let assets = PHAsset.fetchAssets(withLocalIdentifiers: localIdentifiers, options: nil)
  395. PHPhotoLibrary.shared().performChanges({
  396. PHAssetChangeRequest.deleteAssets(assets as NSFastEnumeration)
  397. }, completionHandler: { success, error in
  398. DispatchQueue.main.async {
  399. NCManageDatabase.shared.clearAssetLocalIdentifiers(localIdentifiers, account: account)
  400. completition()
  401. }
  402. })
  403. }
  404. @objc func ocIdToFileId(ocId: String?) -> String? {
  405. guard let ocId = ocId else { return nil }
  406. let items = ocId.components(separatedBy: "oc")
  407. if items.count < 2 { return nil }
  408. guard let intFileId = Int(items[0]) else { return nil }
  409. return String(intFileId)
  410. }
  411. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String) {
  412. var onlineStatus: UIImage?
  413. var statusMessage: String = ""
  414. var messageUserDefined: String = ""
  415. if userStatus?.lowercased() == "online" {
  416. 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)
  417. messageUserDefined = NSLocalizedString("_online_", comment: "")
  418. }
  419. if userStatus?.lowercased() == "away" {
  420. 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)
  421. messageUserDefined = NSLocalizedString("_away_", comment: "")
  422. }
  423. if userStatus?.lowercased() == "dnd" {
  424. onlineStatus = UIImage.init(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  425. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  426. }
  427. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  428. onlineStatus = UIImage.init(named: "userStatusOffline")!.image(color: .black, size: 50)
  429. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  430. }
  431. if let userIcon = userIcon {
  432. statusMessage = userIcon + " "
  433. }
  434. if let userMessage = userMessage {
  435. statusMessage = statusMessage + userMessage
  436. }
  437. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  438. if statusMessage == "" {
  439. statusMessage = messageUserDefined
  440. }
  441. return(onlineStatus, statusMessage)
  442. }
  443. @objc func settingThemingColor(_ themingColor: String?, themingColorElement: String?, themingColorText: String?) {
  444. // COLOR
  445. if themingColor?.first == "#" {
  446. if let color = UIColor(hex: themingColor!) {
  447. NCBrandColor.shared.brand = color
  448. } else {
  449. NCBrandColor.shared.brand = NCBrandColor.shared.customer
  450. }
  451. } else {
  452. NCBrandColor.shared.brand = NCBrandColor.shared.customer
  453. }
  454. // COLOR TEXT
  455. if themingColorText?.first == "#" {
  456. if let color = UIColor(hex: themingColorText!) {
  457. NCBrandColor.shared.brandText = color
  458. } else {
  459. NCBrandColor.shared.brandText = NCBrandColor.shared.customerText
  460. }
  461. } else {
  462. NCBrandColor.shared.brandText = NCBrandColor.shared.customerText
  463. }
  464. // COLOR ELEMENT
  465. if themingColorElement?.first == "#" {
  466. if let color = UIColor(hex: themingColorElement!) {
  467. NCBrandColor.shared.brandElement = color
  468. } else {
  469. NCBrandColor.shared.brandElement = NCBrandColor.shared.brand
  470. }
  471. } else {
  472. NCBrandColor.shared.brandElement = NCBrandColor.shared.brand
  473. }
  474. }
  475. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  476. let asset = AVURLAsset(url: url)
  477. let assetIG = AVAssetImageGenerator(asset: asset)
  478. assetIG.appliesPreferredTrackTransform = true
  479. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  480. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  481. let thumbnailImageRef: CGImage
  482. do {
  483. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  484. } catch let error {
  485. print("Error: \(error)")
  486. return nil
  487. }
  488. return UIImage(cgImage: thumbnailImageRef)
  489. }
  490. func createImageFrom(fileName: String, ocId: String, etag: String, typeFile: String) {
  491. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  492. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  493. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  494. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  495. if FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  496. if !CCUtility.fileProviderStorageExists(ocId, fileNameView: fileName) { return }
  497. if typeFile != NCBrandGlobal.shared.metadataTypeFileImage && typeFile != NCBrandGlobal.shared.metadataTypeFileVideo { return }
  498. if typeFile == NCBrandGlobal.shared.metadataTypeFileImage {
  499. originalImage = UIImage.init(contentsOfFile: fileNamePath)
  500. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCBrandGlobal.shared.sizePreview, height: NCBrandGlobal.shared.sizePreview), isAspectRation: false)
  501. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCBrandGlobal.shared.sizeIcon, height: NCBrandGlobal.shared.sizeIcon), isAspectRation: false)
  502. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  503. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  504. } else if typeFile == NCBrandGlobal.shared.metadataTypeFileVideo {
  505. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  506. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  507. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  508. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  509. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  510. }
  511. }
  512. }