NCUtility.swift 45 KB

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