NCUtility.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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 Foundation
  24. import SVGKit
  25. import KTVHTTPCache
  26. import ZIPFoundation
  27. import Sheeeeeeeeet
  28. import NCCommunication
  29. import CommonCrypto
  30. class NCUtility: NSObject {
  31. @objc static let sharedInstance: NCUtility = {
  32. let instance = NCUtility()
  33. return instance
  34. }()
  35. let activityIndicator = UIActivityIndicatorView(style: .whiteLarge)
  36. let cache = NSCache<NSString, UIImage>()
  37. struct bundleDirectoryType {
  38. var error: Bool = false
  39. var bundleDirectory: String = ""
  40. var immPath: String = ""
  41. }
  42. @objc func createFileName(_ fileName: String, serverUrl: String, account: String) -> String {
  43. var resultFileName = fileName
  44. var exitLoop = false
  45. while exitLoop == false {
  46. if NCManageDatabase.sharedInstance.getMetadata(predicate: NSPredicate(format: "fileNameView == %@ AND serverUrl == %@ AND account == %@", resultFileName, serverUrl, account)) != nil {
  47. var name = NSString(string: resultFileName).deletingPathExtension
  48. let ext = NSString(string: resultFileName).pathExtension
  49. let characters = Array(name)
  50. if characters.count < 2 {
  51. if ext == "" {
  52. resultFileName = name + " " + "1"
  53. } else {
  54. resultFileName = name + " " + "1" + "." + ext
  55. }
  56. } else {
  57. let space = characters[characters.count-2]
  58. let numChar = characters[characters.count-1]
  59. var num = Int(String(numChar))
  60. if (space == " " && num != nil) {
  61. name = String(name.dropLast())
  62. num = num! + 1
  63. if ext == "" {
  64. resultFileName = name + "\(num!)"
  65. } else {
  66. resultFileName = name + "\(num!)" + "." + ext
  67. }
  68. } else {
  69. if ext == "" {
  70. resultFileName = name + " " + "1"
  71. } else {
  72. resultFileName = name + " " + "1" + "." + ext
  73. }
  74. }
  75. }
  76. } else {
  77. exitLoop = true
  78. }
  79. }
  80. return resultFileName
  81. }
  82. @objc func isEncryptedMetadata(_ metadata: tableMetadata) -> Bool {
  83. if metadata.fileName != metadata.fileNameView && metadata.fileName.count == 32 && metadata.fileName.contains(".") == false {
  84. return true
  85. }
  86. return false
  87. }
  88. @objc func getFileSize(asset: PHAsset) -> Int64 {
  89. let resources = PHAssetResource.assetResources(for: asset)
  90. if let resource = resources.first {
  91. if resource.responds(to: #selector(NSDictionary.fileSize)) {
  92. let unsignedInt64 = resource.value(forKey: "fileSize") as! CLong
  93. return Int64(bitPattern: UInt64(unsignedInt64))
  94. }
  95. }
  96. return 0
  97. }
  98. @objc func getScreenWidthForPreview() -> CGFloat {
  99. let screenSize = UIScreen.main.bounds
  100. let screenWidth = screenSize.width * 0.75
  101. return screenWidth
  102. }
  103. @objc func getScreenHeightForPreview() -> CGFloat {
  104. let screenSize = UIScreen.main.bounds
  105. let screenWidth = screenSize.height * 0.75
  106. return screenWidth
  107. }
  108. @objc func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
  109. let scale = newWidth / image.size.width
  110. let newHeight = image.size.height * scale
  111. UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
  112. image.draw(in: (CGRect(x: 0, y: 0, width: newWidth, height: newHeight)))
  113. let newImage = UIGraphicsGetImageFromCurrentImageContext()!
  114. UIGraphicsEndImageContext()
  115. return newImage
  116. }
  117. func cellBlurEffect(with frame: CGRect) -> UIView {
  118. let blurEffect = UIBlurEffect(style: .extraLight)
  119. let blurEffectView = UIVisualEffectView(effect: blurEffect)
  120. blurEffectView.frame = frame
  121. blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  122. blurEffectView.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.2)
  123. return blurEffectView
  124. }
  125. func setLayoutForView(key: String, layout: String, sort: String, ascending: Bool, groupBy: String, directoryOnTop: Bool) {
  126. let string = layout + "|" + sort + "|" + "\(ascending)" + "|" + groupBy + "|" + "\(directoryOnTop)"
  127. UICKeyChainStore.setString(string, forKey: key, service: k_serviceShareKeyChain)
  128. }
  129. func getLayoutForView(key: String) -> (String, String, Bool, String, Bool) {
  130. guard let string = UICKeyChainStore.string(forKey: key, service: k_serviceShareKeyChain) else {
  131. return (k_layout_list, "fileName", true, "none", true)
  132. }
  133. let array = string.components(separatedBy: "|")
  134. if array.count == 5 {
  135. let sort = NSString(string: array[2])
  136. let directoryOnTop = NSString(string: array[4])
  137. return (array[0], array[1], sort.boolValue, array[3], directoryOnTop.boolValue)
  138. }
  139. return (k_layout_list, "fileName", true, "none", true)
  140. }
  141. func convertSVGtoPNGWriteToUserData(svgUrlString: String, fileName: String?, width: CGFloat?, rewrite: Bool, account: String, closure: @escaping (String?) -> ()) {
  142. var fileNamePNG = ""
  143. guard let svgUrlString = svgUrlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else {
  144. return closure(nil)
  145. }
  146. guard let iconURL = URL(string: svgUrlString) else {
  147. return closure(nil)
  148. }
  149. if fileName == nil {
  150. fileNamePNG = iconURL.deletingPathExtension().lastPathComponent + ".png"
  151. } else {
  152. fileNamePNG = fileName!
  153. }
  154. let imageNamePath = CCUtility.getDirectoryUserData() + "/" + fileNamePNG
  155. if !FileManager.default.fileExists(atPath: imageNamePath) || rewrite == true {
  156. NCCommunication.sharedInstance.downloadContent(urlString: iconURL.absoluteString, account: account) { (account, data, errorCode, errorMessage) in
  157. if errorCode == 0 && data != nil {
  158. if let image = UIImage.init(data: data!) {
  159. var newImage: UIImage = image
  160. if width != nil {
  161. let ratio = image.size.height / image.size.width
  162. let newSize = CGSize(width: width!, height: width! * ratio)
  163. let renderFormat = UIGraphicsImageRendererFormat.default()
  164. renderFormat.opaque = false
  165. let renderer = UIGraphicsImageRenderer(size: CGSize(width: newSize.width, height: newSize.height), format: renderFormat)
  166. newImage = renderer.image {
  167. (context) in
  168. image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
  169. }
  170. }
  171. guard let pngImageData = newImage.pngData() else {
  172. return closure(nil)
  173. }
  174. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  175. return closure(imageNamePath)
  176. } else {
  177. guard let svgImage: SVGKImage = SVGKImage(data: data) else {
  178. return closure(nil)
  179. }
  180. if width != nil {
  181. let scale = svgImage.size.height / svgImage.size.width
  182. svgImage.size = CGSize(width: width!, height: width! * scale)
  183. }
  184. guard let image: UIImage = svgImage.uiImage else {
  185. return closure(nil)
  186. }
  187. guard let pngImageData = image.pngData() else {
  188. return closure(nil)
  189. }
  190. CCUtility.write(pngImageData, fileNamePath: imageNamePath)
  191. return closure(imageNamePath)
  192. }
  193. } else {
  194. return closure(nil)
  195. }
  196. }
  197. } else {
  198. return closure(imageNamePath)
  199. }
  200. }
  201. @objc func startActivityIndicator(view: UIView?, bottom: CGFloat) {
  202. guard let view = view else { return }
  203. activityIndicator.color = NCBrandColor.sharedInstance.brand
  204. activityIndicator.hidesWhenStopped = true
  205. view.addSubview(activityIndicator)
  206. activityIndicator.translatesAutoresizingMaskIntoConstraints = false
  207. let horizontalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0)
  208. view.addConstraint(horizontalConstraint)
  209. var verticalConstant: CGFloat = 0
  210. if bottom > 0 {
  211. verticalConstant = (view.frame.size.height / 2) - bottom
  212. }
  213. let verticalConstraint = NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: verticalConstant)
  214. view.addConstraint(verticalConstraint)
  215. activityIndicator.startAnimating()
  216. }
  217. @objc func stopActivityIndicator() {
  218. activityIndicator.stopAnimating()
  219. activityIndicator.removeFromSuperview()
  220. }
  221. @objc func isSimulatorOrTestFlight() -> Bool {
  222. guard let path = Bundle.main.appStoreReceiptURL?.path else {
  223. return false
  224. }
  225. return path.contains("CoreSimulator") || path.contains("sandboxReceipt")
  226. }
  227. @objc func isEditImage(_ fileName: NSString) -> String? {
  228. switch fileName.pathExtension.uppercased() {
  229. case "PNG":
  230. return "PNG";
  231. case "JPG":
  232. return "JPG";
  233. case "JPEG":
  234. return "JPG"
  235. default:
  236. return nil
  237. }
  238. }
  239. @objc func formatSecondsToString(_ seconds: TimeInterval) -> String {
  240. if seconds.isNaN {
  241. return "00:00:00"
  242. }
  243. let sec = Int(seconds.truncatingRemainder(dividingBy: 60))
  244. let min = Int(seconds.truncatingRemainder(dividingBy: 3600) / 60)
  245. let hour = Int(seconds / 3600)
  246. return String(format: "%02d:%02d:%02d", hour, min, sec)
  247. }
  248. @objc func blink(cell: AnyObject?) {
  249. DispatchQueue.main.async {
  250. if let cell = cell as? UITableViewCell {
  251. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  252. UIView.animate(withDuration: 2) {
  253. cell.backgroundColor = .clear
  254. }
  255. } else if let cell = cell as? UICollectionViewCell {
  256. cell.backgroundColor = NCBrandColor.sharedInstance.brand.withAlphaComponent(0.3)
  257. UIView.animate(withDuration: 2) {
  258. cell.backgroundColor = .clear
  259. }
  260. }
  261. }
  262. }
  263. @objc func bestFittingFont(for text: String, in bounds: CGRect, fontDescriptor: UIFontDescriptor) -> UIFont {
  264. let constrainingDimension = min(bounds.width, bounds.height)
  265. let properBounds = CGRect(origin: .zero, size: bounds.size)
  266. var attributes = [NSAttributedString.Key: Any]()
  267. let infiniteBounds = CGSize(width: CGFloat.infinity, height: CGFloat.infinity)
  268. var bestFontSize: CGFloat = constrainingDimension
  269. for fontSize in stride(from: bestFontSize, through: 0, by: -1) {
  270. let newFont = UIFont(descriptor: fontDescriptor, size: fontSize)
  271. attributes[.font] = newFont
  272. let currentFrame = text.boundingRect(with: infiniteBounds, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: attributes, context: nil)
  273. if properBounds.contains(currentFrame) {
  274. bestFontSize = fontSize
  275. break
  276. }
  277. }
  278. return UIFont(descriptor: fontDescriptor, size: bestFontSize)
  279. }
  280. @objc func isRichDocument(_ metadata: tableMetadata) -> Bool {
  281. guard let mimeType = CCUtility.getMimeType(metadata.fileNameView) else {
  282. return false
  283. }
  284. guard let richdocumentsMimetypes = NCManageDatabase.sharedInstance.getRichdocumentsMimetypes(account: metadata.account) else {
  285. return false
  286. }
  287. if richdocumentsMimetypes.count > 0 && mimeType.components(separatedBy: ".").count > 2 {
  288. let mimeTypeArray = mimeType.components(separatedBy: ".")
  289. let mimeType = mimeTypeArray[mimeTypeArray.count - 2] + "." + mimeTypeArray[mimeTypeArray.count - 1]
  290. for richdocumentMimetype: String in richdocumentsMimetypes {
  291. if richdocumentMimetype.contains(mimeType) {
  292. return true
  293. }
  294. }
  295. }
  296. return false
  297. }
  298. @objc func isDirectEditing(_ metadata: tableMetadata) -> String? {
  299. if NCBrandBeta.shared.directEditing == false {
  300. return nil
  301. }
  302. guard let results = NCManageDatabase.sharedInstance.getDirectEditingEditors(account: metadata.account) else {
  303. return nil
  304. }
  305. for result: tableDirectEditingEditors in results {
  306. for mimetype in result.mimetypes {
  307. if mimetype == metadata.contentType {
  308. return result.editor
  309. }
  310. }
  311. for mimetype in result.optionalMimetypes {
  312. if mimetype == metadata.contentType {
  313. return result.editor
  314. }
  315. }
  316. }
  317. return nil
  318. }
  319. @objc func removeAllSettings() {
  320. URLCache.shared.memoryCapacity = 0
  321. URLCache.shared.diskCapacity = 0
  322. KTVHTTPCache.cacheDeleteAllCaches()
  323. NCManageDatabase.sharedInstance.clearDatabase(account: nil, removeAccount: true)
  324. CCUtility.emptyGroupDirectoryProviderStorage()
  325. CCUtility.emptyGroupLibraryDirectory()
  326. CCUtility.emptyDocumentsDirectory()
  327. CCUtility.emptyTemporaryDirectory()
  328. CCUtility.createDirectoryStandard()
  329. CCUtility.deleteAllChainStore()
  330. }
  331. @objc func createAvatar(fileNameSource: String, fileNameSourceAvatar: String) -> UIImage? {
  332. guard let imageSource = UIImage(contentsOfFile: fileNameSource) else { return nil }
  333. let size = Int(k_avatar_size)
  334. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  335. imageSource.draw(in: CGRect(x: 0, y: 0, width: size, height: size))
  336. let image = UIGraphicsGetImageFromCurrentImageContext()
  337. UIGraphicsEndImageContext()
  338. UIGraphicsBeginImageContextWithOptions(CGSize(width: size, height: size), false, 0)
  339. let avatarImageView = CCAvatar.init(image: image, borderColor: .lightGray, borderWidth: 0.5)
  340. //avatarImageView?.alpha = alpha
  341. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  342. avatarImageView?.layer.render(in: context)
  343. guard let imageAvatar = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
  344. UIGraphicsEndImageContext()
  345. guard let data = imageAvatar.pngData() else {
  346. return nil
  347. }
  348. do {
  349. try data.write(to: NSURL(fileURLWithPath: fileNameSourceAvatar) as URL, options: .atomic)
  350. } catch { }
  351. return imageAvatar
  352. }
  353. func loadImage(ocId: String, fileNameView: String, completion: @escaping (UIImage?) -> Void) {
  354. if let image = cache.object(forKey: ocId as NSString) {
  355. completion(image)
  356. return
  357. }
  358. DispatchQueue.global(qos: .background).async { [weak self] in
  359. let loadedImage = UIImage(contentsOfFile: CCUtility.getDirectoryProviderStorageIconOcId(ocId, fileNameView: fileNameView))
  360. DispatchQueue.main.async {
  361. if let loadedImage = loadedImage {
  362. self?.cache.setObject(loadedImage, forKey: ocId as NSString)
  363. }
  364. completion(loadedImage)
  365. }
  366. }
  367. }
  368. @objc func UIColorFromRGB(rgbValue: UInt32) -> UIColor {
  369. return UIColor(
  370. red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
  371. green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
  372. blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
  373. alpha: CGFloat(1.0)
  374. )
  375. }
  376. @objc func RGBFromUIColor(uicolorValue: UIColor) -> UInt32 {
  377. var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
  378. if uicolorValue.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
  379. var colorAsUInt : UInt32 = 0
  380. colorAsUInt += UInt32(red * 255.0) << 16 +
  381. UInt32(green * 255.0) << 8 +
  382. UInt32(blue * 255.0)
  383. return colorAsUInt
  384. }
  385. return 0
  386. }
  387. @objc func IMUnzip(metadata: tableMetadata) -> Bool {
  388. // bak
  389. let atPathBak = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView
  390. let toPathBak = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension + ".bak"
  391. CCUtility.copyFile(atPath: atPathBak, toPath: toPathBak)
  392. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  393. let destination = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId))
  394. let removeAtPath = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension
  395. try? FileManager.default.removeItem(atPath: removeAtPath)
  396. try? FileManager().unzipItem(at: source, to: destination)
  397. let bundleDirectory = NCUtility.sharedInstance.IMGetBundleDirectory(metadata: metadata)
  398. if bundleDirectory.error {
  399. return false
  400. }
  401. if let fileHandle = FileHandle(forReadingAtPath: bundleDirectory.immPath) {
  402. // let dataFormat = fileHandle.readData(ofLength: 1)
  403. // if dataFormat.starts(with: [0x01]) {
  404. // appDelegate.messageNotification("_error_", description: "File format binary error, library imagemeter not present. 🤷‍♂️", visible: true, delay: TimeInterval(k_dismissAfterSecond), type: TWMessageBarMessageType.error, errorCode: errorCode)
  405. // return;
  406. // }
  407. let dataZip = fileHandle.readData(ofLength: 4)
  408. if dataZip.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
  409. try? FileManager().unzipItem(at: NSURL(fileURLWithPath: bundleDirectory.immPath) as URL, to: NSURL(fileURLWithPath: bundleDirectory.bundleDirectory) as URL)
  410. }
  411. fileHandle.closeFile()
  412. }
  413. return true
  414. }
  415. func IMGetBundleDirectory(metadata: tableMetadata) -> bundleDirectoryType {
  416. var error = true
  417. var bundleDirectory = ""
  418. var immPath = ""
  419. let source = URL(fileURLWithPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView))
  420. if let archive = Archive(url: source, accessMode: .read) {
  421. archive.forEach({ (entry) in
  422. let pathComponents = (entry.path as NSString).pathComponents
  423. if pathComponents.count == 2 && (pathComponents.last! as NSString).pathExtension.lowercased() == "imm" {
  424. error = false
  425. bundleDirectory = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + pathComponents.first!
  426. immPath = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + entry.path
  427. }
  428. })
  429. }
  430. return bundleDirectoryType(error: error, bundleDirectory: bundleDirectory, immPath: immPath)
  431. }
  432. func IMIsChange(metadata: tableMetadata, fileNameZipUrl: URL) -> Bool {
  433. let backFile = (CCUtility.getDirectoryProviderStorageOcId(metadata.ocId) + "/" + metadata.fileNameView as NSString).deletingPathExtension + ".bak"
  434. if let md5imiFile = self.md5File(url: fileNameZipUrl) {
  435. if let md5backfile = self.md5File(url: URL(fileURLWithPath: backFile)) {
  436. if md5imiFile == md5backfile {
  437. return false
  438. } else {
  439. return true
  440. }
  441. }
  442. }
  443. return true
  444. }
  445. @objc func permissionsContainsString(_ metadataPermissions: String, permissions: String) -> Bool {
  446. for char in permissions {
  447. if metadataPermissions.contains(char) == false {
  448. return false
  449. }
  450. }
  451. return true
  452. }
  453. @objc func getCustomUserAgentOnlyOffice() -> String {
  454. let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString")!
  455. if UIDevice.current.userInterfaceIdiom == .pad {
  456. return "Mozilla/5.0 (iPad) Nextcloud-iOS/\(appVersion)"
  457. }else{
  458. return "Mozilla/5.0 (iPhone) Mobile Nextcloud-iOS/\(appVersion)"
  459. }
  460. }
  461. func md5File(url: URL) -> Data? {
  462. let bufferSize = 1024 * 1024
  463. do {
  464. // Open file for reading:
  465. let file = try FileHandle(forReadingFrom: url)
  466. defer {
  467. file.closeFile()
  468. }
  469. // Create and initialize MD5 context:
  470. var context = CC_MD5_CTX()
  471. CC_MD5_Init(&context)
  472. // Read up to `bufferSize` bytes, until EOF is reached, and update MD5 context:
  473. while autoreleasepool(invoking: {
  474. let data = file.readData(ofLength: bufferSize)
  475. if data.count > 0 {
  476. data.withUnsafeBytes {
  477. _ = CC_MD5_Update(&context, $0.baseAddress, numericCast(data.count))
  478. }
  479. return true // Continue
  480. } else {
  481. return false // End of file
  482. }
  483. }) { }
  484. // Compute the MD5 digest:
  485. var digest: [UInt8] = Array(repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
  486. _ = CC_MD5_Final(&digest, &context)
  487. return Data(digest)
  488. } catch {
  489. print("Cannot open file:", error.localizedDescription)
  490. return nil
  491. }
  492. }
  493. }