Skip to content
This repository has been archived by the owner on Dec 18, 2022. It is now read-only.

Commit

Permalink
Login working
Browse files Browse the repository at this point in the history
- SKSession fills out correctly
- [SKThing unknownJSONKeys] works flawlessly :)
  • Loading branch information
NSExceptional committed Dec 24, 2015
1 parent 4e6c861 commit cbce45e
Show file tree
Hide file tree
Showing 20 changed files with 1,380 additions and 1,270 deletions.
2,176 changes: 1,098 additions & 1,078 deletions Example/Pods/Pods.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions Example/SnapchatKit-OSX/SnapchatKit-OSX/main.m
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,13 @@ int main(int argc, const char * argv[]) {
// Cannot seem to "solve" a captcha.
// registerAccount(@"[email protected]", @"12345678h", @"1995-08-01");

[SKClient sharedClient].casperAPIKey = kCasperAPIKey;
#ifdef TB_LOGIN
[SKClient sharedClient].casperAPIKey = kCasperAPIKey;
[SKClient sharedClient].casperAPISecret = kCasperAPISecret;
[SKClient sharedClient].casperUserAgent = kCasperUserAgent;
#endif

[[SKClient sharedClient] signInWithUsername:kUsername password:kPassword gmail:kGmail gpass:kGmailPassword completion:^(NSDictionary *dict, NSError *error) {
[[SKClient sharedClient] signInWithUsername:kUsername password:kPassword completion:^(NSDictionary *dict, NSError *error) {
if (!error) {
SKSession *session = [SKClient sharedClient].currentSession;
[dict writeToFile:[directory stringByAppendingPathComponent:@"current-session.plist"] atomically:YES];
Expand Down
4 changes: 3 additions & 1 deletion Pod/Classes/Categories/NSDictionary+SnapchatKit.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,6 @@

- (NSArray *)allKeyPaths;

@end
@end

#define SKMergeDictionaries(a, b) [a dictionaryByReplacingValuesForKeys: b]
6 changes: 2 additions & 4 deletions Pod/Classes/Categories/NSDictionary+SnapchatKit.m
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,8 @@ - (NSDictionary *)dictionaryByReplacingValuesForKeys:(NSDictionary *)dictionary
if (!dictionary || !dictionary.allKeys.count || !self) return self;

NSMutableDictionary *m = self.mutableCopy;
for (NSString *key in dictionary.allKeys)
m[key] = dictionary[key];

return m;
[m setValuesForKeysWithDictionary:dictionary];
return m.copy;
}

- (NSDictionary *)dictionaryByReplacingKeysWithNewKeys:(NSDictionary *)oldKeysToNewKeys {
Expand Down
10 changes: 10 additions & 0 deletions Pod/Classes/Model/SKConversation.m
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ + (NSDictionary *)JSONKeyPathsByPropertyKey {
@"pendingRecievedSnaps": @"pending_received_snaps"};
}

+ (NSArray *)ignoredJSONKeyPathPrefixes {
static NSArray *ignored = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ignored = @[@"conversation_state", @"last_snap", @"conversation_messages.messaging_auth"];
});

return ignored;
}

MTLTransformPropertyDate(lastInteraction)
MTLTransformPropertyDate(lastNotified)
MTLTransformPropertyDate(lastChatRead)
Expand Down
10 changes: 10 additions & 0 deletions Pod/Classes/Model/SKMessage.m
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,16 @@ + (NSDictionary *)JSONKeyPathsByPropertyKey {
@"type": @"chat_message.type"};
}

+ (NSArray *)ignoredJSONKeyPathPrefixes {
static NSArray *ignored = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ignored = @[@"chat_message.saved_state", @"chat_message.preservations"];
});

return ignored;
}

