Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating Independent Gists #3

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions macdown-gistit-tests/Info.plist
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
185 changes: 116 additions & 69 deletions macdown-gistit/MacDownGistItController.m
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@
#import <Cocoa/Cocoa.h>
#import "MacDownGistItController.h"

@interface Gist : NSObject {
@public NSString * text;
@public NSString * ext;

}

@end

@implementation Gist


@end

static NSString * const MacDownGistListLink = @"https://api.github.com/gists";

Expand All @@ -33,7 +45,47 @@ - (BOOL)run:(id)sender
return [self gistify:dc.currentDocument];
}

- (BOOL)gistify:(NSDocument *)document

- (NSArray *) blocksFrom: (NSString *) text {

NSString * str = text;
NSMutableArray * result = [NSMutableArray array];

while (true) {
NSRange range = [str rangeOfString: @"```"];

if (range.length > 0) {
str = [NSString stringWithString: [str substringFromIndex: range.location + range.length]];

NSRange extRange = [str rangeOfString: @"\n"];

NSString * ext = [str substringToIndex: extRange.location];

str = [str substringFromIndex: extRange.location + extRange.length];

NSRange codeRange = [str rangeOfString: @"```"];

NSString * code = [str substringToIndex:codeRange.location];


Gist * gist = [[Gist alloc] init];

gist->text = code;
gist->ext = ext;

[result addObject: gist];

str = [NSString stringWithString: [str substringFromIndex: codeRange.location + codeRange.length]];
}
else break;
}

return result;

}


- (BOOL) gistify:(NSDocument *)document
{
id<MacDownMarkdownSource> markdownSource = (id)document;
NSString *markdown = markdownSource.markdown;
Expand All @@ -43,78 +95,73 @@ - (BOOL)gistify:(NSDocument *)document
if (!fileName.length)
fileName = @"Untitled";

NSURL * url = [NSURL URLWithString:MacDownGistListLink];
NSMutableURLRequest *req =


NSArray * blocks = [self blocksFrom: markdown];

__block NSString * result = @"Your Gists urls:\n";

__block int m = 0;

for (Gist * block in blocks) {

NSURL * url = [NSURL URLWithString:MacDownGistListLink];
NSMutableURLRequest *req =
[NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:0.0];
[req addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSDictionary *object = @{
@"description": @"Uploaded by MacDown. http://macdown.uranusjr.com",
@"public": @YES,
@"files": @{fileName: @{@"content": markdown}},
};
NSData *data = [NSJSONSerialization dataWithJSONObject:object
options:0 error:NULL];
if (!data)
return NO;

req.HTTPMethod = @"POST";
req.HTTPBody = data;

NSURLSessionConfiguration *conf =
[req addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[req addValue:@"application/json" forHTTPHeaderField:@"Accept"];

NSString * fName = [fileName stringByAppendingString: [@"." stringByAppendingString: block->ext]];

NSDictionary *object = @{
@"description": @"Uploaded by MacDown. http://macdown.uranusjr.com",
@"public": @YES,
@"files": @{fName: @{@"content": block->text}},
};
NSData *data = [NSJSONSerialization dataWithJSONObject:object
options:0 error:NULL];

if (!data)
return NO;

req.HTTPMethod = @"POST";
req.HTTPBody = data;

NSURLSessionConfiguration *conf =
[NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:conf];
NSURLSessionTask *task = [session dataTaskWithRequest:req
completionHandler:^(
NSData *data, NSURLResponse *res, NSError *error) {

NSHTTPURLResponse *r = (id)res;
NSString *json = data ?
[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] :
nil;
NSDictionary *object = data ?
[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] :
nil;
NSString *urlstring = object[@"html_url"];

NSAlert *alert = [[NSAlert alloc] init];
if (error)
{
alert = [NSAlert alertWithError:error];
}
else if (![res respondsToSelector:@selector(statusCode)])
{
alert.alertStyle = NSWarningAlertStyle;
alert.messageText = @"Unknown error";
}
else if (r.statusCode != 201 || !urlstring)
{
alert.alertStyle = NSWarningAlertStyle;
NSString *f = @"Unexpection return code %ld";
alert.messageText = [NSString stringWithFormat:f, r.statusCode];
if (json)
alert.informativeText = json;
}

alert.alertStyle = NSInformationalAlertStyle;
alert.messageText = @"Gist created";
alert.informativeText = [NSString stringWithFormat:
@"You gist is at %@\nThe URL has been copied into your clipboard.",
urlstring];

NSPasteboard *pb = [NSPasteboard generalPasteboard];
[pb clearContents];
[pb writeObjects:@[urlstring]];

dispatch_async(dispatch_get_main_queue(), ^{
[alert runModal];
});
}];
[task resume];

NSURLSession *session = [NSURLSession sessionWithConfiguration:conf];
NSURLSessionTask *task = [session dataTaskWithRequest:req
completionHandler:^(
NSData *data, NSURLResponse *res, NSError *error) {
//
// NSHTTPURLResponse *r = (id)res;
// NSString *json = data ?
// [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] :
// nil;
NSDictionary *object = data ?
[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL] :
nil;
NSString *urlstring = object[@"html_url"];


result = [result stringByAppendingString: [@"\n" stringByAppendingString: urlstring]];
m = m + 1;
}];
[task resume];
}

while (m < blocks.count) {}


NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = result;

dispatch_async(dispatch_get_main_queue(), ^{
[alert runModal];
});

return YES;
}

Expand Down