NCUtility.swift 44 KB

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