NCUtility.swift 45 KB

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