EntityFetcher.m 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2014-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 "EntityFetcher.h"
  21. #import "DatabaseManager.h"
  22. #import "AbstractGroupMessage.h"
  23. #import "MyIdentityStore.h"
  24. #import "Contact.h"
  25. #import "UserSettings.h"
  26. #import "BaseMessage.h"
  27. #import "BundleUtil.h"
  28. #import "TextMessage.h"
  29. #import "LicenseStore.h"
  30. #import "NonceHasher.h"
  31. #ifdef DEBUG
  32. static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
  33. #else
  34. static const DDLogLevel ddLogLevel = DDLogLevelWarning;
  35. #endif
  36. @interface EntityFetcher ()
  37. @property NSManagedObjectContext *managedObjectContext;
  38. @end
  39. @implementation EntityFetcher
  40. /*
  41. - (instancetype)init
  42. {
  43. self = [super init];
  44. if (self) {
  45. _managedObjectContext = [[DatabaseManager dbManager] getManagedObjectContext:![NSThread isMainThread]];
  46. }
  47. return self;
  48. }
  49. */
  50. - (instancetype)initWith:(NSManagedObjectContext *) managedObjectContext {
  51. self = [super init];
  52. if (self) {
  53. _managedObjectContext = managedObjectContext;
  54. }
  55. return self;
  56. }
  57. - (id)getManagedObjectById:(NSManagedObjectID *)objectID {
  58. return [_managedObjectContext objectWithID: objectID];
  59. }
  60. - (BaseMessage *)ownMessageWithId:(NSData *)messageId {
  61. return [self singleEntityNamed:@"Message" withPredicate: @"id == %@ AND isOwn == YES", messageId];
  62. }
  63. - (BaseMessage *)messageWithId:(NSData *)messageId {
  64. return [self singleEntityNamed:@"Message" withPredicate: @"id == %@", messageId];
  65. }
  66. - (BaseMessage *)messageWithId:(NSData *)messageId conversation:(Conversation *)conversation {
  67. return [self singleEntityNamed:@"Message" withPredicate: @"id == %@ AND conversation == %@", messageId, conversation];
  68. }
  69. - (NSArray *)quoteMessagesContaining:(NSString *)searchText message:(BaseMessage *)message inConversation:(Conversation *)conversation {
  70. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
  71. NSArray *textMessages = [self entitiesNamed:@"TextMessage" fetchLimit:0 sortedBy:sortDescriptors withPredicate: @"text contains[cd] %@ AND conversation == %@ && date < %@", searchText, conversation, message.date];
  72. NSArray *imageMessages = [self entitiesNamed:@"ImageMessage" fetchLimit:0 sortedBy:sortDescriptors withPredicate: @"conversation == %@ && date < %@", conversation, message.date];
  73. NSArray *fileMessages = [self entitiesNamed:@"FileMessage" fetchLimit:0 sortedBy:sortDescriptors withPredicate: @"conversation == %@ && date < %@", conversation, message.date];
  74. NSArray *locationMessages = [self entitiesNamed:@"LocationMessage" fetchLimit:0 sortedBy:sortDescriptors withPredicate: @"conversation == %@ && date < %@", conversation, message.date];
  75. if (imageMessages.count > 0 || fileMessages.count > 0 || locationMessages.count > 0) {
  76. NSMutableArray *allMessages = [NSMutableArray arrayWithArray:textMessages];
  77. [allMessages addObjectsFromArray:imageMessages];
  78. [allMessages addObjectsFromArray:fileMessages];
  79. [allMessages addObjectsFromArray:locationMessages];
  80. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
  81. [allMessages sortUsingDescriptors:(NSArray *)sortDescriptors];
  82. return allMessages;
  83. } else {
  84. return textMessages;
  85. }
  86. }
  87. - (NSArray *)messagesContaining:(NSString *)searchText inConversation:(Conversation *)conversation {
  88. NSArray *textMessages = [self textMessagesContaining:searchText inConversation:conversation fetchLimit:0];
  89. NSArray *ballotMessages = [self ballotMessagesContaining:searchText inConversation:conversation fetchLimit:0];
  90. NSArray *fileMessages = [self fileMessagesContaining:searchText inConversation:conversation fetchLimit:0];
  91. if ([ballotMessages count] > 0 || [fileMessages count] > 0) {
  92. NSMutableArray *allMessages = [NSMutableArray arrayWithArray:textMessages];
  93. [allMessages addObjectsFromArray:ballotMessages];
  94. [allMessages addObjectsFromArray:fileMessages];
  95. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
  96. [allMessages sortUsingDescriptors:(NSArray *)sortDescriptors];
  97. return allMessages;
  98. } else {
  99. return textMessages;
  100. }
  101. }
  102. - (NSArray *)textMessagesContaining:(NSString *)searchText inConversation:(Conversation *)conversation fetchLimit:(NSInteger)fetchLimit {
  103. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
  104. return [self entitiesNamed:@"TextMessage" fetchLimit:fetchLimit sortedBy:sortDescriptors withPredicate: @"text contains[cd] %@ AND conversation == %@", searchText, conversation];
  105. }
  106. - (NSArray *)ballotMessagesContaining:(NSString *)searchText inConversation:(Conversation *)conversation fetchLimit:(NSInteger)fetchLimit {
  107. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
  108. return [self entitiesNamed:@"BallotMessage" fetchLimit:fetchLimit sortedBy:sortDescriptors withPredicate: @"ballot.title contains[cd] %@ AND conversation == %@", searchText, conversation];
  109. }
  110. - (NSArray *)fileMessagesContaining:(NSString *)searchText inConversation:(Conversation *)conversation fetchLimit:(NSInteger)fetchLimit {
  111. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO]];
  112. return [self entitiesNamed:@"FileMessage" fetchLimit:fetchLimit sortedBy:sortDescriptors withPredicate: @"fileName contains[cd] %@ AND conversation == %@", searchText, conversation];
  113. }
  114. - (Conversation *)conversationForGroupId:(NSData *)groupId {
  115. return [self singleEntityNamed:@"Conversation" withPredicate: @"groupId == %@", groupId];
  116. }
  117. - (Conversation *)conversationForContact:(Contact *)contact {
  118. return [self singleEntityNamed:@"Conversation" withPredicate: @"contact == %@ AND groupId == nil", contact];
  119. }
  120. - (Conversation *)conversationForIdentity:(NSString *)identity {
  121. return [self singleEntityNamed:@"Conversation" withPredicate: @"contact.identity == %@ AND groupId == nil", identity];
  122. }
  123. - (NSArray *)conversationsForMember:(Contact *)contact {
  124. return [self allEntitiesNamed:@"Conversation" sortedBy:nil withPredicate: @"%@ IN members", contact];
  125. }
  126. - (Conversation *)conversationForGroupMessage:(AbstractGroupMessage *)message {
  127. /* is this a group that we started? */
  128. if ([message.groupCreator isEqualToString:[MyIdentityStore sharedMyIdentityStore].identity]) {
  129. return [self singleEntityNamed:@"Conversation" withPredicate: @"contact == nil AND groupId == %@", message.groupId];
  130. } else {
  131. return [self singleEntityNamed:@"Conversation" withPredicate: @"contact.identity == %@ AND groupId == %@", message.groupCreator, message.groupId];
  132. }
  133. }
  134. - (Contact *)contactForId:(NSString *)identity {
  135. return [self singleEntityNamed:@"Contact" withPredicate: @"identity == %@", identity];
  136. }
  137. - (Contact *)contactForId:(NSString *)identity error:(NSError **)error {
  138. NSError *err;
  139. Contact *contact = [self singleEntityNamed:@"Contact" error:&err withPredicate:@"identity == %@", identity];
  140. if (err) {
  141. *error = err;
  142. return nil;
  143. } else {
  144. return contact;
  145. }
  146. }
  147. - (NSArray *)allContacts {
  148. return [self allEntitiesNamed:@"Contact" sortedBy:nil withPredicate:nil];
  149. }
  150. - (NSArray *)allGatewayContacts {
  151. return [self allEntitiesNamed:@"Contact" sortedBy:nil withPredicate: @"identity beginswith '*'"];
  152. }
  153. - (NSArray *)contactsWithVerificationLevel:(NSInteger)verificationLevel {
  154. return [self allEntitiesNamed:@"Contact" sortedBy:nil withPredicate: @"verificationLevel == %@", [NSNumber numberWithInteger:verificationLevel]];
  155. }
  156. - (NSArray *)contactsWithFeatureMaskNil {
  157. return [self allEntitiesNamed:@"Contact" sortedBy:nil withPredicate: @"featureLevel == nil"];
  158. }
  159. - (NSArray *)contactsFilteredByWords:(NSArray *)searchWords {
  160. NSMutableArray *predicates = [NSMutableArray array];
  161. if ([UserSettings sharedUserSettings].hideStaleContacts) {
  162. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"state == %d", kStateActive];
  163. [predicates addObject:predicate];
  164. }
  165. for (NSString *searchWord in searchWords) {
  166. if (searchWord.length > 0) {
  167. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName contains[cd] %@ or lastName contains[cd] %@ or identity contains[c] %@ or publicNickname contains[cd] %@", searchWord, searchWord, searchWord, searchWord];
  168. [predicates addObject:predicate];
  169. }
  170. }
  171. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Contact"];
  172. [fetchRequest setFetchBatchSize:100];
  173. [fetchRequest setPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:predicates]];
  174. NSArray *sortDescriptors = [self nameSortDescriptors];
  175. [fetchRequest setSortDescriptors:sortDescriptors];
  176. return [self executeFetchRequest:fetchRequest];
  177. }
  178. - (NSArray *)contactsFilteredByWords:(NSArray *)searchWords forContactTypes:(ContactTypes)types list:(ContactList)contactList members:(NSMutableSet *)members {
  179. NSMutableArray *predicates = [NSMutableArray array];
  180. if (types == ContactsNoGateway) {
  181. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not identity beginswith '*'"];
  182. [predicates addObject:predicate];
  183. } else if (types == ContactsNoEchoEcho) {
  184. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not identity beginswith 'ECHOECHO'"];
  185. [predicates addObject:predicate];
  186. }
  187. else if (types == ContactsGatewayOnly) {
  188. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"identity beginswith '*'"];
  189. [predicates addObject:predicate];
  190. } else if (types == ContactsNoGatewayNoEchoecho) {
  191. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not identity beginswith '*'"];
  192. [predicates addObject:predicate];
  193. predicate = [NSPredicate predicateWithFormat:@"not identity BEGINSWITH 'ECHOECHO'"];
  194. [predicates addObject:predicate];
  195. }
  196. if ([UserSettings sharedUserSettings].hideStaleContacts) {
  197. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"state == %d", kStateActive];
  198. [predicates addObject:predicate];
  199. }
  200. if (contactList == ContactListWork) {
  201. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"workContact == %@", @1];
  202. [predicates addObject:predicate];
  203. } else {
  204. if (contactList == ContactListContacts) {
  205. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"workContact == %@", @0];
  206. [predicates addObject:predicate];
  207. }
  208. }
  209. for (NSString *searchWord in searchWords) {
  210. if (searchWord.length > 0) {
  211. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstName contains[cd] %@ or lastName contains[cd] %@ or identity contains[c] %@ or publicNickname contains[cd] %@", searchWord, searchWord, searchWord, searchWord];
  212. [predicates addObject:predicate];
  213. }
  214. }
  215. NSMutableArray *allPredicates = [NSMutableArray array];
  216. [allPredicates addObject:[NSCompoundPredicate andPredicateWithSubpredicates:predicates]];
  217. if ([UserSettings sharedUserSettings].hideStaleContacts) {
  218. if (members.count > 0) {
  219. for (Contact *contact in members) {
  220. NSMutableArray *andPredicates = [NSMutableArray array];
  221. NSPredicate *memberPredicate = [NSPredicate predicateWithFormat:@"identity == %@", contact.identity];
  222. [andPredicates addObject:memberPredicate];
  223. for (NSString *searchWord in searchWords) {
  224. if (searchWord.length > 0) {
  225. NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"firstName contains[cd] %@ or lastName contains[cd] %@ or identity contains[c] %@ or publicNickname contains[cd] %@", searchWord, searchWord, searchWord, searchWord];
  226. [andPredicates addObject:searchPredicate];
  227. }
  228. }
  229. [allPredicates addObject:[NSCompoundPredicate andPredicateWithSubpredicates:andPredicates]];
  230. }
  231. }
  232. }
  233. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Contact"];
  234. [fetchRequest setFetchBatchSize:100];
  235. [fetchRequest setPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:allPredicates]];
  236. NSArray *sortDescriptors = [self nameSortDescriptors];
  237. [fetchRequest setSortDescriptors:sortDescriptors];
  238. return [self executeFetchRequest:fetchRequest];
  239. }
  240. - (NSArray *)allGroupConversations {
  241. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"groupName" ascending:YES]];
  242. return [self allEntitiesNamed:@"Conversation" sortedBy:sortDescriptors withPredicate:@"groupId != nil"];
  243. }
  244. - (NSArray *)groupConversationsForContact:(Contact *)contact {
  245. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%@ IN members", contact, contact];
  246. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Conversation"];
  247. fetchRequest.predicate = predicate;
  248. return [self executeFetchRequest:fetchRequest];
  249. }
  250. - (NSArray *)groupConversationsFilteredByWords:(NSArray *)searchWords {
  251. NSMutableArray *predicates = [NSMutableArray array];
  252. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"groupId != nil"];
  253. [predicates addObject:predicate];
  254. for (NSString *searchWord in searchWords) {
  255. if (searchWord.length > 0) {
  256. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"groupName contains[cd] %@", searchWord];
  257. [predicates addObject:predicate];
  258. }
  259. }
  260. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Conversation"];
  261. [fetchRequest setFetchBatchSize:100];
  262. [fetchRequest setPredicate:[NSCompoundPredicate andPredicateWithSubpredicates:predicates]];
  263. return [self executeFetchRequest:fetchRequest];
  264. }
  265. - (NSArray *)allConversations {
  266. return [self allEntitiesNamed:@"Conversation" sortedBy:nil withPredicate:nil];
  267. }
  268. - (NSArray *)allConversationsSorted {
  269. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"marked" ascending:NO], [NSSortDescriptor sortDescriptorWithKey:@"lastMessage.date" ascending:NO]];
  270. return [self allEntitiesNamed:@"Conversation" sortedBy:sortDescriptors withPredicate:nil];
  271. }
  272. - (NSArray *)conversationsWithNegativeUnreadMessageCount {
  273. return [self allEntitiesNamed:@"Conversation" sortedBy:nil withPredicate:@"unreadMessageCount == %@", [NSNumber numberWithInt:-1]];
  274. }
  275. - (NSString *)displayNameForContactId:(NSString *)identity {
  276. /* Is this our own identity? */
  277. if ([identity isEqual:[MyIdentityStore sharedMyIdentityStore].identity])
  278. return [BundleUtil localizedStringForKey:@"me"];
  279. Contact *contact = [self contactForId:identity];
  280. if (contact == nil) {
  281. return identity;
  282. }
  283. return contact.displayName;
  284. }
  285. - (Ballot *)ballotForBallotId:(NSData *)ballotId {
  286. return [self singleEntityNamed:@"Ballot" withPredicate: @"id == %@", ballotId];
  287. }
  288. - (NSInteger)countBallotsForConversation:(Conversation *)conversation {
  289. return [self countEntityNamed:@"Ballot" withPredicate:@"conversation == %@", conversation];
  290. }
  291. - (NSInteger)countOpenBallotsForConversation:(Conversation *)conversation {
  292. return [self countEntityNamed:@"Ballot" withPredicate:@"conversation == %@ && state == %d", conversation, kBallotStateOpen];
  293. }
  294. - (NSInteger)countMediaMessagesForConversation:(Conversation *)conversation {
  295. NSInteger numImages = [self countEntityNamed:@"ImageMessage" withPredicate:@"conversation == %@", conversation];
  296. NSInteger numVideos = [self countEntityNamed:@"VideoMessage" withPredicate:@"conversation == %@", conversation];
  297. NSInteger numFiles = [self countEntityNamed:@"FileMessage" withPredicate:@"conversation == %@", conversation];
  298. return numImages + numVideos + numFiles;
  299. }
  300. - (NSArray *)imageMessagesForConversation:(Conversation *)conversation {
  301. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
  302. return [self allEntitiesNamed:@"ImageMessage" sortedBy:sortDescriptors withPredicate:@"conversation == %@", conversation];
  303. }
  304. - (NSArray *)videoMessagesForConversation:(Conversation *)conversation {
  305. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
  306. return [self allEntitiesNamed:@"VideoMessage" sortedBy:sortDescriptors withPredicate:@"conversation == %@", conversation];
  307. }
  308. - (NSArray *)fileMessagesForConversation:(Conversation *)conversation {
  309. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
  310. return [self allEntitiesNamed:@"FileMessage" sortedBy:sortDescriptors withPredicate:@"conversation == %@", conversation];
  311. }
  312. - (NSArray *)fileMessagesWOStickersForConversation:(Conversation *)conversation {
  313. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]];
  314. return [self allEntitiesNamed:@"FileMessage" sortedBy:sortDescriptors withPredicate:@"(conversation == %@) AND (type != 2)", conversation];
  315. }
  316. - (BallotChoice *)ballotChoiceForBallotId:(NSData *)ballotId choiceId:(NSNumber *)choiceId {
  317. return [self singleEntityNamed:@"BallotChoice" withPredicate: @"id == %@ AND ballot.id == %@", choiceId, ballotId];
  318. }
  319. - (BOOL)isMessageAlreadyInDb:(AbstractMessage *)message {
  320. id result;
  321. if ([message isKindOfClass:[AbstractGroupMessage class]]) {
  322. result = [self singleEntityNamed:@"Message" withPredicate:@"id == %@ AND sender.identity == %@",
  323. message.messageId, message.fromIdentity];
  324. } else {
  325. result = [self singleEntityNamed:@"Message" withPredicate:@"id == %@ AND conversation.contact.identity == %@",
  326. message.messageId, message.fromIdentity];
  327. }
  328. return result != nil;
  329. }
  330. - (BOOL)isNonceAlreadyInDb:(AbstractMessage *)message {
  331. id result;
  332. NSData *hashedNonce = [NonceHasher hashedNonce:message.nonce];
  333. result = [self singleEntityNamed:@"Nonce" withPredicate:@"nonce == %@ OR nonce == %@", message.nonce, hashedNonce];
  334. return result != nil;
  335. }
  336. - (Group *)groupForGroupId:(NSData *)groupId groupCreator:(NSString *)groupCreator {
  337. return [self singleEntityNamed:@"Group" withPredicate: @"groupId == %@ AND groupCreator == %@", groupId, groupCreator];
  338. }
  339. - (Group *)groupForConversation:(Conversation *)conversation {
  340. /* is this a group that we started? */
  341. if (conversation.isGroup) {
  342. if (conversation.contact) {
  343. return [self singleEntityNamed:@"Group" withPredicate: @"groupId == %@ AND groupCreator == %@", conversation.groupId, conversation.contact.identity];
  344. } else {
  345. return [self singleEntityNamed:@"Group" withPredicate: @"groupId == %@ AND groupCreator == nil", conversation.groupId];
  346. }
  347. }
  348. return nil;
  349. }
  350. - (LastGroupSyncRequest *)lastGroupSyncRequestFor:(NSData *)groupId groupCreator:(NSString *)groupCreator sinceDate:(NSDate *)sinceDate {
  351. return [self singleEntityNamed:@"LastGroupSyncRequest" withPredicate: @"groupId == %@ AND groupCreator == %@ AND lastSyncRequest >= %@", groupId, groupCreator, sinceDate];
  352. }
  353. - (NSFetchRequest *)fetchRequestForEntity:(NSString *)entityName {
  354. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  355. fetchRequest.entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:_managedObjectContext];
  356. return fetchRequest;
  357. }
  358. - (NSArray *)executeFetchRequest:(NSFetchRequest *)fetchRequest {
  359. __block NSError *error;
  360. __block NSArray *result;
  361. [_managedObjectContext performBlockAndWait:^{
  362. result = [_managedObjectContext executeFetchRequest:fetchRequest error:&error];
  363. }];
  364. if (result == nil) {
  365. DDLogError(@"Error in fetch request: %@, %@", error, [error userInfo]);
  366. return nil;
  367. } else {
  368. return result;
  369. }
  370. }
  371. - (NSInteger)executeCountFetchRequest:(NSFetchRequest *)fetchRequest {
  372. __block NSError *error;
  373. __block NSUInteger count;
  374. [_managedObjectContext performBlockAndWait:^{
  375. count = [_managedObjectContext countForFetchRequest:fetchRequest error:&error];
  376. }];
  377. if (count != NSNotFound) {
  378. return count;
  379. } else {
  380. return 0;
  381. }
  382. }
  383. - (NSArray *)nameSortDescriptors {
  384. NSArray *sortDescriptors;
  385. if ([UserSettings sharedUserSettings].sortOrderFirstName) {
  386. sortDescriptors = @[
  387. [NSSortDescriptor sortDescriptorWithKey:@"sortIndex" ascending:YES],
  388. [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES selector:@selector(localizedStandardCompare:)],
  389. [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES selector:@selector(localizedStandardCompare:)],
  390. [NSSortDescriptor sortDescriptorWithKey:@"publicNickname" ascending:YES selector:@selector(localizedStandardCompare:)]
  391. ];
  392. } else {
  393. sortDescriptors = @[
  394. [NSSortDescriptor sortDescriptorWithKey:@"sortIndex" ascending:YES],
  395. [NSSortDescriptor sortDescriptorWithKey:@"lastName" ascending:YES selector:@selector(localizedStandardCompare:)],
  396. [NSSortDescriptor sortDescriptorWithKey:@"firstName" ascending:YES selector:@selector(localizedStandardCompare:)],
  397. [NSSortDescriptor sortDescriptorWithKey:@"publicNickname" ascending:YES selector:@selector(localizedStandardCompare:)]
  398. ];
  399. }
  400. return sortDescriptors;
  401. }
  402. - (NSFetchedResultsController *)fetchedResultsControllerForContactTypes:(ContactTypes)types list:(ContactList)contactList members:(NSMutableSet *)members {
  403. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  404. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:_managedObjectContext];
  405. [fetchRequest setEntity:entity];
  406. [fetchRequest setFetchBatchSize:100];
  407. NSMutableArray *predicates = [NSMutableArray array];
  408. if (types == ContactsNoGateway) {
  409. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not identity beginswith '*'"];
  410. [predicates addObject:predicate];
  411. } else if (types == ContactsNoEchoEcho) {
  412. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not identity beginswith 'ECHOECHO'"];
  413. [predicates addObject:predicate];
  414. } else if (types == ContactsGatewayOnly) {
  415. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"identity beginswith '*'"];
  416. [predicates addObject:predicate];
  417. } else if (types == ContactsNoGatewayNoEchoecho) {
  418. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"not identity beginswith '*'"];
  419. [predicates addObject:predicate];
  420. predicate = [NSPredicate predicateWithFormat:@"not identity beginswith 'ECHOECHO'"];
  421. [predicates addObject:predicate];
  422. }
  423. if ([UserSettings sharedUserSettings].hideStaleContacts) {
  424. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"state == %d", kStateActive];
  425. [predicates addObject:predicate];
  426. }
  427. if (contactList == ContactListWork) {
  428. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"workContact == %@ ", @1];
  429. [predicates addObject:predicate];
  430. } else {
  431. if (contactList == ContactListContactsAndWork) {
  432. // do not predicate for work contacts
  433. } else {
  434. if ([LicenseStore requiresLicenseKey]) {
  435. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"workContact == %@ ", @0];
  436. [predicates addObject:predicate];
  437. }
  438. }
  439. }
  440. NSMutableArray *allPredicates = [NSMutableArray array];
  441. [allPredicates addObject:[NSCompoundPredicate andPredicateWithSubpredicates:predicates]];
  442. if ([UserSettings sharedUserSettings].hideStaleContacts) {
  443. if (members.count > 0) {
  444. for (Contact *contact in members) {
  445. NSPredicate *memberPredicate = [NSPredicate predicateWithFormat:@"identity == %@", contact.identity];
  446. [allPredicates addObject:memberPredicate];
  447. }
  448. }
  449. }
  450. [fetchRequest setPredicate:[NSCompoundPredicate orPredicateWithSubpredicates:allPredicates]];
  451. NSArray *sortDescriptors = [self nameSortDescriptors];
  452. [fetchRequest setSortDescriptors:sortDescriptors];
  453. NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:@"sortIndex" cacheName:nil];
  454. return fetchedResultsController;
  455. }
  456. - (NSFetchedResultsController *)fetchedResultsControllerForGroups {
  457. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  458. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Conversation" inManagedObjectContext:_managedObjectContext];
  459. [fetchRequest setEntity:entity];
  460. [fetchRequest setFetchBatchSize:20];
  461. fetchRequest.predicate = [NSPredicate predicateWithFormat:@"groupId != nil"];
  462. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"groupName" ascending:YES]];
  463. [fetchRequest setSortDescriptors:sortDescriptors];
  464. NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:nil];
  465. return fetchedResultsController;
  466. }
  467. - (NSFetchedResultsController *)fetchedResultsControllerForConversations {
  468. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  469. NSEntityDescription *entity = [NSEntityDescription entityForName:@"Conversation" inManagedObjectContext:_managedObjectContext];
  470. [fetchRequest setEntity:entity];
  471. [fetchRequest setFetchBatchSize:20];
  472. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"marked" ascending:NO], [NSSortDescriptor sortDescriptorWithKey:@"lastMessage.date" ascending:NO]];
  473. [fetchRequest setSortDescriptors:sortDescriptors];
  474. NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:nil];
  475. return fetchedResultsController;
  476. }
  477. - (NSFetchedResultsController *)fetchedResultsControllerForWebClientSessions {
  478. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  479. NSEntityDescription *entity = [NSEntityDescription entityForName:@"WebClientSession" inManagedObjectContext:_managedObjectContext];
  480. [fetchRequest setEntity:entity];
  481. [fetchRequest setFetchBatchSize:20];
  482. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"active" ascending:NO], [NSSortDescriptor sortDescriptorWithKey:@"lastConnection" ascending:NO]];
  483. [fetchRequest setSortDescriptors:sortDescriptors];
  484. NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_managedObjectContext sectionNameKeyPath:nil cacheName:nil];
  485. return fetchedResultsController;
  486. }
  487. - (WebClientSession *)webClientSessionForInitiatorPermanentPublicKeyHash:(NSString *)hash {
  488. return [self singleEntityNamed:@"WebClientSession" withPredicate:@"initiatorPermanentPublicKeyHash == %@", hash];
  489. }
  490. - (WebClientSession *)webClientSessionForPrivateKey:(NSData *)privateKey {
  491. return [self singleEntityNamed:@"WebClientSession" withPredicate:@"privateKey == %@", privateKey];
  492. }
  493. - (WebClientSession *)activeWebClientSession {
  494. return [self singleEntityNamed:@"WebClientSession" withPredicate:@"active == YES"];
  495. }
  496. - (NSArray *)allWebClientSessions {
  497. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"lastConnection" ascending:YES]];
  498. return [self allEntitiesNamed:@"WebClientSession" sortedBy:sortDescriptors withPredicate:nil];
  499. }
  500. - (NSArray *)allActiveWebClientSessions {
  501. NSArray *sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"lastConnection" ascending:YES]];
  502. return [self allEntitiesNamed:@"WebClientSession" sortedBy:sortDescriptors withPredicate:@"active == YES"];
  503. }
  504. - (NSArray *)allNotPermanentWebClientSessions {
  505. return [self allEntitiesNamed:@"WebClientSession" sortedBy:nil withPredicate:@"permanent == NO"];
  506. }
  507. #pragma mark - private
  508. - (NSInteger)countEntityNamed:(NSString *)name withPredicate:(NSString *) predicate, ... {
  509. va_list args;
  510. va_start(args, predicate);
  511. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  512. fetchRequest.entity = [NSEntityDescription entityForName:name inManagedObjectContext:_managedObjectContext];
  513. fetchRequest.predicate = [NSPredicate predicateWithFormat:predicate arguments: args];
  514. return [self executeCountFetchRequest: fetchRequest];
  515. }
  516. - (id)singleEntityNamed:(NSString *)name withPredicate:(NSString *) predicate, ... {
  517. va_list args;
  518. va_start(args, predicate);
  519. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  520. fetchRequest.entity = [NSEntityDescription entityForName:name inManagedObjectContext:_managedObjectContext];
  521. fetchRequest.predicate = [NSPredicate predicateWithFormat:predicate arguments: args];
  522. fetchRequest.fetchLimit = 1;
  523. NSArray *result = [self executeFetchRequest:fetchRequest];
  524. if (result != nil && [result count] > 0) {
  525. return [result objectAtIndex: 0];
  526. } else {
  527. return nil;
  528. }
  529. }
  530. - (id)singleEntityNamed:(NSString *)name error:(NSError **)error withPredicate:(NSString *) predicate, ... {
  531. va_list args;
  532. va_start(args, predicate);
  533. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  534. fetchRequest.entity = [NSEntityDescription entityForName:name inManagedObjectContext:_managedObjectContext];
  535. fetchRequest.predicate = [NSPredicate predicateWithFormat:predicate arguments: args];
  536. fetchRequest.fetchLimit = 1;
  537. NSArray *result = [self executeFetchRequest:fetchRequest];
  538. if (result == nil) {
  539. NSDictionary *userInfo = @{
  540. NSLocalizedDescriptionKey: NSLocalizedString(@"Operation was unsuccessful.", nil),
  541. NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"The operation timed out.", nil),
  542. NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Have you tried turning it off and on again?", nil)
  543. };
  544. *error = [NSError errorWithDomain:NSCocoaErrorDomain code:-57 userInfo:userInfo];
  545. return nil;
  546. } else {
  547. if ( [result count] > 0) {
  548. return [result objectAtIndex: 0];
  549. } else {
  550. return nil;
  551. }
  552. }
  553. }
  554. - (NSArray *)entitiesNamed:(NSString *)name fetchLimit:(NSInteger)fetchLimit sortedBy:(NSArray *)sortDescriptors withPredicate:(NSString *) predicate, ... {
  555. va_list args;
  556. va_start(args, predicate);
  557. return [self entitiesNamed:name fetchLimit:fetchLimit sortedBy:sortDescriptors withPredicate:predicate arguments:args];
  558. }
  559. - (NSArray *)allEntitiesNamed:(NSString *)name sortedBy:(NSArray *)sortDescriptors withPredicate:(NSString *) predicate, ... {
  560. va_list args;
  561. va_start(args, predicate);
  562. return [self entitiesNamed:name fetchLimit:0 sortedBy:sortDescriptors withPredicate:predicate arguments:args];
  563. }
  564. - (NSArray *)entitiesNamed:(NSString *)name fetchLimit:(NSInteger)fetchLimit sortedBy:(NSArray *)sortDescriptors withPredicate:(NSString *) predicate arguments:(va_list)args {
  565. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
  566. fetchRequest.entity = [NSEntityDescription entityForName:name inManagedObjectContext:_managedObjectContext];
  567. if (fetchLimit > 0) {
  568. fetchRequest.fetchLimit = fetchLimit;
  569. }
  570. if (predicate) {
  571. fetchRequest.predicate = [NSPredicate predicateWithFormat:predicate arguments: args];
  572. }
  573. if (sortDescriptors) {
  574. fetchRequest.sortDescriptors = sortDescriptors;
  575. }
  576. return [self executeFetchRequest:fetchRequest];
  577. }
  578. - (Tag *)tagForName:(NSString *)name {
  579. return [self singleEntityNamed:@"Tag" withPredicate:@"name == %@", name];
  580. }
  581. @end