NCUtility.swift 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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 UIKit
  24. import SVGKit
  25. import KTVHTTPCache
  26. import NextcloudKit
  27. import PDFKit
  28. import Accelerate
  29. import CoreMedia
  30. import Queuer
  31. import Photos
  32. import JGProgressHUD
  33. class NCUtility: NSObject {
  34. @objc static let shared: NCUtility = {
  35. let instance = NCUtility()
  36. return instance
  37. }()
  38. func setLayoutForView(key: String, serverUrl: String, layoutForView: NCGlobal.layoutForViewType) {
  39. let string = layoutForView.layout + "|" + layoutForView.sort + "|" + "\(layoutForView.ascending)" + "|" + layoutForView.groupBy + "|" + "\(layoutForView.directoryOnTop)" + "|" + layoutForView.titleButtonHeader + "|" + "\(layoutForView.itemForLine)"
  40. var keyStore = key
  41. if serverUrl != "" {
  42. keyStore = serverUrl
  43. }
  44. UICKeyChainStore.setString(string, forKey: keyStore, service: NCGlobal.shared.serviceShareKeyChain)
  45. }
  46. func setLayoutForView(key: String, serverUrl: String, layout: String?) {
  47. var layoutForView: NCGlobal.layoutForViewType = NCUtility.shared.getLayoutForView(key: key, serverUrl: serverUrl)
  48. if let layout = layout {
  49. layoutForView.layout = layout
  50. setLayoutForView(key: key, serverUrl: serverUrl, layoutForView: layoutForView)
  51. }
  52. }
  53. func getLayoutForView(key: String, serverUrl: String, sort: String = "fileName", ascending: Bool = true, titleButtonHeader: String = "_sorted_by_name_a_z_") -> (NCGlobal.layoutForViewType) {
  54. var keyStore = key
  55. var layoutForView: NCGlobal.layoutForViewType = NCGlobal.layoutForViewType(layout: NCGlobal.shared.layoutList, sort: sort, ascending: ascending, groupBy: "none", directoryOnTop: true, titleButtonHeader: titleButtonHeader, itemForLine: 3)
  56. if serverUrl != "" {
  57. keyStore = serverUrl
  58. }
  59. guard let string = UICKeyChainStore.string(forKey: keyStore, service: NCGlobal.shared.serviceShareKeyChain) else {
  60. setLayoutForView(key: key, serverUrl: serverUrl, layoutForView: layoutForView)
  61. return layoutForView
  62. }
  63. let array = string.components(separatedBy: "|")
  64. if array.count >= 7 {
  65. // version 1
  66. layoutForView.layout = array[0]
  67. layoutForView.sort = array[1]
  68. layoutForView.ascending = NSString(string: array[2]).boolValue
  69. layoutForView.groupBy = array[3]
  70. layoutForView.directoryOnTop = NSString(string: array[4]).boolValue
  71. layoutForView.titleButtonHeader = array[5]
  72. layoutForView.itemForLine = Int(NSString(string: array[6]).intValue)
  73. }
  74. return layoutForView
  75. }
  76. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, account: String, closure: @escaping (String?) -> Void) {
  77. var fileNamePNG = ""
  78. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
  79. let iconURL = URL(string: svgUrlString) else {
  80. return closure(nil)
  81. }
  82. if let fileName = fileName {
  83. fileNamePNG = fileName
  84. } else {
  85. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  86. }
  87. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  88. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  89. NextcloudKit.shared.downloadContent(serverUrl: iconURL.absoluteString) { _, data, error in
  90. if error == .success && data != nil {
  91. if let image = UIImage(data: data!) {
  92. var newImage: UIImage = image
  93. if width != nil {
  94. let ratio = image.size.height / image.size.width
  95. let newSize = CGSize(width: width!, height: width! * ratio)
  96. let renderFormat = UIGraphicsImageRendererFormat.default()
  97. renderFormat.opaque = false
  98. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  99. newImage = renderer.image {
  100. _ in
  101. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  102. }
  103. }
  104. guard let pngImageData = newImage.pngData() else {
  105. return closure(nil)
  106. }
  107. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  108. return closure(imageNamePath)
  109. } else {
  110. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  111. return closure(nil)
  112. }
  113. if width != nil {
  114. let scale = svgImage.size.height / svgImage.size.width
  115. svgImage.size = CGSize(width: width!, height: width! * scale)
  116. }
  117. guard let image: UIImage = svgImage.uiImage else {
  118. return closure(nil)
  119. }
  120. guard let pngImageData = image.pngData() else {
  121. return closure(nil)
  122. }
  123. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  124. return closure(imageNamePath)
  125. }
  126. } else {
  127. return closure(nil)
  128. }
  129. }
  130. } else {
  131. return closure(imageNamePath)
  132. }
  133. }
  134. @objc func isSimulatorOrTestFlight() -> Bool {
  135. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  136. return false
  137. }
  138. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  139. }
  140. @objc func isSimulator() -> Bool {
  141. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  142. return false
  143. }
  144. return path.contains("CoreSimulator")
  145. }
  146. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  147. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  148. return false
  149. }
  150. guard let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  151. return false
  152. }
  153. // contentype
  154. for richdocumentMimetype: String in richdocumentsMimetypes {
  155. if richdocumentMimetype.contains(metadata.contentType) || metadata.contentType == "text/plain" {
  156. return true
  157. }
  158. }
  159. // mimetype
  160. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  161. let mimeTypeArray = mimeType.components(separatedBy: ".")
  162. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  163. for richdocumentMimetype: String in richdocumentsMimetypes {
  164. if richdocumentMimetype.contains(mimeType) {
  165. return true
  166. }
  167. }
  168. }
  169. return false
  170. }
  171. @objc func isDirectEditing(account: String, contentType: String) -> [String] {
  172. var editor: [String] = []
  173. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else {
  174. return editor
  175. }
  176. for result: tableDirectEditingEditors in results {
  177. for mimetype in result.mimetypes {
  178. if mimetype == contentType {
  179. editor.append(result.editor)
  180. }
  181. // HARDCODE
  182. // https://github.com/nextcloud/text/issues/913
  183. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  184. editor.append(result.editor)
  185. }
  186. if contentType == "text/html" {
  187. editor.append(result.editor)
  188. }
  189. }
  190. for mimetype in result.optionalMimetypes {
  191. if mimetype == contentType {
  192. editor.append(result.editor)
  193. }
  194. }
  195. }
  196. // HARDCODE
  197. // if editor.count == 0 {
  198. // editor.append(NCGlobal.shared.editorText)
  199. // }
  200. return Array(Set(editor))
  201. }
  202. @objc func removeAllSettings() {
  203. URLCache.shared.memoryCapacity = 0
  204. URLCache.shared.diskCapacity = 0
  205. KTVHTTPCache.cacheDeleteAllCaches()
  206. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  207. CCUtility.removeGroupDirectoryProviderStorage()
  208. CCUtility.removeGroupLibraryDirectory()
  209. CCUtility.removeDocumentsDirectory()
  210. CCUtility.removeTemporaryDirectory()
  211. CCUtility.createDirectoryStandard()
  212. CCUtility.deleteAllChainStore()
  213. }
  214. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  215. for char in permissions {
  216. if metadataPermissions.contains(char) == false {
  217. return false
  218. }
  219. }
  220. return true
  221. }
  222. @objc func getCustomUserAgentNCText() -> String {
  223. let userAgent: String = CCUtility.getUserAgent()
  224. if UIDevice.current.userInterfaceIdiom == .phone {
  225. // NOTE: Hardcoded (May 2022)
  226. // Tested for iPhone SE (1st), iOS 12; iPhone Pro Max, iOS 15.4
  227. // 605.1.15 = WebKit build version
  228. // 15E148 = frozen iOS build number according to: https://chromestatus.com/feature/4558585463832576
  229. return userAgent + " " + "AppleWebKit/605.1.15 Mobile/15E148"
  230. } else {
  231. return userAgent
  232. }
  233. }
  234. @objc func getCustomUserAgentOnlyOffice() -> String {
  235. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  236. if UIDevice.current.userInterfaceIdiom == .pad {
  237. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  238. } else {
  239. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  240. }
  241. }
  242. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  243. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  244. return nil
  245. }
  246. let pageSize = page.bounds(for: .mediaBox)
  247. let pdfScale = width / pageSize.width
  248. // Apply if you're displaying the thumbnail on screen
  249. let scale = UIScreen.main.scale * pdfScale
  250. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  251. return page.thumbnail(of: screenSize, for: .mediaBox)
  252. }
  253. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  254. return true
  255. }
  256. @objc func ocIdToFileId(ocId: String?) -> String? {
  257. guard let ocId = ocId else { return nil }
  258. let items = ocId.components(separatedBy: "oc")
  259. if items.count < 2 { return nil }
  260. guard let intFileId = Int(items[0]) else { return nil }
  261. return String(intFileId)
  262. }
  263. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String, descriptionMessage: String) {
  264. var onlineStatus: UIImage?
  265. var statusMessage: String = ""
  266. var descriptionMessage: String = ""
  267. var messageUserDefined: String = ""
  268. if userStatus?.lowercased() == "online" {
  269. onlineStatus = UIImage(named: "circle_fill")!.image(color: UIColor(red: 103.0/255.0, green: 176.0/255.0, blue: 134.0/255.0, alpha: 1.0), size: 50)
  270. messageUserDefined = NSLocalizedString("_online_", comment: "")
  271. }
  272. if userStatus?.lowercased() == "away" {
  273. onlineStatus = UIImage(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)
  274. messageUserDefined = NSLocalizedString("_away_", comment: "")
  275. }
  276. if userStatus?.lowercased() == "dnd" {
  277. onlineStatus = UIImage(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  278. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  279. descriptionMessage = NSLocalizedString("_dnd_description_", comment: "")
  280. }
  281. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  282. onlineStatus = UIImage(named: "userStatusOffline")!.image(color: .black, size: 50)
  283. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  284. descriptionMessage = NSLocalizedString("_invisible_description_", comment: "")
  285. }
  286. if let userIcon = userIcon {
  287. statusMessage = userIcon + " "
  288. }
  289. if let userMessage = userMessage {
  290. statusMessage += userMessage
  291. }
  292. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  293. if statusMessage == "" {
  294. statusMessage = messageUserDefined
  295. }
  296. return(onlineStatus, statusMessage, descriptionMessage)
  297. }
  298. // MARK: -
  299. func extractFiles(from metadata: tableMetadata, viewController: UIViewController? ,completition: @escaping (_ metadatas: [tableMetadata]) -> Void) {
  300. let chunckSize = CCUtility.getChunkSize() * 1000000
  301. var metadatas: [tableMetadata] = []
  302. let metadataSource = tableMetadata.init(value: metadata)
  303. guard !metadata.isExtractFile else { return completition([metadataSource]) }
  304. guard !metadataSource.assetLocalIdentifier.isEmpty else {
  305. let filePath = CCUtility.getDirectoryProviderStorageOcId(metadataSource.ocId, fileNameView: metadataSource.fileName)!
  306. metadataSource.size = NCUtilityFileSystem.shared.getFileSize(filePath: filePath)
  307. let results = NKCommon.shared.getInternalType(fileName: metadataSource.fileNameView, mimeType: metadataSource.contentType, directory: false)
  308. metadataSource.contentType = results.mimeType
  309. metadataSource.iconName = results.iconName
  310. metadataSource.classFile = results.classFile
  311. if let date = NCUtilityFileSystem.shared.getFileCreationDate(filePath: filePath) {
  312. metadataSource.creationDate = date
  313. }
  314. if let date = NCUtilityFileSystem.shared.getFileModificationDate(filePath: filePath) {
  315. metadataSource.date = date
  316. }
  317. metadataSource.chunk = chunckSize != 0 && metadata.size > chunckSize
  318. metadataSource.e2eEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  319. metadataSource.isExtractFile = true
  320. if let metadata = NCManageDatabase.shared.addMetadata(metadataSource) {
  321. metadatas.append(metadata)
  322. }
  323. return completition(metadatas)
  324. }
  325. extractImageVideoFromAssetLocalIdentifier(metadata: metadataSource, modifyMetadataForUpload: true, viewController: viewController) { metadata, fileNamePath, returnError in
  326. if let metadata = metadata, let fileNamePath = fileNamePath, !returnError {
  327. metadatas.append(metadata)
  328. let toPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)!
  329. NCUtilityFileSystem.shared.moveFile(atPath: fileNamePath, toPath: toPath)
  330. } else {
  331. return completition(metadatas)
  332. }
  333. let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadataSource.assetLocalIdentifier], options: nil)
  334. if metadataSource.livePhoto, fetchAssets.count > 0 {
  335. NCUtility.shared.createMetadataLivePhotoFromMetadata(metadataSource, asset: fetchAssets.firstObject) { metadata in
  336. if let metadata = metadata, let metadata = NCManageDatabase.shared.addMetadata(metadata) {
  337. metadatas.append(metadata)
  338. }
  339. completition(metadatas)
  340. }
  341. } else {
  342. completition(metadatas)
  343. }
  344. }
  345. }
  346. func extractImageVideoFromAssetLocalIdentifier(metadata: tableMetadata, modifyMetadataForUpload: Bool, viewController: UIViewController?, completion: @escaping (_ metadata: tableMetadata?, _ fileNamePath: String?, _ error: Bool) -> ()) {
  347. var fileNamePath: String?
  348. let metadata = tableMetadata.init(value: metadata)
  349. let chunckSize = CCUtility.getChunkSize() * 1000000
  350. var compatibilityFormat: Bool = false
  351. let hud = JGProgressHUD()
  352. func callCompletion(error: Bool) {
  353. if error {
  354. completion(nil, nil, true)
  355. } else {
  356. var metadataReturn = metadata
  357. if modifyMetadataForUpload {
  358. metadata.chunk = chunckSize != 0 && metadata.size > chunckSize
  359. metadata.e2eEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  360. metadata.isExtractFile = true
  361. if let metadata = NCManageDatabase.shared.addMetadata(metadata) {
  362. metadataReturn = metadata
  363. }
  364. }
  365. completion(metadataReturn, fileNamePath, error)
  366. }
  367. }
  368. let fetchAssets = PHAsset.fetchAssets(withLocalIdentifiers: [metadata.assetLocalIdentifier], options: nil)
  369. guard fetchAssets.count > 0, let asset = fetchAssets.firstObject, let extensionAsset = (asset.value(forKey: "filename") as? NSString)?.pathExtension.uppercased() else {
  370. return callCompletion(error: true)
  371. }
  372. let creationDate = asset.creationDate ?? Date()
  373. let modificationDate = asset.modificationDate ?? Date()
  374. if asset.mediaType == PHAssetMediaType.image && (extensionAsset == "HEIC" || extensionAsset == "DNG") && CCUtility.getFormatCompatibility() {
  375. let fileName = (metadata.fileNameView as NSString).deletingPathExtension + ".jpg"
  376. metadata.contentType = "image/jpeg"
  377. metadata.ext = "jpg"
  378. fileNamePath = NSTemporaryDirectory() + fileName
  379. metadata.fileNameView = fileName
  380. if !metadata.e2eEncrypted {
  381. metadata.fileName = fileName
  382. }
  383. compatibilityFormat = true
  384. } else {
  385. fileNamePath = NSTemporaryDirectory() + metadata.fileNameView
  386. }
  387. guard let fileNamePath = fileNamePath else {
  388. return callCompletion(error: true)
  389. }
  390. if asset.mediaType == PHAssetMediaType.image {
  391. let options = PHImageRequestOptions()
  392. options.isNetworkAccessAllowed = true
  393. if compatibilityFormat {
  394. options.deliveryMode = .opportunistic
  395. } else {
  396. options.deliveryMode = .highQualityFormat
  397. }
  398. options.isSynchronous = true
  399. if extensionAsset == "DNG" {
  400. options.version = PHImageRequestOptionsVersion.original
  401. }
  402. options.progressHandler = { (progress, error, stop, info) in
  403. print(progress)
  404. if error != nil { return callCompletion(error: true) }
  405. }
  406. PHImageManager.default().requestImageDataAndOrientation(for: asset, options: options) { data, dataUI, orientation, info in
  407. guard var data = data else { return callCompletion(error: true) }
  408. if compatibilityFormat {
  409. guard let ciImage = CIImage.init(data: data), let colorSpace = ciImage.colorSpace, let dataJPEG = CIContext().jpegRepresentation(of: ciImage, colorSpace: colorSpace) else { return callCompletion(error: true) }
  410. data = dataJPEG
  411. }
  412. NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
  413. do {
  414. try data.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  415. } catch {
  416. return callCompletion(error: true)
  417. }
  418. metadata.creationDate = creationDate as NSDate
  419. metadata.date = modificationDate as NSDate
  420. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  421. return callCompletion(error: false)
  422. }
  423. } else if asset.mediaType == PHAssetMediaType.video {
  424. let options = PHVideoRequestOptions()
  425. options.isNetworkAccessAllowed = true
  426. options.version = PHVideoRequestOptionsVersion.current
  427. options.progressHandler = { (progress, error, stop, info) in
  428. print(progress)
  429. if error != nil { return callCompletion(error: true) }
  430. }
  431. PHImageManager.default().requestAVAsset(forVideo: asset, options: options) { asset, audioMix, info in
  432. if let asset = asset as? AVURLAsset {
  433. NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
  434. do {
  435. try FileManager.default.copyItem(at: asset.url, to: URL(fileURLWithPath: fileNamePath))
  436. metadata.creationDate = creationDate as NSDate
  437. metadata.date = modificationDate as NSDate
  438. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  439. return callCompletion(error: false)
  440. } catch {
  441. return callCompletion(error: true)
  442. }
  443. } else if let asset = asset as? AVComposition, asset.tracks.count > 1, let exporter = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) {
  444. if let viewController = viewController {
  445. DispatchQueue.main.async {
  446. hud.indicatorView = JGProgressHUDRingIndicatorView()
  447. if let indicatorView = hud.indicatorView as? JGProgressHUDRingIndicatorView {
  448. indicatorView.ringWidth = 1.5
  449. }
  450. hud.textLabel.text = NSLocalizedString("_exporting_video_", comment: "")
  451. hud.show(in: viewController.view)
  452. hud.tapOnHUDViewBlock = { hud in
  453. exporter.cancelExport()
  454. }
  455. }
  456. }
  457. exporter.outputURL = URL(fileURLWithPath: fileNamePath)
  458. exporter.outputFileType = AVFileType.mp4
  459. exporter.shouldOptimizeForNetworkUse = true
  460. exporter.exportAsynchronously {
  461. DispatchQueue.main.async { hud.dismiss() }
  462. if exporter.status == .completed {
  463. metadata.creationDate = creationDate as NSDate
  464. metadata.date = modificationDate as NSDate
  465. metadata.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  466. return callCompletion(error: false)
  467. } else {
  468. return callCompletion(error: true)
  469. }
  470. }
  471. while exporter.status == AVAssetExportSession.Status.exporting || exporter.status == AVAssetExportSession.Status.waiting {
  472. hud.progress = exporter.progress
  473. }
  474. } else {
  475. return callCompletion(error: true)
  476. }
  477. }
  478. } else {
  479. return callCompletion(error: true)
  480. }
  481. }
  482. func createMetadataLivePhotoFromMetadata(_ metadata: tableMetadata, asset: PHAsset?, completion: @escaping (_ metadata: tableMetadata?) -> ()) {
  483. guard let asset = asset else { return completion(nil) }
  484. let options = PHLivePhotoRequestOptions()
  485. options.deliveryMode = PHImageRequestOptionsDeliveryMode.fastFormat
  486. options.isNetworkAccessAllowed = true
  487. let chunckSize = CCUtility.getChunkSize() * 1000000
  488. let e2eEncrypted = CCUtility.isFolderEncrypted(metadata.serverUrl, e2eEncrypted: metadata.e2eEncrypted, account: metadata.account, urlBase: metadata.urlBase)
  489. let ocId = NSUUID().uuidString
  490. let fileName = (metadata.fileName as NSString).deletingPathExtension + ".mov"
  491. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileName)!
  492. PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: PHImageContentMode.default, options: options) { livePhoto, info in
  493. guard let livePhoto = livePhoto else { return completion(nil) }
  494. var videoResource: PHAssetResource?
  495. for resource in PHAssetResource.assetResources(for: livePhoto) {
  496. if resource.type == PHAssetResourceType.pairedVideo {
  497. videoResource = resource
  498. break
  499. }
  500. }
  501. guard let videoResource = videoResource else { return completion(nil) }
  502. NCUtilityFileSystem.shared.deleteFile(filePath: fileNamePath)
  503. PHAssetResourceManager.default().writeData(for: videoResource, toFile: URL(fileURLWithPath: fileNamePath), options: nil) { error in
  504. if error != nil { return completion(nil) }
  505. let metadataLivePhoto = NCManageDatabase.shared.createMetadata(account: metadata.account, user: metadata.user, userId: metadata.userId, fileName: fileName, fileNameView: fileName, ocId: ocId, serverUrl: metadata.serverUrl, urlBase: metadata.urlBase, url: "", contentType: "", isLivePhoto: true)
  506. metadataLivePhoto.classFile = NKCommon.typeClassFile.video.rawValue
  507. metadataLivePhoto.e2eEncrypted = e2eEncrypted
  508. metadataLivePhoto.isExtractFile = true
  509. metadataLivePhoto.session = metadata.session
  510. metadataLivePhoto.sessionSelector = metadata.sessionSelector
  511. metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  512. metadataLivePhoto.status = metadata.status
  513. metadataLivePhoto.chunk = chunckSize != 0 && metadata.size > chunckSize
  514. return completion(NCManageDatabase.shared.addMetadata(metadataLivePhoto))
  515. }
  516. }
  517. }
  518. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  519. let asset = AVURLAsset(url: url)
  520. let assetIG = AVAssetImageGenerator(asset: asset)
  521. assetIG.appliesPreferredTrackTransform = true
  522. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  523. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  524. let thumbnailImageRef: CGImage
  525. do {
  526. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  527. } catch let error {
  528. print("Error: \(error)")
  529. return nil
  530. }
  531. return UIImage(cgImage: thumbnailImageRef)
  532. }
  533. func imageFromVideo(url: URL, at time: TimeInterval, completion: @escaping (UIImage?) -> Void) {
  534. DispatchQueue.global().async {
  535. let asset = AVURLAsset(url: url)
  536. let assetIG = AVAssetImageGenerator(asset: asset)
  537. assetIG.appliesPreferredTrackTransform = true
  538. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  539. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  540. let thumbnailImageRef: CGImage
  541. do {
  542. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  543. } catch let error {
  544. print("Error: \(error)")
  545. return completion(nil)
  546. }
  547. DispatchQueue.main.async {
  548. completion(UIImage(cgImage: thumbnailImageRef))
  549. }
  550. }
  551. }
  552. func createImageFrom(fileNameView: String, ocId: String, etag: String, classFile: String) {
  553. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  554. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  555. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  556. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  557. if CCUtility.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  558. if classFile != NKCommon.typeClassFile.image.rawValue && classFile != NKCommon.typeClassFile.video.rawValue { return }
  559. if classFile == NKCommon.typeClassFile.image.rawValue {
  560. originalImage = UIImage(contentsOfFile: fileNamePath)
  561. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview))
  562. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon))
  563. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  564. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  565. } else if classFile == NKCommon.typeClassFile.video.rawValue {
  566. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  567. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  568. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  569. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  570. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  571. }
  572. }
  573. @objc func getVersionApp(withBuild: Bool = true) -> String {
  574. if let dictionary = Bundle.main.infoDictionary {
  575. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  576. if withBuild {
  577. return "\(version).\(build)"
  578. } else {
  579. return "\(version)"
  580. }
  581. }
  582. }
  583. return ""
  584. }
  585. func loadImage(named imageName: String, color: UIColor = NCBrandColor.shared.gray, size: CGFloat = 50, symbolConfiguration: Any? = nil) -> UIImage {
  586. var image: UIImage?
  587. // see https://stackoverflow.com/questions/71764255
  588. let sfSymbolName = imageName.replacingOccurrences(of: "_", with: ".")
  589. if let symbolConfiguration = symbolConfiguration {
  590. image = UIImage(systemName: sfSymbolName, withConfiguration: symbolConfiguration as? UIImage.Configuration)?.withTintColor(color, renderingMode: .alwaysOriginal)
  591. } else {
  592. image = UIImage(systemName: sfSymbolName)?.withTintColor(color, renderingMode: .alwaysOriginal)
  593. }
  594. if image == nil {
  595. image = UIImage(named: imageName)?.image(color: color, size: size)
  596. }
  597. if let image = image {
  598. return image
  599. }
  600. return UIImage(named: "file")!.image(color: color, size: size)
  601. }
  602. @objc func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage {
  603. let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png"
  604. let localFilePath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  605. if let localImage = UIImage(contentsOfFile: localFilePath) {
  606. return createAvatar(image: localImage, size: 30)
  607. } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  608. return loadedAvatar
  609. } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) {
  610. return avatarImg
  611. } else { return getDefaultUserIcon() }
  612. }
  613. func getDefaultUserIcon() -> UIImage {
  614. let config = UIImage.SymbolConfiguration(pointSize: 30)
  615. return NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config)
  616. }
  617. @objc func createAvatar(image: UIImage, size: CGFloat) -> UIImage {
  618. var avatarImage = image
  619. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  620. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  621. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  622. avatarImage.draw(in: rect)
  623. avatarImage = UIGraphicsGetImageFromCurrentImageContext() ?? image
  624. UIGraphicsEndImageContext()
  625. return avatarImage
  626. }
  627. func createAvatar(displayName: String, size: CGFloat) -> UIImage? {
  628. guard let initials = displayName.uppercaseInitials else {
  629. return nil
  630. }
  631. let userColor = NCGlobal.shared.usernameToColor(displayName)
  632. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  633. var avatarImage: UIImage?
  634. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  635. let context = UIGraphicsGetCurrentContext()
  636. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  637. context?.setFillColor(userColor)
  638. context?.fill(rect)
  639. let textStyle = NSMutableParagraphStyle()
  640. textStyle.alignment = NSTextAlignment.center
  641. let lineHeight = UIFont.systemFont(ofSize: UIFont.systemFontSize).pointSize
  642. NSString(string: initials)
  643. .draw(
  644. in: CGRect(x: 0, y: (size - lineHeight) / 2, width: size, height: lineHeight),
  645. withAttributes: [NSAttributedString.Key.paragraphStyle: textStyle])
  646. avatarImage = UIGraphicsGetImageFromCurrentImageContext()
  647. UIGraphicsEndImageContext()
  648. return avatarImage
  649. }
  650. /*
  651. Facebook's comparison algorithm:
  652. */
  653. func compare(tolerance: Float, expected: Data, observed: Data) throws -> Bool {
  654. enum customError: Error {
  655. case unableToGetUIImageFromData
  656. case unableToGetCGImageFromData
  657. case unableToGetColorSpaceFromCGImage
  658. case imagesHasDifferentSizes
  659. case unableToInitializeContext
  660. }
  661. guard let expectedUIImage = UIImage(data: expected), let observedUIImage = UIImage(data: observed) else {
  662. throw customError.unableToGetUIImageFromData
  663. }
  664. guard let expectedCGImage = expectedUIImage.cgImage, let observedCGImage = observedUIImage.cgImage else {
  665. throw customError.unableToGetCGImageFromData
  666. }
  667. guard let expectedColorSpace = expectedCGImage.colorSpace, let observedColorSpace = observedCGImage.colorSpace else {
  668. throw customError.unableToGetColorSpaceFromCGImage
  669. }
  670. if expectedCGImage.width != observedCGImage.width || expectedCGImage.height != observedCGImage.height {
  671. throw customError.imagesHasDifferentSizes
  672. }
  673. let imageSize = CGSize(width: expectedCGImage.width, height: expectedCGImage.height)
  674. let numberOfPixels = Int(imageSize.width * imageSize.height)
  675. // Checking that our `UInt32` buffer has same number of bytes as image has.
  676. let bytesPerRow = min(expectedCGImage.bytesPerRow, observedCGImage.bytesPerRow)
  677. assert(MemoryLayout<UInt32>.stride == bytesPerRow / Int(imageSize.width))
  678. let expectedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  679. let observedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  680. let expectedPixelsRaw = UnsafeMutableRawPointer(expectedPixels)
  681. let observedPixelsRaw = UnsafeMutableRawPointer(observedPixels)
  682. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  683. guard let expectedContext = CGContext(data: expectedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  684. bitsPerComponent: expectedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  685. space: expectedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  686. expectedPixels.deallocate()
  687. observedPixels.deallocate()
  688. throw customError.unableToInitializeContext
  689. }
  690. guard let observedContext = CGContext(data: observedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  691. bitsPerComponent: observedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  692. space: observedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  693. expectedPixels.deallocate()
  694. observedPixels.deallocate()
  695. throw customError.unableToInitializeContext
  696. }
  697. expectedContext.draw(expectedCGImage, in: CGRect(origin: .zero, size: imageSize))
  698. observedContext.draw(observedCGImage, in: CGRect(origin: .zero, size: imageSize))
  699. let expectedBuffer = UnsafeBufferPointer(start: expectedPixels, count: numberOfPixels)
  700. let observedBuffer = UnsafeBufferPointer(start: observedPixels, count: numberOfPixels)
  701. var isEqual = true
  702. if tolerance == 0 {
  703. isEqual = expectedBuffer.elementsEqual(observedBuffer)
  704. } else {
  705. // Go through each pixel in turn and see if it is different
  706. var numDiffPixels = 0
  707. for pixel in 0 ..< numberOfPixels where expectedBuffer[pixel] != observedBuffer[pixel] {
  708. // If this pixel is different, increment the pixel diff count and see if we have hit our limit.
  709. numDiffPixels += 1
  710. let percentage = 100 * Float(numDiffPixels) / Float(numberOfPixels)
  711. if percentage > tolerance {
  712. isEqual = false
  713. break
  714. }
  715. }
  716. }
  717. expectedPixels.deallocate()
  718. observedPixels.deallocate()
  719. return isEqual
  720. }
  721. func stringFromTime(_ time: CMTime) -> String {
  722. let interval = Int(CMTimeGetSeconds(time))
  723. let seconds = interval % 60
  724. let minutes = (interval / 60) % 60
  725. let hours = (interval / 3600)
  726. if hours > 0 {
  727. return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
  728. } else {
  729. return String(format: "%02d:%02d", minutes, seconds)
  730. }
  731. }
  732. func colorNavigationController(_ navigationController: UINavigationController?, backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) {
  733. let appearance = UINavigationBarAppearance()
  734. appearance.titleTextAttributes = [.foregroundColor: titleColor]
  735. appearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
  736. if withoutShadow {
  737. appearance.shadowColor = .clear
  738. appearance.shadowImage = UIImage()
  739. }
  740. if let tintColor = tintColor {
  741. navigationController?.navigationBar.tintColor = tintColor
  742. }
  743. navigationController?.view.backgroundColor = backgroundColor
  744. navigationController?.navigationBar.barTintColor = titleColor
  745. navigationController?.navigationBar.standardAppearance = appearance
  746. navigationController?.navigationBar.compactAppearance = appearance
  747. navigationController?.navigationBar.scrollEdgeAppearance = appearance
  748. }
  749. func getEncondingDataType(data: Data) -> String.Encoding? {
  750. if let _ = String(data: data, encoding: .utf8) {
  751. return .utf8
  752. }
  753. if let _ = String(data: data, encoding: .ascii) {
  754. return .ascii
  755. }
  756. if let _ = String(data: data, encoding: .isoLatin1) {
  757. return .isoLatin1
  758. }
  759. if let _ = String(data: data, encoding: .isoLatin2) {
  760. return .isoLatin2
  761. }
  762. if let _ = String(data: data, encoding: .windowsCP1250) {
  763. return .windowsCP1250
  764. }
  765. if let _ = String(data: data, encoding: .windowsCP1251) {
  766. return .windowsCP1251
  767. }
  768. if let _ = String(data: data, encoding: .windowsCP1252) {
  769. return .windowsCP1252
  770. }
  771. if let _ = String(data: data, encoding: .windowsCP1253) {
  772. return .windowsCP1253
  773. }
  774. if let _ = String(data: data, encoding: .windowsCP1254) {
  775. return .windowsCP1254
  776. }
  777. if let _ = String(data: data, encoding: .macOSRoman) {
  778. return .macOSRoman
  779. }
  780. if let _ = String(data: data, encoding: .japaneseEUC) {
  781. return .japaneseEUC
  782. }
  783. if let _ = String(data: data, encoding: .nextstep) {
  784. return .nextstep
  785. }
  786. if let _ = String(data: data, encoding: .nonLossyASCII) {
  787. return .nonLossyASCII
  788. }
  789. if let _ = String(data: data, encoding: .shiftJIS) {
  790. return .shiftJIS
  791. }
  792. if let _ = String(data: data, encoding: .symbol) {
  793. return .symbol
  794. }
  795. if let _ = String(data: data, encoding: .unicode) {
  796. return .unicode
  797. }
  798. if let _ = String(data: data, encoding: .utf16) {
  799. return .utf16
  800. }
  801. if let _ = String(data: data, encoding: .utf16BigEndian) {
  802. return .utf16BigEndian
  803. }
  804. if let _ = String(data: data, encoding: .utf16LittleEndian) {
  805. return .utf16LittleEndian
  806. }
  807. if let _ = String(data: data, encoding: .utf32) {
  808. return .utf32
  809. }
  810. if let _ = String(data: data, encoding: .utf32BigEndian) {
  811. return .utf32BigEndian
  812. }
  813. if let _ = String(data: data, encoding: .utf32LittleEndian) {
  814. return .utf32LittleEndian
  815. }
  816. return nil
  817. }
  818. func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
  819. return UIDevice.current.systemVersion.compare(version,
  820. options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending
  821. }
  822. func getAvatarFromIconUrl(metadata: tableMetadata) -> String? {
  823. var ownerId: String?
  824. if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  825. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  826. var found:Bool = false
  827. for item in splitIconUrl {
  828. if found {
  829. ownerId = item
  830. break
  831. }
  832. if item == "avatar" { found = true}
  833. }
  834. }
  835. return ownerId
  836. }
  837. // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
  838. func isValidEmail(_ email: String) -> Bool {
  839. let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
  840. let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
  841. return emailPred.evaluate(with: email)
  842. }
  843. func createFilePreviewImage(ocId: String, etag: String, fileNameView: String, classFile: String, status: Int, createPreviewMedia: Bool) -> UIImage? {
  844. var imagePreview: UIImage?
  845. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  846. let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  847. if FileManager().fileExists(atPath: iconImagePath) {
  848. imagePreview = UIImage(contentsOfFile: iconImagePath)
  849. } else if !createPreviewMedia {
  850. return nil
  851. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.typeClassFile.image.rawValue && FileManager().fileExists(atPath: filePath) {
  852. if let image = UIImage(contentsOfFile: filePath), let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)), let data = image.jpegData(compressionQuality: 0.5) {
  853. do {
  854. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  855. imagePreview = image
  856. } catch { }
  857. }
  858. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.typeClassFile.video.rawValue && FileManager().fileExists(atPath: filePath) {
  859. if let image = NCUtility.shared.imageFromVideo(url: URL(fileURLWithPath: filePath), at: 0), let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)), let data = image.jpegData(compressionQuality: 0.5) {
  860. do {
  861. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  862. imagePreview = image
  863. } catch { }
  864. }
  865. }
  866. return imagePreview
  867. }
  868. @discardableResult
  869. func convertDataToImage(data: Data?, size:CGSize, fileNameToWrite: String?) -> UIImage? {
  870. guard let data = data else { return nil }
  871. var returnImage: UIImage?
  872. if let image = UIImage(data: data), let image = image.resizeImage(size: size) {
  873. returnImage = image
  874. } else if let image = SVGKImage(data: data) {
  875. image.size = size
  876. returnImage = image.uiImage
  877. } else {
  878. print("error")
  879. }
  880. if let fileName = fileNameToWrite, let image = returnImage {
  881. do {
  882. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  883. try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  884. } catch { }
  885. }
  886. return returnImage
  887. }
  888. }