NCUtility.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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 NextcloudKit
  25. import PDFKit
  26. import Accelerate
  27. import CoreMedia
  28. import Photos
  29. import Alamofire
  30. #if !EXTENSION
  31. import SVGKit
  32. #endif
  33. class NCUtility: NSObject {
  34. let utilityFileSystem = NCUtilityFileSystem()
  35. #if !EXTENSION
  36. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String? = nil, width: CGFloat? = nil, rewrite: Bool, account: String, id: Int? = nil, completion: @escaping (_ imageNamePath: String?, _ id: Int?) -> Void) {
  37. var fileNamePNG = ""
  38. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
  39. let iconURL = URL(string: svgUrlString) else {
  40. return completion(nil, id)
  41. }
  42. if let fileName = fileName {
  43. fileNamePNG = fileName
  44. } else {
  45. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  46. }
  47. let imageNamePath = utilityFileSystem.directoryUserData + "/" + fileNamePNG
  48. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  49. NextcloudKit.shared.downloadContent(serverUrl: iconURL.absoluteString) { _, data, error in
  50. if error == .success && data != nil {
  51. if let image = UIImage(data: data!) {
  52. var newImage: UIImage = image
  53. if width != nil {
  54. let ratio = image.size.height / image.size.width
  55. let newSize = CGSize(width: width!, height: width! * ratio)
  56. let renderFormat = UIGraphicsImageRendererFormat.default()
  57. renderFormat.opaque = false
  58. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  59. newImage = renderer.image { _ in
  60. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  61. }
  62. }
  63. guard let pngImageData = newImage.pngData() else {
  64. return completion(nil, id)
  65. }
  66. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  67. return completion(imageNamePath, id)
  68. } else {
  69. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  70. return completion(nil, id)
  71. }
  72. if width != nil {
  73. let scale = svgImage.size.height / svgImage.size.width
  74. svgImage.size = CGSize(width: width!, height: width! * scale)
  75. }
  76. guard let image: UIImage = svgImage.uiImage else {
  77. return completion(nil, id)
  78. }
  79. guard let pngImageData = image.pngData() else {
  80. return completion(nil, id)
  81. }
  82. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  83. return completion(imageNamePath, id)
  84. }
  85. } else {
  86. return completion(nil, id)
  87. }
  88. }
  89. } else {
  90. return completion(imageNamePath, id)
  91. }
  92. }
  93. #endif
  94. @objc func isSimulatorOrTestFlight() -> Bool {
  95. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  96. return false
  97. }
  98. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  99. }
  100. func isSimulator() -> Bool {
  101. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  102. return false
  103. }
  104. return path.contains("CoreSimulator")
  105. }
  106. func isRichDocument(_ metadata: tableMetadata) -> Bool {
  107. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  108. return false
  109. }
  110. // contentype
  111. for richdocumentMimetype: String in NCGlobal.shared.capabilityRichdocumentsMimetypes {
  112. if richdocumentMimetype.contains(metadata.contentType) || metadata.contentType == "text/plain" {
  113. return true
  114. }
  115. }
  116. // mimetype
  117. if !NCGlobal.shared.capabilityRichdocumentsMimetypes.isEmpty && mimeType.components(separatedBy: ".").count > 2 {
  118. let mimeTypeArray = mimeType.components(separatedBy: ".")
  119. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  120. for richdocumentMimetype: String in NCGlobal.shared.capabilityRichdocumentsMimetypes {
  121. if richdocumentMimetype.contains(mimeType) {
  122. return true
  123. }
  124. }
  125. }
  126. return false
  127. }
  128. func isDirectEditing(account: String, contentType: String) -> [String] {
  129. var editor: [String] = []
  130. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else {
  131. return editor
  132. }
  133. for result: tableDirectEditingEditors in results {
  134. for mimetype in result.mimetypes {
  135. if mimetype == contentType {
  136. editor.append(result.editor)
  137. }
  138. // HARDCODE
  139. // https://github.com/nextcloud/text/issues/913
  140. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  141. editor.append(result.editor)
  142. }
  143. if contentType == "text/html" {
  144. editor.append(result.editor)
  145. }
  146. }
  147. for mimetype in result.optionalMimetypes {
  148. if mimetype == contentType {
  149. editor.append(result.editor)
  150. }
  151. }
  152. }
  153. return Array(Set(editor))
  154. }
  155. #if !EXTENSION
  156. @objc func removeAllSettings() {
  157. URLCache.shared.memoryCapacity = 0
  158. URLCache.shared.diskCapacity = 0
  159. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  160. utilityFileSystem.removeGroupDirectoryProviderStorage()
  161. utilityFileSystem.removeGroupLibraryDirectory()
  162. utilityFileSystem.removeDocumentsDirectory()
  163. utilityFileSystem.removeTemporaryDirectory()
  164. utilityFileSystem.createDirectoryStandard()
  165. NCKeychain().removeAll()
  166. }
  167. #endif
  168. func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  169. for char in permissions {
  170. if metadataPermissions.contains(char) == false {
  171. return false
  172. }
  173. }
  174. return true
  175. }
  176. func getCustomUserAgentNCText() -> String {
  177. if UIDevice.current.userInterfaceIdiom == .phone {
  178. // NOTE: Hardcoded (May 2022)
  179. // Tested for iPhone SE (1st), iOS 12 iPhone Pro Max, iOS 15.4
  180. // 605.1.15 = WebKit build version
  181. // 15E148 = frozen iOS build number according to: https://chromestatus.com/feature/4558585463832576
  182. return userAgent + " " + "AppleWebKit/605.1.15 Mobile/15E148"
  183. } else {
  184. return userAgent
  185. }
  186. }
  187. func getCustomUserAgentOnlyOffice() -> String {
  188. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  189. if UIDevice.current.userInterfaceIdiom == .pad {
  190. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  191. } else {
  192. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  193. }
  194. }
  195. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  196. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  197. return nil
  198. }
  199. let pageSize = page.bounds(for: .mediaBox)
  200. let pdfScale = width / pageSize.width
  201. // Apply if you're displaying the thumbnail on screen
  202. let scale = UIScreen.main.scale * pdfScale
  203. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  204. return page.thumbnail(of: screenSize, for: .mediaBox)
  205. }
  206. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  207. return true
  208. }
  209. @objc func ocIdToFileId(ocId: String?) -> String? {
  210. guard let ocId = ocId else { return nil }
  211. let items = ocId.components(separatedBy: "oc")
  212. if items.count < 2 { return nil }
  213. guard let intFileId = Int(items[0]) else { return nil }
  214. return String(intFileId)
  215. }
  216. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String, descriptionMessage: String) {
  217. var onlineStatus: UIImage?
  218. var statusMessage: String = ""
  219. var descriptionMessage: String = ""
  220. var messageUserDefined: String = ""
  221. if userStatus?.lowercased() == "online" {
  222. 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)
  223. messageUserDefined = NSLocalizedString("_online_", comment: "")
  224. }
  225. if userStatus?.lowercased() == "away" {
  226. 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)
  227. messageUserDefined = NSLocalizedString("_away_", comment: "")
  228. }
  229. if userStatus?.lowercased() == "dnd" {
  230. onlineStatus = UIImage(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  231. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  232. descriptionMessage = NSLocalizedString("_dnd_description_", comment: "")
  233. }
  234. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  235. onlineStatus = UIImage(named: "userStatusOffline")!.image(color: .black, size: 50)
  236. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  237. descriptionMessage = NSLocalizedString("_invisible_description_", comment: "")
  238. }
  239. if let userIcon = userIcon {
  240. statusMessage = userIcon + " "
  241. }
  242. if let userMessage = userMessage {
  243. statusMessage += userMessage
  244. }
  245. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  246. if statusMessage.isEmpty {
  247. statusMessage = messageUserDefined
  248. }
  249. return(onlineStatus, statusMessage, descriptionMessage)
  250. }
  251. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  252. let asset = AVURLAsset(url: url)
  253. let assetIG = AVAssetImageGenerator(asset: asset)
  254. assetIG.appliesPreferredTrackTransform = true
  255. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  256. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  257. let thumbnailImageRef: CGImage
  258. do {
  259. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  260. } catch let error {
  261. print("Error: \(error)")
  262. return nil
  263. }
  264. return UIImage(cgImage: thumbnailImageRef)
  265. }
  266. func imageFromVideo(url: URL, at time: TimeInterval, completion: @escaping (UIImage?) -> Void) {
  267. DispatchQueue.global().async {
  268. let asset = AVURLAsset(url: url)
  269. let assetIG = AVAssetImageGenerator(asset: asset)
  270. assetIG.appliesPreferredTrackTransform = true
  271. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  272. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  273. let thumbnailImageRef: CGImage
  274. do {
  275. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  276. } catch let error {
  277. print("Error: \(error)")
  278. return completion(nil)
  279. }
  280. DispatchQueue.main.async {
  281. completion(UIImage(cgImage: thumbnailImageRef))
  282. }
  283. }
  284. }
  285. func createImageFrom(fileNameView: String, ocId: String, etag: String, classFile: String) {
  286. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  287. let fileNamePath = utilityFileSystem.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)
  288. let fileNamePathPreview = utilityFileSystem.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)
  289. let fileNamePathIcon = utilityFileSystem.getDirectoryProviderStorageIconOcId(ocId, etag: etag)
  290. if utilityFileSystem.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  291. if classFile != NKCommon.TypeClassFile.image.rawValue && classFile != NKCommon.TypeClassFile.video.rawValue { return }
  292. if classFile == NKCommon.TypeClassFile.image.rawValue {
  293. originalImage = UIImage(contentsOfFile: fileNamePath)
  294. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview))
  295. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon))
  296. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  297. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  298. } else if classFile == NKCommon.TypeClassFile.video.rawValue {
  299. let videoPath = NSTemporaryDirectory() + "tempvideo.mp4"
  300. utilityFileSystem.linkItem(atPath: fileNamePath, toPath: videoPath)
  301. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  302. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  303. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  304. }
  305. }
  306. @objc func getVersionApp(withBuild: Bool = true) -> String {
  307. if let dictionary = Bundle.main.infoDictionary {
  308. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  309. if withBuild {
  310. return "\(version).\(build)"
  311. } else {
  312. return "\(version)"
  313. }
  314. }
  315. }
  316. return ""
  317. }
  318. func loadImage(named imageName: String, color: UIColor = UIColor.systemGray, size: CGFloat = 50, symbolConfiguration: Any? = nil, renderingMode: UIImage.RenderingMode = .alwaysOriginal) -> UIImage {
  319. var image: UIImage?
  320. // see https://stackoverflow.com/questions/71764255
  321. let sfSymbolName = imageName.replacingOccurrences(of: "_", with: ".")
  322. if let symbolConfiguration {
  323. image = UIImage(systemName: sfSymbolName, withConfiguration: symbolConfiguration as? UIImage.Configuration)?.withTintColor(color, renderingMode: renderingMode)
  324. } else {
  325. image = UIImage(systemName: sfSymbolName)?.withTintColor(color, renderingMode: renderingMode)
  326. }
  327. if image == nil {
  328. image = UIImage(named: imageName)?.image(color: color, size: size)
  329. }
  330. if let image {
  331. return image
  332. }
  333. return UIImage(named: "file")!.image(color: color, size: size)
  334. }
  335. @objc func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage {
  336. let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png"
  337. let localFilePath = utilityFileSystem.directoryUserData + "/" + fileName
  338. if var localImage = UIImage(contentsOfFile: localFilePath) {
  339. let rect = CGRect(x: 0, y: 0, width: 30, height: 30)
  340. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  341. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  342. localImage.draw(in: rect)
  343. localImage = UIGraphicsGetImageFromCurrentImageContext() ?? localImage
  344. UIGraphicsEndImageContext()
  345. return localImage
  346. } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  347. return loadedAvatar
  348. } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) {
  349. return avatarImg
  350. } else {
  351. let config = UIImage.SymbolConfiguration(pointSize: 30)
  352. return loadImage(named: "person.crop.circle", symbolConfiguration: config)
  353. }
  354. }
  355. func createAvatar(displayName: String, size: CGFloat) -> UIImage? {
  356. guard let initials = displayName.uppercaseInitials else {
  357. return nil
  358. }
  359. let userColor = NCGlobal.shared.usernameToColor(displayName)
  360. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  361. var avatarImage: UIImage?
  362. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  363. let context = UIGraphicsGetCurrentContext()
  364. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  365. context?.setFillColor(userColor)
  366. context?.fill(rect)
  367. let textStyle = NSMutableParagraphStyle()
  368. textStyle.alignment = NSTextAlignment.center
  369. let lineHeight = UIFont.systemFont(ofSize: UIFont.systemFontSize).pointSize
  370. NSString(string: initials)
  371. .draw(
  372. in: CGRect(x: 0, y: (size - lineHeight) / 2, width: size, height: lineHeight),
  373. withAttributes: [NSAttributedString.Key.paragraphStyle: textStyle])
  374. avatarImage = UIGraphicsGetImageFromCurrentImageContext()
  375. UIGraphicsEndImageContext()
  376. return avatarImage
  377. }
  378. /*
  379. Facebook's comparison algorithm:
  380. */
  381. func compare(tolerance: Float, expected: Data, observed: Data) throws -> Bool {
  382. enum customError: Error {
  383. case unableToGetUIImageFromData
  384. case unableToGetCGImageFromData
  385. case unableToGetColorSpaceFromCGImage
  386. case imagesHasDifferentSizes
  387. case unableToInitializeContext
  388. }
  389. guard let expectedUIImage = UIImage(data: expected), let observedUIImage = UIImage(data: observed) else {
  390. throw customError.unableToGetUIImageFromData
  391. }
  392. guard let expectedCGImage = expectedUIImage.cgImage, let observedCGImage = observedUIImage.cgImage else {
  393. throw customError.unableToGetCGImageFromData
  394. }
  395. guard let expectedColorSpace = expectedCGImage.colorSpace, let observedColorSpace = observedCGImage.colorSpace else {
  396. throw customError.unableToGetColorSpaceFromCGImage
  397. }
  398. if expectedCGImage.width != observedCGImage.width || expectedCGImage.height != observedCGImage.height {
  399. throw customError.imagesHasDifferentSizes
  400. }
  401. let imageSize = CGSize(width: expectedCGImage.width, height: expectedCGImage.height)
  402. let numberOfPixels = Int(imageSize.width * imageSize.height)
  403. // Checking that our `UInt32` buffer has same number of bytes as image has.
  404. let bytesPerRow = min(expectedCGImage.bytesPerRow, observedCGImage.bytesPerRow)
  405. assert(MemoryLayout<UInt32>.stride == bytesPerRow / Int(imageSize.width))
  406. let expectedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  407. let observedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  408. let expectedPixelsRaw = UnsafeMutableRawPointer(expectedPixels)
  409. let observedPixelsRaw = UnsafeMutableRawPointer(observedPixels)
  410. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  411. guard let expectedContext = CGContext(data: expectedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  412. bitsPerComponent: expectedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  413. space: expectedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  414. expectedPixels.deallocate()
  415. observedPixels.deallocate()
  416. throw customError.unableToInitializeContext
  417. }
  418. guard let observedContext = CGContext(data: observedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  419. bitsPerComponent: observedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  420. space: observedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  421. expectedPixels.deallocate()
  422. observedPixels.deallocate()
  423. throw customError.unableToInitializeContext
  424. }
  425. expectedContext.draw(expectedCGImage, in: CGRect(origin: .zero, size: imageSize))
  426. observedContext.draw(observedCGImage, in: CGRect(origin: .zero, size: imageSize))
  427. let expectedBuffer = UnsafeBufferPointer(start: expectedPixels, count: numberOfPixels)
  428. let observedBuffer = UnsafeBufferPointer(start: observedPixels, count: numberOfPixels)
  429. var isEqual = true
  430. if tolerance == 0 {
  431. isEqual = expectedBuffer.elementsEqual(observedBuffer)
  432. } else {
  433. // Go through each pixel in turn and see if it is different
  434. var numDiffPixels = 0
  435. for pixel in 0 ..< numberOfPixels where expectedBuffer[pixel] != observedBuffer[pixel] {
  436. // If this pixel is different, increment the pixel diff count and see if we have hit our limit.
  437. numDiffPixels += 1
  438. let percentage = 100 * Float(numDiffPixels) / Float(numberOfPixels)
  439. if percentage > tolerance {
  440. isEqual = false
  441. break
  442. }
  443. }
  444. }
  445. expectedPixels.deallocate()
  446. observedPixels.deallocate()
  447. return isEqual
  448. }
  449. func createFilePreviewImage(ocId: String, etag: String, fileNameView: String, classFile: String, status: Int, createPreviewMedia: Bool) -> UIImage? {
  450. var imagePreview: UIImage?
  451. let filePath = utilityFileSystem.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)
  452. let iconImagePath = utilityFileSystem.getDirectoryProviderStorageIconOcId(ocId, etag: etag)
  453. if FileManager().fileExists(atPath: iconImagePath) {
  454. imagePreview = UIImage(contentsOfFile: iconImagePath)
  455. } else if !createPreviewMedia {
  456. return nil
  457. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.TypeClassFile.image.rawValue && FileManager().fileExists(atPath: filePath) {
  458. if let image = UIImage(contentsOfFile: filePath), let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)), let data = image.jpegData(compressionQuality: 0.5) {
  459. do {
  460. try data.write(to: URL(fileURLWithPath: iconImagePath), options: .atomic)
  461. imagePreview = image
  462. } catch { }
  463. }
  464. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.TypeClassFile.video.rawValue && FileManager().fileExists(atPath: filePath) {
  465. if let image = imageFromVideo(url: URL(fileURLWithPath: filePath), at: 0), let image = image.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon)), let data = image.jpegData(compressionQuality: 0.5) {
  466. do {
  467. try data.write(to: URL(fileURLWithPath: iconImagePath), options: .atomic)
  468. imagePreview = image
  469. } catch { }
  470. }
  471. }
  472. return imagePreview
  473. }
  474. func getLocation(latitude: Double, longitude: Double, completion: @escaping (String?) -> Void) {
  475. let geocoder = CLGeocoder()
  476. let llocation = CLLocation(latitude: latitude, longitude: longitude)
  477. if let location = NCManageDatabase.shared.getLocationFromLatAndLong(latitude: latitude, longitude: longitude) {
  478. completion(location)
  479. } else {
  480. geocoder.reverseGeocodeLocation(llocation) { placemarks, error in
  481. if error == nil, let placemark = placemarks?.first {
  482. let locationComponents: [String] = [placemark.name, placemark.locality, placemark.country]
  483. .compactMap {$0}
  484. let location = locationComponents.joined(separator: ", ")
  485. NCManageDatabase.shared.addGeocoderLocation(location, latitude: latitude, longitude: longitude)
  486. completion(location)
  487. }
  488. }
  489. }
  490. }
  491. // https://stackoverflow.com/questions/5887248/ios-app-maximum-memory-budget/19692719#19692719
  492. // https://stackoverflow.com/questions/27556807/swift-pointer-problems-with-mach-task-basic-info/27559770#27559770
  493. func getMemoryUsedAndDeviceTotalInMegabytes() -> (Float, Float) {
  494. var usedmegabytes: Float = 0
  495. let totalbytes = Float(ProcessInfo.processInfo.physicalMemory)
  496. let totalmegabytes = totalbytes / 1024.0 / 1024.0
  497. var info = mach_task_basic_info()
  498. var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
  499. let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
  500. $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
  501. task_info(
  502. mach_task_self_,
  503. task_flavor_t(MACH_TASK_BASIC_INFO),
  504. $0,
  505. &count
  506. )
  507. }
  508. }
  509. if kerr == KERN_SUCCESS {
  510. let usedbytes: Float = Float(info.resident_size)
  511. usedmegabytes = usedbytes / 1024.0 / 1024.0
  512. }
  513. return (usedmegabytes, totalmegabytes)
  514. }
  515. func removeForbiddenCharacters(_ fileName: String) -> String {
  516. var fileName = fileName
  517. let arrayForbiddenCharacters = ["/"]
  518. for character in arrayForbiddenCharacters {
  519. fileName = fileName.replacingOccurrences(of: character, with: "")
  520. }
  521. return fileName
  522. }
  523. func dateDiff(_ date: Date?) -> String {
  524. guard let date else { return "" }
  525. let today = Date()
  526. var ti = date.timeIntervalSince(today)
  527. ti = ti * -1
  528. if ti < 60 {
  529. return NSLocalizedString("_less_a_minute_", comment: "")
  530. } else if ti < 3600 {
  531. let diff = Int(round(ti / 60))
  532. if diff == 1 {
  533. return NSLocalizedString("_a_minute_ago_", comment: "")
  534. } else {
  535. return String.localizedStringWithFormat(NSLocalizedString("_minutes_ago_", comment: ""), diff)
  536. }
  537. } else if ti < 86400 {
  538. let diff = Int(round(ti / 60))
  539. if diff == 1 {
  540. return NSLocalizedString("_an_hour_ago_", comment: "")
  541. } else {
  542. return String.localizedStringWithFormat(NSLocalizedString("_hours_ago_", comment: ""), diff)
  543. }
  544. } else if ti < 86400 * 30 {
  545. let diff = Int(round(ti / 60 / 60 / 24))
  546. if diff == 1 {
  547. return NSLocalizedString("_a_day_ago_", comment: "")
  548. } else {
  549. return String.localizedStringWithFormat(NSLocalizedString("_days_ago_", comment: ""), diff)
  550. }
  551. } else {
  552. let formatter = DateFormatter()
  553. formatter.formatterBehavior = .behavior10_4
  554. formatter.dateStyle = .medium
  555. return formatter.string(from: date)
  556. }
  557. }
  558. }