NCUtility.swift 34 KB

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