Private
Public Access
1
0
Files
Kordophone/kordophone/Bridge/Operations/MBIMMessagesListOperation.m

99 lines
3.7 KiB
Objective-C

//
// MBIMMessagesListOperation.m
// kordophoned
//
// Created by James Magahern on 11/13/18.
// Copyright © 2018 James Magahern. All rights reserved.
//
#import "MBIMMessagesListOperation.h"
#import "MBIMHTTPUtilities.h"
#import "IMMessageItem+Encoded.h"
#import "MBIMErrorResponse.h"
#import "IMCore_ClassDump.h"
#define kDefaultMessagesLimit 75
@implementation MBIMMessagesListOperation
+ (void)load { [super load]; }
+ (NSString *)endpointName
{
return @"messages";
}
- (void)main
{
__block NSObject<HTTPResponse> *response = nil;
do {
// Required parameters
NSString *guid = [self valueForQueryItemWithName:@"guid"];
// Optional
NSString *limitValue = [self valueForQueryItemWithName:@"limit"];
NSDate *beforeDate = nil;
NSString *beforeDateValue = [self valueForQueryItemWithName:@"beforeDate"];
if (beforeDateValue) {
beforeDate = [beforeDateValue ISO8601Date];
if (!beforeDate) {
response = [[MBIMErrorResponse alloc] initWithErrorCode:500 message:@"Unable to decode ISO8601 beforeDate value"];
break;
}
}
NSString *beforeMessageGUID = [self valueForQueryItemWithName:@"beforeMessageGUID"];
if (!guid) {
response = [[MBIMErrorResponse alloc] initWithErrorCode:500 message:@"No GUID provided."];
break;
}
__block NSMutableArray *messages = [NSMutableArray array];
dispatch_sync([[self class] sharedIMAccessQueue], ^{
IMChat *chat = [[IMChatRegistry sharedInstance] existingChatWithGUID:guid];
if (!chat) {
MBIMLogInfo(@"Chat with guid: %@ not found", guid);
response = [[HTTPErrorResponse alloc] initWithErrorCode:500];
} else {
// Load messages
// (Must be done on main queue for some reason)
dispatch_sync(dispatch_get_main_queue(), ^{
NSUInteger limit = kDefaultMessagesLimit;
if (limitValue) {
limit = [limitValue integerValue];
}
if (beforeMessageGUID) {
if ([chat respondsToSelector:@selector(loadMessagesBeforeAndAfterGUID:numberOfMessagesToLoadBeforeGUID:numberOfMessagesToLoadAfterGUID:loadImmediately:threadIdentifier:)]) {
[chat loadMessagesBeforeAndAfterGUID:beforeMessageGUID numberOfMessagesToLoadBeforeGUID:limit numberOfMessagesToLoadAfterGUID:0 loadImmediately:YES threadIdentifier:nil];
} else {
[chat loadMessagesBeforeAndAfterGUID:beforeMessageGUID numberOfMessagesToLoadBeforeGUID:limit numberOfMessagesToLoadAfterGUID:0 loadImmediately:YES];
}
} else {
[chat loadMessagesBeforeDate:beforeDate limit:limit loadImmediately:YES];
}
[[chat chatItems] enumerateMessagesWithOptions:0 usingBlock:^(IMMessage *message, BOOL *stop) {
if ([[message guid] isEqual:beforeMessageGUID]) {
*stop = YES;
return;
}
NSDictionary *messageDict = [message mbim_dictionaryRepresentation];
[messages addObject:messageDict];
}];
});
}
});
response = [MBIMJSONDataResponse responseWithJSONObject:messages];
} while (0);
self.serverCompletionBlock(response);
}
@end