NCUtility.swift 29 KB

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