NCUtility.swift 35 KB

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