NCUtility.swift 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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.isExtractFile = true
  435. metadataLivePhoto.session = metadata.session
  436. metadataLivePhoto.sessionSelector = metadata.sessionSelector
  437. metadataLivePhoto.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath)
  438. metadataLivePhoto.status = metadata.status
  439. metadataLivePhoto.chunk = chunckSize != 0 && metadata.size > chunckSize
  440. return completion(NCManageDatabase.shared.addMetadata(metadataLivePhoto))
  441. }
  442. }
  443. }
  444. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  445. let asset = AVURLAsset(url: url)
  446. let assetIG = AVAssetImageGenerator(asset: asset)
  447. assetIG.appliesPreferredTrackTransform = true
  448. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  449. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  450. let thumbnailImageRef: CGImage
  451. do {
  452. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  453. } catch let error {
  454. print("Error: \(error)")
  455. return nil
  456. }
  457. return UIImage(cgImage: thumbnailImageRef)
  458. }
  459. func imageFromVideo(url: URL, at time: TimeInterval, completion: @escaping (UIImage?) -> Void) {
  460. DispatchQueue.global(qos: .background).async {
  461. let asset = AVURLAsset(url: url)
  462. let assetIG = AVAssetImageGenerator(asset: asset)
  463. assetIG.appliesPreferredTrackTransform = true
  464. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  465. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  466. let thumbnailImageRef: CGImage
  467. do {
  468. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  469. } catch let error {
  470. print("Error: \(error)")
  471. return completion(nil)
  472. }
  473. DispatchQueue.main.async {
  474. completion(UIImage(cgImage: thumbnailImageRef))
  475. }
  476. }
  477. }
  478. func createImageFrom(fileNameView: String, ocId: String, etag: String, classFile: String) {
  479. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  480. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  481. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  482. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  483. if CCUtility.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  484. if classFile != NCCommunicationCommon.typeClassFile.image.rawValue && classFile != NCCommunicationCommon.typeClassFile.video.rawValue { return }
  485. if classFile == NCCommunicationCommon.typeClassFile.image.rawValue {
  486. originalImage = UIImage(contentsOfFile: fileNamePath)
  487. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview), isAspectRation: false)
  488. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon), isAspectRation: false)
  489. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  490. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  491. } else if classFile == NCCommunicationCommon.typeClassFile.video.rawValue {
  492. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  493. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  494. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  495. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  496. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  497. }
  498. }
  499. @objc func getVersionApp(withBuild: Bool = true) -> String {
  500. if let dictionary = Bundle.main.infoDictionary {
  501. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  502. if withBuild {
  503. return "\(version).\(build)"
  504. } else {
  505. return "\(version)"
  506. }
  507. }
  508. }
  509. return ""
  510. }
  511. func loadImage(named imageName: String, color: UIColor = NCBrandColor.shared.gray, size: CGFloat = 50, symbolConfiguration: Any? = nil) -> UIImage {
  512. var image: UIImage?
  513. if #available(iOS 13.0, *) {
  514. // see https://stackoverflow.com/questions/71764255
  515. let sfSymbolName = imageName.replacingOccurrences(of: "_", with: ".")
  516. if let symbolConfiguration = symbolConfiguration {
  517. image = UIImage(systemName: sfSymbolName, withConfiguration: symbolConfiguration as? UIImage.Configuration)?.imageColor(color)
  518. } else {
  519. image = UIImage(systemName: sfSymbolName)?.imageColor(color)
  520. }
  521. if image == nil {
  522. image = UIImage(named: imageName)?.image(color: color, size: size)
  523. }
  524. } else {
  525. image = UIImage(named: imageName)?.image(color: color, size: size)
  526. }
  527. if let image = image {
  528. return image
  529. }
  530. return UIImage(named: "file")!.image(color: color, size: size)
  531. }
  532. @objc func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage {
  533. let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png"
  534. let localFilePath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  535. if let localImage = UIImage(contentsOfFile: localFilePath) {
  536. return createAvatar(image: localImage, size: 30)
  537. } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  538. return loadedAvatar
  539. } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) {
  540. return avatarImg
  541. } else { return getDefaultUserIcon() }
  542. }
  543. func getDefaultUserIcon() -> UIImage {
  544. if #available(iOS 13.0, *) {
  545. let config = UIImage.SymbolConfiguration(pointSize: 30)
  546. return NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config)
  547. } else {
  548. return NCUtility.shared.loadImage(named: "person.crop.circle", size: 30)
  549. }
  550. }
  551. @objc func createAvatar(image: UIImage, size: CGFloat) -> UIImage {
  552. var avatarImage = image
  553. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  554. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  555. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  556. avatarImage.draw(in: rect)
  557. avatarImage = UIGraphicsGetImageFromCurrentImageContext() ?? image
  558. UIGraphicsEndImageContext()
  559. return avatarImage
  560. }
  561. func createAvatar(displayName: String, size: CGFloat) -> UIImage? {
  562. guard let initials = displayName.uppercaseInitials else {
  563. return nil
  564. }
  565. let userColor = NCGlobal.shared.usernameToColor(displayName)
  566. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  567. var avatarImage: UIImage?
  568. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  569. let context = UIGraphicsGetCurrentContext()
  570. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  571. context?.setFillColor(userColor)
  572. context?.fill(rect)
  573. let textStyle = NSMutableParagraphStyle()
  574. textStyle.alignment = NSTextAlignment.center
  575. let lineHeight = UIFont.systemFont(ofSize: UIFont.systemFontSize).pointSize
  576. NSString(string: initials)
  577. .draw(
  578. in: CGRect(x: 0, y: (size - lineHeight) / 2, width: size, height: lineHeight),
  579. withAttributes: [NSAttributedString.Key.paragraphStyle: textStyle])
  580. avatarImage = UIGraphicsGetImageFromCurrentImageContext()
  581. UIGraphicsEndImageContext()
  582. return avatarImage
  583. }
  584. // MARK: -
  585. @objc func startActivityIndicator(backgroundView: UIView?, blurEffect: Bool, bottom: CGFloat = 0, style: UIActivityIndicatorView.Style = .whiteLarge) {
  586. if self.activityIndicator != nil {
  587. stopActivityIndicator()
  588. }
  589. DispatchQueue.main.async {
  590. self.activityIndicator = UIActivityIndicatorView(style: style)
  591. guard let activityIndicator = self.activityIndicator else { return }
  592. if self.viewBackgroundActivityIndicator != nil { return }
  593. activityIndicator.color = NCBrandColor.shared.label
  594. activityIndicator.hidesWhenStopped = true
  595. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  596. let sizeActivityIndicator = activityIndicator.frame.height + 50
  597. self.viewActivityIndicator = UIView(frame: CGRect(x: 0, y: 0, width: sizeActivityIndicator, height: sizeActivityIndicator))
  598. self.viewActivityIndicator?.translatesAutoresizingMaskIntoConstraints = false
  599. self.viewActivityIndicator?.layer.cornerRadius = 10
  600. self.viewActivityIndicator?.layer.masksToBounds = true
  601. self.viewActivityIndicator?.backgroundColor = .clear
  602. #if !EXTENSION
  603. if backgroundView == nil {
  604. if let window = UIApplication.shared.keyWindow {
  605. self.viewBackgroundActivityIndicator?.removeFromSuperview()
  606. self.viewBackgroundActivityIndicator = NCViewActivityIndicator(frame: window.bounds)
  607. window.addSubview(self.viewBackgroundActivityIndicator!)
  608. self.viewBackgroundActivityIndicator?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  609. self.viewBackgroundActivityIndicator?.backgroundColor = .clear
  610. }
  611. } else {
  612. self.viewBackgroundActivityIndicator = backgroundView
  613. }
  614. #else
  615. self.viewBackgroundActivityIndicator = backgroundView
  616. #endif
  617. // VIEW ACTIVITY INDICATOR
  618. guard let viewActivityIndicator = self.viewActivityIndicator else { return }
  619. viewActivityIndicator.addSubview(activityIndicator)
  620. if blurEffect {
  621. let blurEffect = UIBlurEffect(style: .regular)
  622. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  623. blurEffectView.frame = viewActivityIndicator.frame
  624. viewActivityIndicator.insertSubview(blurEffectView, at: 0)
  625. }
  626. NSLayoutConstraint.activate([
  627. viewActivityIndicator.widthAnchor.constraint(equalToConstant: sizeActivityIndicator),
  628. viewActivityIndicator.heightAnchor.constraint(equalToConstant: sizeActivityIndicator),
  629. activityIndicator.centerXAnchor.constraint(equalTo: viewActivityIndicator.centerXAnchor),
  630. activityIndicator.centerYAnchor.constraint(equalTo: viewActivityIndicator.centerYAnchor)
  631. ])
  632. // BACKGROUD VIEW ACTIVITY INDICATOR
  633. guard let viewBackgroundActivityIndicator = self.viewBackgroundActivityIndicator else { return }
  634. viewBackgroundActivityIndicator.addSubview(viewActivityIndicator)
  635. var verticalConstant: CGFloat = 0
  636. if bottom > 0 {
  637. verticalConstant = (viewBackgroundActivityIndicator.frame.size.height / 2) - bottom
  638. }
  639. NSLayoutConstraint.activate([
  640. viewActivityIndicator.centerXAnchor.constraint(equalTo: viewBackgroundActivityIndicator.centerXAnchor),
  641. viewActivityIndicator.centerYAnchor.constraint(equalTo: viewBackgroundActivityIndicator.centerYAnchor, constant: verticalConstant)
  642. ])
  643. activityIndicator.startAnimating()
  644. }
  645. }
  646. @objc func stopActivityIndicator() {
  647. DispatchQueue.main.async {
  648. self.activityIndicator?.stopAnimating()
  649. self.activityIndicator?.removeFromSuperview()
  650. self.activityIndicator = nil
  651. self.viewActivityIndicator?.removeFromSuperview()
  652. self.viewActivityIndicator = nil
  653. if self.viewBackgroundActivityIndicator is NCViewActivityIndicator {
  654. self.viewBackgroundActivityIndicator?.removeFromSuperview()
  655. }
  656. self.viewBackgroundActivityIndicator = nil
  657. }
  658. }
  659. /*
  660. Facebook's comparison algorithm:
  661. */
  662. func compare(tolerance: Float, expected: Data, observed: Data) throws -> Bool {
  663. enum customError: Error {
  664. case unableToGetUIImageFromData
  665. case unableToGetCGImageFromData
  666. case unableToGetColorSpaceFromCGImage
  667. case imagesHasDifferentSizes
  668. case unableToInitializeContext
  669. }
  670. guard let expectedUIImage = UIImage(data: expected), let observedUIImage = UIImage(data: observed) else {
  671. throw customError.unableToGetUIImageFromData
  672. }
  673. guard let expectedCGImage = expectedUIImage.cgImage, let observedCGImage = observedUIImage.cgImage else {
  674. throw customError.unableToGetCGImageFromData
  675. }
  676. guard let expectedColorSpace = expectedCGImage.colorSpace, let observedColorSpace = observedCGImage.colorSpace else {
  677. throw customError.unableToGetColorSpaceFromCGImage
  678. }
  679. if expectedCGImage.width != observedCGImage.width || expectedCGImage.height != observedCGImage.height {
  680. throw customError.imagesHasDifferentSizes
  681. }
  682. let imageSize = CGSize(width: expectedCGImage.width, height: expectedCGImage.height)
  683. let numberOfPixels = Int(imageSize.width * imageSize.height)
  684. // Checking that our `UInt32` buffer has same number of bytes as image has.
  685. let bytesPerRow = min(expectedCGImage.bytesPerRow, observedCGImage.bytesPerRow)
  686. assert(MemoryLayout<UInt32>.stride == bytesPerRow / Int(imageSize.width))
  687. let expectedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  688. let observedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  689. let expectedPixelsRaw = UnsafeMutableRawPointer(expectedPixels)
  690. let observedPixelsRaw = UnsafeMutableRawPointer(observedPixels)
  691. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  692. guard let expectedContext = CGContext(data: expectedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  693. bitsPerComponent: expectedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  694. space: expectedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  695. expectedPixels.deallocate()
  696. observedPixels.deallocate()
  697. throw customError.unableToInitializeContext
  698. }
  699. guard let observedContext = CGContext(data: observedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  700. bitsPerComponent: observedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  701. space: observedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  702. expectedPixels.deallocate()
  703. observedPixels.deallocate()
  704. throw customError.unableToInitializeContext
  705. }
  706. expectedContext.draw(expectedCGImage, in: CGRect(origin: .zero, size: imageSize))
  707. observedContext.draw(observedCGImage, in: CGRect(origin: .zero, size: imageSize))
  708. let expectedBuffer = UnsafeBufferPointer(start: expectedPixels, count: numberOfPixels)
  709. let observedBuffer = UnsafeBufferPointer(start: observedPixels, count: numberOfPixels)
  710. var isEqual = true
  711. if tolerance == 0 {
  712. isEqual = expectedBuffer.elementsEqual(observedBuffer)
  713. } else {
  714. // Go through each pixel in turn and see if it is different
  715. var numDiffPixels = 0
  716. for pixel in 0 ..< numberOfPixels where expectedBuffer[pixel] != observedBuffer[pixel] {
  717. // If this pixel is different, increment the pixel diff count and see if we have hit our limit.
  718. numDiffPixels += 1
  719. let percentage = 100 * Float(numDiffPixels) / Float(numberOfPixels)
  720. if percentage > tolerance {
  721. isEqual = false
  722. break
  723. }
  724. }
  725. }
  726. expectedPixels.deallocate()
  727. observedPixels.deallocate()
  728. return isEqual
  729. }
  730. func stringFromTime(_ time: CMTime) -> String {
  731. let interval = Int(CMTimeGetSeconds(time))
  732. let seconds = interval % 60
  733. let minutes = (interval / 60) % 60
  734. let hours = (interval / 3600)
  735. if hours > 0 {
  736. return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
  737. } else {
  738. return String(format: "%02d:%02d", minutes, seconds)
  739. }
  740. }
  741. func colorNavigationController(_ navigationController: UINavigationController?, backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) {
  742. if #available(iOS 13.0, *) {
  743. // iOS 14, 15
  744. let appearance = UINavigationBarAppearance()
  745. appearance.titleTextAttributes = [.foregroundColor: titleColor]
  746. appearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
  747. if withoutShadow {
  748. appearance.shadowColor = .clear
  749. appearance.shadowImage = UIImage()
  750. }
  751. if let tintColor = tintColor {
  752. navigationController?.navigationBar.tintColor = tintColor
  753. }
  754. navigationController?.view.backgroundColor = backgroundColor
  755. navigationController?.navigationBar.barTintColor = titleColor
  756. navigationController?.navigationBar.standardAppearance = appearance
  757. navigationController?.navigationBar.compactAppearance = appearance
  758. navigationController?.navigationBar.scrollEdgeAppearance = appearance
  759. } else {
  760. navigationController?.navigationBar.isTranslucent = true
  761. navigationController?.navigationBar.barTintColor = backgroundColor
  762. if withoutShadow {
  763. navigationController?.navigationBar.shadowImage = UIImage()
  764. navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
  765. }
  766. let titleDict: NSDictionary = [NSAttributedString.Key.foregroundColor: titleColor]
  767. navigationController?.navigationBar.titleTextAttributes = titleDict as? [NSAttributedString.Key: Any]
  768. if let tintColor = tintColor {
  769. navigationController?.navigationBar.tintColor = tintColor
  770. }
  771. }
  772. }
  773. func getEncondingDataType(data: Data) -> String.Encoding? {
  774. if let _ = String(data: data, encoding: .utf8) {
  775. return .utf8
  776. }
  777. if let _ = String(data: data, encoding: .ascii) {
  778. return .ascii
  779. }
  780. if let _ = String(data: data, encoding: .isoLatin1) {
  781. return .isoLatin1
  782. }
  783. if let _ = String(data: data, encoding: .isoLatin2) {
  784. return .isoLatin2
  785. }
  786. if let _ = String(data: data, encoding: .windowsCP1250) {
  787. return .windowsCP1250
  788. }
  789. if let _ = String(data: data, encoding: .windowsCP1251) {
  790. return .windowsCP1251
  791. }
  792. if let _ = String(data: data, encoding: .windowsCP1252) {
  793. return .windowsCP1252
  794. }
  795. if let _ = String(data: data, encoding: .windowsCP1253) {
  796. return .windowsCP1253
  797. }
  798. if let _ = String(data: data, encoding: .windowsCP1254) {
  799. return .windowsCP1254
  800. }
  801. if let _ = String(data: data, encoding: .macOSRoman) {
  802. return .macOSRoman
  803. }
  804. if let _ = String(data: data, encoding: .japaneseEUC) {
  805. return .japaneseEUC
  806. }
  807. if let _ = String(data: data, encoding: .nextstep) {
  808. return .nextstep
  809. }
  810. if let _ = String(data: data, encoding: .nonLossyASCII) {
  811. return .nonLossyASCII
  812. }
  813. if let _ = String(data: data, encoding: .shiftJIS) {
  814. return .shiftJIS
  815. }
  816. if let _ = String(data: data, encoding: .symbol) {
  817. return .symbol
  818. }
  819. if let _ = String(data: data, encoding: .unicode) {
  820. return .unicode
  821. }
  822. if let _ = String(data: data, encoding: .utf16) {
  823. return .utf16
  824. }
  825. if let _ = String(data: data, encoding: .utf16BigEndian) {
  826. return .utf16BigEndian
  827. }
  828. if let _ = String(data: data, encoding: .utf16LittleEndian) {
  829. return .utf16LittleEndian
  830. }
  831. if let _ = String(data: data, encoding: .utf32) {
  832. return .utf32
  833. }
  834. if let _ = String(data: data, encoding: .utf32BigEndian) {
  835. return .utf32BigEndian
  836. }
  837. if let _ = String(data: data, encoding: .utf32LittleEndian) {
  838. return .utf32LittleEndian
  839. }
  840. return nil
  841. }
  842. func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
  843. return UIDevice.current.systemVersion.compare(version,
  844. options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending
  845. }
  846. func getAvatarFromIconUrl(metadata: tableMetadata) -> String? {
  847. var ownerId: String?
  848. if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  849. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  850. var found:Bool = false
  851. for item in splitIconUrl {
  852. if found {
  853. ownerId = item
  854. break
  855. }
  856. if item == "avatar" { found = true}
  857. }
  858. }
  859. return ownerId
  860. }
  861. }
  862. // MARK: -
  863. class NCViewActivityIndicator: UIView {
  864. // MARK: - View Life Cycle
  865. override init(frame: CGRect) {
  866. super.init(frame: frame)
  867. }
  868. required init?(coder: NSCoder) {
  869. fatalError("init(coder:) has not been implemented")
  870. }
  871. }