PhotosAccessHelper.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. import Foundation
  21. import CocoaLumberjackSwift
  22. #if compiler(>=5.3)
  23. import PhotosUI
  24. #endif
  25. let tmpDirectory = "tmpImages/"
  26. enum PhotosPickerError : Error {
  27. case fileNotFound
  28. case fileTooLarge
  29. case unknown
  30. }
  31. @objc class PhotosAccessHelper : NSObject {
  32. let completion : (([Any], DKImagePickerController?) -> Void)
  33. var pickerController : DKImagePickerController?
  34. @objc init(completion : @escaping (([Any], DKImagePickerController?) -> Void)) {
  35. self.completion = completion
  36. super.init()
  37. }
  38. @objc func showPicker(viewController : UIViewController, limit : Int) {
  39. #if compiler(>=5.3)
  40. if #available(iOS 14, *), !PhotosRightsHelper().haveFullAccess() {
  41. let photoLibrary = PHPhotoLibrary.shared()
  42. var config = PHPickerConfiguration(photoLibrary: photoLibrary)
  43. config.selectionLimit = limit
  44. let picker = PHPickerViewController(configuration: config)
  45. picker.delegate = self
  46. viewController.present(picker, animated: true, completion: nil)
  47. return
  48. }
  49. #endif
  50. // Show our custom picker if we have full access or if we are < iOS 14
  51. PHPhotoLibrary.requestAuthorization({status in
  52. let assetCollectionView = UITableView.appearance(whenContainedInInstancesOf: [DKImagePickerController.self])
  53. assetCollectionView.backgroundColor = Colors.background()
  54. DispatchQueue.main.async {
  55. self.pickerController = self.setupDKImagePickerController(limit: limit)
  56. guard let pickerController = self.pickerController else {
  57. return
  58. }
  59. viewController.present(pickerController, animated: true, completion: nil)
  60. }
  61. })
  62. }
  63. @objc func setupDKImagePickerController(limit : Int) -> DKImagePickerController {
  64. let picker = DKImagePickerController()
  65. picker.assetType = .allAssets
  66. picker.showsCancelButton = true
  67. picker.showsEmptyAlbums = false
  68. picker.allowMultipleTypes = true
  69. picker.autoDownloadWhenAssetIsInCloud = false
  70. picker.defaultSelectedAssets = []
  71. picker.sourceType = .photo
  72. picker.maxSelectableCount = limit
  73. picker.UIDelegate = ThreemaImagePickerControllerDefaultUIDelegate()
  74. picker.allowsLandscape = true
  75. picker.didSelectAsset = self.didSelectAsset
  76. picker.didSelectAssets = self.didSelectAssets
  77. return picker
  78. }
  79. func didSelectAsset(picker : DKImagePickerController, asset : DKAsset) {
  80. if (asset.isVideo && asset.originalAsset!.duration > (MediaConverter.videoMaxDurationAtCurrentQuality() + 1) * 60) {
  81. picker.deselectAsset(asset)
  82. let errorTitle = BundleUtil.localizedString(forKey: "video_too_long_title")
  83. let errorMessage = String(format: BundleUtil.localizedString(forKey: "video_too_long_message"), MediaConverter.videoMaxDurationAtCurrentQuality())
  84. UIAlertTemplate.showAlert(owner: picker, title: errorTitle, message: errorMessage)
  85. }
  86. }
  87. func didSelectAssets(assets : [DKAsset]) {
  88. guard let pickerController = self.pickerController else {
  89. return
  90. }
  91. completion(assets, pickerController)
  92. }
  93. @objc static func cleanTemporaryDirectory() {
  94. let fileManager = FileManager.default
  95. let tmpDirURL = FileManager.default.temporaryDirectory.appendingPathComponent(tmpDirectory)
  96. try? fileManager.removeItem(at: tmpDirURL)
  97. }
  98. @objc static func getTempDir() -> URL {
  99. let fileManager = FileManager.default
  100. let tmpDirURL = FileManager.default.temporaryDirectory.appendingPathComponent(tmpDirectory)
  101. if !fileManager.fileExists(atPath: tmpDirURL.absoluteString) {
  102. do {
  103. try fileManager.createDirectory(at: tmpDirURL, withIntermediateDirectories: true, attributes: nil)
  104. } catch {
  105. DDLogError("Error \(error.localizedDescription)")
  106. }
  107. }
  108. return tmpDirURL
  109. }
  110. @objc static func storeImageToTmprDir(imageData : UIImage) -> URL {
  111. let tmpDir = self.getTempDir()
  112. let fileName = FileUtility.getTemporarySendableFileName(base: "image")
  113. let fileUrl = tmpDir.appendingPathComponent(fileName + ".jpeg")
  114. let data = imageData.jpegData(compressionQuality: 1.0)
  115. do {
  116. try data?.write(to: fileUrl)
  117. } catch {
  118. DDLogError("Error \(error.localizedDescription)")
  119. }
  120. return fileUrl
  121. }
  122. }
  123. #if compiler(>=5.3)
  124. @available(iOS 14, *)
  125. extension PhotosAccessHelper : PHPickerViewControllerDelegate {
  126. func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
  127. var photos : [Any] = []
  128. let sema = DispatchSemaphore.init(value: 0)
  129. for result in results {
  130. if result.itemProvider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
  131. result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier, completionHandler: { (url, error) in
  132. defer { sema.signal() }
  133. photos.append(self.loadImage(from: url))
  134. if(error != nil) {
  135. DDLogError("Could not load item \(error!)")
  136. }
  137. })
  138. } else if result.itemProvider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
  139. result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier, completionHandler: { (url, error) in
  140. defer { sema.signal() }
  141. photos.append(self.loadVideo(from: url))
  142. if(error != nil) {
  143. DDLogError("Could not load item \(error!)")
  144. }
  145. })
  146. }
  147. }
  148. for _ in results {
  149. sema.wait()
  150. }
  151. picker.dismiss(animated: true, completion: nil)
  152. completion(photos, nil)
  153. }
  154. func loadVideo(from url : URL?) -> Any {
  155. guard let url = url else {
  156. return PhotosPickerError.fileNotFound
  157. }
  158. let tmpDirURL = PhotosAccessHelper.getTempDir()
  159. let fileManager = FileManager.default
  160. let filename = FileUtility.getTemporarySendableFileName(base: "video", directoryURL: tmpDirURL, pathExtension: url.pathExtension)
  161. let newUrl = tmpDirURL.appendingPathComponent(filename).appendingPathExtension(url.pathExtension)
  162. if !MediaConverter.isVideoDurationValid(at: url) {
  163. return PhotosPickerError.fileTooLarge
  164. } else {
  165. do { try fileManager.copyItem(at: url, to: newUrl) } catch {
  166. return PhotosPickerError.fileNotFound
  167. }
  168. return newUrl
  169. }
  170. }
  171. func loadImage(from url : URL?) -> Any {
  172. guard let url = url else {
  173. return PhotosPickerError.fileNotFound
  174. }
  175. let tmpDirURL = PhotosAccessHelper.getTempDir()
  176. let fileManager = FileManager.default
  177. let filename = FileUtility.getTemporarySendableFileName(base: "image", directoryURL: tmpDirURL, pathExtension: url.pathExtension)
  178. let newUrl = tmpDirURL.appendingPathComponent(filename).appendingPathExtension(url.pathExtension)
  179. do { try fileManager.copyItem(at: url, to: newUrl) } catch {
  180. DDLogError("Could not load image \(error)")
  181. return PhotosPickerError.fileNotFound
  182. }
  183. return newUrl
  184. }
  185. }
  186. #endif