NCUtility.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  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. #if !EXTENSION
  30. import SVGKit
  31. #endif
  32. class NCUtility: NSObject {
  33. @objc static let shared: NCUtility = {
  34. let instance = NCUtility()
  35. return instance
  36. }()
  37. #if !EXTENSION
  38. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String? = nil, width: CGFloat? = nil, rewrite: Bool, account: String, id: Int? = nil, completion: @escaping (_ imageNamePath: String?, _ id: Int?) -> Void) {
  39. var fileNamePNG = ""
  40. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
  41. let iconURL = URL(string: svgUrlString) else {
  42. return completion(nil, id)
  43. }
  44. if let fileName = fileName {
  45. fileNamePNG = fileName
  46. } else {
  47. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  48. }
  49. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  50. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  51. NextcloudKit.shared.downloadContent(serverUrl: iconURL.absoluteString) { _, data, error in
  52. if error == .success && data != nil {
  53. if let image = UIImage(data: data!) {
  54. var newImage: UIImage = image
  55. if width != nil {
  56. let ratio = image.size.height / image.size.width
  57. let newSize = CGSize(width: width!, height: width! * ratio)
  58. let renderFormat = UIGraphicsImageRendererFormat.default()
  59. renderFormat.opaque = false
  60. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  61. newImage = renderer.image {
  62. _ 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. @objc func isSimulator() -> Bool {
  104. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  105. return false
  106. }
  107. return path.contains("CoreSimulator")
  108. }
  109. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  110. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  111. return false
  112. }
  113. guard let richdocumentsMimetypes = NCManageDatabase.shared.getCapabilitiesServerArray(account: metadata.account, elements: NCElementsJSON.shared.capabilitiesRichdocumentsMimetypes) else {
  114. return false
  115. }
  116. // contentype
  117. for richdocumentMimetype: String in richdocumentsMimetypes {
  118. if richdocumentMimetype.contains(metadata.contentType) || metadata.contentType == "text/plain" {
  119. return true
  120. }
  121. }
  122. // mimetype
  123. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  124. let mimeTypeArray = mimeType.components(separatedBy: ".")
  125. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  126. for richdocumentMimetype: String in richdocumentsMimetypes {
  127. if richdocumentMimetype.contains(mimeType) {
  128. return true
  129. }
  130. }
  131. }
  132. return false
  133. }
  134. @objc func isDirectEditing(account: String, contentType: String) -> [String] {
  135. var editor: [String] = []
  136. guard let results = NCManageDatabase.shared.getDirectEditingEditors(account: account) else {
  137. return editor
  138. }
  139. for result: tableDirectEditingEditors in results {
  140. for mimetype in result.mimetypes {
  141. if mimetype == contentType {
  142. editor.append(result.editor)
  143. }
  144. // HARDCODE
  145. // https://github.com/nextcloud/text/issues/913
  146. if mimetype == "text/markdown" && contentType == "text/x-markdown" {
  147. editor.append(result.editor)
  148. }
  149. if contentType == "text/html" {
  150. editor.append(result.editor)
  151. }
  152. }
  153. for mimetype in result.optionalMimetypes {
  154. if mimetype == contentType {
  155. editor.append(result.editor)
  156. }
  157. }
  158. }
  159. // HARDCODE
  160. // if editor.count == 0 {
  161. // editor.append(NCGlobal.shared.editorText)
  162. // }
  163. return Array(Set(editor))
  164. }
  165. #if !EXTENSION
  166. @objc func removeAllSettings() {
  167. URLCache.shared.memoryCapacity = 0
  168. URLCache.shared.diskCapacity = 0
  169. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  170. CCUtility.removeGroupDirectoryProviderStorage()
  171. CCUtility.removeGroupLibraryDirectory()
  172. CCUtility.removeDocumentsDirectory()
  173. CCUtility.removeTemporaryDirectory()
  174. CCUtility.createDirectoryStandard()
  175. CCUtility.deleteAllChainStore()
  176. }
  177. #endif
  178. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  179. for char in permissions {
  180. if metadataPermissions.contains(char) == false {
  181. return false
  182. }
  183. }
  184. return true
  185. }
  186. @objc func getCustomUserAgentNCText() -> String {
  187. let userAgent: String = CCUtility.getUserAgent()
  188. if UIDevice.current.userInterfaceIdiom == .phone {
  189. // NOTE: Hardcoded (May 2022)
  190. // Tested for iPhone SE (1st), iOS 12; iPhone Pro Max, iOS 15.4
  191. // 605.1.15 = WebKit build version
  192. // 15E148 = frozen iOS build number according to: https://chromestatus.com/feature/4558585463832576
  193. return userAgent + " " + "AppleWebKit/605.1.15 Mobile/15E148"
  194. } else {
  195. return userAgent
  196. }
  197. }
  198. @objc func getCustomUserAgentOnlyOffice() -> String {
  199. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  200. if UIDevice.current.userInterfaceIdiom == .pad {
  201. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  202. } else {
  203. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  204. }
  205. }
  206. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  207. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  208. return nil
  209. }
  210. let pageSize = page.bounds(for: .mediaBox)
  211. let pdfScale = width / pageSize.width
  212. // Apply if you're displaying the thumbnail on screen
  213. let scale = UIScreen.main.scale * pdfScale
  214. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  215. return page.thumbnail(of: screenSize, for: .mediaBox)
  216. }
  217. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  218. return true
  219. }
  220. @objc func ocIdToFileId(ocId: String?) -> String? {
  221. guard let ocId = ocId else { return nil }
  222. let items = ocId.components(separatedBy: "oc")
  223. if items.count < 2 { return nil }
  224. guard let intFileId = Int(items[0]) else { return nil }
  225. return String(intFileId)
  226. }
  227. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String, descriptionMessage: String) {
  228. var onlineStatus: UIImage?
  229. var statusMessage: String = ""
  230. var descriptionMessage: String = ""
  231. var messageUserDefined: String = ""
  232. if userStatus?.lowercased() == "online" {
  233. 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)
  234. messageUserDefined = NSLocalizedString("_online_", comment: "")
  235. }
  236. if userStatus?.lowercased() == "away" {
  237. 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)
  238. messageUserDefined = NSLocalizedString("_away_", comment: "")
  239. }
  240. if userStatus?.lowercased() == "dnd" {
  241. onlineStatus = UIImage(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  242. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  243. descriptionMessage = NSLocalizedString("_dnd_description_", comment: "")
  244. }
  245. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  246. onlineStatus = UIImage(named: "userStatusOffline")!.image(color: .black, size: 50)
  247. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  248. descriptionMessage = NSLocalizedString("_invisible_description_", comment: "")
  249. }
  250. if let userIcon = userIcon {
  251. statusMessage = userIcon + " "
  252. }
  253. if let userMessage = userMessage {
  254. statusMessage += userMessage
  255. }
  256. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  257. if statusMessage == "" {
  258. statusMessage = messageUserDefined
  259. }
  260. return(onlineStatus, statusMessage, descriptionMessage)
  261. }
  262. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  263. let asset = AVURLAsset(url: url)
  264. let assetIG = AVAssetImageGenerator(asset: asset)
  265. assetIG.appliesPreferredTrackTransform = true
  266. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  267. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  268. let thumbnailImageRef: CGImage
  269. do {
  270. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  271. } catch let error {
  272. print("Error: \(error)")
  273. return nil
  274. }
  275. return UIImage(cgImage: thumbnailImageRef)
  276. }
  277. func imageFromVideo(url: URL, at time: TimeInterval, completion: @escaping (UIImage?) -> Void) {
  278. DispatchQueue.global().async {
  279. let asset = AVURLAsset(url: url)
  280. let assetIG = AVAssetImageGenerator(asset: asset)
  281. assetIG.appliesPreferredTrackTransform = true
  282. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  283. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  284. let thumbnailImageRef: CGImage
  285. do {
  286. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  287. } catch let error {
  288. print("Error: \(error)")
  289. return completion(nil)
  290. }
  291. DispatchQueue.main.async {
  292. completion(UIImage(cgImage: thumbnailImageRef))
  293. }
  294. }
  295. }
  296. func createImageFrom(fileNameView: String, ocId: String, etag: String, classFile: String) {
  297. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  298. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  299. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  300. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  301. if CCUtility.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  302. if classFile != NKCommon.TypeClassFile.image.rawValue && classFile != NKCommon.TypeClassFile.video.rawValue { return }
  303. if classFile == NKCommon.TypeClassFile.image.rawValue {
  304. originalImage = UIImage(contentsOfFile: fileNamePath)
  305. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview))
  306. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon))
  307. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  308. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  309. } else if classFile == NKCommon.TypeClassFile.video.rawValue {
  310. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  311. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  312. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  313. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  314. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  315. }
  316. }
  317. @objc func getVersionApp(withBuild: Bool = true) -> String {
  318. if let dictionary = Bundle.main.infoDictionary {
  319. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  320. if withBuild {
  321. return "\(version).\(build)"
  322. } else {
  323. return "\(version)"
  324. }
  325. }
  326. }
  327. return ""
  328. }
  329. func loadImage(named imageName: String, color: UIColor = UIColor.systemGray, size: CGFloat = 50, symbolConfiguration: Any? = nil) -> UIImage {
  330. var image: UIImage?
  331. // see https://stackoverflow.com/questions/71764255
  332. let sfSymbolName = imageName.replacingOccurrences(of: "_", with: ".")
  333. if let symbolConfiguration = symbolConfiguration {
  334. image = UIImage(systemName: sfSymbolName, withConfiguration: symbolConfiguration as? UIImage.Configuration)?.withTintColor(color, renderingMode: .alwaysOriginal)
  335. } else {
  336. image = UIImage(systemName: sfSymbolName)?.withTintColor(color, renderingMode: .alwaysOriginal)
  337. }
  338. if image == nil {
  339. image = UIImage(named: imageName)?.image(color: color, size: size)
  340. }
  341. if let image = image {
  342. return image
  343. }
  344. return UIImage(named: "file")!.image(color: color, size: size)
  345. }
  346. @objc func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage {
  347. let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png"
  348. let localFilePath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  349. if let localImage = UIImage(contentsOfFile: localFilePath) {
  350. return createAvatar(image: localImage, size: 30)
  351. } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  352. return loadedAvatar
  353. } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) {
  354. return avatarImg
  355. } else { return getDefaultUserIcon() }
  356. }
  357. func getDefaultUserIcon() -> UIImage {
  358. let config = UIImage.SymbolConfiguration(pointSize: 30)
  359. return NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config)
  360. }
  361. @objc func createAvatar(image: UIImage, size: CGFloat) -> UIImage {
  362. var avatarImage = image
  363. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  364. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  365. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  366. avatarImage.draw(in: rect)
  367. avatarImage = UIGraphicsGetImageFromCurrentImageContext() ?? image
  368. UIGraphicsEndImageContext()
  369. return avatarImage
  370. }
  371. func createAvatar(displayName: String, size: CGFloat) -> UIImage? {
  372. guard let initials = displayName.uppercaseInitials else {
  373. return nil
  374. }
  375. let userColor = NCGlobal.shared.usernameToColor(displayName)
  376. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  377. var avatarImage: UIImage?
  378. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  379. let context = UIGraphicsGetCurrentContext()
  380. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  381. context?.setFillColor(userColor)
  382. context?.fill(rect)
  383. let textStyle = NSMutableParagraphStyle()
  384. textStyle.alignment = NSTextAlignment.center
  385. let lineHeight = UIFont.systemFont(ofSize: UIFont.systemFontSize).pointSize
  386. NSString(string: initials)
  387. .draw(
  388. in: CGRect(x: 0, y: (size - lineHeight) / 2, width: size, height: lineHeight),
  389. withAttributes: [NSAttributedString.Key.paragraphStyle: textStyle])
  390. avatarImage = UIGraphicsGetImageFromCurrentImageContext()
  391. UIGraphicsEndImageContext()
  392. return avatarImage
  393. }
  394. /*
  395. Facebook's comparison algorithm:
  396. */
  397. func compare(tolerance: Float, expected: Data, observed: Data) throws -> Bool {
  398. enum customError: Error {
  399. case unableToGetUIImageFromData
  400. case unableToGetCGImageFromData
  401. case unableToGetColorSpaceFromCGImage
  402. case imagesHasDifferentSizes
  403. case unableToInitializeContext
  404. }
  405. guard let expectedUIImage = UIImage(data: expected), let observedUIImage = UIImage(data: observed) else {
  406. throw customError.unableToGetUIImageFromData
  407. }
  408. guard let expectedCGImage = expectedUIImage.cgImage, let observedCGImage = observedUIImage.cgImage else {
  409. throw customError.unableToGetCGImageFromData
  410. }
  411. guard let expectedColorSpace = expectedCGImage.colorSpace, let observedColorSpace = observedCGImage.colorSpace else {
  412. throw customError.unableToGetColorSpaceFromCGImage
  413. }
  414. if expectedCGImage.width != observedCGImage.width || expectedCGImage.height != observedCGImage.height {
  415. throw customError.imagesHasDifferentSizes
  416. }
  417. let imageSize = CGSize(width: expectedCGImage.width, height: expectedCGImage.height)
  418. let numberOfPixels = Int(imageSize.width * imageSize.height)
  419. // Checking that our `UInt32` buffer has same number of bytes as image has.
  420. let bytesPerRow = min(expectedCGImage.bytesPerRow, observedCGImage.bytesPerRow)
  421. assert(MemoryLayout<UInt32>.stride == bytesPerRow / Int(imageSize.width))
  422. let expectedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  423. let observedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  424. let expectedPixelsRaw = UnsafeMutableRawPointer(expectedPixels)
  425. let observedPixelsRaw = UnsafeMutableRawPointer(observedPixels)
  426. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  427. guard let expectedContext = CGContext(data: expectedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  428. bitsPerComponent: expectedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  429. space: expectedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  430. expectedPixels.deallocate()
  431. observedPixels.deallocate()
  432. throw customError.unableToInitializeContext
  433. }
  434. guard let observedContext = CGContext(data: observedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  435. bitsPerComponent: observedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  436. space: observedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  437. expectedPixels.deallocate()
  438. observedPixels.deallocate()
  439. throw customError.unableToInitializeContext
  440. }
  441. expectedContext.draw(expectedCGImage, in: CGRect(origin: .zero, size: imageSize))
  442. observedContext.draw(observedCGImage, in: CGRect(origin: .zero, size: imageSize))
  443. let expectedBuffer = UnsafeBufferPointer(start: expectedPixels, count: numberOfPixels)
  444. let observedBuffer = UnsafeBufferPointer(start: observedPixels, count: numberOfPixels)
  445. var isEqual = true
  446. if tolerance == 0 {
  447. isEqual = expectedBuffer.elementsEqual(observedBuffer)
  448. } else {
  449. // Go through each pixel in turn and see if it is different
  450. var numDiffPixels = 0
  451. for pixel in 0 ..< numberOfPixels where expectedBuffer[pixel] != observedBuffer[pixel] {
  452. // If this pixel is different, increment the pixel diff count and see if we have hit our limit.
  453. numDiffPixels += 1
  454. let percentage = 100 * Float(numDiffPixels) / Float(numberOfPixels)
  455. if percentage > tolerance {
  456. isEqual = false
  457. break
  458. }
  459. }
  460. }
  461. expectedPixels.deallocate()
  462. observedPixels.deallocate()
  463. return isEqual
  464. }
  465. func stringFromTime(_ time: CMTime) -> String {
  466. let interval = Int(CMTimeGetSeconds(time))
  467. let seconds = interval % 60
  468. let minutes = (interval / 60) % 60
  469. let hours = (interval / 3600)
  470. if hours > 0 {
  471. return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
  472. } else {
  473. return String(format: "%02d:%02d", minutes, seconds)
  474. }
  475. }
  476. func colorNavigationController(_ navigationController: UINavigationController?, backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) {
  477. let appearance = UINavigationBarAppearance()
  478. appearance.titleTextAttributes = [.foregroundColor: titleColor]
  479. appearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
  480. if withoutShadow {
  481. appearance.shadowColor = .clear
  482. appearance.shadowImage = UIImage()
  483. }
  484. if let tintColor = tintColor {
  485. navigationController?.navigationBar.tintColor = tintColor
  486. }
  487. navigationController?.view.backgroundColor = backgroundColor
  488. navigationController?.navigationBar.barTintColor = titleColor
  489. navigationController?.navigationBar.standardAppearance = appearance
  490. navigationController?.navigationBar.compactAppearance = appearance
  491. navigationController?.navigationBar.scrollEdgeAppearance = appearance
  492. }
  493. func getEncondingDataType(data: Data) -> String.Encoding? {
  494. if let _ = String(data: data, encoding: .utf8) {
  495. return .utf8
  496. }
  497. if let _ = String(data: data, encoding: .ascii) {
  498. return .ascii
  499. }
  500. if let _ = String(data: data, encoding: .isoLatin1) {
  501. return .isoLatin1
  502. }
  503. if let _ = String(data: data, encoding: .isoLatin2) {
  504. return .isoLatin2
  505. }
  506. if let _ = String(data: data, encoding: .windowsCP1250) {
  507. return .windowsCP1250
  508. }
  509. if let _ = String(data: data, encoding: .windowsCP1251) {
  510. return .windowsCP1251
  511. }
  512. if let _ = String(data: data, encoding: .windowsCP1252) {
  513. return .windowsCP1252
  514. }
  515. if let _ = String(data: data, encoding: .windowsCP1253) {
  516. return .windowsCP1253
  517. }
  518. if let _ = String(data: data, encoding: .windowsCP1254) {
  519. return .windowsCP1254
  520. }
  521. if let _ = String(data: data, encoding: .macOSRoman) {
  522. return .macOSRoman
  523. }
  524. if let _ = String(data: data, encoding: .japaneseEUC) {
  525. return .japaneseEUC
  526. }
  527. if let _ = String(data: data, encoding: .nextstep) {
  528. return .nextstep
  529. }
  530. if let _ = String(data: data, encoding: .nonLossyASCII) {
  531. return .nonLossyASCII
  532. }
  533. if let _ = String(data: data, encoding: .shiftJIS) {
  534. return .shiftJIS
  535. }
  536. if let _ = String(data: data, encoding: .symbol) {
  537. return .symbol
  538. }
  539. if let _ = String(data: data, encoding: .unicode) {
  540. return .unicode
  541. }
  542. if let _ = String(data: data, encoding: .utf16) {
  543. return .utf16
  544. }
  545. if let _ = String(data: data, encoding: .utf16BigEndian) {
  546. return .utf16BigEndian
  547. }
  548. if let _ = String(data: data, encoding: .utf16LittleEndian) {
  549. return .utf16LittleEndian
  550. }
  551. if let _ = String(data: data, encoding: .utf32) {
  552. return .utf32
  553. }
  554. if let _ = String(data: data, encoding: .utf32BigEndian) {
  555. return .utf32BigEndian
  556. }
  557. if let _ = String(data: data, encoding: .utf32LittleEndian) {
  558. return .utf32LittleEndian
  559. }
  560. return nil
  561. }
  562. func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
  563. return UIDevice.current.systemVersion.compare(version,
  564. options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending
  565. }
  566. func getAvatarFromIconUrl(metadata: tableMetadata) -> String? {
  567. var ownerId: String?
  568. if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  569. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  570. var found:Bool = false
  571. for item in splitIconUrl {
  572. if found {
  573. ownerId = item
  574. break
  575. }
  576. if item == "avatar" { found = true}
  577. }
  578. }
  579. return ownerId
  580. }
  581. // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
  582. func isValidEmail(_ email: String) -> Bool {
  583. let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
  584. let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
  585. return emailPred.evaluate(with: email)
  586. }
  587. func createFilePreviewImage(ocId: String, etag: String, fileNameView: String, classFile: String, status: Int, createPreviewMedia: Bool) -> UIImage? {
  588. var imagePreview: UIImage?
  589. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  590. let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  591. if FileManager().fileExists(atPath: iconImagePath) {
  592. imagePreview = UIImage(contentsOfFile: iconImagePath)
  593. } else if !createPreviewMedia {
  594. return nil
  595. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.TypeClassFile.image.rawValue && FileManager().fileExists(atPath: filePath) {
  596. 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) {
  597. do {
  598. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  599. imagePreview = image
  600. } catch { }
  601. }
  602. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.TypeClassFile.video.rawValue && FileManager().fileExists(atPath: filePath) {
  603. 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) {
  604. do {
  605. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  606. imagePreview = image
  607. } catch { }
  608. }
  609. }
  610. return imagePreview
  611. }
  612. func isDirectoryE2EE(serverUrl: String, userBase: NCUserBaseUrl) -> Bool {
  613. return isDirectoryE2EE(serverUrl: serverUrl, account: userBase.account, urlBase: userBase.urlBase, userId: userBase.userId)
  614. }
  615. func isDirectoryE2EE(file: NKFile) -> Bool {
  616. return isDirectoryE2EE(serverUrl: file.serverUrl, account: file.account, urlBase: file.urlBase, userId: file.userId)
  617. }
  618. @objc func isDirectoryE2EE(serverUrl: String, account: String, urlBase: String, userId: String) -> Bool {
  619. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: urlBase, userId: userId) || serverUrl == ".." { return false }
  620. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)) {
  621. return directory.e2eEncrypted
  622. }
  623. return false
  624. }
  625. func createViewImageAndText(image: UIImage, title: String? = nil) -> UIView {
  626. let imageView = UIImageView()
  627. let titleView = UIView()
  628. let label = UILabel()
  629. if let title = title {
  630. label.text = title + " "
  631. } else {
  632. label.text = " "
  633. }
  634. label.sizeToFit()
  635. label.center = titleView.center
  636. label.textAlignment = NSTextAlignment.center
  637. imageView.image = image
  638. let imageAspect = (imageView.image?.size.width ?? 0) / (imageView.image?.size.height ?? 0)
  639. let imageX = label.frame.origin.x - label.frame.size.height * imageAspect
  640. let imageY = label.frame.origin.y
  641. let imageWidth = label.frame.size.height * imageAspect
  642. let imageHeight = label.frame.size.height
  643. if title != nil {
  644. imageView.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
  645. titleView.addSubview(label)
  646. } else {
  647. imageView.frame = CGRect(x: imageX / 2, y: imageY, width: imageWidth, height: imageHeight)
  648. }
  649. imageView.contentMode = UIView.ContentMode.scaleAspectFit
  650. titleView.addSubview(imageView)
  651. titleView.sizeToFit()
  652. return titleView
  653. }
  654. }