NCUtility.swift 42 KB

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