+ (NSValueTransformer *)messageKindJSONTransformer {
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *type, BOOL *success, NSError *__autoreleasing *error) {
return @(SKMessageKindFromString(type));
Expand Down
16 changes: 3 additions & 13 deletions Pod/Classes/Model/SKRequest.h
Original file line number Diff line number Diff line change
Expand Up @@ -58,23 +58,14 @@
This method will replace all ekeys in a request query with the given values in \c endpoints. */
+ (void)overrideEndpoints:(NSDictionary *)endpoints;

/**
@param endpoint The endpoint of the request relative to the base URL.
@param json The parameters for the request.
@param gauth Optional parameter set to the X-Snapchat-Client-Auth-Token header field.
@param token The Snapchat auth token returned from logging in. Used to set the req_token parameter for requests.
*/
+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json gauth:(NSString *)gauth token:(NSString *)token callback:(RequestBlock)callback;

/**
@param endpoint The endpoint of the request relative to the base URL.
@param json The parameters for the request.
@param httpHeaders Optional. Sets the corresponding header fields.
@param token The Snapchat auth token returned from logging in. Used to set the req_token parameter for requests.
*/
+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json headers:(NSDictionary *)httpHeaders token:(NSString *)token callback:(RequestBlock)callback;
+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json headers:(NSDictionary *)httpHeaders callback:(RequestBlock)callback;

+ (void)get:(NSString *)endpoint callback:(RequestBlock)callback;
+ (void)get:(NSString *)endpoint headers:(NSDictionary *)httpHeaders callback:(RequestBlock)callback;

+ (void)sendEvents:(NSDictionary *)eventData callback:(RequestBlock)callback;

Expand All @@ -89,11 +80,10 @@
- Content-Type
@param endpoint The endpoint to post to. Example: @"/loq/login"
@param token The token to use to generate the req_token query parameter. Defaults to kStaticToken.
@param params The JSON key-value mapping parameters of the request. Example: ?foo=bar would be @{@"foo": @"bar"}
@param httpHeaders Additional HTTP header fields to set or override. This parameter may be nil.
*/
- (id)initWithPOSTEndpoint:(NSString *)endpoint token:(NSString *)token query:(NSDictionary *)params headers:(NSDictionary *)httpHeaders ts:(NSString *)timestamp;
- (id)initWithPOSTEndpoint:(NSString *)endpoint query:(NSDictionary *)params headers:(NSDictionary *)httpHeaders;


/**
Expand Down
25 changes: 8 additions & 17 deletions Pod/Classes/Model/SKRequest.m
Original file line number Diff line number Diff line change
Expand Up @@ -87,24 +87,19 @@ + (NSError *)unknownError {

#pragma mark POST / GET

+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json gauth:(NSString *)gauth token:(NSString *)token callback:(RequestBlock)callback {
NSDictionary *headers = @{SKHeaders.clientAuthToken: [NSString stringWithFormat:@"Bearer %@", gauth]};
[self postTo:endpoint query:json headers:headers token:token callback:callback];
}

+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json headers:(NSDictionary *)httpHeaders token:(NSString *)token callback:(RequestBlock)callback {
+ (void)postTo:(NSString *)endpoint query:(NSDictionary *)json headers:(NSDictionary *)httpHeaders callback:(RequestBlock)callback {
NSParameterAssert(endpoint); NSParameterAssert(callback);

SKRequest *request = [[SKRequest alloc] initWithPOSTEndpoint:endpoint token:token query:json headers:httpHeaders ts:nil];
SKRequest *request = [[SKRequest alloc] initWithPOSTEndpoint:endpoint query:json headers:httpHeaders];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:callback];
[dataTask resume];
}

+ (void)get:(NSString *)endpoint callback:(RequestBlock)callback {
+ (void)get:(NSString *)endpoint headers:(NSDictionary *)httpHeaders callback:(RequestBlock)callback {
NSParameterAssert(endpoint); NSParameterAssert(callback);
SKRequest *request = [[SKRequest alloc] initWithGETEndpoint:endpoint headers:nil];
SKRequest *request = [[SKRequest alloc] initWithGETEndpoint:endpoint headers:httpHeaders];

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:callback];
Expand Down Expand Up @@ -140,8 +135,8 @@ - (id)initWithHeaderFields:(NSDictionary *)httpHeaders {
return self;
}

- (id)initWithPOSTEndpoint:(NSString *)endpoint token:(NSString *)token query:(NSDictionary *)params headers:(NSDictionary *)httpHeaders ts:(NSString *)timestamp {
if (!token) token = SKConsts.staticToken;
- (id)initWithPOSTEndpoint:(NSString *)endpoint query:(NSDictionary *)params headers:(NSDictionary *)httpHeaders {
NSParameterAssert(params[@"timestamp"]);
httpHeaders = SKRequestApplyHeaderOverrides(httpHeaders, endpoint);

self = [self initWithHeaderFields:httpHeaders];
Expand All @@ -152,11 +147,7 @@ - (id)initWithPOSTEndpoint:(NSString *)endpoint token:(NSString *)token query:(N
self.HTTPMethod = @"POST";

NSMutableDictionary *json = [params mutableCopy];
if (!timestamp) timestamp = [NSString timestamp];

// HTTP body
if (!json[@"req_token"]) json[@"req_token"] = [NSString hashSCString:token and:timestamp];
if (!json[@"timestamp"]) json[@"timestamp"] = @([timestamp longLongValue]);
NSString *timestamp = params[@"timestamp"];

// Set HTTPBody
// Only for uploading snaps here
Expand All @@ -176,7 +167,7 @@ - (id)initWithPOSTEndpoint:(NSString *)endpoint token:(NSString *)token query:(N

self.HTTPBody = body;
} else {
self.HTTPBody = [[NSString queryStringWithParams:json] dataUsingEncoding:NSUTF8StringEncoding];
self.HTTPBody = [[NSString queryStringWithParams:json] dataUsingEncoding:NSUTF8StringEncoding];
}

if ([endpoint isEqualToString:SKEPSnaps.loadBlob] || [endpoint isEqualToString:SKEPChat.media])
Expand Down
35 changes: 28 additions & 7 deletions Pod/Classes/Model/SKSession.m
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ + (NSDictionary *)JSONKeyPathsByPropertyKey {
@"canUseCash": @"updates_response.allowed_to_use_cash",
@"isCashActive": @"udpates_response.is_cash_active",
@"cashCustomerIdentifier": @"updates_response.cash_customer_id",
@"cashClientProperties": @"updates_response.client_properties",
@"clientProperties": @"updates_response.client_properties",
@"cashProvider": @"updates_response.cash_provider",
@"email": @"updates_response.email",
@"mobileNumber": @"updates_response.mobile",
Expand All @@ -111,7 +111,7 @@ + (NSDictionary *)JSONKeyPathsByPropertyKey {
@"recents": @"updates_response.recents",
@"requests": @"updates_response.requests",
@"addedFriendsTimestamp": @"updates_response.added_friends_timestamp",
@"auth_token": @"updates_response.auth_token",
@"authToken": @"updates_response.auth_token",
@"canSeeMatureContent": @"updates_response.can_view_mature_content",
@"countryCode": @"updates_response.countryCode",
@"devicetoken": @"updates_response.device_token",
Expand Down Expand Up @@ -151,12 +151,27 @@ + (NSDictionary *)JSONKeyPathsByPropertyKey {
@"trophyCase": @"identity_check_response.trophy_case.response",
@"serverInfo": @"server_info",
@"ringerSoundOn": @"updates_response.ringing_sound_setting",
@"payReplaySnaps": @"updates_response.feature_settings.pay_replay_snaps",
@"IAPEnabledCurrencies": @"updates_response.enabled_iap_currencies",
@"enabledLensStoreCurrencies": @"updates_response.enabled_lens_store_currencies",
@"friendmojis": @"updates_response.friendmoji_dict",
@"friendmojisReadOnly": @"updates_response.friendmoji_read_only_dict",
@"friendmojisMutable": @"updates_response.friendmoji_mutable_dict",
@"industries": @"updates_response.industries"};
@"industries": @"updates_response.industries",
@"enableGuggenheim": @"updates_response.feature_settings.guggenheim_enabled"};
}

+ (NSArray *)ignoredJSONKeyPathPrefixes {
static NSArray *ignored = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ignored = @[@"updates_response.friendmoji_dict", @"updates_response.friendmoji_read_only_dict",
@"updates_response.friendmoji_mutable_dict", @"ad_placement_metadata",
@"updates_response.study_settings", @"sponsored", @"updates_response.client_properties",
@"updates_response.targeting", @"messaging_gateway_info"];
});

return ignored;
}

+ (NSValueTransformer *)bestFriendUsernamesJSONTransformer {
Expand All @@ -167,10 +182,6 @@ + (NSValueTransformer *)bestFriendUsernamesJSONTransformer {
}];
}

+ (NSValueTransformer *)discoverSupportedJSONTransformer {
return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"supported": @YES, @"device_not_supported": @NO} defaultValue:@NO reverseDefaultValue:@"device_not_supported"];
}

MTLTransformPropertyDate(addedFriendsTimestamp)
MTLTransformPropertyDate(lastAddressBookUpdateDate)
MTLTransformPropertyDate(lastReplayedSnapDate)
Expand All @@ -181,7 +192,10 @@ + (NSValueTransformer *)addedFriendsJSONTransformer { return [self sk_modelMutab
+ (NSValueTransformer *)conversationsJSONTransformer { return [self sk_modelMutableOrderedSetTransformerForClass:[SKConversation class]]; }
+ (NSValueTransformer *)storiesJSONTransformer { return [self sk_modelMutableOrderedSetTransformerForClass:[SKStoryCollection class]]; }
+ (NSValueTransformer *)userStoriesJSONTransformer { return [self sk_modelMutableOrderedSetTransformerForClass:[SKUserStory class]]; }
+ (NSValueTransformer *)groupStoriesJSONTransformer { return [self sk_modelMutableOrderedSetTransformerForClass:[SKStory class]]; }
+ (NSValueTransformer *)trophyCaseJSONTransformer { return [self sk_modelMutableOrderedSetTransformerForClass:[SKTrophy class]]; }
+ (NSValueTransformer *)ringerSoundOnJSONTransformer { return [self sk_onOffTransformer]; }
+ (NSValueTransformer *)enableNotificationSoundsJSONTransformer { return [self sk_onOffTransformer]; }

+ (NSValueTransformer *)storyPrivacyJSONTransformer {
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *p, BOOL *success, NSError *__autoreleasing *error) {
Expand All @@ -199,6 +213,13 @@ + (NSValueTransformer *)privacyEveryoneJSONTransformer {
}];
}

+ (NSValueTransformer *)discoverSupportedJSONTransformer {
return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"supported": @YES, @"device_not_supported": @NO} defaultValue:@NO reverseDefaultValue:@"device_not_supported"];
}

+ (NSValueTransformer *)canUseCashJSONTransformer {
return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"OK": @YES, @"NO_VERIFIED_PHONE": @NO} defaultValue:@NO reverseDefaultValue:@"NO_VERIFIED_PHONE"];
}

@end

Expand Down
14 changes: 12 additions & 2 deletions Pod/Classes/Model/SKStoryCollection.m
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,21 @@ + (NSDictionary *)JSONKeyPathsByPropertyKey {
@"isLocal": @"is_local",
@"viewedThumbnail": @"thumbnails.viewed.url",
@"unviewedThumbnail": @"thumbnails.unviewed.url",
@"viewedThumbnailNeedsAuth": @"thumbnails.viewed.needs_auth",
@"unviewedThumbnailNeedsAuth": @"thumbnails.unviewed.needs_auth",
@"viewedThumbNeedsAuth": @"thumbnails.viewed.needs_auth",
@"unviewedThumbNeedsAuth": @"thumbnails.unviewed.needs_auth",
@"stories": @"stories"};
}

+ (NSArray *)ignoredJSONKeyPathPrefixes {
static NSArray *ignored = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ignored = @[@"ad_placement_metadata"];
});

return ignored;
}

MTLTransformPropertyURL(viewedThumbnail)
MTLTransformPropertyURL(unviewedThumbnail)

Expand Down
5 changes: 5 additions & 0 deletions Pod/Classes/Model/SKThing.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ return [self sk_dateTransformer]; }
+ (NSValueTransformer *)sk_dateTransformer;
/// Transforms strings into NSURL objects.
+ (NSValueTransformer *)sk_urlTransformer;
/// Transforms strings from "ON" and "OFF" to YES and NO.
+ (NSValueTransformer *)sk_onOffTransformer;
/// Transforms an array of dictionaries into an array of model objects of class \c cls.
+ (NSValueTransformer *)sk_modelArrayTransformerForClass:(Class)cls;
/// Transforms an array of dictionaries into an ordered set of model objects of class \c cls.
Expand All @@ -38,6 +40,9 @@ return [self sk_dateTransformer]; }
+ (NSArray *)knownJSONKeys;
/// Calculated once when first accessed, using \c knownJSONKeys.
+ (NSArray *)unknownJSONKeys;
+ (NSDictionary *)allSubclassesUnknownJSONKeys;
/// Used to filter out unused JSON keys I don't want to use.
+ (NSArray *)ignoredJSONKeyPathPrefixes;

/// Transforms \c jsons to an array of model objects of class \c cls.
+ (NSArray *)transformJSONArray:(NSArray *)jsons toModelsOfClass:(Class)cls;
Expand Down
35 changes: 28 additions & 7 deletions Pod/Classes/Model/SKThing.m
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ @implementation SKThing

- (id)initWithDictionary:(NSDictionary *)json {
NSParameterAssert(json.allKeys.count > 0);
self = [super initWithDictionary:json error:nil];
self = [MTLJSONAdapter modelOfClass:[self class] fromJSONDictionary:json error:nil];

#if kDebugJSON
static dispatch_once_t onceToken;
Expand All @@ -53,11 +53,28 @@ + (NSArray *)knownJSONKeys {

+ (NSArray *)unknownJSONKeys {
NSMutableSet *unknown = [NSMutableSet setWithArray:[_allJSONKeys[CLASS_KEY] allObjects]];
NSArray *ignored = [self ignoredJSONKeyPathPrefixes];
[unknown minusSet:_knownJSONKeys[CLASS_KEY] ?: [NSSet set]];

return unknown.allObjects;
NSMutableSet *unknownWithoutIgnored = unknown.mutableCopy;

for (NSString *prefix in ignored)
for (NSString *key in unknown)
if ([key hasPrefix:prefix])
[unknownWithoutIgnored removeObject:key];

unknown = unknownWithoutIgnored.mutableCopy;

for (NSString *prefix in unknown)
for (NSString *fullKey in [self knownJSONKeys])
if ([fullKey hasPrefix:prefix])
[unknownWithoutIgnored removeObject:prefix];

return unknownWithoutIgnored.allObjects;
}

+ (NSArray *)ignoredJSONKeyPathPrefixes { return @[]; }

+ (void)setAllJSONKeys:(NSArray *)keys {
NSMutableSet *all = _allJSONKeys[CLASS_KEY];
if (all)
Expand All @@ -78,15 +95,15 @@ - (NSDictionary *)JSONDictionary {
return [MTLJSONAdapter JSONDictionaryFromModel:self error:nil];
}

+ (NSArray *)allSubclassesUnknownJSONKeys {
+ (NSDictionary *)allSubclassesUnknownJSONKeys {
NSArray *subclasses = [self allSubclasses];

NSMutableArray *allUnknownKeys = [NSMutableArray array];
NSMutableDictionary *allUnknownKeys = [NSMutableDictionary dictionary];

for (Class c in subclasses) {
NSArray *unknown = [c unknownJSONKeys];
if (unknown.count)
[allUnknownKeys addObject:[NSString stringWithFormat:@"%@: %@", NSStringFromClass(c), unknown.JSONString]];
allUnknownKeys[NSStringFromClass(c)] = [unknown sortedArrayUsingSelector:@selector(compare:)];
}

return allUnknownKeys;
Expand Down Expand Up @@ -137,8 +154,12 @@ + (NSValueTransformer *)sk_urlTransformer {
return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
}

+ (NSValueTransformer *)sk_onOffTransformer {
return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{@"ON": @YES, @"OFF": @NO} defaultValue:@NO reverseDefaultValue:@"OFF"];
}

+ (NSValueTransformer *)sk_modelArrayTransformerForClass:(Class)cls {
NSParameterAssert([(id)[cls class] isKindOfClass:[SKThing class]]);
NSParameterAssert([(id)[cls class] isSubclassOfClass:[SKThing class]]);

return [MTLValueTransformer transformerUsingForwardBlock:^id(NSArray *dictionaries, BOOL *success, NSError *__autoreleasing *error) {
NSMutableArray *models = [NSMutableArray new];
Expand All @@ -151,7 +172,7 @@ + (NSValueTransformer *)sk_modelArrayTransformerForClass:(Class)cls {
}

+ (NSValueTransformer *)sk_modelMutableOrderedSetTransformerForClass:(Class)cls {
NSParameterAssert([(id)[cls class] isKindOfClass:[SKThing class]]);
NSParameterAssert([(id)[cls class] isSubclassOfClass:[SKThing class]]);

return [MTLValueTransformer transformerUsingForwardBlock:^id(NSArray *dictionaries, BOOL *success, NSError *__autoreleasing *error) {
NSMutableOrderedSet *models = [NSMutableOrderedSet orderedSet];
Expand Down
3 changes: 3 additions & 0 deletions Pod/Classes/Model/SKUser.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
/** \c nil if the user is not a shared story. */
@property (nonatomic, readonly) NSString *sharedStoryIdentifier;

/** Number of days the snap streak has gone on for, if at all. */
@property (nonatomic, readonly) NSInteger snapStreakCount;

/** NO if your stories are hidden from this user in "who can see my stories?". */
@property (nonatomic, readonly) BOOL canSeeCustomStories;
@property (nonatomic, readonly) BOOL needsLove;
Expand Down
Loading

0 comments on commit cbce45e

Please sign in to comment.