AlbumManager.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2019-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 Photos
  21. import UIKit
  22. import CocoaLumberjackSwift
  23. @objc class AlbumManager: NSObject {
  24. static let albumName = "Threema Media"
  25. let successMessage = "Successfully saved image to Camera Roll."
  26. let permissionNotGrantedMessage = "Permission to save images not granted"
  27. let writeErrorMessage = "Error writing to image library:"
  28. let generalError = "Could not create error message"
  29. @objc static let shared = AlbumManager()
  30. private var assetCollection: PHAssetCollection!
  31. private override init() {
  32. super.init()
  33. if let assetCollection = fetchAssetCollectionForAlbum() {
  34. self.assetCollection = assetCollection
  35. return
  36. }
  37. }
  38. private func checkAuthorizationWithHandler(completion: @escaping ((_ authorizationState: PhotosRights) -> Void)) {
  39. let accessAllowed = PhotosRightsHelper.checkAccessAllowed(rightsHelper: PhotosRightsHelper())
  40. completion(accessAllowed)
  41. }
  42. private func fetchAssetCollectionForAlbum() -> PHAssetCollection? {
  43. let fetchOptions = PHFetchOptions()
  44. fetchOptions.predicate = NSPredicate(format: "title = %@", AlbumManager.albumName)
  45. let collection = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
  46. if let _: AnyObject = collection.firstObject {
  47. return collection.firstObject
  48. }
  49. return nil
  50. }
  51. @objc func save_ori(image: UIImage) {
  52. self.checkAuthorizationWithHandler { (authorizationState) in
  53. if authorizationState == .full, self.assetCollection != nil {
  54. PHPhotoLibrary.shared().performChanges({
  55. let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
  56. guard let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset else {
  57. DDLogError("Could not create placeholder")
  58. return
  59. }
  60. if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection) {
  61. let enumeration: NSArray = [assetPlaceHolder]
  62. albumChangeRequest.addAssets(enumeration)
  63. }
  64. }, completionHandler: { (success, error) in
  65. if success {
  66. DDLogNotice(self.successMessage)
  67. } else {
  68. guard let err = error else {
  69. DDLogError(self.generalError)
  70. return
  71. }
  72. DDLogError(self.writeErrorMessage + "\(err.localizedDescription)")
  73. }
  74. })
  75. } else if authorizationState == .write || authorizationState == .potentialWrite {
  76. UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.savedImage), nil)
  77. } else {
  78. DDLogNotice(self.permissionNotGrantedMessage)
  79. }
  80. }
  81. }
  82. @objc func savedImage(_ im:UIImage, error:Error?, context:UnsafeMutableRawPointer?) {
  83. if ((error) != nil) {
  84. guard let err = error else {
  85. DDLogError(self.generalError)
  86. return
  87. }
  88. DDLogError(self.writeErrorMessage + "\(err.localizedDescription)")
  89. } else {
  90. DDLogNotice(successMessage)
  91. }
  92. }
  93. @objc func save(image: UIImage) {
  94. func saveIt(_ validAssets: PHAssetCollection){
  95. PHPhotoLibrary.shared().performChanges({
  96. let assetChangeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
  97. if let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset {
  98. if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection) {
  99. let enumeration: NSArray = [assetPlaceHolder]
  100. albumChangeRequest.addAssets(enumeration)
  101. }
  102. }
  103. }, completionHandler: { (success, error) in
  104. if success {
  105. DDLogNotice(self.successMessage)
  106. } else {
  107. guard let err = error else {
  108. DDLogError(self.generalError)
  109. return
  110. }
  111. DDLogError(self.writeErrorMessage + "\(err.localizedDescription)")
  112. }
  113. })
  114. }
  115. self.checkAuthorizationWithHandler { (authorizationState) in
  116. if authorizationState == .full {
  117. if let validAssets = self.assetCollection { // Album already exists
  118. saveIt(validAssets)
  119. } else {
  120. PHPhotoLibrary.shared().performChanges({
  121. PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: AlbumManager.albumName) // create an asset collection with the album name
  122. }) { success, error in
  123. if success, let validAssets = self.fetchAssetCollectionForAlbum() {
  124. self.assetCollection = validAssets
  125. saveIt(validAssets)
  126. } else {
  127. DDLogError(self.writeErrorMessage + " \(error!.localizedDescription)")
  128. }
  129. }
  130. }
  131. } else if authorizationState == .write || authorizationState == .potentialWrite {
  132. UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.savedImage), nil)
  133. } else {
  134. DDLogNotice(self.permissionNotGrantedMessage)
  135. }
  136. }
  137. }
  138. @objc func save(url: URL, isVideo: Bool, completionHandler: @escaping ((_ success: Bool) -> Void)) {
  139. func saveIt(_ validAssets: PHAssetCollection){
  140. PHPhotoLibrary.shared().performChanges({
  141. var assetChangeRequest: PHAssetChangeRequest? = nil
  142. if isVideo == true {
  143. assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: url)
  144. } else {
  145. assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: url)
  146. }
  147. if let assetPlaceHolder = assetChangeRequest?.placeholderForCreatedAsset {
  148. if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection) {
  149. let enumeration: NSArray = [assetPlaceHolder]
  150. albumChangeRequest.addAssets(enumeration)
  151. }
  152. }
  153. }, completionHandler: { (success, error) in
  154. if success {
  155. DDLogNotice(self.successMessage)
  156. completionHandler(true)
  157. } else {
  158. guard let err = error else {
  159. DDLogError(self.generalError)
  160. return
  161. }
  162. DDLogError(self.writeErrorMessage + "\(err.localizedDescription)")
  163. completionHandler(false)
  164. }
  165. })
  166. }
  167. self.checkAuthorizationWithHandler { (authorizationState) in
  168. if authorizationState == .full {
  169. if let validAssets = self.assetCollection { // Album already exists
  170. saveIt(validAssets)
  171. } else {
  172. PHPhotoLibrary.shared().performChanges({
  173. PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: AlbumManager.albumName) // create an asset collection with the album name
  174. }) { success, error in
  175. if success, let validAssets = self.fetchAssetCollectionForAlbum() {
  176. self.assetCollection = validAssets
  177. saveIt(validAssets)
  178. } else {
  179. guard let err = error else {
  180. DDLogError(self.generalError)
  181. return
  182. }
  183. DDLogError(self.writeErrorMessage + "\(err.localizedDescription)")
  184. }
  185. }
  186. }
  187. } else if authorizationState == .write || authorizationState == .potentialWrite {
  188. if isVideo {
  189. self.saveMovieFromURL(movieURL: url)
  190. } else {
  191. guard let data = try? Data(contentsOf: url) else {
  192. DDLogError(self.writeErrorMessage)
  193. return
  194. }
  195. let image = UIImage(data: data)!
  196. UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.savedImage), nil)
  197. }
  198. } else {
  199. DDLogNotice(self.permissionNotGrantedMessage)
  200. }
  201. }
  202. }
  203. @objc func saveMovieFromURL(movieURL: URL) {
  204. if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(movieURL.absoluteString) {
  205. UISaveVideoAtPathToSavedPhotosAlbum(movieURL.absoluteString, self, #selector(self.savedImage), nil)
  206. }
  207. }
  208. @objc func saveMovieToLibrary(movieURL: URL, completionHandler: @escaping ((_ success: Bool) -> Void)) {
  209. func saveIt(_ validAssets: PHAssetCollection){
  210. PHPhotoLibrary.shared().performChanges({
  211. if let assetChangeRequest = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: movieURL) {
  212. guard let assetPlaceHolder = assetChangeRequest.placeholderForCreatedAsset else {
  213. DDLogError("Could not create placeholder")
  214. return
  215. }
  216. if let albumChangeRequest = PHAssetCollectionChangeRequest(for: self.assetCollection) {
  217. let enumeration: NSArray = [assetPlaceHolder]
  218. albumChangeRequest.addAssets(enumeration)
  219. }
  220. }
  221. }, completionHandler: { (success, error) in
  222. if success {
  223. completionHandler(true)
  224. DDLogNotice("Successfully saved video to Camera Roll.")
  225. } else {
  226. completionHandler(false)
  227. DDLogError("Error writing to movie library: \(error!.localizedDescription)")
  228. }
  229. })
  230. }
  231. self.checkAuthorizationWithHandler { (authorizationState) in
  232. if authorizationState == .full {
  233. if let validAssets = self.assetCollection { // Album already exists
  234. saveIt(validAssets)
  235. } else {
  236. PHPhotoLibrary.shared().performChanges({
  237. PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: AlbumManager.albumName) // create an asset collection with the album name
  238. }) { success, error in
  239. if success, let validAssets = self.fetchAssetCollectionForAlbum() {
  240. self.assetCollection = validAssets
  241. saveIt(validAssets)
  242. } else {
  243. guard let err = error else {
  244. DDLogError(self.generalError)
  245. return
  246. }
  247. DDLogError(self.writeErrorMessage + "\(err.localizedDescription)")
  248. }
  249. }
  250. }
  251. } else if authorizationState == .write || authorizationState == .potentialWrite {
  252. self.saveMovieFromURL(movieURL: movieURL)
  253. } else {
  254. DDLogNotice(self.permissionNotGrantedMessage)
  255. }
  256. }
  257. }
  258. }