NCUtility.swift 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. //
  2. // NCUtility.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 25/06/18.
  6. // Copyright © 2018 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import UIKit
  24. import SVGKit
  25. import NextcloudKit
  26. import PDFKit
  27. import Accelerate
  28. import CoreMedia
  29. import Photos
  30. import JGProgressHUD
  31. #if !EXTENSION
  32. import KTVHTTPCache
  33. #endif
  34. class NCUtility: NSObject {
  35. @objc static let shared: NCUtility = {
  36. let instance = NCUtility()
  37. return instance
  38. }()
  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 = CCUtility.getDirectoryUserData() + "/" + 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 {
  63. _ in
  64. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  65. }
  66. }
  67. guard let pngImageData = newImage.pngData() else {
  68. return completion(nil, id)
  69. }
  70. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  71. return completion(imageNamePath, id)
  72. } else {
  73. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  74. return completion(nil, id)
  75. }
  76. if width != nil {
  77. let scale = svgImage.size.height / svgImage.size.width
  78. svgImage.size = CGSize(width: width!, height: width! * scale)
  79. }
  80. guard let image: UIImage = svgImage.uiImage else {
  81. return completion(nil, id)
  82. }
  83. guard let pngImageData = image.pngData() else {
  84. return completion(nil, id)
  85. }
  86. try? pngImageData.write(to: URL(fileURLWithPath: imageNamePath))
  87. return completion(imageNamePath, id)
  88. }
  89. } else {
  90. return completion(nil, id)
  91. }
  92. }
  93. } else {
  94. return completion(imageNamePath, id)
  95. }
  96. }
  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. KTVHTTPCache.cacheDeleteAllCaches()
  170. NCManageDatabase.shared.clearDatabase(account: nil, removeAccount: true)
  171. CCUtility.removeGroupDirectoryProviderStorage()
  172. CCUtility.removeGroupLibraryDirectory()
  173. CCUtility.removeDocumentsDirectory()
  174. CCUtility.removeTemporaryDirectory()
  175. CCUtility.createDirectoryStandard()
  176. CCUtility.deleteAllChainStore()
  177. }
  178. #endif
  179. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  180. for char in permissions {
  181. if metadataPermissions.contains(char) == false {
  182. return false
  183. }
  184. }
  185. return true
  186. }
  187. @objc func getCustomUserAgentNCText() -> String {
  188. let userAgent: String = CCUtility.getUserAgent()
  189. if UIDevice.current.userInterfaceIdiom == .phone {
  190. // NOTE: Hardcoded (May 2022)
  191. // Tested for iPhone SE (1st), iOS 12; iPhone Pro Max, iOS 15.4
  192. // 605.1.15 = WebKit build version
  193. // 15E148 = frozen iOS build number according to: https://chromestatus.com/feature/4558585463832576
  194. return userAgent + " " + "AppleWebKit/605.1.15 Mobile/15E148"
  195. } else {
  196. return userAgent
  197. }
  198. }
  199. @objc func getCustomUserAgentOnlyOffice() -> String {
  200. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  201. if UIDevice.current.userInterfaceIdiom == .pad {
  202. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  203. } else {
  204. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  205. }
  206. }
  207. @objc func pdfThumbnail(url: URL, width: CGFloat = 240) -> UIImage? {
  208. guard let data = try? Data(contentsOf: url), let page = PDFDocument(data: data)?.page(at: 0) else {
  209. return nil
  210. }
  211. let pageSize = page.bounds(for: .mediaBox)
  212. let pdfScale = width / pageSize.width
  213. // Apply if you're displaying the thumbnail on screen
  214. let scale = UIScreen.main.scale * pdfScale
  215. let screenSize = CGSize(width: pageSize.width * scale, height: pageSize.height * scale)
  216. return page.thumbnail(of: screenSize, for: .mediaBox)
  217. }
  218. @objc func isQuickLookDisplayable(metadata: tableMetadata) -> Bool {
  219. return true
  220. }
  221. @objc func ocIdToFileId(ocId: String?) -> String? {
  222. guard let ocId = ocId else { return nil }
  223. let items = ocId.components(separatedBy: "oc")
  224. if items.count < 2 { return nil }
  225. guard let intFileId = Int(items[0]) else { return nil }
  226. return String(intFileId)
  227. }
  228. func getUserStatus(userIcon: String?, userStatus: String?, userMessage: String?) -> (onlineStatus: UIImage?, statusMessage: String, descriptionMessage: String) {
  229. var onlineStatus: UIImage?
  230. var statusMessage: String = ""
  231. var descriptionMessage: String = ""
  232. var messageUserDefined: String = ""
  233. if userStatus?.lowercased() == "online" {
  234. 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)
  235. messageUserDefined = NSLocalizedString("_online_", comment: "")
  236. }
  237. if userStatus?.lowercased() == "away" {
  238. 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)
  239. messageUserDefined = NSLocalizedString("_away_", comment: "")
  240. }
  241. if userStatus?.lowercased() == "dnd" {
  242. onlineStatus = UIImage(named: "userStatusDnd")?.resizeImage(size: CGSize(width: 100, height: 100), isAspectRation: false)
  243. messageUserDefined = NSLocalizedString("_dnd_", comment: "")
  244. descriptionMessage = NSLocalizedString("_dnd_description_", comment: "")
  245. }
  246. if userStatus?.lowercased() == "offline" || userStatus?.lowercased() == "invisible" {
  247. onlineStatus = UIImage(named: "userStatusOffline")!.image(color: .black, size: 50)
  248. messageUserDefined = NSLocalizedString("_invisible_", comment: "")
  249. descriptionMessage = NSLocalizedString("_invisible_description_", comment: "")
  250. }
  251. if let userIcon = userIcon {
  252. statusMessage = userIcon + " "
  253. }
  254. if let userMessage = userMessage {
  255. statusMessage += userMessage
  256. }
  257. statusMessage = statusMessage.trimmingCharacters(in: .whitespaces)
  258. if statusMessage == "" {
  259. statusMessage = messageUserDefined
  260. }
  261. return(onlineStatus, statusMessage, descriptionMessage)
  262. }
  263. func imageFromVideo(url: URL, at time: TimeInterval) -> UIImage? {
  264. let asset = AVURLAsset(url: url)
  265. let assetIG = AVAssetImageGenerator(asset: asset)
  266. assetIG.appliesPreferredTrackTransform = true
  267. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  268. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  269. let thumbnailImageRef: CGImage
  270. do {
  271. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  272. } catch let error {
  273. print("Error: \(error)")
  274. return nil
  275. }
  276. return UIImage(cgImage: thumbnailImageRef)
  277. }
  278. func imageFromVideo(url: URL, at time: TimeInterval, completion: @escaping (UIImage?) -> Void) {
  279. DispatchQueue.global().async {
  280. let asset = AVURLAsset(url: url)
  281. let assetIG = AVAssetImageGenerator(asset: asset)
  282. assetIG.appliesPreferredTrackTransform = true
  283. assetIG.apertureMode = AVAssetImageGenerator.ApertureMode.encodedPixels
  284. let cmTime = CMTime(seconds: time, preferredTimescale: 60)
  285. let thumbnailImageRef: CGImage
  286. do {
  287. thumbnailImageRef = try assetIG.copyCGImage(at: cmTime, actualTime: nil)
  288. } catch let error {
  289. print("Error: \(error)")
  290. return completion(nil)
  291. }
  292. DispatchQueue.main.async {
  293. completion(UIImage(cgImage: thumbnailImageRef))
  294. }
  295. }
  296. }
  297. func createImageFrom(fileNameView: String, ocId: String, etag: String, classFile: String) {
  298. var originalImage, scaleImagePreview, scaleImageIcon: UIImage?
  299. let fileNamePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  300. let fileNamePathPreview = CCUtility.getDirectoryProviderStoragePreviewOcId(ocId, etag: etag)!
  301. let fileNamePathIcon = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  302. if CCUtility.fileProviderStorageSize(ocId, fileNameView: fileNameView) > 0 && FileManager().fileExists(atPath: fileNamePathPreview) && FileManager().fileExists(atPath: fileNamePathIcon) { return }
  303. if classFile != NKCommon.typeClassFile.image.rawValue && classFile != NKCommon.typeClassFile.video.rawValue { return }
  304. if classFile == NKCommon.typeClassFile.image.rawValue {
  305. originalImage = UIImage(contentsOfFile: fileNamePath)
  306. scaleImagePreview = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizePreview, height: NCGlobal.shared.sizePreview))
  307. scaleImageIcon = originalImage?.resizeImage(size: CGSize(width: NCGlobal.shared.sizeIcon, height: NCGlobal.shared.sizeIcon))
  308. try? scaleImagePreview?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  309. try? scaleImageIcon?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  310. } else if classFile == NKCommon.typeClassFile.video.rawValue {
  311. let videoPath = NSTemporaryDirectory()+"tempvideo.mp4"
  312. NCUtilityFileSystem.shared.linkItem(atPath: fileNamePath, toPath: videoPath)
  313. originalImage = imageFromVideo(url: URL(fileURLWithPath: videoPath), at: 0)
  314. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathPreview))
  315. try? originalImage?.jpegData(compressionQuality: 0.7)?.write(to: URL(fileURLWithPath: fileNamePathIcon))
  316. }
  317. }
  318. @objc func getVersionApp(withBuild: Bool = true) -> String {
  319. if let dictionary = Bundle.main.infoDictionary {
  320. if let version = dictionary["CFBundleShortVersionString"], let build = dictionary["CFBundleVersion"] {
  321. if withBuild {
  322. return "\(version).\(build)"
  323. } else {
  324. return "\(version)"
  325. }
  326. }
  327. }
  328. return ""
  329. }
  330. func loadImage(named imageName: String, color: UIColor = NCBrandColor.shared.gray, size: CGFloat = 50, symbolConfiguration: Any? = nil) -> UIImage {
  331. var image: UIImage?
  332. // see https://stackoverflow.com/questions/71764255
  333. let sfSymbolName = imageName.replacingOccurrences(of: "_", with: ".")
  334. if let symbolConfiguration = symbolConfiguration {
  335. image = UIImage(systemName: sfSymbolName, withConfiguration: symbolConfiguration as? UIImage.Configuration)?.withTintColor(color, renderingMode: .alwaysOriginal)
  336. } else {
  337. image = UIImage(systemName: sfSymbolName)?.withTintColor(color, renderingMode: .alwaysOriginal)
  338. }
  339. if image == nil {
  340. image = UIImage(named: imageName)?.image(color: color, size: size)
  341. }
  342. if let image = image {
  343. return image
  344. }
  345. return UIImage(named: "file")!.image(color: color, size: size)
  346. }
  347. @objc func loadUserImage(for user: String, displayName: String?, userBaseUrl: NCUserBaseUrl) -> UIImage {
  348. let fileName = userBaseUrl.userBaseUrl + "-" + user + ".png"
  349. let localFilePath = String(CCUtility.getDirectoryUserData()) + "/" + fileName
  350. if let localImage = UIImage(contentsOfFile: localFilePath) {
  351. return createAvatar(image: localImage, size: 30)
  352. } else if let loadedAvatar = NCManageDatabase.shared.getImageAvatarLoaded(fileName: fileName) {
  353. return loadedAvatar
  354. } else if let displayName = displayName, !displayName.isEmpty, let avatarImg = createAvatar(displayName: displayName, size: 30) {
  355. return avatarImg
  356. } else { return getDefaultUserIcon() }
  357. }
  358. func getDefaultUserIcon() -> UIImage {
  359. let config = UIImage.SymbolConfiguration(pointSize: 30)
  360. return NCUtility.shared.loadImage(named: "person.crop.circle", symbolConfiguration: config)
  361. }
  362. @objc func createAvatar(image: UIImage, size: CGFloat) -> UIImage {
  363. var avatarImage = image
  364. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  365. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  366. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  367. avatarImage.draw(in: rect)
  368. avatarImage = UIGraphicsGetImageFromCurrentImageContext() ?? image
  369. UIGraphicsEndImageContext()
  370. return avatarImage
  371. }
  372. func createAvatar(displayName: String, size: CGFloat) -> UIImage? {
  373. guard let initials = displayName.uppercaseInitials else {
  374. return nil
  375. }
  376. let userColor = NCGlobal.shared.usernameToColor(displayName)
  377. let rect = CGRect(x: 0, y: 0, width: size, height: size)
  378. var avatarImage: UIImage?
  379. UIGraphicsBeginImageContextWithOptions(rect.size, false, 3.0)
  380. let context = UIGraphicsGetCurrentContext()
  381. UIBezierPath(roundedRect: rect, cornerRadius: rect.size.height).addClip()
  382. context?.setFillColor(userColor)
  383. context?.fill(rect)
  384. let textStyle = NSMutableParagraphStyle()
  385. textStyle.alignment = NSTextAlignment.center
  386. let lineHeight = UIFont.systemFont(ofSize: UIFont.systemFontSize).pointSize
  387. NSString(string: initials)
  388. .draw(
  389. in: CGRect(x: 0, y: (size - lineHeight) / 2, width: size, height: lineHeight),
  390. withAttributes: [NSAttributedString.Key.paragraphStyle: textStyle])
  391. avatarImage = UIGraphicsGetImageFromCurrentImageContext()
  392. UIGraphicsEndImageContext()
  393. return avatarImage
  394. }
  395. /*
  396. Facebook's comparison algorithm:
  397. */
  398. func compare(tolerance: Float, expected: Data, observed: Data) throws -> Bool {
  399. enum customError: Error {
  400. case unableToGetUIImageFromData
  401. case unableToGetCGImageFromData
  402. case unableToGetColorSpaceFromCGImage
  403. case imagesHasDifferentSizes
  404. case unableToInitializeContext
  405. }
  406. guard let expectedUIImage = UIImage(data: expected), let observedUIImage = UIImage(data: observed) else {
  407. throw customError.unableToGetUIImageFromData
  408. }
  409. guard let expectedCGImage = expectedUIImage.cgImage, let observedCGImage = observedUIImage.cgImage else {
  410. throw customError.unableToGetCGImageFromData
  411. }
  412. guard let expectedColorSpace = expectedCGImage.colorSpace, let observedColorSpace = observedCGImage.colorSpace else {
  413. throw customError.unableToGetColorSpaceFromCGImage
  414. }
  415. if expectedCGImage.width != observedCGImage.width || expectedCGImage.height != observedCGImage.height {
  416. throw customError.imagesHasDifferentSizes
  417. }
  418. let imageSize = CGSize(width: expectedCGImage.width, height: expectedCGImage.height)
  419. let numberOfPixels = Int(imageSize.width * imageSize.height)
  420. // Checking that our `UInt32` buffer has same number of bytes as image has.
  421. let bytesPerRow = min(expectedCGImage.bytesPerRow, observedCGImage.bytesPerRow)
  422. assert(MemoryLayout<UInt32>.stride == bytesPerRow / Int(imageSize.width))
  423. let expectedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  424. let observedPixels = UnsafeMutablePointer<UInt32>.allocate(capacity: numberOfPixels)
  425. let expectedPixelsRaw = UnsafeMutableRawPointer(expectedPixels)
  426. let observedPixelsRaw = UnsafeMutableRawPointer(observedPixels)
  427. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
  428. guard let expectedContext = CGContext(data: expectedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  429. bitsPerComponent: expectedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  430. space: expectedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  431. expectedPixels.deallocate()
  432. observedPixels.deallocate()
  433. throw customError.unableToInitializeContext
  434. }
  435. guard let observedContext = CGContext(data: observedPixelsRaw, width: Int(imageSize.width), height: Int(imageSize.height),
  436. bitsPerComponent: observedCGImage.bitsPerComponent, bytesPerRow: bytesPerRow,
  437. space: observedColorSpace, bitmapInfo: bitmapInfo.rawValue) else {
  438. expectedPixels.deallocate()
  439. observedPixels.deallocate()
  440. throw customError.unableToInitializeContext
  441. }
  442. expectedContext.draw(expectedCGImage, in: CGRect(origin: .zero, size: imageSize))
  443. observedContext.draw(observedCGImage, in: CGRect(origin: .zero, size: imageSize))
  444. let expectedBuffer = UnsafeBufferPointer(start: expectedPixels, count: numberOfPixels)
  445. let observedBuffer = UnsafeBufferPointer(start: observedPixels, count: numberOfPixels)
  446. var isEqual = true
  447. if tolerance == 0 {
  448. isEqual = expectedBuffer.elementsEqual(observedBuffer)
  449. } else {
  450. // Go through each pixel in turn and see if it is different
  451. var numDiffPixels = 0
  452. for pixel in 0 ..< numberOfPixels where expectedBuffer[pixel] != observedBuffer[pixel] {
  453. // If this pixel is different, increment the pixel diff count and see if we have hit our limit.
  454. numDiffPixels += 1
  455. let percentage = 100 * Float(numDiffPixels) / Float(numberOfPixels)
  456. if percentage > tolerance {
  457. isEqual = false
  458. break
  459. }
  460. }
  461. }
  462. expectedPixels.deallocate()
  463. observedPixels.deallocate()
  464. return isEqual
  465. }
  466. func stringFromTime(_ time: CMTime) -> String {
  467. let interval = Int(CMTimeGetSeconds(time))
  468. let seconds = interval % 60
  469. let minutes = (interval / 60) % 60
  470. let hours = (interval / 3600)
  471. if hours > 0 {
  472. return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
  473. } else {
  474. return String(format: "%02d:%02d", minutes, seconds)
  475. }
  476. }
  477. func colorNavigationController(_ navigationController: UINavigationController?, backgroundColor: UIColor, titleColor: UIColor, tintColor: UIColor?, withoutShadow: Bool) {
  478. let appearance = UINavigationBarAppearance()
  479. appearance.titleTextAttributes = [.foregroundColor: titleColor]
  480. appearance.largeTitleTextAttributes = [.foregroundColor: titleColor]
  481. if withoutShadow {
  482. appearance.shadowColor = .clear
  483. appearance.shadowImage = UIImage()
  484. }
  485. if let tintColor = tintColor {
  486. navigationController?.navigationBar.tintColor = tintColor
  487. }
  488. navigationController?.view.backgroundColor = backgroundColor
  489. navigationController?.navigationBar.barTintColor = titleColor
  490. navigationController?.navigationBar.standardAppearance = appearance
  491. navigationController?.navigationBar.compactAppearance = appearance
  492. navigationController?.navigationBar.scrollEdgeAppearance = appearance
  493. }
  494. func getEncondingDataType(data: Data) -> String.Encoding? {
  495. if let _ = String(data: data, encoding: .utf8) {
  496. return .utf8
  497. }
  498. if let _ = String(data: data, encoding: .ascii) {
  499. return .ascii
  500. }
  501. if let _ = String(data: data, encoding: .isoLatin1) {
  502. return .isoLatin1
  503. }
  504. if let _ = String(data: data, encoding: .isoLatin2) {
  505. return .isoLatin2
  506. }
  507. if let _ = String(data: data, encoding: .windowsCP1250) {
  508. return .windowsCP1250
  509. }
  510. if let _ = String(data: data, encoding: .windowsCP1251) {
  511. return .windowsCP1251
  512. }
  513. if let _ = String(data: data, encoding: .windowsCP1252) {
  514. return .windowsCP1252
  515. }
  516. if let _ = String(data: data, encoding: .windowsCP1253) {
  517. return .windowsCP1253
  518. }
  519. if let _ = String(data: data, encoding: .windowsCP1254) {
  520. return .windowsCP1254
  521. }
  522. if let _ = String(data: data, encoding: .macOSRoman) {
  523. return .macOSRoman
  524. }
  525. if let _ = String(data: data, encoding: .japaneseEUC) {
  526. return .japaneseEUC
  527. }
  528. if let _ = String(data: data, encoding: .nextstep) {
  529. return .nextstep
  530. }
  531. if let _ = String(data: data, encoding: .nonLossyASCII) {
  532. return .nonLossyASCII
  533. }
  534. if let _ = String(data: data, encoding: .shiftJIS) {
  535. return .shiftJIS
  536. }
  537. if let _ = String(data: data, encoding: .symbol) {
  538. return .symbol
  539. }
  540. if let _ = String(data: data, encoding: .unicode) {
  541. return .unicode
  542. }
  543. if let _ = String(data: data, encoding: .utf16) {
  544. return .utf16
  545. }
  546. if let _ = String(data: data, encoding: .utf16BigEndian) {
  547. return .utf16BigEndian
  548. }
  549. if let _ = String(data: data, encoding: .utf16LittleEndian) {
  550. return .utf16LittleEndian
  551. }
  552. if let _ = String(data: data, encoding: .utf32) {
  553. return .utf32
  554. }
  555. if let _ = String(data: data, encoding: .utf32BigEndian) {
  556. return .utf32BigEndian
  557. }
  558. if let _ = String(data: data, encoding: .utf32LittleEndian) {
  559. return .utf32LittleEndian
  560. }
  561. return nil
  562. }
  563. func SYSTEM_VERSION_LESS_THAN(version: String) -> Bool {
  564. return UIDevice.current.systemVersion.compare(version,
  565. options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending
  566. }
  567. func getAvatarFromIconUrl(metadata: tableMetadata) -> String? {
  568. var ownerId: String?
  569. if metadata.iconUrl.contains("http") && metadata.iconUrl.contains("avatar") {
  570. let splitIconUrl = metadata.iconUrl.components(separatedBy: "/")
  571. var found:Bool = false
  572. for item in splitIconUrl {
  573. if found {
  574. ownerId = item
  575. break
  576. }
  577. if item == "avatar" { found = true}
  578. }
  579. }
  580. return ownerId
  581. }
  582. // https://stackoverflow.com/questions/25471114/how-to-validate-an-e-mail-address-in-swift
  583. func isValidEmail(_ email: String) -> Bool {
  584. let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
  585. let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
  586. return emailPred.evaluate(with: email)
  587. }
  588. func createFilePreviewImage(ocId: String, etag: String, fileNameView: String, classFile: String, status: Int, createPreviewMedia: Bool) -> UIImage? {
  589. var imagePreview: UIImage?
  590. let filePath = CCUtility.getDirectoryProviderStorageOcId(ocId, fileNameView: fileNameView)!
  591. let iconImagePath = CCUtility.getDirectoryProviderStorageIconOcId(ocId, etag: etag)!
  592. if FileManager().fileExists(atPath: iconImagePath) {
  593. imagePreview = UIImage(contentsOfFile: iconImagePath)
  594. } else if !createPreviewMedia {
  595. return nil
  596. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.typeClassFile.image.rawValue && FileManager().fileExists(atPath: filePath) {
  597. 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) {
  598. do {
  599. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  600. imagePreview = image
  601. } catch { }
  602. }
  603. } else if createPreviewMedia && status >= NCGlobal.shared.metadataStatusNormal && classFile == NKCommon.typeClassFile.video.rawValue && FileManager().fileExists(atPath: filePath) {
  604. 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) {
  605. do {
  606. try data.write(to: URL.init(fileURLWithPath: iconImagePath), options: .atomic)
  607. imagePreview = image
  608. } catch { }
  609. }
  610. }
  611. return imagePreview
  612. }
  613. @discardableResult
  614. func convertDataToImage(data: Data?, size:CGSize, fileNameToWrite: String?) -> UIImage? {
  615. guard let data = data else { return nil }
  616. var returnImage: UIImage?
  617. if let image = UIImage(data: data), let image = image.resizeImage(size: size) {
  618. returnImage = image
  619. } else if let image = SVGKImage(data: data) {
  620. image.size = size
  621. returnImage = image.uiImage
  622. } else {
  623. print("error")
  624. }
  625. if let fileName = fileNameToWrite, let image = returnImage {
  626. do {
  627. let fileNamePath: String = CCUtility.getDirectoryUserData() + "/" + fileName + ".png"
  628. try image.pngData()?.write(to: URL(fileURLWithPath: fileNamePath), options: .atomic)
  629. } catch { }
  630. }
  631. return returnImage
  632. }
  633. func isDirectoryE2EE(serverUrl: String, userBase: NCUserBaseUrl) -> Bool {
  634. return isDirectoryE2EE(serverUrl: serverUrl, account: userBase.account, urlBase: userBase.urlBase, userId: userBase.userId)
  635. }
  636. func isDirectoryE2EE(file: NKFile) -> Bool {
  637. return isDirectoryE2EE(serverUrl: file.serverUrl, account: file.account, urlBase: file.urlBase, userId: file.userId)
  638. }
  639. @objc func isDirectoryE2EE(metadata: tableMetadata) -> Bool {
  640. return isDirectoryE2EE(serverUrl: metadata.serverUrl, account: metadata.account, urlBase: metadata.urlBase, userId: metadata.userId)
  641. }
  642. @objc func isDirectoryE2EE(serverUrl: String, account: String, urlBase: String, userId: String) -> Bool {
  643. if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: urlBase, userId: userId) || serverUrl == ".." { return false }
  644. if let directory = NCManageDatabase.shared.getTableDirectory(predicate: NSPredicate(format: "account == %@ AND serverUrl == %@", account, serverUrl)) {
  645. return directory.e2eEncrypted
  646. }
  647. return false
  648. }
  649. func createViewImageAndText(image: UIImage, title: String? = nil) -> UIView {
  650. let imageView = UIImageView()
  651. let titleView = UIView()
  652. let label = UILabel()
  653. if let title = title {
  654. label.text = title + " "
  655. } else {
  656. label.text = " "
  657. }
  658. label.sizeToFit()
  659. label.center = titleView.center
  660. label.textAlignment = NSTextAlignment.center
  661. imageView.image = image
  662. let imageAspect = (imageView.image?.size.width ?? 0) / (imageView.image?.size.height ?? 0)
  663. let imageX = label.frame.origin.x - label.frame.size.height * imageAspect
  664. let imageY = label.frame.origin.y
  665. let imageWidth = label.frame.size.height * imageAspect
  666. let imageHeight = label.frame.size.height
  667. if title != nil {
  668. imageView.frame = CGRect(x: imageX, y: imageY, width: imageWidth, height: imageHeight)
  669. titleView.addSubview(label)
  670. } else {
  671. imageView.frame = CGRect(x: imageX / 2, y: imageY, width: imageWidth, height: imageHeight)
  672. }
  673. imageView.contentMode = UIView.ContentMode.scaleAspectFit
  674. titleView.addSubview(imageView)
  675. titleView.sizeToFit()
  676. return titleView
  677. }
  678. }