NCUtility.swift 32 KB

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