NCUtility.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. class NCUtility: NSObject {
  31. let utilityFileSystem = NCUtilityFileSystem()
  32. let global = NCGlobal.shared
  33. func isSimulatorOrTestFlight() -> Bool {
  34. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  35. return false
  36. }
  37. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  38. }
  39. func isSimulator() -> Bool {
  40. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  41. return false
  42. }
  43. return path.contains("CoreSimulator")
  44. }
  45. func isTypeFileRichDocument(_ metadata: tableMetadata) -> Bool {
  46. guard metadata.fileNameView != "." else { return false }
  47. let fileExtension = (metadata.fileNameView as NSString).pathExtension
  48. guard !fileExtension.isEmpty else { return false }
  49. guard let mimeType = UTType(tag: fileExtension.uppercased(), tagClass: .filenameExtension, conformingTo: nil)?.identifier else { return false }
  50. /// contentype
  51. if !NCCapabilities.shared.getCapabilities(account: metadata.account).capabilityRichDocumentsMimetypes.filter({ $0.contains(metadata.contentType) || $0.contains("text/plain") }).isEmpty {
  52. return true
  53. }
  54. /// mimetype
  55. if !NCCapabilities.shared.getCapabilities(account: metadata.account).capabilityRichDocumentsMimetypes.isEmpty && mimeType.components(separatedBy: ".").count > 2 {
  56. let mimeTypeArray = mimeType.components(separatedBy: ".")
  57. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  58. if !NCCapabilities.shared.getCapabilities(account: metadata.account).capabilityRichDocumentsMimetypes.filter({ $0.contains(mimeType) }).isEmpty {
  59. return true
  60. }
  61. }
  62. return false
  63. }
  64. func editorsDirectEditing(account: String, contentType: String) -> [String] {
  65. var editor: [String] = []
  66. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else { return editor }
  67. for result: tableDirectEditingEditors in results {
  68. for mimetype in result.mimetypes {
  69. if mimetype == contentType {
  70. editor.append(result.editor)
  71. }
  72. // HARDCODE
  73. // https://github.com/nextcloud/text/issues/913
  74. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  75. editor.append(result.editor)
  76. }
  77. if contentType == "text/html" {
  78. editor.append(result.editor)
  79. }
  80. }
  81. for mimetype in result.optionalMimetypes {
  82. if mimetype == contentType {
  83. editor.append(result.editor)
  84. }
  85. }
  86. }
  87. return Array(Set(editor))
  88. }
  89. func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  90. for char in permissions {
  91. if metadataPermissions.contains(char) == false {
  92. return false
  93. }
  94. }
  95. return true
  96. }
  97. func getCustomUserAgentNCText() -> String {
  98. if UIDevice.current.userInterfaceIdiom == .phone {
  99. // NOTE: Hardcoded (May 2022)
  100. // Tested for iPhone SE (1st), iOS 12 iPhone Pro Max, iOS 15.4
  101. // 605.1.15 = WebKit build version
  102. // 15E148 = frozen iOS build number according to: https://chromestatus.com/feature/4558585463832576
  103. return userAgent + " " + "AppleWebKit/605.1.15 Mobile/15E148"
  104. } else {
  105. return userAgent
  106. }
  107. }
  108. func getCustomUserAgentOnlyOffice() -> String {
  109. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  110. if UIDevice.current.userInterfaceIdiom == .pad {
  111. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  112. } else {
  113. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  114. }
  115. }
  116. func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  117. return true
  118. }
  119. func ocIdToFileId(ocId: String?) -> String? {
  120. guard let ocId = ocId else { return nil }
  121. let items = ocId.components(separatedBy: "oc")
  122. if items.count < 2 { return nil }
  123. guard let intFileId = Int(items[0]) else { return nil }
  124. return String(intFileId)
  125. }
  126. @objc func getVersionApp(withBuild: Bool = true) -> String {
  127. if let dictionary = Bundle.main.infoDictionary {
  128. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  129. if withBuild {
  130. return "\(version).\(build)"
  131. } else {
  132. return "\(version)"
  133. }
  134. }
  135. }
  136. return ""
  137. }
  138. /*
  139. Facebook's comparison algorithm:
  140. */
  141. func compare(tolerance: Float, expected: Data, observed: Data) throws -> Bool {
  142. enum customError: Error {
  143. case unableToGetUIImageFromData
  144. case unableToGetCGImageFromData
  145. case unableToGetColorSpaceFromCGImage
  146. case imagesHasDifferentSizes
  147. case unableToInitializeContext
  148. }
  149. guard let expectedUIImage = UIImage(data: expected), let observedUIImage = UIImage(data: observed) else {
  150. throw customError.unableToGetUIImageFromData
  151. }
  152. guard let expectedCGImage = expectedUIImage.cgImage, let observedCGImage = observedUIImage.cgImage else {
  153. throw customError.unableToGetCGImageFromData
  154. }
  155. guard let expectedColorSpace = expectedCGImage.colorSpace, let observedColorSpace = observedCGImage.colorSpace else {
  156. throw customError.unableToGetColorSpaceFromCGImage
  157. }
  158. if expectedCGImage.width != observedCGImage.width || expectedCGImage.height != observedCGImage.height {
  159. throw customError.imagesHasDifferentSizes
  160. }
  161. let imageSize = CGSize(width: expectedCGImage.width, height: expectedCGImage.height)
  162. let numberOfPixels = Int(imageSize.width * imageSize.height)
  163. // Checking that our `UInt32` buffer has same number of bytes as image has.
  164. let bytesPerRow = min(expectedCGImage.bytesPerRow, observedCGImage.bytesPerRow)
  165. assert(MemoryLayout<UInt32>.stride == bytesPerRow / Int(imageSize.width))
  166. let expectedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  167. let observedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  168. let expectedPixelsRaw = UnsafeMutableRawPointer(expectedPixels)
  169. let observedPixelsRaw = UnsafeMutableRawPointer(observedPixels)
  170. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  171. guard let expectedContext = CGContext(data: expectedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  172. bitsPerComponent: expectedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  173. space: expectedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  174. expectedPixels.deallocate()
  175. observedPixels.deallocate()
  176. throw customError.unableToInitializeContext
  177. }
  178. guard let observedContext = CGContext(data: observedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  179. bitsPerComponent: observedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  180. space: observedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  181. expectedPixels.deallocate()
  182. observedPixels.deallocate()
  183. throw customError.unableToInitializeContext
  184. }
  185. expectedContext.draw(expectedCGImage, in: CGRect(origin: .zero, size: imageSize))
  186. observedContext.draw(observedCGImage, in: CGRect(origin: .zero, size: imageSize))
  187. let expectedBuffer = UnsafeBufferPointer(start: expectedPixels, count: numberOfPixels)
  188. let observedBuffer = UnsafeBufferPointer(start: observedPixels, count: numberOfPixels)
  189. var isEqual = true
  190. if tolerance == 0 {
  191. isEqual = expectedBuffer.elementsEqual(observedBuffer)
  192. } else {
  193. // Go through each pixel in turn and see if it is different
  194. var numDiffPixels = 0
  195. for pixel in 0 ..< numberOfPixels where expectedBuffer[pixel] != observedBuffer[pixel] {
  196. // If this pixel is different, increment the pixel diff count and see if we have hit our limit.
  197. numDiffPixels += 1
  198. let percentage = 100 * Float(numDiffPixels) / Float(numberOfPixels)
  199. if percentage > tolerance {
  200. isEqual = false
  201. break
  202. }
  203. }
  204. }
  205. expectedPixels.deallocate()
  206. observedPixels.deallocate()
  207. return isEqual
  208. }
  209. func getLocation(latitude: Double, longitude: Double, completion: @escaping (String?) -> Void) {
  210. let geocoder = CLGeocoder()
  211. let llocation = CLLocation(latitude: latitude, longitude: longitude)
  212. if let location = NCManageDatabase.shared.getLocationFromLatAndLong(latitude: latitude, longitude: longitude) {
  213. completion(location)
  214. } else {
  215. geocoder.reverseGeocodeLocation(llocation) { placemarks, error in
  216. if error == nil, let placemark = placemarks?.first {
  217. let locationComponents: [String] = [placemark.name, placemark.locality, placemark.country]
  218. .compactMap {$0}
  219. let location = locationComponents.joined(separator: ", ")
  220. NCManageDatabase.shared.addGeocoderLocation(location, latitude: latitude, longitude: longitude)
  221. completion(location)
  222. }
  223. }
  224. }
  225. }
  226. // https://stackoverflow.com/questions/5887248/ios-app-maximum-memory-budget/19692719#19692719
  227. // https://stackoverflow.com/questions/27556807/swift-pointer-problems-with-mach-task-basic-info/27559770#27559770
  228. func getMemoryUsedAndDeviceTotalInMegabytes() -> (Float, Float) {
  229. var usedmegabytes: Float = 0
  230. let totalbytes = Float(ProcessInfo.processInfo.physicalMemory)
  231. let totalmegabytes = totalbytes / 1024.0 / 1024.0
  232. var info = mach_task_basic_info()
  233. var count = mach_msg_type_number_t(MemoryLayout<mach_task_basic_info>.size) / 4
  234. let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
  235. $0.withMemoryRebound(to: integer_t.self, capacity: 1) {
  236. task_info(
  237. mach_task_self_,
  238. task_flavor_t(MACH_TASK_BASIC_INFO),
  239. $0,
  240. &count
  241. )
  242. }
  243. }
  244. if kerr == KERN_SUCCESS {
  245. let usedbytes: Float = Float(info.resident_size)
  246. usedmegabytes = usedbytes / 1024.0 / 1024.0
  247. }
  248. return (usedmegabytes, totalmegabytes)
  249. }
  250. func removeForbiddenCharacters(_ fileName: String) -> String {
  251. var fileName = fileName
  252. for character in global.forbiddenCharacters {
  253. fileName = fileName.replacingOccurrences(of: character, with: "")
  254. }
  255. return fileName
  256. }
  257. func getHeightHeaderEmptyData(view: UIView, portraitOffset: CGFloat, landscapeOffset: CGFloat, isHeaderMenuTransferViewEnabled: Bool = false) -> CGFloat {
  258. var height: CGFloat = 0
  259. if UIDevice.current.orientation.isPortrait {
  260. height = (view.frame.height / 2) - (view.safeAreaInsets.top / 2) + portraitOffset
  261. } else {
  262. height = (view.frame.height / 2) + landscapeOffset + CGFloat(isHeaderMenuTransferViewEnabled ? 35 : 0)
  263. }
  264. return height
  265. }
  266. }