This repository has been archived by the owner on May 19, 2018. It is now read-only.
/
GHBlob.m
73 lines (65 loc) · 2.74 KB
/
GHBlob.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#import "GHResource.h"
#import "GHBlob.h"
#import "GHRepository.h"
#import "NSString+Extensions.h"
#import "NSDictionary+Extensions.h"
#import "MF_Base64Additions.h"
#import "AFHTTPRequestOperation.h"
@implementation GHBlob
- (id)initWithRepo:(GHRepository *)repo path:(NSString *)path ref:(NSString*)ref {
self = [super init];
if (self) {
self.repository = repo;
self.path = path;
self.resourcePath = [NSString stringWithFormat:kRepoContentFormat, self.repository.owner, self.repository.name, self.path, ref];
}
return self;
}
- (BOOL)isMarkdown {
return [self.path hasSuffix:@".md"] || [self.path hasSuffix:@".markdown"];
}
- (loadSuccess)onLoadSuccess {
return ^(AFHTTPRequestOperation *operation, id data) {
if ([data isKindOfClass:NSDictionary.class]) {
self.path = [data safeStringForKey:@"path"];
}
if (self.isMarkdown) {
// set initial data without marking as loaded
// and running the success blocks
NSDictionary *headers = operation.response.allHeaderFields;
NSURL *url = operation.response.URL;
D3JLog(@"\n%@: Loading %@ finished.\n\nHeaders:\n%@\n\nData:\n%@\n", self.class, url, headers, data);
[self setHeaderValues:headers];
[self setValues:data];
// then fetch rendered markdown
GHResource *resource = [[GHResource alloc] initWithPath:self.resourcePath];
resource.resourceContentType = kResourceContentTypeHTML;
[resource loadWithSuccess:^(GHResource *instance, id data) {
super.onLoadSuccess(operation, data);
}];
} else {
super.onLoadSuccess(operation, data);
}
};
}
#pragma mark Loading
- (void)setValues:(id)response {
if ([response isKindOfClass:NSDictionary.class]) {
self.path = [response safeStringForKey:@"path"];
self.size = [response safeIntegerForKey:@"size"];
self.htmlURL = [response safeURLForKey:@"html_url"];
self.encoding = [response safeStringForKey:@"encoding"];
if ([self.encoding isEqualToString:@"utf-8"]) {
self.content = [response safeStringForKey:@"content"];
} else if ([self.encoding isEqualToString:@"base64"]) {
NSString *cont = [response safeStringForKey:@"content"];
self.content = [NSString stringFromBase64String:cont];
self.contentData = [NSData dataWithBase64String:cont];
}
} else if ([response isKindOfClass:NSData.class]) {
// the response is not a dictionary, because we requested
// the html mime type which returns the HTML representation
self.contentHTML = [[NSString alloc] initWithData:(NSData *)response encoding:NSUTF8StringEncoding];
}
}
@end