Skip to content

Instantly share code, notes, and snippets.

@umrashrf
Created March 26, 2012 07:56
Show Gist options
  • Save umrashrf/2203803 to your computer and use it in GitHub Desktop.
Save umrashrf/2203803 to your computer and use it in GitHub Desktop.
iOS YouTube Uploader
(function() {
if (Cordova.hasResource("youtubeUploader")) return;
Cordova.addResource("youtubeUploader");
function YouTubeUploader() {
}
YouTubeUploader.prototype.uploadVideo = function(file, success, fail) {
return Cordova.exec(success, fail, "org.apache.cordova.youtubeUploader", "uploadVideo", [file]);
};
Cordova.addConstructor(function() {
if (!window.plugins) window.plugins = {};
if (!window.plugins.youtubeUploader) {
window.plugins.youtubeUploader = new YouTubeUploader();
} else {
console.log("Not installing YouTubeUploader: window.plugins.youtubeUploader already exists");
}
});
})();
//
// YouTubeUploader.h
// Created by Umair Ashraf on 3/7/12.
//
#import <Foundation/Foundation.h>
#import <CORDOVA/CDVPLUGIN.h>
#import "XMLReader.h"
@interface YouTubeUploader : CDVPlugin {
NSString *YouTubeUsername;
NSString *GoogleUsername;
NSString *Password;
NSString *Source;
NSString *DeveloperKey;
NSString *AuthToken;
NSString *UploadURL;
NSString *UploadToken;
NSString *callbackID;
}
@property (nonatomic, retain) NSString* YouTubeUsername;
@property (nonatomic, retain) NSString* GoogleUsername;
@property (nonatomic, retain) NSString* Password;
@property (nonatomic, retain) NSString* Source;
@property (nonatomic, retain) NSString* DeveloperKey;
@property (nonatomic, retain) NSString* AuthToken;
@property (nonatomic, retain) NSString* UploadURL;
@property (nonatomic, retain) NSString* UploadToken;
@property (nonatomic, copy) NSString* callbackID;
- (void) uploadVideo:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) login;
- (void) prepareVideoUpload:(NSString *)filename;
- (NSString *) upload:(NSString *)file;
@end
//
// YouTubeUploader.m
// Created by Umair Ashraf on 3/7/12.
//
#import "YouTubeUploader.h"
@implementation YouTubeUploader
@synthesize YouTubeUsername;
@synthesize GoogleUsername;
@synthesize Password;
@synthesize Source;
@synthesize DeveloperKey;
@synthesize AuthToken;
@synthesize UploadURL;
@synthesize UploadToken;
@synthesize callbackID;
-(void)uploadVideo:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
self.YouTubeUsername = @"";
self.GoogleUsername = @"";
self.Password = @"";
self.Source = @"";
self.DeveloperKey = @"";
//The first argument in the arguments parameter is the callbackID.
//We use this to send data back to the successCallback or failureCallback
//through PluginResult.
self.callbackID = [arguments pop];
//Get the string that javascript sent us
NSString *file = [arguments objectAtIndex:0];
[self login];
[self prepareVideoUpload:[file lastPathComponent]];
NSString *url = [self upload:file];
//bool uploaded = [self directUpload:file];
if (url != nil) {
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//Call the Success Javascript function
[self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]];
} else {
//Create Plugin Result
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
//Call the Failure Javascript function
[self writeJavascript: [pluginResult toErrorCallbackString:self.callbackID]];
}
}
- (void) login {
NSURL *url = [NSURL URLWithString:@"https://www.google.com/accounts/ClientLogin"];
NSString *params = [[NSString alloc] initWithFormat:@"Email=%@&Passwd=%@&source=%@&service=youtube", self.GoogleUsername, self.Password, self.Source];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSString *responseText = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *tokens = [responseText componentsSeparatedByString:@"\n"];
if ([tokens count] >= 3) {
NSArray *authToken = [[tokens objectAtIndex:2] componentsSeparatedByString:@"="];
if ([authToken count] >= 2) {
self.AuthToken = [authToken objectAtIndex:1];
}
}
}
- (void) prepareVideoUpload:(NSString *) filename {
NSString *title = filename;
title = @"The Video";
NSString *desc = @"Video description goes here...";
NSString *category = @"People";
NSString *keywords = @"video";
NSString *xml = [NSString stringWithFormat:
@"<?xml version=\"1.0\"?>"
@"<entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:media=\"http://search.yahoo.com/mrss/\" xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">"
@"<media:group>"
@"<media:title type=\"plain\">%@</media:title>"
@"<media:description type=\"plain\">%@</media:description>"
@"<media:category scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">%@</media:category>"
@"<media:keywords>%@</media:keywords>"
@"</media:group>"
@"</entry>", title, desc, category, keywords];
NSURL *url = [NSURL URLWithString:@"https://gdata.youtube.com/action/GetUploadToken"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"GoogleLogin auth=\"%@\"", self.AuthToken] forHTTPHeaderField:@"Authorization"];
[request setValue:@"2" forHTTPHeaderField:@"GData-Version"];
[request setValue:[NSString stringWithFormat:@"key=%@", self.DeveloperKey] forHTTPHeaderField:@"X-GData-Key"];
[request setValue:@"application/atom+xml; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%u", [xml length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:[xml dataUsingEncoding:NSUTF8StringEncoding]];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSString *responseText = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
if (response != nil) {
NSDictionary *dic = [XMLReader dictionaryForXMLString:responseText error:nil];
NSString *url = [[dic valueForKey:@"response"] valueForKey:@"url"];
NSString *token = [[dic valueForKey:@"response"] valueForKey:@"token"];
self.UploadURL = url;
self.UploadToken = token;
}
}
- (NSString *) upload:(NSString *)file {
//[self writeJavascript:[NSString stringWithFormat:@"console.log('File name: %@');", [file lastPathComponent]]];
NSString *boundary = @"qwerty";
NSString *nextURL = @"http://yahoo.com/";
NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:file]];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?nexturl=%@", self.UploadURL, nextURL]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"token\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: text/plain\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[self.UploadToken dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"\r\n", [file lastPathComponent]] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:fileData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
NSError *requestError;
NSURLResponse *urlResponse = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
NSArray *location = [[[httpResponse URL] absoluteString] componentsSeparatedByString:@"id="];
if ([location count] >= 2) {
NSString *video_url = [NSString stringWithFormat:@"http://www.youtube.com/watch?v=%@", [location objectAtIndex:1]];
return video_url;
}
return nil;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment