EntityDestroyer.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 Foundation
  21. @objc public class EntityDestroyer: NSObject {
  22. private let objCnx: NSManagedObjectContext
  23. private let logger: ValidationLogger
  24. @objc public required init(managedObjectContext: NSManagedObjectContext) {
  25. self.objCnx = managedObjectContext
  26. self.logger = ValidationLogger.shared()
  27. }
  28. /**
  29. Delete media files of audio, file, image and video messages.
  30. - Parameters:
  31. - olderThan: All message older than that date will be deleted
  32. - Returns:
  33. Count of deleted media files
  34. */
  35. public func deleteMedias(olderThan: Date?) -> Int? {
  36. var deletedObjects: Int = 0
  37. if let count = self.deleteMediasOf(messageType: AudioMessage.self, olderThan: olderThan) {
  38. deletedObjects += count
  39. }
  40. if let count = self.deleteMediasOf(messageType: FileMessage.self, olderThan: olderThan) {
  41. deletedObjects += count
  42. }
  43. if let count = self.deleteMediasOf(messageType: ImageMessage.self, olderThan: olderThan) {
  44. deletedObjects += count
  45. }
  46. if let count = self.deleteMediasOf(messageType: VideoMessage.self, olderThan: olderThan) {
  47. deletedObjects += count
  48. }
  49. return deletedObjects
  50. }
  51. func deleteMediasOf<T :BaseMessage>(messageType: T.Type, olderThan: Date?) -> Int? {
  52. guard messageType is AudioMessage.Type || messageType is FileMessage.Type || messageType is ImageMessage.Type || messageType is VideoMessage.Type else {
  53. return nil
  54. }
  55. do {
  56. let mediaMetaInfo = try getMediaMetaInfo(messageType: messageType)
  57. if let olderThan = olderThan {
  58. mediaMetaInfo.fetchMessages.predicate = NSPredicate(format: "%K != nil AND date < %@", mediaMetaInfo.relationship, olderThan as NSDate)
  59. }
  60. else {
  61. mediaMetaInfo.fetchMessages.predicate = NSPredicate(format: "%K != nil", mediaMetaInfo.relationship)
  62. }
  63. let messages = try self.objCnx.fetch(mediaMetaInfo.fetchMessages)
  64. var deleteMediaIDs: [NSManagedObjectID] = []
  65. var updateMessageIDs: [NSManagedObjectID] = []
  66. for message in messages {
  67. if let message = message as? T {
  68. deleteMediaIDs.append(contentsOf: message.objectIDs(forRelationshipNamed: mediaMetaInfo.relationship))
  69. updateMessageIDs.append(message.objectID)
  70. }
  71. }
  72. let deleteFilenames = self.getExternalFilenames(ofMessages: messages, includeThumbnail: false)
  73. if deleteMediaIDs.count > 0 {
  74. var changes = [AnyHashable : [NSManagedObjectID]]()
  75. // Delete medias
  76. let deleteMediaBatch = NSBatchDeleteRequest(objectIDs: deleteMediaIDs)
  77. deleteMediaBatch.resultType = .resultTypeObjectIDs
  78. let deleteMediaResult = try self.objCnx.execute(deleteMediaBatch) as? NSBatchDeleteResult
  79. if let deletedIDs = deleteMediaResult?.result as? [NSManagedObjectID] {
  80. changes[NSDeletedObjectsKey] = deletedIDs
  81. }
  82. // Update blobIDs to nil (to prevent downloading blob again)
  83. if updateMessageIDs.count > 0 {
  84. var updatedIDs: [NSManagedObjectID] = []
  85. for updateID in updateMessageIDs {
  86. if let updateMessage = try self.objCnx.existingObject(with: updateID) as? T {
  87. if updateMessage.value(forKey: mediaMetaInfo.blobIDField) != nil {
  88. self.objCnx.performAndWait {
  89. updateMessage.setValue(nil, forKey: mediaMetaInfo.blobIDField)
  90. do {
  91. try self.objCnx.save()
  92. updatedIDs.append(updateID)
  93. }
  94. catch let error as NSError {
  95. self.logger.logString("Cloud not update message. \(error), \(error.userInfo)")
  96. }
  97. }
  98. }
  99. }
  100. }
  101. changes[NSUpdatedObjectsKey] = updatedIDs
  102. }
  103. if changes.count > 0 {
  104. let dbManager = DatabaseManager()
  105. dbManager.refreshDirtyObjectIDs(changes, into:self.objCnx)
  106. }
  107. self.deleteExternalFiles(list: deleteFilenames)
  108. }
  109. return messages.count
  110. }
  111. catch let error as NSError {
  112. self.logger.logString("Could not delete medias. \(error), \(error.userInfo)")
  113. }
  114. return 0;
  115. }
  116. /**
  117. Delete all kind of messages.
  118. - Parameters:
  119. - olderThan: All message older than that date will be deleted
  120. - Returns:
  121. Count of deleted messages
  122. */
  123. public func deleteMessages(olderThan: Date?) -> Int? {
  124. do {
  125. let fetchMessages = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
  126. if let olderThan = olderThan {
  127. fetchMessages.predicate = NSPredicate(format: "date < %@", olderThan as NSDate)
  128. }
  129. let messages = try self.objCnx.fetch(fetchMessages)
  130. let deleteFilenames = self.getExternalFilenames(ofMessages: messages, includeThumbnail: true)
  131. let batch = NSBatchDeleteRequest(fetchRequest: fetchMessages)
  132. batch.resultType = NSBatchDeleteRequestResultType.resultTypeObjectIDs
  133. let deleteResult = try self.objCnx.execute(batch) as? NSBatchDeleteResult
  134. if let deletedIDs = deleteResult?.result as? [NSManagedObjectID] {
  135. let dbManager = DatabaseManager()
  136. dbManager.refreshDirtyObjectIDs([NSDeletedObjectsKey: deletedIDs], into:self.objCnx)
  137. self.deleteExternalFiles(list: deleteFilenames)
  138. return deletedIDs.count
  139. }
  140. return nil
  141. }
  142. catch let error as NSError {
  143. self.logger.logString("Could not delete messages. \(error), \(error.userInfo)")
  144. }
  145. return nil
  146. }
  147. /**
  148. Delete all kind of messages within conversation.
  149. - Parameters:
  150. - ofConversation: Delete all message of this conversation
  151. - Returns:
  152. Count of deleted messages
  153. */
  154. @objc public func deleteMessages(ofCoversation: Conversation) -> Int {
  155. do {
  156. let fetchMessages = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
  157. fetchMessages.predicate = NSPredicate(format: "conversation = %@", ofCoversation)
  158. let messages = try self.objCnx.fetch(fetchMessages)
  159. let deleteFilenames = self.getExternalFilenames(ofMessages: messages, includeThumbnail: true)
  160. let batch = NSBatchDeleteRequest(fetchRequest: fetchMessages)
  161. batch.resultType = NSBatchDeleteRequestResultType.resultTypeObjectIDs
  162. let deleteResult = try self.objCnx.execute(batch) as? NSBatchDeleteResult
  163. if let deletedIDs = deleteResult?.result as? [NSManagedObjectID] {
  164. let dbManager = DatabaseManager()
  165. dbManager.refreshDirtyObjectIDs([NSDeletedObjectsKey: deletedIDs], into:self.objCnx)
  166. self.deleteExternalFiles(list: deleteFilenames)
  167. return deletedIDs.count
  168. }
  169. return 0
  170. }
  171. catch let error as NSError {
  172. self.logger.logString("Could not delete messages. \(error), \(error.userInfo)")
  173. }
  174. return 0
  175. }
  176. /**
  177. Delete particular DB object.
  178. - Parameters:
  179. - object: object to delete
  180. */
  181. @objc public func deleteObject(object: NSManagedObject) {
  182. if let conversation = object as? Conversation {
  183. let count = deleteMessages(ofCoversation: conversation)
  184. print("\(count) messages deleted from conversation")
  185. }
  186. let deleteFilenames = self.getExternalFilenames(ofMessages: [object], includeThumbnail: true)
  187. self.objCnx.delete(object)
  188. self.deleteExternalFiles(list: deleteFilenames)
  189. }
  190. private func getMediaMetaInfo<T: Any>(messageType: T.Type) throws -> (fetchMessages: NSFetchRequest<NSManagedObject>, relationship: String, blobIDField: String) {
  191. var fetchMessages: NSFetchRequest<NSManagedObject>
  192. var relationship: String
  193. var blobIDField: String
  194. if messageType is AudioMessage.Type {
  195. fetchMessages = NSFetchRequest<NSManagedObject>(entityName: "AudioMessage")
  196. relationship = "audio"
  197. blobIDField = "audioBlobId"
  198. }
  199. else if messageType is FileMessage.Type {
  200. fetchMessages = NSFetchRequest<NSManagedObject>(entityName: "FileMessage")
  201. relationship = "data"
  202. blobIDField = "blobId"
  203. }
  204. else if messageType is ImageMessage.Type {
  205. fetchMessages = NSFetchRequest<NSManagedObject>(entityName: "ImageMessage")
  206. relationship = "image"
  207. blobIDField = "imageBlobId"
  208. }
  209. else if messageType is VideoMessage.Type {
  210. fetchMessages = NSFetchRequest<NSManagedObject>(entityName: "VideoMessage")
  211. relationship = "video"
  212. blobIDField = "videoBlobId"
  213. }
  214. else {
  215. fatalError("message type not defined")
  216. }
  217. return (fetchMessages, relationship, blobIDField)
  218. }
  219. /**
  220. List names of external files.
  221. - Parameters:
  222. - ofMessages: Check messages to external data files
  223. - includeThumbnail: Check messages to external thumbnail files
  224. - Returns: Names of external files
  225. */
  226. private func getExternalFilenames(ofMessages: [Any], includeThumbnail: Bool) -> [String] {
  227. var externalFilenames: [String] = []
  228. for message in ofMessages {
  229. if let externalStorageInfo = message as? ExternalStorageInfo {
  230. // Refreshing media objects, otherwise external filenames can not be evaluated for new messages
  231. let mediaMetaInfo: (fetchMessages: NSFetchRequest<NSManagedObject>, relationship: String, blobIDField: String)?
  232. switch message {
  233. case is AudioMessage:
  234. mediaMetaInfo = try? getMediaMetaInfo(messageType: AudioMessage.self)
  235. case is FileMessage:
  236. mediaMetaInfo = try? getMediaMetaInfo(messageType: FileMessage.self)
  237. case is ImageMessage:
  238. mediaMetaInfo = try? getMediaMetaInfo(messageType: ImageMessage.self)
  239. case is VideoMessage:
  240. mediaMetaInfo = try? getMediaMetaInfo(messageType: VideoMessage.self)
  241. default:
  242. mediaMetaInfo = nil
  243. }
  244. if let relationship = mediaMetaInfo?.relationship,
  245. let message = message as? NSManagedObject {
  246. var mediaIDs = [NSManagedObjectID]()
  247. mediaIDs.append(contentsOf: message.objectIDs(forRelationshipNamed: relationship))
  248. for mediaId in mediaIDs {
  249. if let mediaObj = try? objCnx.existingObject(with: mediaId) {
  250. objCnx.refresh(mediaObj, mergeChanges: true)
  251. }
  252. }
  253. }
  254. // Get external file name
  255. if let filename = externalStorageInfo.getFilename() {
  256. externalFilenames.append(filename)
  257. }
  258. if includeThumbnail,
  259. let thumbnailname = externalStorageInfo.getThumbnailname?() {
  260. externalFilenames.append(thumbnailname)
  261. }
  262. }
  263. }
  264. return externalFilenames;
  265. }
  266. /**
  267. Delete external files.
  268. - Parameters:
  269. - list: List of filenames to delete
  270. */
  271. private func deleteExternalFiles(list: [String]) {
  272. if list.count > 0 {
  273. for filename in list {
  274. let fileUrl = FileUtility.appDataDirectory?.appendingPathComponent(".ThreemaData_SUPPORT/_EXTERNAL_DATA/\(filename)")
  275. FileUtility.delete(fileUrl: fileUrl)
  276. }
  277. }
  278. }
  279. }