├── iphonecouchsync ├── .couchapprc ├── language ├── _id ├── views │ ├── syncView │ │ └── map.js │ └── myView │ │ └── map.js ├── vendor │ └── couchapp │ │ ├── evently │ │ ├── account │ │ │ ├── loginForm │ │ │ │ ├── after.js │ │ │ │ ├── selectors │ │ │ │ │ └── form │ │ │ │ │ │ └── submit.js │ │ │ │ └── mustache.html │ │ │ ├── signupForm │ │ │ │ ├── after.js │ │ │ │ ├── selectors │ │ │ │ │ └── form │ │ │ │ │ │ └── submit.js │ │ │ │ └── mustache.html │ │ │ ├── loggedIn │ │ │ │ ├── selectors.json │ │ │ │ ├── after.js │ │ │ │ ├── mustache.html │ │ │ │ └── data.js │ │ │ ├── loggedOut │ │ │ │ ├── mustache.html │ │ │ │ └── selectors.json │ │ │ ├── adminParty │ │ │ │ └── mustache.html │ │ │ ├── doLogout.js │ │ │ ├── doLogin.js │ │ │ ├── doSignup.js │ │ │ └── _init.js │ │ └── README.md │ │ ├── metadata.json │ │ ├── lib │ │ ├── redirect.js │ │ ├── list.js │ │ ├── cache.js │ │ ├── code.js │ │ ├── linkup.js │ │ ├── utils.js │ │ ├── atom.js │ │ ├── validate.js │ │ ├── path.js │ │ └── docform.js │ │ └── _attachments │ │ ├── loader.js │ │ └── jquery.couch.app.util.js ├── couchapp.json ├── .couchappignore ├── README.md └── _attachments │ ├── index.html │ ├── styles.css │ ├── tooltip.js │ └── script.js ├── images ├── coke.png ├── bananas.png ├── oranges.png └── raspberries.png ├── iphoneSync ├── icon.png ├── icon@x2.png ├── iphoneSync │ ├── en.lproj │ │ └── InfoPlist.strings │ ├── coke.png │ ├── bananas.png │ ├── oranges.png │ ├── RootViewController.h │ ├── iphoneSync-Prefix.pch │ ├── main.m │ ├── UIImage+TableCellImageScaler.h │ ├── Product.m │ ├── ChildTableViewController.h │ ├── DataController.h │ ├── Product.h │ ├── UIImage+TableCellImageScaler.m │ ├── iphoneSyncAppDelegate.h │ ├── SyncController.h │ ├── iphoneSync-Info.plist │ ├── product.json │ ├── iphoneSyncAppDelegate.m │ ├── DataController.m │ ├── ChildTableViewController.m │ └── RootViewController.m ├── DropboxSDK │ ├── Resources │ │ ├── db_logo.png │ │ ├── db_logo@2x.png │ │ ├── db_background.png │ │ ├── db_link_button.png │ │ ├── db_link_header.png │ │ ├── db_create_account.png │ │ ├── db_link_header@2x.png │ │ ├── db_create_account@2x.png │ │ ├── db_link_button_down.png │ │ ├── db_create_account_button.png │ │ └── db_create_account_button_down.png │ ├── DBError.m │ ├── MPOAuth │ │ ├── MPDebug.h │ │ ├── NSURLResponse+Encoding.h │ │ ├── MPOAuthURLResponse.h │ │ ├── NSString+URLEscapingAdditions.h │ │ ├── NSURL+MPURLParameterAdditions.h │ │ ├── MPOAuth.h │ │ ├── MPOAuthCredentialConcreteStore+KeychainAdditions.h │ │ ├── NSURLResponse+Encoding.m │ │ ├── MPOAuthURLResponse.m │ │ ├── MPOAuthParameterFactory.h │ │ ├── MPURLRequestParameter.h │ │ ├── MPOAuthSignatureParameter.h │ │ ├── MPOAuthAuthenticationMethod.h │ │ ├── MPOAuthURLRequest.h │ │ ├── MPOAuthConnection.h │ │ ├── MPOAuthCredentialStore.h │ │ ├── MPOAuthAuthenticationMethodOAuth.h │ │ ├── MPOAuthCredentialConcreteStore.h │ │ ├── Crypto │ │ │ └── Base64Transcoder.h │ │ ├── MPOAuthAPIRequestLoader.h │ │ ├── NSString+URLEscapingAdditions.m │ │ ├── MPOAuthConnection.m │ │ ├── MPOAuthSignatureParameter.m │ │ ├── MPOAuthCredentiaIConcreteStore+KeychainAdditionsMac.m │ │ ├── MPOAuthURLRequest.m │ │ ├── MPOAuthAPI.h │ │ ├── NSURL+MPURLParameterAdditions.m │ │ └── MPOAuthAuthenticationMethod.m │ ├── DropboxSDK.h │ ├── NSString+Dropbox.h │ ├── DBError.h │ ├── NSString+Dropbox.m │ ├── DBQuota.h │ ├── DBLoadingView.h │ ├── DBAccountInfo.h │ ├── DBCreateAccountController.h │ ├── DBMetadata.h │ ├── DBLoginController.h │ ├── DBSession.h │ ├── DBQuota.m │ ├── DBAccountInfo.m │ ├── DBRequest.h │ ├── DBSession.m │ └── DBMetadata.m ├── AsiHttpRequest │ ├── ASIInputStream.h │ ├── ASIHTTPRequestConfig.h │ ├── ASIAuthenticationDialog.h │ ├── ASIHTTPRequestDelegate.h │ ├── ASIProgressDelegate.h │ ├── ASIDataDecompressor.h │ ├── ASIDataCompressor.h │ ├── ASIDownloadCache.h │ ├── ASIFormDataRequest.h │ ├── ASIInputStream.m │ ├── ASICacheDelegate.h │ └── ASINetworkQueue.h └── Classes │ ├── NSObject+JSON.h │ ├── NSObject+JSON.m │ ├── SBJsonTokeniser.h │ ├── JSON.h │ ├── SBJsonStreamWriterState.h │ ├── SBJsonStreamParserAdapter.h │ ├── SBJsonStreamParserState.h │ ├── SBJsonWriter.m │ ├── SBJsonParser.m │ ├── SBJsonParser.h │ └── SBJsonStreamParser.h ├── .gitignore ├── mit-license.txt └── README.md /iphonecouchsync/.couchapprc: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /iphonecouchsync/language: -------------------------------------------------------------------------------- 1 | javascript -------------------------------------------------------------------------------- /iphonecouchsync/_id: -------------------------------------------------------------------------------- 1 | _design/iphonecouchsync -------------------------------------------------------------------------------- /iphonecouchsync/views/syncView/map.js: -------------------------------------------------------------------------------- 1 | function(doc) { 2 | emit([doc.name], doc) 3 | } -------------------------------------------------------------------------------- /images/coke.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/images/coke.png -------------------------------------------------------------------------------- /images/bananas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/images/bananas.png -------------------------------------------------------------------------------- /images/oranges.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/images/oranges.png -------------------------------------------------------------------------------- /iphoneSync/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/icon.png -------------------------------------------------------------------------------- /images/raspberries.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/images/raspberries.png -------------------------------------------------------------------------------- /iphoneSync/icon@x2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/icon@x2.png -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/en.lproj/InfoPlist.strings: -------------------------------------------------------------------------------- 1 | /* Localized versions of Info.plist keys */ 2 | 3 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/coke.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/iphoneSync/coke.png -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/bananas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/iphoneSync/bananas.png -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/oranges.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/iphoneSync/oranges.png -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loginForm/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("input[name=name]", this).focus(); 3 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/signupForm/after.js: -------------------------------------------------------------------------------- 1 | function() { 2 | $("input[name=name]", this).focus(); 3 | } -------------------------------------------------------------------------------- /iphonecouchsync/couchapp.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "iphone couch sync", 3 | "description": "test app for the iphone couch sync" 4 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loggedIn/selectors.json: -------------------------------------------------------------------------------- 1 | { 2 | "a[href=#logout]" : {"click" : ["doLogout"]} 3 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loggedOut/mustache.html: -------------------------------------------------------------------------------- 1 | Signup or Login -------------------------------------------------------------------------------- /iphonecouchsync/views/myView/map.js: -------------------------------------------------------------------------------- 1 | function(doc) { 2 | if (doc.name && doc.description) { 3 | emit(doc.name, doc); 4 | } 5 | } -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_logo.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_logo@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_logo@2x.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_background.png -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loggedIn/after.js: -------------------------------------------------------------------------------- 1 | function(e, r) { 2 | $$(this).userCtx = r.userCtx; 3 | $$(this).info = r.info; 4 | }; -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_link_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_link_button.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_link_header.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_link_header.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_create_account.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_create_account.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_link_header@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_link_header@2x.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_create_account@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_create_account@2x.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_link_button_down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_link_button_down.png -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_create_account_button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_create_account_button.png -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loggedOut/selectors.json: -------------------------------------------------------------------------------- 1 | { 2 | "a[href=#signup]" : {"click" : ["signupForm"]}, 3 | "a[href=#login]" : {"click" : ["loginForm"]} 4 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "couchapp", 3 | "description": "official couchapp vendor", 4 | "fetch_uri": "git://github.com/couchapp/vendor.git" 5 | } 6 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/Resources/db_create_account_button_down.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nickfox/iphoneCloudSync/HEAD/iphoneSync/DropboxSDK/Resources/db_create_account_button_down.png -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/adminParty/mustache.html: -------------------------------------------------------------------------------- 1 |

Admin party, everyone is admin! Fix this in Futon before proceeding.

-------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/lib/redirect.js: -------------------------------------------------------------------------------- 1 | exports.permanent = function(redirect) { 2 | return { 3 | code : 301, 4 | headers : { 5 | "Location" : redirect 6 | } 7 | }; 8 | }; -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/doLogout.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var elem = $(this); 3 | $.couch.logout({ 4 | success : function() { 5 | elem.trigger("_init"); 6 | } 7 | }); 8 | } -------------------------------------------------------------------------------- /iphonecouchsync/.couchappignore: -------------------------------------------------------------------------------- 1 | [ 2 | // filenames matching these regexps will not be pushed to the database 3 | // uncomment to activate; separate entries with "," 4 | // ".*~$" 5 | // ".*\\.swp$" 6 | // ".*\\.bak$" 7 | ] -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loggedIn/mustache.html: -------------------------------------------------------------------------------- 1 | Welcome 2 | {{name}}! 3 | Logout? 4 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loggedIn/data.js: -------------------------------------------------------------------------------- 1 | function(e, r) { 2 | return { 3 | name : r.userCtx.name, 4 | uri_name : encodeURIComponent(r.userCtx.name), 5 | auth_db : encodeURIComponent(r.info.authentication_db) 6 | }; 7 | } -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/DBError.m: -------------------------------------------------------------------------------- 1 | // 2 | // DBError.m 3 | // DropboxSDK 4 | // 5 | // Created by Brian Smith on 7/21/10. 6 | // Copyright 2010 Dropbox, Inc. All rights reserved. 7 | // 8 | 9 | #import "DBError.h" 10 | 11 | NSString* DBErrorDomain = @"dropbox.com"; 12 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/doLogin.js: -------------------------------------------------------------------------------- 1 | function(e, name, pass) { 2 | var elem = $(this); 3 | $.couch.login({ 4 | name : name, 5 | password : pass, 6 | success : function(r) { 7 | elem.trigger("_init") 8 | } 9 | }); 10 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/doSignup.js: -------------------------------------------------------------------------------- 1 | function(e, name, pass) { 2 | var elem = $(this); 3 | $.couch.signup({ 4 | name : name 5 | }, pass, { 6 | success : function() { 7 | elem.trigger("doLogin", [name, pass]); 8 | } 9 | }); 10 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loginForm/selectors/form/submit.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | var name = $('input[name=name]', this).val(), 3 | pass = $('input[name=password]', this).val(); 4 | $(this).trigger('doLogin', [name, pass]); 5 | return false; 6 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/signupForm/selectors/form/submit.js: -------------------------------------------------------------------------------- 1 | function(e) { 2 | var name = $('input[name=name]', this).val(), 3 | pass = $('input[name=password]', this).val(); 4 | $(this).trigger('doSignup', [name, pass]); 5 | return false; 6 | } -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPDebug.h: -------------------------------------------------------------------------------- 1 | // 2 | // MPDebug.h 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 09.02.06. 6 | // Copyright 2009 matrixPointer. All rights reserved. 7 | // 8 | 9 | #ifdef DEBUG 10 | #define MPLog(...) NSLog(__VA_ARGS__) 11 | #else 12 | #define MPLog(...) do { } while (0) 13 | #endif 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | build/* 3 | *.pbxuser 4 | !default.pbxuser 5 | *.mode1v3 6 | !default.mode1v3 7 | *.mode2v3 8 | !default.mode2v3 9 | *.perspectivev3 10 | !default.perspectivev3 11 | *.xcworkspace 12 | !default.xcworkspace 13 | xcuserdata 14 | profile 15 | *.moved-aside 16 | 17 | # old skool 18 | .svn 19 | 20 | # osx noise 21 | .DS_Store 22 | profile -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/lib/list.js: -------------------------------------------------------------------------------- 1 | // Helpers for writing server-side _list functions in CouchDB 2 | exports.withRows = function(fun) { 3 | var f = function() { 4 | var row = getRow(); 5 | return row && fun(row); 6 | }; 7 | f.iterator = true; 8 | return f; 9 | } 10 | 11 | exports.send = function(chunk) { 12 | send(chunk + "\n") 13 | } -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/loginForm/mustache.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | or Signup 6 |
7 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/signupForm/mustache.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 | or Login 6 |
7 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/NSURLResponse+Encoding.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURL+MPEncodingAdditions.h 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.05. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | 12 | @interface NSURLResponse (EncodingAdditions) 13 | - (NSStringEncoding)encoding; 14 | @end 15 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/RootViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // RootViewController.h 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class DataController; 12 | 13 | @interface RootViewController : UITableViewController { 14 | DataController *dataController; 15 | } 16 | 17 | @end 18 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/iphoneSync-Prefix.pch: -------------------------------------------------------------------------------- 1 | // 2 | // Prefix header for all source files of the 'iphoneSync' target in the 'iphoneSync' project 3 | // 4 | 5 | #import 6 | 7 | #ifndef __IPHONE_3_0 8 | #warning "This project uses features only available in iPhone SDK 3.0 and later." 9 | #endif 10 | 11 | #ifdef __OBJC__ 12 | #import 13 | #import 14 | #endif 15 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | int main(int argc, char *argv[]) 12 | { 13 | NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 14 | int retVal = UIApplicationMain(argc, argv, nil, nil); 15 | [pool release]; 16 | return retVal; 17 | } 18 | -------------------------------------------------------------------------------- /iphonecouchsync/README.md: -------------------------------------------------------------------------------- 1 | ## iPhone couchDB Catalog 2 | 3 | To push to cloudant: 4 | 5 | couchapp push http://USERNAME:PASSWORD@USERNAME.cloudant.com/iphonecouchsync 6 | 7 | Now view your app at: 8 | 9 | http://USERNAME.cloudant.com/iphonecouchsync/_design/iphonecouchsync/index.html 10 | 11 | The view that the phone uses to get json file: 12 | 13 | https://USERNAME.cloudant.com/iphonecouchsync/_design/iphonecouchsync/_view/syncView 14 | 15 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/DropboxSDK.h: -------------------------------------------------------------------------------- 1 | /* 2 | * DropboxSDK.h 3 | * DropboxSDK 4 | * 5 | * Created by Brian Smith on 7/13/10. 6 | * Copyright 2010 Dropbox, Inc. All rights reserved. 7 | * 8 | */ 9 | 10 | /* Import this file to get the most important header files imported */ 11 | #import "DBSession.h" 12 | #import "DBRestClient.h" 13 | #import "DBLoginController.h" 14 | #import "DBAccountInfo.h" 15 | #import "DBMetadata.h" 16 | #import "DBQuota.h" 17 | #import "DBError.h" -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/UIImage+TableCellImageScaler.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+TableCellImageScaler.h 3 | // Sunset 4 | // 5 | // Created by nickfox on 3/25/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | // category to scale a table cell image 10 | // http://atastypixel.com/blog/easy-rounded-corners-on-uitableviewcell-image-view/ 11 | 12 | @interface UIImage (TableCellImageScaler) 13 | - (UIImage*)imageScaledToSize:(CGSize)size; 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/Product.m: -------------------------------------------------------------------------------- 1 | // 2 | // Product.m 3 | // Sunset 4 | // 5 | // Created by nickfox on 3/23/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import "Product.h" 10 | 11 | @implementation Product 12 | 13 | @synthesize productID, name, description, image; 14 | 15 | - (void)dealloc { 16 | [productID release]; 17 | [name release]; 18 | [description release]; 19 | [image release]; 20 | [super dealloc]; 21 | } 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/evently/account/_init.js: -------------------------------------------------------------------------------- 1 | function() { 2 | var elem = $(this); 3 | $$(this).userCtx = null; 4 | $.couch.session({ 5 | success : function(r) { 6 | var userCtx = r.userCtx; 7 | if (userCtx.name) { 8 | elem.trigger("loggedIn", [r]); 9 | } else if (userCtx.roles.indexOf("_admin") != -1) { 10 | elem.trigger("adminParty"); 11 | } else { 12 | elem.trigger("loggedOut"); 13 | }; 14 | } 15 | }); 16 | } -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/NSString+Dropbox.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSString+Dropbox.h 3 | // DropboxSDK 4 | // 5 | // Created by Brian Smith on 7/19/10. 6 | // Copyright 2010 Dropbox, Inc. All rights reserved. 7 | // 8 | 9 | 10 | @interface NSString (Dropbox) 11 | 12 | // This will take a path for a resource and normalize so you can compare paths 13 | - (NSString*)normalizedDropboxPath; 14 | 15 | // Normalizes both paths and compares them 16 | - (BOOL)isEqualToDropboxPath:(NSString*)otherPath; 17 | 18 | @end 19 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/ChildTableViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ChildTableViewController.h 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class Product; 12 | 13 | @interface ChildTableViewController : UITableViewController { 14 | UIView *headerView; 15 | Product *product; 16 | } 17 | @property (nonatomic, retain) IBOutlet UIView *headerView; 18 | @property (nonatomic, retain) Product *product; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/DBError.h: -------------------------------------------------------------------------------- 1 | // 2 | // DBError.h 3 | // DropboxSDK 4 | // 5 | // Created by Brian Smith on 7/21/10. 6 | // Copyright 2010 Dropbox, Inc. All rights reserved. 7 | // 8 | 9 | /* This file contains error codes and the dropbox error domain */ 10 | 11 | extern NSString* DBErrorDomain; 12 | 13 | // Error codes in the dropbox.com domain represent the HTTP status code if less than 1000 14 | typedef enum { 15 | DBErrorNone = 0, 16 | DBErrorGenericError = 1000, 17 | DBErrorFileNotFound, 18 | DBErrorInsufficientDiskSpace, 19 | } DBErrorCode; 20 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthURLResponse.h: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthURLResponse.h 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.05. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | 12 | @interface MPOAuthURLResponse : NSObject { 13 | NSURLResponse *_urlResponse; 14 | NSDictionary *_oauthParameters; 15 | } 16 | 17 | @property (nonatomic, readonly, retain) NSURLResponse *urlResponse; 18 | @property (nonatomic, readonly, retain) NSDictionary *oauthParameters; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/DataController.h: -------------------------------------------------------------------------------- 1 | // 2 | // DataController.h 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | 12 | @interface DataController : NSObject { 13 | NSMutableArray *product; 14 | NSMutableString *currentProduct; 15 | } 16 | 17 | 18 | @property (nonatomic, retain) NSMutableArray *product; 19 | @property (nonatomic, retain) NSMutableString *currentProduct; 20 | 21 | 22 | -(void) loadJsonFromFile; 23 | 24 | @end 25 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/_attachments/loader.js: -------------------------------------------------------------------------------- 1 | 2 | function couchapp_load(scripts) { 3 | for (var i=0; i < scripts.length; i++) { 4 | document.write(' 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 36 | 37 | 38 |
ProductDetails
    18 | 19 | 20 |
    21 | 22 | 23 | 24 | 26 | 27 | 28 | 29 | 33 |
    25 |
     
    30 | 31 | 32 |
    34 |
    35 |
    39 | 40 | -------------------------------------------------------------------------------- /iphonecouchsync/_attachments/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: arial, helvetica, sans-serif; 3 | font-size: 0.95em; 4 | } 5 | 6 | .hover { 7 | background-color:#ccc; 8 | } 9 | 10 | ul { 11 | width:200px; 12 | list-style-type:square; 13 | } 14 | 15 | .formDescription { 16 | text-align:right; 17 | } 18 | 19 | .buttons { 20 | font-size: 0.75em; 21 | width:150px; 22 | } 23 | 24 | input { 25 | font-size: 0.95em; 26 | width:250px; 27 | } 28 | 29 | /* dont' change the order of these next to, has to come after the input above */ 30 | #productImage { 31 | width:295px; 32 | } 33 | 34 | .packageimages { 35 | width:295px; 36 | } 37 | 38 | select { 39 | font-size: 0.85em; 40 | width:250px; 41 | } 42 | 43 | table.formTable { 44 | border-width: 1px; 45 | border-spacing: 1px; 46 | border-style: outset; 47 | border-color: #fff; 48 | border-collapse: collapse; 49 | background-color: #fff; 50 | } 51 | table.formTable td { 52 | border-width: 1px; 53 | padding: 5px; 54 | border-style: inset; 55 | border-color: #fff; 56 | -moz-border-radius: ; 57 | } 58 | 59 | .formTextArea { 60 | width: 600px; 61 | height: 120px; 62 | border: 1px solid #000; 63 | padding: 5px; 64 | font-family: arial, helvetica, sans-serif; 65 | font-size: 0.95em; 66 | } 67 | 68 | table.productTable { 69 | border-width: 1px; 70 | border-spacing: 2px; 71 | border-style: outset; 72 | border-color: #000; 73 | border-collapse: collapse; 74 | background-color: #fff; 75 | } 76 | table.productTable th { 77 | border-width: 1px; 78 | padding: 1px; 79 | border-style: inset; 80 | border-color: #000; 81 | background-color: #ccc; 82 | -moz-border-radius: ; 83 | } 84 | table.productTable td { 85 | border-width: 1px; 86 | padding: 5px; 87 | border-style: inset; 88 | border-color: #000; 89 | -moz-border-radius: ; 90 | } 91 | /* tool tip */ 92 | 93 | #text {margin:50px auto; width:500px} 94 | .hotspot {color:#900; padding-bottom:1px; border-bottom:1px dotted #900; cursor:pointer} 95 | 96 | #tt {position:absolute; display:block;} 97 | #tttop {display:block; height:5px; margin-left:5px;overflow:hidden} 98 | #ttcont {display:block; padding:2px 12px 3px 7px;margin-left:5px; background:#666; color:#FFF} 99 | #ttbot {display:block; height:5px; margin-left:5px;overflow:hidden} 100 | -------------------------------------------------------------------------------- /iphonecouchsync/_attachments/tooltip.js: -------------------------------------------------------------------------------- 1 | var tooltip=function(){ 2 | var id = 'tt'; 3 | var top = 3; 4 | var left = 3; 5 | var maxw = 300; 6 | var speed = 10; 7 | var timer = 20; 8 | var endalpha = 95; 9 | var alpha = 0; 10 | var tt,t,c,b,h; 11 | var ie = document.all ? true : false; 12 | return{ 13 | show:function(v,w){ 14 | if(tt == null){ 15 | tt = document.createElement('div'); 16 | tt.setAttribute('id',id); 17 | t = document.createElement('div'); 18 | t.setAttribute('id',id + 'top'); 19 | c = document.createElement('div'); 20 | c.setAttribute('id',id + 'cont'); 21 | b = document.createElement('div'); 22 | b.setAttribute('id',id + 'bot'); 23 | tt.appendChild(t); 24 | tt.appendChild(c); 25 | tt.appendChild(b); 26 | document.body.appendChild(tt); 27 | tt.style.opacity = 0; 28 | tt.style.filter = 'alpha(opacity=0)'; 29 | document.onmousemove = this.pos; 30 | } 31 | tt.style.display = 'block'; 32 | c.innerHTML = v; 33 | tt.style.width = w ? w + 'px' : 'auto'; 34 | if(!w && ie){ 35 | t.style.display = 'none'; 36 | b.style.display = 'none'; 37 | tt.style.width = tt.offsetWidth; 38 | t.style.display = 'block'; 39 | b.style.display = 'block'; 40 | } 41 | if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'} 42 | h = parseInt(tt.offsetHeight) + top; 43 | clearInterval(tt.timer); 44 | tt.timer = setInterval(function(){tooltip.fade(1)},timer); 45 | }, 46 | pos:function(e){ 47 | var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY; 48 | var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX; 49 | tt.style.top = (u - h) + 'px'; 50 | tt.style.left = (l + left) + 'px'; 51 | }, 52 | fade:function(d){ 53 | var a = alpha; 54 | if((a != endalpha && d == 1) || (a != 0 && d == -1)){ 55 | var i = speed; 56 | if(endalpha - a < speed && d == 1){ 57 | i = endalpha - a; 58 | }else if(alpha < speed && d == -1){ 59 | i = a; 60 | } 61 | alpha = a + (i * d); 62 | tt.style.opacity = alpha * .01; 63 | tt.style.filter = 'alpha(opacity=' + alpha + ')'; 64 | }else{ 65 | clearInterval(tt.timer); 66 | if(d == -1){tt.style.display = 'none'} 67 | } 68 | }, 69 | hide:function(){ 70 | clearInterval(tt.timer); 71 | tt.timer = setInterval(function(){tooltip.fade(-1)},timer); 72 | } 73 | }; 74 | }(); -------------------------------------------------------------------------------- /iphoneSync/Classes/NSObject+JSON.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2009 Stig Brautaset. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the author nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #import 31 | 32 | #pragma mark JSON Writing 33 | 34 | /// Adds JSON generation to NSArray 35 | @interface NSArray (NSArray_SBJsonWriting) 36 | 37 | /// Returns a string containing the receiver encoded in JSON. 38 | - (NSString *)JSONRepresentation; 39 | 40 | @end 41 | 42 | 43 | /// Adds JSON generation to NSArray 44 | @interface NSDictionary (NSDictionary_SBJsonWriting) 45 | 46 | /// Returns a string containing the receiver encoded in JSON. 47 | - (NSString *)JSONRepresentation; 48 | 49 | @end 50 | 51 | #pragma mark JSON Parsing 52 | 53 | /// Adds JSON parsing methods to NSString 54 | @interface NSString (NSString_SBJsonParsing) 55 | 56 | /// Returns the NSDictionary or NSArray represented by the receiver's JSON representation, or nil on error 57 | - (id)JSONValue; 58 | 59 | @end 60 | 61 | 62 | -------------------------------------------------------------------------------- /iphoneSync/Classes/NSObject+JSON.m: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2009 Stig Brautaset. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the author nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #import "NSObject+JSON.h" 31 | #import "SBJsonWriter.h" 32 | #import "SBJsonParser.h" 33 | 34 | @implementation NSObject (NSObject_SBJsonWriting) 35 | 36 | - (NSString *)JSONRepresentation { 37 | SBJsonWriter *jsonWriter = [SBJsonWriter new]; 38 | NSString *json = [jsonWriter stringWithObject:self]; 39 | if (!json) 40 | NSLog(@"-JSONRepresentation failed. Error is: %@", jsonWriter.error); 41 | [jsonWriter release]; 42 | return json; 43 | } 44 | 45 | @end 46 | 47 | 48 | 49 | @implementation NSString (NSString_SBJsonParsing) 50 | 51 | - (id)JSONValue { 52 | SBJsonParser *jsonParser = [SBJsonParser new]; 53 | id repr = [jsonParser objectWithString:self]; 54 | if (!repr) 55 | NSLog(@"-JSONValue failed. Error is: %@", jsonParser.error); 56 | [jsonParser release]; 57 | return repr; 58 | } 59 | 60 | @end 61 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthConnection.m: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthConnection.m 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.05. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import "MPOAuthConnection.h" 10 | #import "MPOAuthURLRequest.h" 11 | #import "MPOAuthURLResponse.h" 12 | #import "MPOAuthParameterFactory.h" 13 | #import "MPOAuthCredentialConcreteStore.h" 14 | 15 | @interface MPOAuthURLResponse () 16 | @property (nonatomic, readwrite, retain) NSURLResponse *urlResponse; 17 | @property (nonatomic, readwrite, retain) NSDictionary *oauthParameters; 18 | @end 19 | 20 | @implementation MPOAuthConnection 21 | 22 | + (MPOAuthConnection *)connectionWithRequest:(MPOAuthURLRequest *)inRequest delegate:(id)inDelegate credentials:(NSObject *)inCredentials { 23 | MPOAuthConnection *aConnection = [[MPOAuthConnection alloc] initWithRequest:inRequest delegate:inDelegate credentials:inCredentials]; 24 | return [aConnection autorelease]; 25 | } 26 | 27 | + (NSData *)sendSynchronousRequest:(MPOAuthURLRequest *)inRequest usingCredentials:(NSObject *)inCredentials returningResponse:(MPOAuthURLResponse **)outResponse error:(NSError **)inError { 28 | [inRequest addParameters:[inCredentials oauthParameters]]; 29 | NSURLRequest *urlRequest = [inRequest urlRequestSignedWithSecret:[inCredentials signingKey] usingMethod:[inCredentials signatureMethod]]; 30 | NSURLResponse *urlResponse = nil; 31 | NSData *responseData = [self sendSynchronousRequest:urlRequest returningResponse:&urlResponse error:inError]; 32 | MPOAuthURLResponse *oauthResponse = [[[MPOAuthURLResponse alloc] init] autorelease]; 33 | oauthResponse.urlResponse = urlResponse; 34 | *outResponse = oauthResponse; 35 | 36 | return responseData; 37 | } 38 | 39 | - (id)initWithRequest:(MPOAuthURLRequest *)inRequest delegate:(id)inDelegate credentials:(NSObject *)inCredentials { 40 | [inRequest addParameters:[inCredentials oauthParameters]]; 41 | NSURLRequest *urlRequest = [inRequest urlRequestSignedWithSecret:[inCredentials signingKey] usingMethod:[inCredentials signatureMethod]]; 42 | if (self = [super initWithRequest:urlRequest delegate:inDelegate]) { 43 | _credentials = [inCredentials retain]; 44 | } 45 | return self; 46 | } 47 | 48 | - (oneway void)dealloc { 49 | [_credentials release]; 50 | 51 | [super dealloc]; 52 | } 53 | 54 | @synthesize credentials = _credentials; 55 | 56 | #pragma mark - 57 | 58 | @end 59 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/iphoneSyncAppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // iphoneSyncAppDelegate.m 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import "iphoneSyncAppDelegate.h" 10 | #import "SyncController.h" 11 | 12 | @implementation iphoneSyncAppDelegate 13 | 14 | @synthesize window=_window; 15 | @synthesize navigationController=_navigationController; 16 | @synthesize syncController; 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | 20 | // from dropbox app 21 | NSString *consumerKey = @"DROPBOX_CONSUMER_KEY"; 22 | NSString *consumerSecret = @"DROPBOX_CONSUMER_SECRET"; 23 | 24 | DBSession* session = [[DBSession alloc] initWithConsumerKey:consumerKey consumerSecret:consumerSecret]; 25 | session.delegate = self; 26 | [DBSession setSharedSession:session]; 27 | [session release]; 28 | 29 | self.window.rootViewController = self.navigationController; 30 | 31 | self.syncController = [[SyncController alloc] init]; 32 | 33 | [self.window makeKeyAndVisible]; 34 | return YES; 35 | } 36 | 37 | - (void)applicationDidBecomeActive:(UIApplication *)application { 38 | 39 | [self.syncController checkForCouchDBUpdates]; 40 | [self.syncController getLocalFileList]; 41 | 42 | if (![[DBSession sharedSession] isLinked]) { 43 | NSLog(@"is not Linked"); 44 | // your dropbox email and password 45 | [self.syncController.restClient loginWithEmail:@"DROPBOX_EMAIL" password:@"DROPBOX_PASSWORD"]; 46 | } else { 47 | NSLog(@"isLinked"); 48 | NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 49 | NSString *dropboxHash = [prefs stringForKey:@"dropboxHash"]; 50 | [self.syncController.restClient loadMetadata:@"/syncfolder" withHash:dropboxHash]; 51 | } 52 | } 53 | 54 | - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session { 55 | NSLog(@"Session received authorization failure."); 56 | } 57 | 58 | - (void)applicationWillResignActive:(UIApplication *)application{ 59 | } 60 | 61 | - (void)applicationDidEnterBackground:(UIApplication *)application { 62 | } 63 | 64 | - (void)applicationWillEnterForeground:(UIApplication *)application{ 65 | } 66 | 67 | - (void)applicationWillTerminate:(UIApplication *)application { 68 | } 69 | 70 | - (void)dealloc { 71 | [syncController release]; 72 | [_window release]; 73 | [_navigationController release]; 74 | [super dealloc]; 75 | } 76 | 77 | @end 78 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonTokeniser.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010, Stig Brautaset. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | Neither the name of the the author nor the names of its contributors 17 | may be used to endorse or promote products derived from this software 18 | without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 21 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 23 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #import 34 | 35 | typedef enum { 36 | sbjson_token_eof, 37 | sbjson_token_error, 38 | sbjson_token_object_start, 39 | sbjson_token_key_value_separator, 40 | sbjson_token_object_end, 41 | sbjson_token_array_start, 42 | sbjson_token_array_end, 43 | sbjson_token_separator, 44 | sbjson_token_string, 45 | sbjson_token_string_encoded, 46 | sbjson_token_integer, 47 | sbjson_token_double, 48 | sbjson_token_true, 49 | sbjson_token_false, 50 | sbjson_token_null, 51 | } sbjson_token_t; 52 | 53 | @interface SBJsonTokeniser : NSObject { 54 | NSUInteger tokenStart, tokenLength; 55 | NSMutableData *buf; 56 | const char *bufbytes; 57 | NSUInteger bufbytesLength; 58 | NSString *error; 59 | NSCharacterSet *illegalCharacterSet; 60 | } 61 | 62 | @property(copy, readonly) NSString *error; 63 | 64 | - (void)appendData:(NSData*)data; 65 | 66 | - (sbjson_token_t)next; 67 | - (BOOL)getToken:(const char **)utf8 length:(NSUInteger*)length; 68 | - (NSString*)getDecodedStringToken; 69 | 70 | @end 71 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/lib/path.js: -------------------------------------------------------------------------------- 1 | // from couch.js 2 | function encodeOptions(options) { 3 | var buf = []; 4 | if (typeof(options) == "object" && options !== null) { 5 | for (var name in options) { 6 | if (!options.hasOwnProperty(name)) {continue;} 7 | var value = options[name]; 8 | if (name == "key" || name == "startkey" || name == "endkey") { 9 | value = JSON.stringify(value); 10 | } 11 | buf.push(encodeURIComponent(name) + "=" + encodeURIComponent(value)); 12 | } 13 | } 14 | if (!buf.length) { 15 | return ""; 16 | } 17 | return "?" + buf.join("&"); 18 | } 19 | 20 | function concatArgs(array, args) { 21 | for (var i=0; i < args.length; i++) { 22 | array.push(args[i]); 23 | }; 24 | return array; 25 | }; 26 | 27 | function makePath(array) { 28 | var options, path; 29 | 30 | if (typeof array[array.length - 1] != "string") { 31 | // it's a params hash 32 | options = array.pop(); 33 | } 34 | path = array.map(function(item) {return encodeURIComponent(item)}).join('/'); 35 | if (options) { 36 | return path + encodeOptions(options); 37 | } else { 38 | return path; 39 | } 40 | }; 41 | 42 | exports.init = function(req) { 43 | return { 44 | asset : function() { 45 | var p = req.path, parts = ['', p[0], p[1] , p[2]]; 46 | return makePath(concatArgs(parts, arguments)); 47 | }, 48 | show : function() { 49 | var p = req.path, parts = ['', p[0], p[1] , p[2], '_show']; 50 | return makePath(concatArgs(parts, arguments)); 51 | }, 52 | list : function() { 53 | var p = req.path, parts = ['', p[0], p[1] , p[2], '_list']; 54 | return makePath(concatArgs(parts, arguments)); 55 | }, 56 | update : function() { 57 | var p = req.path, parts = ['', p[0], p[1] , p[2], '_update']; 58 | return makePath(concatArgs(parts, arguments)); 59 | }, 60 | limit : function(limit) { 61 | var query = req.query; 62 | var l = query.limit; 63 | query.limit = limit; 64 | var view = req.path[req.path.length - 1]; 65 | var list = req.path[req.path.length - 2]; 66 | var link = this.list(list, view, query); 67 | query.limit = l; 68 | return link; 69 | }, 70 | older : function(key) { 71 | if (!typeof key == "undefined") return null; 72 | var query = req.query; 73 | query.startkey = key; 74 | query.skip=1; 75 | var view = req.path[req.path.length - 1]; 76 | var list = req.path[req.path.length - 2]; 77 | return this.list(list, view, query); 78 | }, 79 | absolute : function(path) { 80 | return 'http://' + req.headers.Host + path; 81 | } 82 | } 83 | }; 84 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/DBRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // DBRestRequest.h 3 | // DropboxSDK 4 | // 5 | // Created by Brian Smith on 4/9/10. 6 | // Copyright 2010 Dropbox, Inc. All rights reserved. 7 | // 8 | 9 | 10 | @protocol DBNetworkRequestDelegate; 11 | 12 | /* DBRestRequest will download a URL either into a file that you provied the name to or it will 13 | create an NSData object with the result. When it has completed downloading the URL, it will 14 | notify the target with a selector that takes the DBRestRequest as the only parameter. */ 15 | @interface DBRequest : NSObject { 16 | NSURLRequest* request; 17 | id target; 18 | SEL selector; 19 | NSURLConnection* urlConnection; 20 | NSFileHandle* fileHandle; 21 | 22 | SEL failureSelector; 23 | SEL downloadProgressSelector; 24 | SEL uploadProgressSelector; 25 | NSString* resultFilename; 26 | NSString* tempFilename; 27 | NSDictionary* userInfo; 28 | 29 | NSHTTPURLResponse* response; 30 | NSInteger bytesDownloaded; 31 | CGFloat downloadProgress; 32 | CGFloat uploadProgress; 33 | NSMutableData* resultData; 34 | NSError* error; 35 | } 36 | 37 | /* Set this to get called when _any_ request starts or stops. This should hook into whatever 38 | network activity indicator system you have. */ 39 | + (void)setNetworkRequestDelegate:(id)delegate; 40 | 41 | /* This constructor downloads the URL into the resultData object */ 42 | - (id)initWithURLRequest:(NSURLRequest*)request andInformTarget:(id)target selector:(SEL)selector; 43 | 44 | /* Cancels the request and prevents it from sending additional messages to the delegate. */ 45 | - (void)cancel; 46 | 47 | @property (nonatomic, assign) SEL failureSelector; // To send failure events to a different selector set this 48 | @property (nonatomic, assign) SEL downloadProgressSelector; // To receive download progress events set this 49 | @property (nonatomic, assign) SEL uploadProgressSelector; // To receive upload progress events set this 50 | @property (nonatomic, retain) NSString* resultFilename; // The file to put the HTTP body in, otherwise body is stored in resultData 51 | @property (nonatomic, retain) NSDictionary* userInfo; 52 | 53 | @property (nonatomic, readonly) NSURLRequest* request; 54 | @property (nonatomic, readonly) NSHTTPURLResponse* response; 55 | @property (nonatomic, readonly) NSInteger statusCode; 56 | @property (nonatomic, readonly) CGFloat downloadProgress; 57 | @property (nonatomic, readonly) CGFloat uploadProgress; 58 | @property (nonatomic, readonly) NSData* resultData; 59 | @property (nonatomic, readonly) NSString* resultString; 60 | @property (nonatomic, readonly) NSObject* resultJSON; 61 | @property (nonatomic, readonly) NSError* error; 62 | 63 | @end 64 | 65 | 66 | @protocol DBNetworkRequestDelegate 67 | 68 | - (void)networkRequestStarted; 69 | - (void)networkRequestStopped; 70 | 71 | @end 72 | -------------------------------------------------------------------------------- /iphoneSync/AsiHttpRequest/ASIFormDataRequest.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASIFormDataRequest.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 07/11/2008. 6 | // Copyright 2008-2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "ASIHTTPRequest.h" 11 | #import "ASIHTTPRequestConfig.h" 12 | 13 | typedef enum _ASIPostFormat { 14 | ASIMultipartFormDataPostFormat = 0, 15 | ASIURLEncodedPostFormat = 1 16 | 17 | } ASIPostFormat; 18 | 19 | @interface ASIFormDataRequest : ASIHTTPRequest { 20 | 21 | // Parameters that will be POSTed to the url 22 | NSMutableArray *postData; 23 | 24 | // Files that will be POSTed to the url 25 | NSMutableArray *fileData; 26 | 27 | ASIPostFormat postFormat; 28 | 29 | NSStringEncoding stringEncoding; 30 | 31 | #if DEBUG_FORM_DATA_REQUEST 32 | // Will store a string version of the request body that will be printed to the console when ASIHTTPREQUEST_DEBUG is set in GCC_PREPROCESSOR_DEFINITIONS 33 | NSString *debugBodyString; 34 | #endif 35 | 36 | } 37 | 38 | #pragma mark utilities 39 | - (NSString*)encodeURL:(NSString *)string; 40 | 41 | #pragma mark setup request 42 | 43 | // Add a POST variable to the request 44 | - (void)addPostValue:(id )value forKey:(NSString *)key; 45 | 46 | // Set a POST variable for this request, clearing any others with the same key 47 | - (void)setPostValue:(id )value forKey:(NSString *)key; 48 | 49 | // Add the contents of a local file to the request 50 | - (void)addFile:(NSString *)filePath forKey:(NSString *)key; 51 | 52 | // Same as above, but you can specify the content-type and file name 53 | - (void)addFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key; 54 | 55 | // Add the contents of a local file to the request, clearing any others with the same key 56 | - (void)setFile:(NSString *)filePath forKey:(NSString *)key; 57 | 58 | // Same as above, but you can specify the content-type and file name 59 | - (void)setFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key; 60 | 61 | // Add the contents of an NSData object to the request 62 | - (void)addData:(NSData *)data forKey:(NSString *)key; 63 | 64 | // Same as above, but you can specify the content-type and file name 65 | - (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key; 66 | 67 | // Add the contents of an NSData object to the request, clearing any others with the same key 68 | - (void)setData:(NSData *)data forKey:(NSString *)key; 69 | 70 | // Same as above, but you can specify the content-type and file name 71 | - (void)setData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key; 72 | 73 | 74 | @property (assign) ASIPostFormat postFormat; 75 | @property (assign) NSStringEncoding stringEncoding; 76 | @end 77 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/DataController.m: -------------------------------------------------------------------------------- 1 | // 2 | // DataController.m 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import "DataController.h" 10 | #import "JSON.h" 11 | #import "Product.h" 12 | 13 | @implementation DataController 14 | 15 | @synthesize product, currentProduct; 16 | 17 | -(id) init { 18 | if ((self = [super init])) { 19 | [self loadJsonFromFile]; 20 | } 21 | return self; 22 | } 23 | 24 | -(void) loadJsonFromFile { 25 | 26 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 27 | NSString *documentsDirectory = [paths objectAtIndex:0]; 28 | NSString *documentProductFilePath = [documentsDirectory stringByAppendingPathComponent:@"product.json"]; 29 | NSString *bundleProductFilePath = [[NSBundle mainBundle] pathForResource:@"product" ofType:@"json"]; 30 | NSString *productFilePath; 31 | NSFileManager *fileManager = [[NSFileManager alloc] init]; 32 | 33 | // means we have a product.json file from couchdb 34 | if ([fileManager fileExistsAtPath:documentProductFilePath]) { 35 | // NSLog(@"documentProductFilePath: %@", documentProductFilePath); 36 | productFilePath = [[NSString alloc] initWithString:documentProductFilePath]; 37 | } else { 38 | // NSLog(@"bundleProductFilePath: %@", bundleProductFilePath); 39 | productFilePath = [[NSString alloc] initWithString:bundleProductFilePath]; 40 | } 41 | [fileManager release]; 42 | 43 | NSError *error = nil; 44 | NSString *fileContent = [[NSString alloc] initWithContentsOfFile:productFilePath encoding:NSUTF8StringEncoding error:&error]; 45 | if (error) { 46 | NSLog(@"file error: %@", [error localizedDescription]); 47 | } 48 | [productFilePath release]; 49 | 50 | SBJsonParser *parser = [[SBJsonParser alloc] init]; 51 | NSDictionary *json = (NSDictionary *) [parser objectWithString:fileContent error:nil]; 52 | NSArray *items = [json objectForKey:@"rows"]; 53 | 54 | self.product = [NSMutableArray arrayWithCapacity: 5]; 55 | 56 | for (int i = 0; i < [items count]; i++) { 57 | Product *tempProduct = [[Product alloc] init]; 58 | 59 | NSDictionary *value = [[items objectAtIndex:i] objectForKey:@"value"]; 60 | tempProduct.productID = [value objectForKey:@"_id"]; 61 | tempProduct.name = [value objectForKey:@"name"]; 62 | tempProduct.description = [value objectForKey:@"description"]; 63 | tempProduct.image = [value objectForKey:@"image"]; 64 | 65 | [self.product addObject:tempProduct]; 66 | [tempProduct release]; 67 | } 68 | 69 | self.currentProduct = [[NSMutableString alloc] initWithString:@""]; 70 | 71 | [fileContent release]; 72 | [parser release]; 73 | } 74 | 75 | - (void)dealloc { 76 | [product release]; 77 | [currentProduct release]; 78 | [super dealloc]; 79 | } 80 | 81 | @end 82 | 83 | -------------------------------------------------------------------------------- /iphoneSync/Classes/JSON.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2009-2010 Stig Brautaset. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the author nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | /** 31 | @mainpage A strict JSON parser and generator for Objective-C 32 | 33 | JSON (JavaScript Object Notation) is a lightweight data-interchange 34 | format. This framework provides two apis for parsing and generating 35 | JSON. One standard object-based and a higher level api consisting of 36 | categories added to existing Objective-C classes. 37 | 38 | This framework does its best to be as strict as possible, both in what it accepts and what it generates. For example, it does not support trailing commas in arrays or objects. Nor does it support embedded comments, or anything else not in the JSON specification. This is considered a feature. 39 | 40 | @section Links 41 | 42 | @li Project home page. 43 | @li Online version of the API documentation. 44 | 45 | */ 46 | 47 | 48 | // This setting of 1 is best if you copy the source into your project. 49 | // The build transforms the 1 to a 0 when building the framework and static lib. 50 | 51 | #if 1 52 | 53 | #import "SBJsonParser.h" 54 | #import "SBJsonWriter.h" 55 | #import "SBJsonStreamWriter.h" 56 | #import "SBJsonStreamParser.h" 57 | #import "SBJsonStreamParserAdapter.h" 58 | #import "NSObject+JSON.h" 59 | 60 | #else 61 | 62 | #import 63 | #import 64 | #import 65 | #import 66 | #import 67 | #import 68 | 69 | #endif 70 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonStreamWriterState.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010, Stig Brautaset. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | Neither the name of the the author nor the names of its contributors 17 | may be used to endorse or promote products derived from this software 18 | without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 21 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 23 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #import 34 | 35 | @class SBJsonStreamWriter; 36 | 37 | @interface SBJsonStreamWriterState : NSObject 38 | - (BOOL)isInvalidState:(SBJsonStreamWriter*)writer; 39 | - (void)appendSeparator:(SBJsonStreamWriter*)writer; 40 | - (BOOL)expectingKey:(SBJsonStreamWriter*)writer; 41 | - (void)transitionState:(SBJsonStreamWriter*)writer; 42 | - (void)appendWhitespace:(SBJsonStreamWriter*)writer; 43 | @end 44 | 45 | @interface SBJsonStreamWriterStateObjectStart : SBJsonStreamWriterState 46 | @end 47 | 48 | @interface SBJsonStreamWriterStateObjectKey : SBJsonStreamWriterStateObjectStart 49 | @end 50 | 51 | @interface SBJsonStreamWriterStateObjectValue : SBJsonStreamWriterState 52 | @end 53 | 54 | @interface SBJsonStreamWriterStateArrayStart : SBJsonStreamWriterState 55 | @end 56 | 57 | @interface SBJsonStreamWriterStateArrayValue : SBJsonStreamWriterState 58 | @end 59 | 60 | @interface SBJsonStreamWriterStateStart : SBJsonStreamWriterState 61 | + (id)sharedInstance; 62 | @end 63 | 64 | @interface SBJsonStreamWriterStateComplete : SBJsonStreamWriterState 65 | @end 66 | 67 | @interface SBJsonStreamWriterStateError : SBJsonStreamWriterState 68 | @end 69 | 70 | extern SBJsonStreamWriterStateStart *kSBJsonStreamWriterStateStart; 71 | extern SBJsonStreamWriterStateComplete *kSBJsonStreamWriterStateComplete; 72 | extern SBJsonStreamWriterStateError *kSBJsonStreamWriterStateError; 73 | extern SBJsonStreamWriterStateObjectStart *kSBJsonStreamWriterStateObjectStart; 74 | extern SBJsonStreamWriterStateArrayStart *kSBJsonStreamWriterStateArrayStart; 75 | 76 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthSignatureParameter.m: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthSignatureParameter.m 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.07. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import "MPOAuthSignatureParameter.h" 10 | #import "MPOAuthURLRequest.h" 11 | #import "NSString+URLEscapingAdditions.h" 12 | #import "NSURL+MPURLParameterAdditions.h" 13 | 14 | #import 15 | #include "Base64Transcoder.h" 16 | 17 | @interface MPOAuthSignatureParameter () 18 | - (id)initUsingHMAC_SHA1WithText:(NSString *)inText andSecret:(NSString *)inSecret forRequest:(MPOAuthURLRequest *)inRequest; 19 | @end 20 | 21 | @implementation MPOAuthSignatureParameter 22 | 23 | + (NSString *)signatureBaseStringUsingParameterString:(NSString *)inParameterString forRequest:(MPOAuthURLRequest *)inRequest { 24 | return [NSString stringWithFormat:@"%@&%@&%@", [inRequest HTTPMethod], 25 | [[inRequest.url absoluteNormalizedString] stringByAddingURIPercentEscapesUsingEncoding:NSUTF8StringEncoding], 26 | [inParameterString stringByAddingURIPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 27 | } 28 | 29 | + (NSString *)HMAC_SHA1SignatureForText:(NSString *)inText usingSecret:(NSString *)inSecret { 30 | NSData *secretData = [inSecret dataUsingEncoding:NSUTF8StringEncoding]; 31 | NSData *textData = [inText dataUsingEncoding:NSUTF8StringEncoding]; 32 | unsigned char result[CC_SHA1_DIGEST_LENGTH]; 33 | 34 | CCHmacContext hmacContext; 35 | bzero(&hmacContext, sizeof(CCHmacContext)); 36 | CCHmacInit(&hmacContext, kCCHmacAlgSHA1, secretData.bytes, secretData.length); 37 | CCHmacUpdate(&hmacContext, textData.bytes, textData.length); 38 | CCHmacFinal(&hmacContext, result); 39 | 40 | //Base64 Encoding 41 | char base64Result[32]; 42 | size_t theResultLength = 32; 43 | Base64EncodeData(result, 20, base64Result, &theResultLength); 44 | NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength]; 45 | NSString *base64EncodedResult = [[[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding] autorelease]; 46 | 47 | return base64EncodedResult; 48 | } 49 | 50 | - (id)initWithText:(NSString *)inText andSecret:(NSString *)inSecret forRequest:(MPOAuthURLRequest *)inRequest usingMethod:(NSString *)inMethod { 51 | if ([inMethod isEqual:kMPOAuthSignatureMethodHMACSHA1]) { 52 | self = [self initUsingHMAC_SHA1WithText:inText andSecret:inSecret forRequest:inRequest]; 53 | } else if ([inMethod isEqualToString:kMPOAuthSignatureMethodPlaintext]) { 54 | if (self = [super init]) { 55 | self.name = @"oauth_signature"; 56 | self.value = inSecret; 57 | } 58 | } else { 59 | [self release]; 60 | self = nil; 61 | [NSException raise:@"Unsupported Signature Method" format:@"The signature method \"%@\" is not currently support by MPOAuthConnection", inMethod]; 62 | } 63 | 64 | return self; 65 | } 66 | 67 | - (id)initUsingHMAC_SHA1WithText:(NSString *)inText andSecret:(NSString *)inSecret forRequest:(MPOAuthURLRequest *)inRequest { 68 | if (self = [super init]) { 69 | NSString *signatureBaseString = [MPOAuthSignatureParameter signatureBaseStringUsingParameterString:inText forRequest:inRequest]; 70 | 71 | self.name = @"oauth_signature"; 72 | self.value = [MPOAuthSignatureParameter HMAC_SHA1SignatureForText:signatureBaseString usingSecret:inSecret]; 73 | } 74 | return self; 75 | } 76 | 77 | - (oneway void)dealloc { 78 | [super dealloc]; 79 | } 80 | 81 | @end 82 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/_attachments/jquery.couch.app.util.js: -------------------------------------------------------------------------------- 1 | $.log = function(m) { 2 | if (window && window.console && window.console.log) { 3 | window.console.log(arguments.length == 1 ? m : arguments); 4 | } 5 | }; 6 | 7 | // http://stackoverflow.com/questions/1184624/serialize-form-to-json-with-jquery/1186309#1186309 8 | $.fn.serializeObject = function() { 9 | var o = {}; 10 | var a = this.serializeArray(); 11 | $.each(a, function() { 12 | if (o[this.name]) { 13 | if (!o[this.name].push) { 14 | o[this.name] = [o[this.name]]; 15 | } 16 | o[this.name].push(this.value || ''); 17 | } else { 18 | o[this.name] = this.value || ''; 19 | } 20 | }); 21 | return o; 22 | }; 23 | 24 | // todo remove this crap 25 | function escapeHTML(st) { 26 | return( 27 | st && st.replace(/&/g,'&'). 28 | replace(/>/g,'>'). 29 | replace(/'+a+''; 42 | }).replace(/\@([\w\-]+)/g,function(user,name) { 43 | return ''+user+''; 44 | }).replace(/\#([\w\-\.]+)/g,function(word,tag) { 45 | return ''+word+''; 46 | }); 47 | }; 48 | 49 | $.fn.prettyDate = function() { 50 | $(this).each(function() { 51 | var string, title = $(this).attr("title"); 52 | if (title) { 53 | string = $.prettyDate(title); 54 | } else { 55 | string = $.prettyDate($(this).text()); 56 | } 57 | $(this).text(string); 58 | }); 59 | }; 60 | 61 | $.prettyDate = function(time){ 62 | 63 | var date = new Date(time.replace(/-/g,"/").replace("T", " ").replace("Z", " +0000").replace(/(\d*\:\d*:\d*)\.\d*/g,"$1")), 64 | diff = (((new Date()).getTime() - date.getTime()) / 1000), 65 | day_diff = Math.floor(diff / 86400); 66 | 67 | if (isNaN(day_diff)) return time; 68 | 69 | return day_diff < 1 && ( 70 | diff < 60 && "just now" || 71 | diff < 120 && "1 minute ago" || 72 | diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" || 73 | diff < 7200 && "1 hour ago" || 74 | diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") || 75 | day_diff == 1 && "yesterday" || 76 | day_diff < 21 && day_diff + " days ago" || 77 | day_diff < 45 && Math.ceil( day_diff / 7 ) + " weeks ago" || 78 | time; 79 | // day_diff < 730 && Math.ceil( day_diff / 31 ) + " months ago" || 80 | // Math.ceil( day_diff / 365 ) + " years ago"; 81 | }; 82 | 83 | $.argsToArray = function(args) { 84 | if (!args.callee) return args; 85 | var array = []; 86 | for (var i=0; i < args.length; i++) { 87 | array.push(args[i]); 88 | }; 89 | return array; 90 | } 91 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonStreamParserAdapter.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010, Stig Brautaset. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | Neither the name of the the author nor the names of its contributors 17 | may be used to endorse or promote products derived from this software 18 | without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 21 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 23 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #import 34 | #import "SBJsonStreamParser.h" 35 | 36 | typedef enum { 37 | SBJsonStreamParserAdapterNone, 38 | SBJsonStreamParserAdapterArray, 39 | SBJsonStreamParserAdapterObject, 40 | } SBJsonStreamParserAdapterType; 41 | 42 | /** 43 | @brief Delegate for getting objects & arrays from the stream parser adapter 44 | 45 | You will most likely find it much more convenient to implement this 46 | than the raw SBJsonStreamParserDelegate protocol. 47 | 48 | @see The TwitterStream example project. 49 | */ 50 | @protocol SBJsonStreamParserAdapterDelegate 51 | @optional 52 | /// Called when a JSON array is found 53 | - (void)parser:(SBJsonStreamParser*)parser foundArray:(NSArray*)array; 54 | 55 | /// Called when a JSON object is found 56 | - (void)parser:(SBJsonStreamParser*)parser foundObject:(NSDictionary*)dict; 57 | 58 | @end 59 | 60 | 61 | @interface SBJsonStreamParserAdapter : NSObject { 62 | id delegate; 63 | NSUInteger skip, depth; 64 | __weak NSMutableArray *array; 65 | __weak NSMutableDictionary *dict; 66 | NSMutableArray *keyStack; 67 | NSMutableArray *stack; 68 | 69 | SBJsonStreamParserAdapterType currentType; 70 | } 71 | 72 | /** 73 | @brief How many levels to skip 74 | 75 | This is useful for parsing HUGE JSON documents, particularly if it consists of an 76 | outer array and multiple objects. 77 | 78 | If you set this to N it will skip the outer N levels and call the -parser:foundArray: 79 | or -parser:foundObject: methods for each of the inner objects, as appropriate. 80 | 81 | @see The StreamParserIntegrationTest.m file for examples 82 | */ 83 | @property NSUInteger skip; 84 | 85 | /// Set this to the object you want to receive messages 86 | @property (assign) id delegate; 87 | 88 | @end 89 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonStreamParserState.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010, Stig Brautaset. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | Neither the name of the the author nor the names of its contributors 17 | may be used to endorse or promote products derived from this software 18 | without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 21 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 23 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #import 34 | 35 | #import "SBJsonTokeniser.h" 36 | #import "SBJsonStreamParser.h" 37 | 38 | @interface SBJsonStreamParserState : NSObject 39 | 40 | - (BOOL)parser:(SBJsonStreamParser*)parser shouldAcceptToken:(sbjson_token_t)token; 41 | - (BOOL)parserShouldStop:(SBJsonStreamParser*)parser; 42 | - (SBJsonStreamParserStatus)parserShouldReturn:(SBJsonStreamParser*)parser; 43 | - (void)parser:(SBJsonStreamParser*)parser shouldTransitionTo:(sbjson_token_t)tok; 44 | - (BOOL)needKey; 45 | 46 | - (NSString*)name; 47 | 48 | @end 49 | 50 | @interface SBJsonStreamParserStateStart : SBJsonStreamParserState 51 | + (id)sharedInstance; 52 | @end 53 | 54 | @interface SBJsonStreamParserStateComplete : SBJsonStreamParserState 55 | @end 56 | 57 | @interface SBJsonStreamParserStateError : SBJsonStreamParserState 58 | @end 59 | 60 | 61 | @interface SBJsonStreamParserStateObjectStart : SBJsonStreamParserState 62 | @end 63 | 64 | @interface SBJsonStreamParserStateObjectGotKey : SBJsonStreamParserState 65 | @end 66 | 67 | @interface SBJsonStreamParserStateObjectSeparator : SBJsonStreamParserState 68 | @end 69 | 70 | @interface SBJsonStreamParserStateObjectGotValue : SBJsonStreamParserState 71 | @end 72 | 73 | @interface SBJsonStreamParserStateObjectNeedKey : SBJsonStreamParserState 74 | @end 75 | 76 | @interface SBJsonStreamParserStateArrayStart : SBJsonStreamParserState 77 | @end 78 | 79 | @interface SBJsonStreamParserStateArrayGotValue : SBJsonStreamParserState 80 | @end 81 | 82 | @interface SBJsonStreamParserStateArrayNeedValue : SBJsonStreamParserState 83 | @end 84 | 85 | extern SBJsonStreamParserStateStart *kSBJsonStreamParserStateStart; 86 | extern SBJsonStreamParserStateError *kSBJsonStreamParserStateError; 87 | extern SBJsonStreamParserStateObjectStart *kSBJsonStreamParserStateObjectStart; 88 | extern SBJsonStreamParserStateArrayStart *kSBJsonStreamParserStateArrayStart; 89 | 90 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthCredentiaIConcreteStore+KeychainAdditionsMac.m: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthCredentialConcreteStore+TokenAdditionsMac.m 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.13. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import "MPOAuthCredentialConcreteStore+KeychainAdditions.h" 10 | 11 | #if !TARGET_OS_IPHONE || (TARGET_IPHONE_SIMULATOR && !__IPHONE_3_0) 12 | 13 | @interface MPOAuthCredentialConcreteStore (KeychainAdditionsMac) 14 | - (NSString *)findValueFromKeychainUsingName:(NSString *)inName returningItem:(SecKeychainItemRef *)outKeychainItemRef; 15 | @end 16 | 17 | @implementation MPOAuthCredentialConcreteStore (KeychainAdditions) 18 | 19 | - (void)addToKeychainUsingName:(NSString *)inName andValue:(NSString *)inValue { 20 | NSString *serverName = [self.baseURL host]; 21 | NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier]; 22 | NSString *securityDomain = [self.authenticationURL host]; 23 | NSString *uniqueName = [NSString stringWithFormat:@"%@.%@", bundleID, inName]; 24 | SecKeychainItemRef existingKeychainItem = NULL; 25 | 26 | if ([self findValueFromKeychainUsingName:inName returningItem:&existingKeychainItem]) { 27 | // This is MUCH easier than updating the item attributes/data 28 | SecKeychainItemDelete(existingKeychainItem); 29 | } 30 | 31 | SecKeychainAddInternetPassword(NULL /* default keychain */, 32 | [serverName length], [serverName UTF8String], 33 | [securityDomain length], [securityDomain UTF8String], 34 | [uniqueName length], [uniqueName UTF8String], /* account name */ 35 | 0, NULL, /* path */ 36 | 0, 37 | 'oaut' /* OAuth, not an official OSType code */, 38 | kSecAuthenticationTypeDefault, 39 | [inValue length], [inValue UTF8String], 40 | NULL); 41 | } 42 | 43 | - (NSString *)findValueFromKeychainUsingName:(NSString *)inName { 44 | return [self findValueFromKeychainUsingName:inName returningItem:NULL]; 45 | } 46 | 47 | - (NSString *)findValueFromKeychainUsingName:(NSString *)inName returningItem:(SecKeychainItemRef *)outKeychainItemRef { 48 | NSString *foundPassword = nil; 49 | NSString *serverName = [self.baseURL host]; 50 | NSString *securityDomain = [self.authenticationURL host]; 51 | NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier]; 52 | NSString *uniqueName = [NSString stringWithFormat:@"%@.%@", bundleID, inName]; 53 | 54 | UInt32 passwordLength = 0; 55 | const char *passwordString = NULL; 56 | 57 | OSStatus status = SecKeychainFindInternetPassword(NULL /* default keychain */, 58 | [serverName length], [serverName UTF8String], 59 | [securityDomain length], [securityDomain UTF8String], 60 | [uniqueName length], [uniqueName UTF8String], 61 | 0, NULL, /* path */ 62 | 0, 63 | kSecProtocolTypeAny, 64 | kSecAuthenticationTypeAny, 65 | (UInt32 *)&passwordLength, 66 | (void **)&passwordString, 67 | outKeychainItemRef); 68 | 69 | if (status == noErr && passwordLength) { 70 | NSData *passwordStringData = [NSData dataWithBytes:passwordString length:passwordLength]; 71 | foundPassword = [[NSString alloc] initWithData:passwordStringData encoding:NSUTF8StringEncoding]; 72 | } 73 | 74 | return [foundPassword autorelease]; 75 | } 76 | 77 | - (void)removeValueFromKeychainUsingName:(NSString *)inName { 78 | SecKeychainItemRef aKeychainItem = NULL; 79 | 80 | [self findValueFromKeychainUsingName:inName returningItem:&aKeychainItem]; 81 | 82 | if (aKeychainItem) { 83 | SecKeychainItemDelete(aKeychainItem); 84 | } 85 | } 86 | 87 | @end 88 | 89 | #endif 90 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonWriter.m: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2009 Stig Brautaset. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the author nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #import "SBJsonWriter.h" 31 | #import "SBJsonStreamWriter.h" 32 | 33 | @implementation SBJsonWriter 34 | 35 | @synthesize sortKeys; 36 | @synthesize humanReadable; 37 | 38 | @synthesize error; 39 | @synthesize maxDepth; 40 | 41 | - (id)init { 42 | self = [super init]; 43 | if (self) 44 | self.maxDepth = 512; 45 | return self; 46 | } 47 | 48 | - (void)dealloc { 49 | [error release]; 50 | [super dealloc]; 51 | } 52 | 53 | - (NSString*)stringWithObject:(id)value { 54 | NSData *data = [self dataWithObject:value]; 55 | if (data) 56 | return [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; 57 | return nil; 58 | } 59 | 60 | - (NSString*)stringWithObject:(id)value error:(NSError**)error_ { 61 | NSString *tmp = [self stringWithObject:value]; 62 | if (tmp) 63 | return tmp; 64 | 65 | if (error_) { 66 | NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:error, NSLocalizedDescriptionKey, nil]; 67 | *error_ = [NSError errorWithDomain:@"org.brautaset.json.parser.ErrorDomain" code:0 userInfo:ui]; 68 | } 69 | 70 | return nil; 71 | } 72 | 73 | - (NSData*)dataWithObject:(id)object { 74 | SBJsonStreamWriter *streamWriter = [[[SBJsonStreamWriter alloc] init] autorelease]; 75 | streamWriter.sortKeys = self.sortKeys; 76 | streamWriter.maxDepth = self.maxDepth; 77 | streamWriter.humanReadable = self.humanReadable; 78 | 79 | BOOL ok = NO; 80 | if ([object isKindOfClass:[NSDictionary class]]) 81 | ok = [streamWriter writeObject:object]; 82 | 83 | else if ([object isKindOfClass:[NSArray class]]) 84 | ok = [streamWriter writeArray:object]; 85 | 86 | else if ([object respondsToSelector:@selector(proxyForJson)]) 87 | return [self dataWithObject:[object proxyForJson]]; 88 | else { 89 | self.error = @"Not valid type for JSON"; 90 | return nil; 91 | } 92 | 93 | if (ok) 94 | return streamWriter.data; 95 | 96 | self.error = streamWriter.error; 97 | return nil; 98 | } 99 | 100 | 101 | 102 | @end 103 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthURLRequest.m: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthURLRequest.m 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.05. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import "MPOAuthURLRequest.h" 10 | #import "MPURLRequestParameter.h" 11 | #import "MPOAuthSignatureParameter.h" 12 | #import "MPDebug.h" 13 | 14 | #import "NSURL+MPURLParameterAdditions.h" 15 | #import "NSString+URLEscapingAdditions.h" 16 | 17 | @interface MPOAuthURLRequest () 18 | @property (nonatomic, readwrite, retain) NSURLRequest *urlRequest; 19 | @end 20 | 21 | @implementation MPOAuthURLRequest 22 | 23 | - (id)initWithURL:(NSURL *)inURL andParameters:(NSArray *)inParameters { 24 | if (self = [super init]) { 25 | self.url = inURL; 26 | _parameters = inParameters ? [inParameters mutableCopy] : [[NSMutableArray alloc] initWithCapacity:10]; 27 | self.HTTPMethod = @"GET"; 28 | } 29 | return self; 30 | } 31 | 32 | - (id)initWithURLRequest:(NSURLRequest *)inRequest { 33 | if (self = [super init]) { 34 | self.url = [[inRequest URL] urlByRemovingQuery]; 35 | self.parameters = [[MPURLRequestParameter parametersFromString:[[inRequest URL] query]] mutableCopy]; 36 | self.HTTPMethod = [inRequest HTTPMethod]; 37 | } 38 | return self; 39 | } 40 | 41 | - (oneway void)dealloc { 42 | self.url = nil; 43 | self.HTTPMethod = nil; 44 | self.urlRequest = nil; 45 | self.parameters = nil; 46 | 47 | [super dealloc]; 48 | } 49 | 50 | @synthesize url = _url; 51 | @synthesize HTTPMethod = _httpMethod; 52 | @synthesize urlRequest = _urlRequest; 53 | @synthesize parameters = _parameters; 54 | 55 | #pragma mark - 56 | 57 | - (NSMutableURLRequest*)urlRequestSignedWithSecret:(NSString *)inSecret usingMethod:(NSString *)inScheme { 58 | [self.parameters sortUsingSelector:@selector(compare:)]; 59 | 60 | NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc] init]; 61 | NSMutableString *parameterString = [[NSMutableString alloc] initWithString:[MPURLRequestParameter parameterStringForParameters:self.parameters]]; 62 | MPOAuthSignatureParameter *signatureParameter = [[MPOAuthSignatureParameter alloc] initWithText:parameterString andSecret:inSecret forRequest:self usingMethod:inScheme]; 63 | [parameterString appendFormat:@"&%@", [signatureParameter URLEncodedParameterString]]; 64 | 65 | [aRequest setHTTPMethod:self.HTTPMethod]; 66 | 67 | if ([[self HTTPMethod] isEqualToString:@"GET"] && [self.parameters count]) { 68 | NSString *urlString = [NSString stringWithFormat:@"%@?%@", [self.url absoluteString], parameterString]; 69 | MPLog( @"urlString - %@", urlString); 70 | 71 | [aRequest setURL:[NSURL URLWithString:urlString]]; 72 | } else if ([[self HTTPMethod] isEqualToString:@"POST"]) { 73 | NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding]; 74 | MPLog(@"urlString - %@", self.url); 75 | MPLog(@"postDataString - %@", parameterString); 76 | 77 | [aRequest setURL:self.url]; 78 | [aRequest setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"]; 79 | [aRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 80 | [aRequest setHTTPBody:postData]; 81 | } else { 82 | [NSException raise:@"UnhandledHTTPMethodException" format:@"The requested HTTP method, %@, is not supported", self.HTTPMethod]; 83 | } 84 | 85 | [parameterString release]; 86 | [signatureParameter release]; 87 | 88 | self.urlRequest = aRequest; 89 | [aRequest release]; 90 | 91 | return aRequest; 92 | } 93 | 94 | #pragma mark - 95 | 96 | - (void)addParameters:(NSArray *)inParameters { 97 | [self.parameters addObjectsFromArray:inParameters]; 98 | } 99 | 100 | @end 101 | -------------------------------------------------------------------------------- /iphoneSync/AsiHttpRequest/ASIInputStream.m: -------------------------------------------------------------------------------- 1 | // 2 | // ASIInputStream.m 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 10/08/2009. 6 | // Copyright 2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import "ASIInputStream.h" 10 | #import "ASIHTTPRequest.h" 11 | 12 | // Used to ensure only one request can read data at once 13 | static NSLock *readLock = nil; 14 | 15 | @implementation ASIInputStream 16 | 17 | + (void)initialize 18 | { 19 | if (self == [ASIInputStream class]) { 20 | readLock = [[NSLock alloc] init]; 21 | } 22 | } 23 | 24 | + (id)inputStreamWithFileAtPath:(NSString *)path request:(ASIHTTPRequest *)theRequest 25 | { 26 | ASIInputStream *theStream = [[[self alloc] init] autorelease]; 27 | [theStream setRequest:theRequest]; 28 | [theStream setStream:[NSInputStream inputStreamWithFileAtPath:path]]; 29 | return theStream; 30 | } 31 | 32 | + (id)inputStreamWithData:(NSData *)data request:(ASIHTTPRequest *)theRequest 33 | { 34 | ASIInputStream *theStream = [[[self alloc] init] autorelease]; 35 | [theStream setRequest:theRequest]; 36 | [theStream setStream:[NSInputStream inputStreamWithData:data]]; 37 | return theStream; 38 | } 39 | 40 | - (void)dealloc 41 | { 42 | [stream release]; 43 | [super dealloc]; 44 | } 45 | 46 | // Called when CFNetwork wants to read more of our request body 47 | // When throttling is on, we ask ASIHTTPRequest for the maximum amount of data we can read 48 | - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len 49 | { 50 | [readLock lock]; 51 | unsigned long toRead = len; 52 | if ([ASIHTTPRequest isBandwidthThrottled]) { 53 | toRead = [ASIHTTPRequest maxUploadReadLength]; 54 | if (toRead > len) { 55 | toRead = len; 56 | } else if (toRead == 0) { 57 | toRead = 1; 58 | } 59 | [request performThrottling]; 60 | } 61 | [ASIHTTPRequest incrementBandwidthUsedInLastSecond:toRead]; 62 | [readLock unlock]; 63 | return [stream read:buffer maxLength:toRead]; 64 | } 65 | 66 | /* 67 | * Implement NSInputStream mandatory methods to make sure they are implemented 68 | * (necessary for MacRuby for example) and avoid the overhead of method 69 | * forwarding for these common methods. 70 | */ 71 | - (void)open 72 | { 73 | [stream open]; 74 | } 75 | 76 | - (void)close 77 | { 78 | [stream close]; 79 | } 80 | 81 | - (id)delegate 82 | { 83 | return [stream delegate]; 84 | } 85 | 86 | - (void)setDelegate:(id)delegate 87 | { 88 | [stream setDelegate:delegate]; 89 | } 90 | 91 | - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode 92 | { 93 | [stream scheduleInRunLoop:aRunLoop forMode:mode]; 94 | } 95 | 96 | - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode 97 | { 98 | [stream removeFromRunLoop:aRunLoop forMode:mode]; 99 | } 100 | 101 | - (id)propertyForKey:(NSString *)key 102 | { 103 | return [stream propertyForKey:key]; 104 | } 105 | 106 | - (BOOL)setProperty:(id)property forKey:(NSString *)key 107 | { 108 | return [stream setProperty:property forKey:key]; 109 | } 110 | 111 | - (NSStreamStatus)streamStatus 112 | { 113 | return [stream streamStatus]; 114 | } 115 | 116 | - (NSError *)streamError 117 | { 118 | return [stream streamError]; 119 | } 120 | 121 | // If we get asked to perform a method we don't have (probably internal ones), 122 | // we'll just forward the message to our stream 123 | 124 | - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector 125 | { 126 | return [stream methodSignatureForSelector:aSelector]; 127 | } 128 | 129 | - (void)forwardInvocation:(NSInvocation *)anInvocation 130 | { 131 | [anInvocation invokeWithTarget:stream]; 132 | } 133 | 134 | @synthesize stream; 135 | @synthesize request; 136 | @end 137 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthAPI.h: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthAPI.h 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.05. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "MPOAuthCredentialStore.h" 11 | #import "MPOAuthParameterFactory.h" 12 | 13 | extern NSString * const MPOAuthNotificationAccessTokenReceived; 14 | extern NSString * const MPOAuthNotificationAccessTokenRejected; 15 | extern NSString * const MPOAuthNotificationAccessTokenRefreshed; 16 | extern NSString * const MPOAuthNotificationOAuthCredentialsReady; 17 | extern NSString * const MPOAuthNotificationErrorHasOccurred; 18 | 19 | extern NSString * const MPOAuthCredentialRequestTokenKey; 20 | extern NSString * const MPOAuthCredentialRequestTokenSecretKey; 21 | extern NSString * const MPOAuthCredentialAccessTokenKey; 22 | extern NSString * const MPOAuthCredentialAccessTokenSecretKey; 23 | extern NSString * const MPOAuthCredentialSessionHandleKey; 24 | 25 | extern NSString * const MPOAuthTokenRefreshDateDefaultsKey; 26 | 27 | typedef enum { 28 | MPOAuthSignatureSchemePlainText, 29 | MPOAuthSignatureSchemeHMACSHA1, 30 | MPOAuthSignatureSchemeRSASHA1 31 | } MPOAuthSignatureScheme; 32 | 33 | typedef enum { 34 | MPOAuthAuthenticationStateUnauthenticated = 0, 35 | MPOAuthAuthenticationStateAuthenticating = 1, 36 | MPOAuthAuthenticationStateAuthenticated = 2 37 | } MPOAuthAuthenticationState; 38 | 39 | @protocol MPOAuthAPIInternalClient 40 | @end 41 | 42 | @class MPOAuthAuthenticationMethod; 43 | 44 | @interface MPOAuthAPI : NSObject { 45 | @private 46 | id credentials_; 47 | NSURL *baseURL_; 48 | NSURL *authenticationURL_; 49 | MPOAuthAuthenticationMethod *authenticationMethod_; 50 | MPOAuthSignatureScheme signatureScheme_; 51 | NSMutableArray *activeLoaders_; 52 | MPOAuthAuthenticationState oauthAuthenticationState_; 53 | } 54 | 55 | @property (nonatomic, readonly, retain) id credentials; 56 | @property (nonatomic, readonly, retain) NSURL *baseURL; 57 | @property (nonatomic, readonly, retain) NSURL *authenticationURL; 58 | @property (nonatomic, readwrite, retain) MPOAuthAuthenticationMethod *authenticationMethod; 59 | @property (nonatomic, readwrite, assign) MPOAuthSignatureScheme signatureScheme; 60 | 61 | @property (nonatomic, readonly, assign) MPOAuthAuthenticationState authenticationState; 62 | 63 | 64 | - (id)initWithCredentials:(NSDictionary *)inCredentials andBaseURL:(NSURL *)inURL; 65 | - (id)initWithCredentials:(NSDictionary *)inCredentials authenticationURL:(NSURL *)inAuthURL andBaseURL:(NSURL *)inBaseURL; 66 | - (id)initWithCredentials:(NSDictionary *)inCredentials authenticationURL:(NSURL *)inAuthURL andBaseURL:(NSURL *)inBaseURL autoStart:(BOOL)aFlag; 67 | 68 | - (void)authenticate; 69 | - (BOOL)isAuthenticated; 70 | 71 | - (void)performMethod:(NSString *)inMethod withTarget:(id)inTarget andAction:(SEL)inAction; 72 | - (void)performMethod:(NSString *)inMethod atURL:(NSURL *)inURL withParameters:(NSArray *)inParameters withTarget:(id)inTarget andAction:(SEL)inAction; 73 | - (void)performPOSTMethod:(NSString *)inMethod atURL:(NSURL *)inURL withParameters:(NSArray *)inParameters withTarget:(id)inTarget andAction:(SEL)inAction; 74 | - (void)performURLRequest:(NSURLRequest *)inRequest withTarget:(id)inTarget andAction:(SEL)inAction; 75 | 76 | - (NSData *)dataForMethod:(NSString *)inMethod; 77 | - (NSData *)dataForMethod:(NSString *)inMethod withParameters:(NSArray *)inParameters; 78 | - (NSData *)dataForURL:(NSURL *)inURL andMethod:(NSString *)inMethod withParameters:(NSArray *)inParameters; 79 | 80 | - (id)credentialNamed:(NSString *)inCredentialName; 81 | - (void)setCredential:(id)inCredential withName:(NSString *)inName; 82 | - (void)removeCredentialNamed:(NSString *)inName; 83 | 84 | - (void)discardCredentials; 85 | 86 | @end 87 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/NSURL+MPURLParameterAdditions.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURL+MPURLParameterAdditions.m 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 08.12.08. 6 | // Copyright 2008 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import "NSURL+MPURLParameterAdditions.h" 10 | #import "MPURLRequestParameter.h" 11 | #import "NSString+URLEscapingAdditions.h" 12 | 13 | @implementation NSURL (MPURLParameterAdditions) 14 | 15 | - (NSURL *)urlByAddingParameters:(NSArray *)inParameters { 16 | NSMutableArray *parameters = [[NSMutableArray alloc] init]; 17 | NSString *queryString = [self query]; 18 | NSString *absoluteString = [self absoluteString]; 19 | NSRange parameterRange = [absoluteString rangeOfString:@"?"]; 20 | 21 | if (parameterRange.location != NSNotFound) { 22 | parameterRange.length = [absoluteString length] - parameterRange.location; 23 | [parameters addObjectsFromArray:[MPURLRequestParameter parametersFromString:queryString]]; 24 | absoluteString = [absoluteString substringToIndex:parameterRange.location]; 25 | } 26 | 27 | [parameters addObjectsFromArray:inParameters]; 28 | 29 | return [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", absoluteString, [MPURLRequestParameter parameterStringForParameters:[parameters autorelease]]]]; 30 | } 31 | 32 | - (NSURL *)urlByAddingParameterDictionary:(NSDictionary *)inParameterDictionary { 33 | NSMutableDictionary *parameterDictionary = [inParameterDictionary mutableCopy]; 34 | NSString *queryString = [self query]; 35 | NSString *absoluteString = [self absoluteString]; 36 | NSRange parameterRange = [absoluteString rangeOfString:@"?"]; 37 | NSURL *composedURL = self; 38 | 39 | if (parameterRange.location != NSNotFound) { 40 | parameterRange.length = [absoluteString length] - parameterRange.location; 41 | 42 | //[parameterDictionary addEntriesFromDictionary:inParameterDictionary]; 43 | [parameterDictionary addEntriesFromDictionary:[MPURLRequestParameter parameterDictionaryFromString:queryString]]; 44 | 45 | composedURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", [absoluteString substringToIndex:parameterRange.location], [MPURLRequestParameter parameterStringForDictionary:parameterDictionary]]]; 46 | } else if ([parameterDictionary count]) { 47 | composedURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@?%@", absoluteString, [MPURLRequestParameter parameterStringForDictionary:parameterDictionary]]]; 48 | } 49 | 50 | [parameterDictionary release]; 51 | 52 | return composedURL; 53 | } 54 | 55 | - (NSURL *)urlByRemovingQuery { 56 | NSURL *composedURL = self; 57 | NSString *absoluteString = [self absoluteString]; 58 | NSRange queryRange = [absoluteString rangeOfString:@"?"]; 59 | 60 | if (queryRange.location != NSNotFound) { 61 | NSString *urlSansQuery = [absoluteString substringToIndex:queryRange.location]; 62 | composedURL = [NSURL URLWithString:urlSansQuery]; 63 | } 64 | 65 | return composedURL; 66 | } 67 | 68 | - (NSString *)absoluteNormalizedString { 69 | NSString *normalizedString = [self absoluteString]; 70 | 71 | if ([[self path] length] == 0 && [[self query] length] == 0) { 72 | normalizedString = [NSString stringWithFormat:@"%@/", [self absoluteString]]; 73 | } 74 | 75 | return normalizedString; 76 | } 77 | 78 | - (BOOL)domainMatches:(NSString *)inString { 79 | BOOL matches = NO; 80 | 81 | NSString *domain = [self host]; 82 | matches = [domain isIPAddress] && [domain isEqualToString:inString]; 83 | 84 | int domainLength = [domain length]; 85 | int requestedDomainLength = [inString length]; 86 | 87 | if (!matches) { 88 | if (domainLength > requestedDomainLength) { 89 | matches = [domain rangeOfString:inString].location == (domainLength - requestedDomainLength); 90 | } else if (domainLength == (requestedDomainLength - 1)) { 91 | matches = ([inString compare:domain options:NSCaseInsensitiveSearch range:NSMakeRange(1, domainLength)] == NSOrderedSame); 92 | } 93 | } 94 | 95 | return matches; 96 | } 97 | 98 | @end 99 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/ChildTableViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ChildTableViewController.m 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import "ChildTableViewController.h" 10 | #import "Product.h" 11 | #import 12 | 13 | @implementation ChildTableViewController 14 | @synthesize headerView, product; 15 | 16 | - (void)viewDidLoad { 17 | [super viewDidLoad]; 18 | self.title = self.product.name; 19 | 20 | CGRect imageFrame = CGRectMake((self.tableView.bounds.size.width-200)/2, 20, 200, 200); // x,y,w,h 21 | UIImage *image = [UIImage imageNamed:self.product.image]; 22 | UIImageView *imageView; 23 | 24 | if (image) { 25 | imageView = [[UIImageView alloc] initWithImage:image]; 26 | } else { 27 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 28 | NSString *documentsDirectory = [paths objectAtIndex:0]; 29 | NSString *documentProductFilePath = [documentsDirectory stringByAppendingPathComponent:@"syncfolder"]; 30 | NSString *temp = [documentProductFilePath stringByAppendingString:@"/"]; 31 | NSString *imagePath = [temp stringByAppendingString:product.image]; 32 | 33 | UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; 34 | imageView = [[UIImageView alloc] initWithImage:image]; 35 | 36 | } 37 | 38 | imageView.layer.cornerRadius = 7; 39 | imageView.layer.masksToBounds = YES; 40 | [imageView.layer setBorderColor: [[UIColor grayColor] CGColor]]; 41 | [imageView.layer setBackgroundColor: [[UIColor whiteColor] CGColor]]; 42 | [imageView.layer setBorderWidth: 1.0]; 43 | imageView.frame = imageFrame; 44 | [self.headerView addSubview:imageView]; 45 | [imageView release]; 46 | 47 | } 48 | 49 | - (void)viewDidUnload { 50 | [self setHeaderView:nil]; 51 | [super viewDidUnload]; 52 | } 53 | 54 | - (void)dealloc { 55 | [product release]; 56 | [headerView release]; 57 | [super dealloc]; 58 | } 59 | 60 | - (void)didReceiveMemoryWarning { 61 | [super didReceiveMemoryWarning]; 62 | } 63 | 64 | #pragma mark - Table view data source 65 | 66 | - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath { 67 | UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0]; 68 | 69 | NSString *cellText = self.product.description; 70 | CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT); 71 | CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap]; 72 | return labelSize.height + 15; 73 | } 74 | 75 | - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 76 | return 1; 77 | } 78 | 79 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 80 | return 1; 81 | } 82 | 83 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 84 | static NSString *CellIdentifier = @"Cell"; 85 | 86 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 87 | if (cell == nil) { 88 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 89 | } 90 | 91 | // Configure the cell... 92 | 93 | cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0]; 94 | cell.textLabel.numberOfLines = 0; 95 | cell.textLabel.lineBreakMode = UILineBreakModeWordWrap; 96 | cell.textLabel.text = product.description; 97 | 98 | return cell; 99 | } 100 | 101 | #pragma mark - Table view delegate 102 | 103 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 104 | 105 | } 106 | 107 | @end 108 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonParser.m: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2009,2010 Stig Brautaset. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the author nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #import "SBJsonParser.h" 31 | #import "SBJsonStreamParser.h" 32 | #import "SBJsonStreamParserAdapter.h" 33 | 34 | @interface SBJsonParser () 35 | @end 36 | 37 | 38 | @implementation SBJsonParser 39 | 40 | @synthesize maxDepth; 41 | @synthesize error; 42 | 43 | #pragma mark SBJsonStreamParserAdapterDelegate 44 | 45 | - (void)parser:(SBJsonStreamParser*)parser foundArray:(NSArray *)array { 46 | value = [array retain]; 47 | } 48 | 49 | - (void)parser:(SBJsonStreamParser*)parser foundObject:(NSDictionary *)dict { 50 | value = [dict retain]; 51 | } 52 | 53 | - (id)init { 54 | self = [super init]; 55 | if (self) 56 | self.maxDepth = 512; 57 | return self; 58 | } 59 | 60 | - (void)dealloc { 61 | [error release]; 62 | [super dealloc]; 63 | } 64 | 65 | #pragma mark Methods 66 | 67 | - (id)objectWithData:(NSData *)data { 68 | 69 | if (!data) { 70 | self.error = @"Input was 'nil'"; 71 | return nil; 72 | } 73 | 74 | SBJsonStreamParserAdapter *adapter = [SBJsonStreamParserAdapter new]; 75 | adapter.delegate = self; 76 | 77 | SBJsonStreamParser *parser = [SBJsonStreamParser new]; 78 | parser.maxDepth = self.maxDepth; 79 | parser.delegate = adapter; 80 | 81 | id retval = nil; 82 | switch ([parser parse:data]) { 83 | case SBJsonStreamParserComplete: 84 | retval = [value autorelease]; 85 | break; 86 | 87 | case SBJsonStreamParserWaitingForData: 88 | self.error = @"Didn't find full object before EOF"; 89 | break; 90 | 91 | case SBJsonStreamParserError: 92 | self.error = parser.error; 93 | break; 94 | } 95 | 96 | 97 | [adapter release]; 98 | [parser release]; 99 | 100 | return retval; 101 | } 102 | 103 | - (id)objectWithString:(NSString *)repr { 104 | return [self objectWithData:[repr dataUsingEncoding:NSUTF8StringEncoding]]; 105 | } 106 | 107 | - (id)objectWithString:(NSString*)repr error:(NSError**)error_ { 108 | id tmp = [self objectWithString:repr]; 109 | if (tmp) 110 | return tmp; 111 | 112 | if (error_) { 113 | NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:error, NSLocalizedDescriptionKey, nil]; 114 | *error_ = [NSError errorWithDomain:@"org.brautaset.json.parser.ErrorDomain" code:0 userInfo:ui]; 115 | } 116 | 117 | return nil; 118 | } 119 | 120 | @end 121 | -------------------------------------------------------------------------------- /iphoneSync/iphoneSync/RootViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // RootViewController.m 3 | // iphoneSync 4 | // 5 | // Created by nickfox on 5/12/11. 6 | // Copyright 2011 websmithing.com. All rights reserved. 7 | // 8 | 9 | #import "RootViewController.h" 10 | #import "ChildTableViewController.h" 11 | #import "DataController.h" 12 | #import "UIImage+TableCellImageScaler.h" 13 | #import 14 | #import "Product.h" 15 | 16 | @implementation RootViewController 17 | 18 | - (void)viewDidLoad { 19 | [super viewDidLoad]; 20 | self.title = @"Catalog"; 21 | 22 | dataController = [[DataController alloc] init]; 23 | 24 | [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(couchDBNotificationHandler:) name:@"couchDBChanged" object:nil]; 25 | } 26 | 27 | - (void)couchDBNotificationHandler:(NSNotification *)notification 28 | { 29 | NSLog(@"notification: %@",(NSString*)[notification object]); 30 | [dataController loadJsonFromFile]; 31 | [self.tableView reloadData]; 32 | 33 | } 34 | 35 | - (void)dealloc { 36 | [dataController release]; 37 | [super dealloc]; 38 | } 39 | 40 | - (void)didReceiveMemoryWarning { 41 | [super didReceiveMemoryWarning]; 42 | } 43 | 44 | - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ 45 | return 67; 46 | } 47 | 48 | - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 49 | return 1; 50 | } 51 | 52 | - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 53 | return [dataController.product count]; 54 | } 55 | 56 | // Customize the appearance of table view cells. 57 | - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 58 | static NSString *CellIdentifier = @"Cell"; 59 | 60 | UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 61 | if (cell == nil) { 62 | cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 63 | } 64 | 65 | // Configure the cell. 66 | Product *product = (Product *)[dataController.product objectAtIndex:indexPath.row]; 67 | 68 | cell.imageView.layer.masksToBounds = YES; 69 | cell.imageView.layer.cornerRadius = 7.0; 70 | UIImage *image = [UIImage imageNamed:product.image]; 71 | 72 | if (image) { 73 | // this is using the category in UIImage+TableCellImageScaler.h 74 | cell.imageView.image = [image imageScaledToSize:CGSizeMake(60, 60)]; 75 | } else { 76 | NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 77 | NSString *documentsDirectory = [paths objectAtIndex:0]; 78 | NSString *documentProductFilePath = [documentsDirectory stringByAppendingPathComponent:@"syncfolder"]; 79 | NSString *temp = [documentProductFilePath stringByAppendingString:@"/"]; 80 | NSString *imagePath = [temp stringByAppendingString:product.image]; 81 | 82 | //NSLog(@"imagePath: %@", imagePath); 83 | 84 | UIImage *image = [UIImage imageWithContentsOfFile:imagePath]; 85 | cell.imageView.image = [image imageScaledToSize:CGSizeMake(60, 60)]; 86 | 87 | } 88 | 89 | cell.textLabel.text = product.name; 90 | cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 91 | 92 | return cell; 93 | } 94 | 95 | - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 96 | ChildTableViewController *childTableViewController = [[ChildTableViewController alloc] initWithNibName:@"ChildTableViewController" bundle:nil]; 97 | 98 | childTableViewController.product = (Product *)[dataController.product objectAtIndex:indexPath.row]; 99 | 100 | [self.navigationController pushViewController:childTableViewController animated:YES]; 101 | [childTableViewController release]; 102 | } 103 | 104 | @end 105 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/DBSession.m: -------------------------------------------------------------------------------- 1 | // 2 | // DBSession.m 3 | // DropboxSDK 4 | // 5 | // Created by Brian Smith on 4/8/10. 6 | // Copyright 2010 Dropbox, Inc. All rights reserved. 7 | // 8 | 9 | #import "DBSession.h" 10 | #import "MPOAuthCredentialConcreteStore.h" 11 | #import "MPOAuthSignatureParameter.h" 12 | 13 | 14 | NSString* kDBDropboxAPIHost = @"api.dropbox.com"; 15 | NSString* kDBDropboxAPIContentHost = @"api-content.dropbox.com"; 16 | NSString* kDBDropboxAPIVersion = @"0"; 17 | 18 | static DBSession* _sharedSession = nil; 19 | static NSString* kDBDropboxSavedCredentialsKey = @"kDBDropboxSavedCredentialsKey"; 20 | 21 | 22 | @interface DBSession () 23 | 24 | - (NSDictionary*)savedCredentials; 25 | - (void)saveCredentials:(NSDictionary*)credentials; 26 | - (void)clearSavedCredentials; 27 | 28 | @end 29 | 30 | 31 | @implementation DBSession 32 | 33 | + (DBSession*)sharedSession { 34 | return _sharedSession; 35 | } 36 | 37 | + (void)setSharedSession:(DBSession*)session { 38 | if (session == _sharedSession) return; 39 | [_sharedSession release]; 40 | _sharedSession = [session retain]; 41 | } 42 | 43 | - (id)initWithConsumerKey:(NSString*)key consumerSecret:(NSString*)secret { 44 | if ((self = [super init])) { 45 | 46 | NSMutableDictionary* credentials = 47 | [NSMutableDictionary dictionaryWithObjectsAndKeys: 48 | key, kMPOAuthCredentialConsumerKey, 49 | secret, kMPOAuthCredentialConsumerSecret, 50 | kMPOAuthSignatureMethodHMACSHA1, kMPOAuthSignatureMethod, nil]; 51 | 52 | NSDictionary* savedCredentials = [self savedCredentials]; 53 | if (savedCredentials != nil) { 54 | if ([key isEqualToString:[savedCredentials objectForKey:kMPOAuthCredentialConsumerKey]]) { 55 | 56 | [credentials setObject:[savedCredentials objectForKey:kMPOAuthCredentialAccessToken] 57 | forKey:kMPOAuthCredentialAccessToken]; 58 | [credentials setObject:[savedCredentials objectForKey:kMPOAuthCredentialAccessTokenSecret] 59 | forKey:kMPOAuthCredentialAccessTokenSecret]; 60 | } else { 61 | [self clearSavedCredentials]; 62 | } 63 | } 64 | 65 | credentialStore = [[MPOAuthCredentialConcreteStore alloc] initWithCredentials:credentials]; 66 | } 67 | return self; 68 | } 69 | 70 | - (void)dealloc { 71 | [credentialStore release]; 72 | [super dealloc]; 73 | } 74 | 75 | @synthesize credentialStore; 76 | @synthesize delegate; 77 | 78 | - (void)updateAccessToken:(NSString*)token accessTokenSecret:(NSString*)secret { 79 | credentialStore.accessToken = token; 80 | credentialStore.accessTokenSecret = secret; 81 | NSDictionary* credentials = [NSDictionary dictionaryWithObjectsAndKeys: 82 | credentialStore.consumerKey, kMPOAuthCredentialConsumerKey, 83 | credentialStore.accessToken, kMPOAuthCredentialAccessToken, 84 | credentialStore.accessTokenSecret, kMPOAuthCredentialAccessTokenSecret, 85 | nil]; 86 | [self saveCredentials:credentials]; 87 | } 88 | 89 | - (BOOL) isLinked { 90 | return credentialStore.accessToken != nil; 91 | } 92 | 93 | - (void)unlink { 94 | credentialStore.accessToken = nil; 95 | credentialStore.accessTokenSecret = nil; 96 | [self clearSavedCredentials]; 97 | } 98 | 99 | #pragma mark private methods 100 | 101 | - (NSDictionary*)savedCredentials { 102 | return [[NSUserDefaults standardUserDefaults] objectForKey:kDBDropboxSavedCredentialsKey]; 103 | } 104 | 105 | - (void)saveCredentials:(NSDictionary*)credentials { 106 | if (credentials == nil) return; 107 | 108 | [[NSUserDefaults standardUserDefaults] 109 | setObject:credentials forKey:kDBDropboxSavedCredentialsKey]; 110 | [[NSUserDefaults standardUserDefaults] synchronize]; 111 | } 112 | 113 | - (void)clearSavedCredentials { 114 | [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDBDropboxSavedCredentialsKey]; 115 | } 116 | 117 | @end 118 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### iPhoneCloudSync 2 | 3 | This application allows an iPhone app to sync with a couchDB database in the cloud and also a dropbox repository. The iPhone application is a very simple catalog with product descriptions and images. There are 3 parts to this application: 4 | 5 | 1. the couchDB application that is used to update the product on the iPhone 6 | 2. and the dropbox repository that is used to store the images used on the iPhone 7 | 3. the iphone application 8 | 9 | First I'll explain how to create the couchDB application. The couchDB does not need to be installed on the local machine. Instead, we'll create a couchDB using [Cloudant](http://www.cloudant.com). The first thing you need to do is install couchApp on your local machine. We'll assume that you are using a mac for everything. Follow the [tutorial here](http://benoitc.github.com/couchapp/download.html) to install couchApp. Also read this [short tutorial](http://benoitc.github.com/couchapp/getting_started.html) explaining what a couchApp is. Once you have couchApp installed, go to [Cloudant](http://www.cloudant.com) and create a new account. Next download this repo and cd to the iphonecouchsync directory and then run the following command from the command line: 10 | 11 | couchapp push http://username:password@username.cloudant.com/iphonecouchsync 12 | 13 | where username and password are from the cloudant account you just created. Once you have done this, you will be given an url that will allow you to view and add product: 14 | 15 | http://username.cloudant.com/iphonecouchsync/_design/iphonecouchsync/index.html 16 | 17 | Add three new products using coke.png, oranges.png and bananas.png for images. Ok, we are now done with couchdb for now. Go and create a dropbox account if you have not done so already and then create a folder called syncfolder. Create a new dropbox app at [Dropbox Developers](https://www.dropbox.com/developers/apps) and get the consumer key and secret. Select iPhone for type of app. We are done with dropbox portion for now. 18 | 19 | Lastly, we need to set up the iPhone app with the dropbox and couchdb info. In the iPhoneSyncAppDelegate.m file, replace the DROPBOX_CONSUMER_KEY and DROPBOX_CONSUMER_SECRET on lines 21 and 22 with the ones you just got from dropbox. Also replace the DROPBOX_EMAIL and DROPBOX_PASSWORD with those from dropbox. Dropbox does not recommend that you hardcode the email and password into the app. They would prefer that you ask the user to give you the email and password (once) to get your oAuth token. Here is the code to do that [from the DBRoulette Dropbox example in the SDK](https://www.dropbox.com/developers/releases): 20 | 21 | - (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session { 22 | DBLoginController* loginController = [[DBLoginController new] autorelease]; 23 | [loginController presentFromController:navigationController]; 24 | } 25 | 26 | In the SyncController.m file, replace the COUCHDB_USERNAME and COUCHDB_PASSWORD on lines 29 and 30. The app is now set up and ready for testing. Run the app and you should see bananas, coke and oranges displayed in the table view. Now to test the sync operation. Go to dropbox and upload the raspberries.png file into the syncfolder. Then go to couchdb and create a new product called Raspberries and make sure to name the image file raspberry.png. Now close the iphone app and reopen it and you should see the raspberry product appear in the tableview. If you run into problems, uncomment the lines 25 - 27 in the SyncController.m class: 27 | 28 | NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 29 | [prefs setObject:@"" forKey:@"dropboxHash"]; 30 | [prefs setObject:@"" forKey:@"lastSequenceFromCouchDB"]; 31 | 32 | Run the app again. This will clear out any stale values that might be left in the user defaults. Re-comment the lines and run the app yet again to see the syncing operation. The sync operation is initiated in this iphoneSyncAppDelegate callback: 33 | 34 | - (void)applicationDidBecomeActive:(UIApplication *)application 35 | 36 | That's it for this app. I'll be creating a tutorial soon explaining how the app works. In the future, I will try to build another app that stores images directly in the couchDB, that would be a cleaner and a less error prone way of building the app but for now this does show how to do syncing on two different platforms for different data types. 37 | 38 | -------------------------------------------------------------------------------- /iphonecouchsync/vendor/couchapp/lib/docform.js: -------------------------------------------------------------------------------- 1 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 | // use this file except in compliance with the License. You may obtain a copy 3 | // of the License at 4 | // 5 | // http://www.apache.org/licenses/LICENSE-2.0 6 | // 7 | // Unless required by applicable law or agreed to in writing, software 8 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 | // License for the specific language governing permissions and limitations under 11 | // the License. 12 | 13 | // turn the form into deep json 14 | // field names like 'author-email' get turned into json like 15 | // {"author":{"email":"quentin@example.com"}} 16 | // acts on doc by reference, so you can safely pass non-form fields through 17 | 18 | function docForm(formSelector, opts) { 19 | var localFormDoc = {}; 20 | opts = opts || {}; 21 | opts.fields = opts.fields || []; 22 | 23 | // turn the form into deep json 24 | // field names like 'author-email' get turned into json like 25 | // {"author":{"email":"quentin@example.com"}} 26 | function formToDeepJSON(form, fields, doc) { 27 | form = $(form); 28 | fields.forEach(function(field) { 29 | var element = form.find("[name="+field+"]"), 30 | parts = field.split('-'), 31 | frontObj = doc, frontName = parts.shift(); 32 | 33 | if (element.attr('type') === 'checkbox') { 34 | var val = element.attr('checked'); 35 | } else { 36 | var val = element.val(); 37 | if (!val) { 38 | if (frontObj[field]) { 39 | delete frontObj[field]; 40 | } 41 | return; 42 | } 43 | } 44 | 45 | while (parts.length > 0) { 46 | frontObj[frontName] = frontObj[frontName] || {}; 47 | frontObj = frontObj[frontName]; 48 | frontName = parts.shift(); 49 | } 50 | frontObj[frontName] = val; 51 | }); 52 | } 53 | 54 | // Apply the behavior 55 | $(formSelector).submit(function(e) { 56 | e.preventDefault(); 57 | if (opts.validate && opts.validate() == false) { return false;} 58 | // formToDeepJSON acts on localFormDoc by reference 59 | formToDeepJSON(this, opts.fields, localFormDoc); 60 | if (opts.beforeSave) {opts.beforeSave(localFormDoc);} 61 | db.saveDoc(localFormDoc, { 62 | success : function(resp) { 63 | if (opts.success) {opts.success(resp, localFormDoc);} 64 | } 65 | }); 66 | 67 | return false; 68 | }); 69 | 70 | // populate form from an existing doc 71 | function docToForm(doc) { 72 | var form = $(formSelector); 73 | // fills in forms 74 | opts.fields.forEach(function(field) { 75 | var parts = field.split('-'); 76 | var run = true, frontObj = doc, frontName = parts.shift(); 77 | while (frontObj && parts.length > 0) { 78 | frontObj = frontObj[frontName]; 79 | frontName = parts.shift(); 80 | } 81 | if (frontObj && frontObj[frontName]) { 82 | var element = form.find("[name="+field+"]"); 83 | if (element.attr('type') === 'checkbox') { 84 | element.attr('checked', frontObj[frontName]); 85 | } else { 86 | element.val(frontObj[frontName]); 87 | } 88 | } 89 | }); 90 | } 91 | 92 | if (opts.id) { 93 | db.openDoc(opts.id, { 94 | attachPrevRev : opts.attachPrevRev, 95 | error: function() { 96 | if (opts.error) {opts.error.apply(opts, arguments);} 97 | }, 98 | success: function(doc) { 99 | if (opts.load || opts.onLoad) {(opts.load || opts.onLoad)(doc);} 100 | localFormDoc = doc; 101 | docToForm(doc); 102 | }}); 103 | } else if (opts.template) { 104 | if (opts.load || opts.onLoad) {(opts.load || opts.onLoad)(opts.template);} 105 | localFormDoc = opts.template; 106 | docToForm(localFormDoc); 107 | } 108 | var instance = { 109 | deleteDoc : function(opts) { 110 | opts = opts || {}; 111 | if (confirm("Really delete this document?")) { 112 | db.removeDoc(localFormDoc, opts); 113 | } 114 | }, 115 | localDoc : function() { 116 | formToDeepJSON(formSelector, opts.fields, localFormDoc); 117 | return localFormDoc; 118 | } 119 | }; 120 | return instance; 121 | } 122 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonParser.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2009 Stig Brautaset. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * Neither the name of the author nor the names of its contributors may be used 15 | to endorse or promote products derived from this software without specific 16 | prior written permission. 17 | 18 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 21 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 22 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 23 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 24 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 25 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 26 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | */ 29 | 30 | #import 31 | 32 | /** 33 | @brief The JSON parser class. 34 | 35 | JSON is mapped to Objective-C types in the following way: 36 | 37 | @li Null -> NSNull 38 | @li String -> NSMutableString 39 | @li Array -> NSMutableArray 40 | @li Object -> NSMutableDictionary 41 | @li Boolean -> NSNumber (initialised with -initWithBool:) 42 | @li Number -> (NSNumber | NSDecimalNumber) 43 | 44 | Since Objective-C doesn't have a dedicated class for boolean values, these turns into NSNumber 45 | instances. These are initialised with the -initWithBool: method, and 46 | round-trip back to JSON properly. (They won't silently suddenly become 0 or 1; they'll be 47 | represented as 'true' and 'false' again.) 48 | 49 | As an optimisation short JSON integers turn into NSNumber instances, while complex ones turn into NSDecimalNumber instances. 50 | We can thus avoid any loss of precision as JSON allows ridiculously large numbers. 51 | 52 | */ 53 | 54 | @interface SBJsonParser : NSObject { 55 | id value; 56 | NSString *error; 57 | NSUInteger depth, maxDepth; 58 | 59 | } 60 | 61 | /** 62 | @brief The maximum recursing depth. 63 | 64 | Defaults to 512. If the input is nested deeper than this the input will be deemed to be 65 | malicious and the parser returns nil, signalling an error. ("Nested too deep".) You can 66 | turn off this security feature by setting the maxDepth value to 0. 67 | */ 68 | @property NSUInteger maxDepth; 69 | 70 | /** 71 | @brief Return an error trace, or nil if there was no errors. 72 | 73 | Note that this method returns the trace of the last method that failed. 74 | You need to check the return value of the call you're making to figure out 75 | if the call actually failed, before you know call this method. 76 | */ 77 | @property(copy) NSString *error; 78 | 79 | /** 80 | @brief Return the object represented by the given NSData object. 81 | 82 | The data *must* be UTF8 encoded. 83 | @param data the data to parse. 84 | 85 | */ 86 | - (id)objectWithData:(NSData*)data; 87 | 88 | /** 89 | @brief Return the object represented by the given string 90 | 91 | Returns the object represented by the passed-in string or nil on error. The returned object can be 92 | a string, number, boolean, null, array or dictionary. 93 | 94 | @param repr the json string to parse 95 | */ 96 | - (id)objectWithString:(NSString *)repr; 97 | 98 | /** 99 | @brief Return the object represented by the given string 100 | 101 | Returns the object represented by the passed-in string or nil on error. The returned object can be 102 | a string, number, boolean, null, array or dictionary. 103 | 104 | @param jsonText the json string to parse 105 | @param error pointer to an NSError object to populate on error 106 | */ 107 | 108 | - (id)objectWithString:(NSString*)jsonText 109 | error:(NSError**)error; 110 | 111 | @end 112 | 113 | 114 | -------------------------------------------------------------------------------- /iphonecouchsync/_attachments/script.js: -------------------------------------------------------------------------------- 1 | var db = $.couch.db(getCurrentDBName()); 2 | 3 | function getCurrentDBName() { 4 | return window.location.pathname.split("/")[1]; 5 | } 6 | 7 | $(document).ready(function() { 8 | 9 | // init page 10 | clearForm(); 11 | refreshItems(); 12 | $('#productName').focus(); 13 | 14 | // create new product 15 | $('input#createButton').click(function(e) { 16 | var productName = $('#productName').val(); 17 | 18 | if ($('#productName').val().length == 0) { 19 | alert("Product name is required."); 20 | $('#productName').focus(); 21 | return; 22 | } 23 | 24 | if ($('#productDescription').val().length == 0) { 25 | alert("Product description is required."); 26 | $('#productDescription').focus(); 27 | return; 28 | } 29 | 30 | var aTask = { 31 | name: $('#productName').val(), 32 | description: $('#productDescription').val(), 33 | image: $('#productImage').val() 34 | } 35 | 36 | db.saveDoc(aTask, { success: function(resp) { 37 | $('#messages').html(productName + ' created.'); 38 | refreshItems(); 39 | }}); 40 | 41 | clearForm(); 42 | }); 43 | 44 | // update product 45 | $('input#updateButton').click(function(e) { 46 | var productName = $('#productName').val(); 47 | 48 | if ($('#productName').val().length == 0) { 49 | alert("Product name is required."); 50 | $('#productName').focus(); 51 | return; 52 | } 53 | 54 | if ($('#productDescription').val().length == 0) { 55 | alert("Product description is required."); 56 | $('#productDescription').focus(); 57 | return; 58 | } 59 | 60 | var aTask = { 61 | _id: $('#productID').val(), 62 | _rev: $('#productRev').val(), 63 | name: $('#productName').val(), 64 | description: $('#productDescription').val(), 65 | image: $('#productImage').val() 66 | } 67 | 68 | db.saveDoc(aTask, { success: function(resp) { 69 | $('#messages').html(productName + ' updated.'); 70 | refreshItems(); 71 | 72 | $('#productRev').val(resp.rev); 73 | }}); 74 | }); 75 | 76 | // delete product 77 | $('input#deleteButton').click(function(e) { 78 | var productName = $('#productName').val(); 79 | 80 | if ($('#productID').val().length == 0) { 81 | return; 82 | } 83 | 84 | var aTask = { 85 | _id: $('#productID').val(), 86 | _rev: $('#productRev').val() 87 | } 88 | 89 | db.removeDoc(aTask, { success: function(resp) { 90 | $('#messages').html(productName + ' deleted.'); 91 | refreshItems(); 92 | }}); 93 | 94 | clearForm(); 95 | }); 96 | 97 | // clear fields 98 | $('input#clearButton').click(function(e) { 99 | clearForm(); 100 | $('#productName').focus(); 101 | }); 102 | }); 103 | 104 | function refreshItems() { 105 | $("ul#productData").empty(); 106 | 107 | db.view("iphonecouchsync/myView", { 108 | success: function(data){ 109 | data.rows.map(function(row) { 110 | $('ul#productData').append('
  • ' 111 | + row.value.name 112 | + '
  • '); 113 | 114 | $("ul#productData").mouseover(function() { 115 | $(this).css('cursor', 'pointer'); 116 | }); 117 | 118 | $('#' + row.value._id).mouseover(function() { 119 | $(this).addClass('hover'); 120 | }); 121 | 122 | $('#' + row.value._id).mouseout(function() { 123 | $(this).removeClass('hover'); 124 | }); 125 | 126 | $('#' + row.value._id).click(function() { 127 | clearForm(); 128 | $('#productID').val(row.value._id); 129 | $('#productRev').val(row.value._rev); 130 | $('#productName').val(row.value.name); 131 | $('#productDescription').val(row.value.description); 132 | $('#productImage').val(row.value.image); 133 | 134 | return false; 135 | }); 136 | }); 137 | }, 138 | error: function(req, textStatus, errorThrown){alert('Error: '+ textStatus);} 139 | }); 140 | } 141 | 142 | function clearForm() { 143 | $('#productID').val(''); 144 | $('#productRev').val(''); 145 | $('#productName').val(''); 146 | $('#productDescription').val(''); 147 | $('#productImage').val(''); 148 | }; -------------------------------------------------------------------------------- /iphoneSync/AsiHttpRequest/ASICacheDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASICacheDelegate.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 01/05/2010. 6 | // Copyright 2010 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | @class ASIHTTPRequest; 11 | 12 | // Cache policies control the behaviour of a cache and how requests use the cache 13 | // When setting a cache policy, you can use a combination of these values as a bitmask 14 | // For example: [request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy|ASIDoNotWriteToCacheCachePolicy]; 15 | // Note that some of the behaviours below are mutally exclusive - you cannot combine ASIAskServerIfModifiedWhenStaleCachePolicy and ASIAskServerIfModifiedCachePolicy, for example. 16 | typedef enum _ASICachePolicy { 17 | 18 | // The default cache policy. When you set a request to use this, it will use the cache's defaultCachePolicy 19 | // ASIDownloadCache's default cache policy is 'ASIAskServerIfModifiedWhenStaleCachePolicy' 20 | ASIUseDefaultCachePolicy = 0, 21 | 22 | // Tell the request not to read from the cache 23 | ASIDoNotReadFromCacheCachePolicy = 1, 24 | 25 | // The the request not to write to the cache 26 | ASIDoNotWriteToCacheCachePolicy = 2, 27 | 28 | // Ask the server if there is an updated version of this resource (using a conditional GET) ONLY when the cached data is stale 29 | ASIAskServerIfModifiedWhenStaleCachePolicy = 4, 30 | 31 | // Always ask the server if there is an updated version of this resource (using a conditional GET) 32 | ASIAskServerIfModifiedCachePolicy = 8, 33 | 34 | // If cached data exists, use it even if it is stale. This means requests will not talk to the server unless the resource they are requesting is not in the cache 35 | ASIOnlyLoadIfNotCachedCachePolicy = 16, 36 | 37 | // If cached data exists, use it even if it is stale. If cached data does not exist, stop (will not set an error on the request) 38 | ASIDontLoadCachePolicy = 32, 39 | 40 | // Specifies that cached data may be used if the request fails. If cached data is used, the request will succeed without error. Usually used in combination with other options above. 41 | ASIFallbackToCacheIfLoadFailsCachePolicy = 64 42 | } ASICachePolicy; 43 | 44 | // Cache storage policies control whether cached data persists between application launches (ASICachePermanentlyCacheStoragePolicy) or not (ASICacheForSessionDurationCacheStoragePolicy) 45 | // Calling [ASIHTTPRequest clearSession] will remove any data stored using ASICacheForSessionDurationCacheStoragePolicy 46 | typedef enum _ASICacheStoragePolicy { 47 | ASICacheForSessionDurationCacheStoragePolicy = 0, 48 | ASICachePermanentlyCacheStoragePolicy = 1 49 | } ASICacheStoragePolicy; 50 | 51 | 52 | @protocol ASICacheDelegate 53 | 54 | @required 55 | 56 | // Should return the cache policy that will be used when requests have their cache policy set to ASIDefaultCachePolicy 57 | - (ASICachePolicy)defaultCachePolicy; 58 | 59 | - (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request; 60 | 61 | // Should Remove cached data for a particular request 62 | - (void)removeCachedDataForRequest:(ASIHTTPRequest *)request; 63 | 64 | // Should return YES if the cache considers its cached response current for the request 65 | // Should return NO is the data is not cached, or (for example) if the cached headers state the request should have expired 66 | - (BOOL)isCachedDataCurrentForRequest:(ASIHTTPRequest *)request; 67 | 68 | // Should store the response for the passed request in the cache 69 | // When a non-zero maxAge is passed, it should be used as the expiry time for the cached response 70 | - (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge; 71 | 72 | // Should return an NSDictionary of cached headers for the passed URL, if it is stored in the cache 73 | - (NSDictionary *)cachedResponseHeadersForURL:(NSURL *)url; 74 | 75 | // Should return the cached body of a response for the passed URL, if it is stored in the cache 76 | - (NSData *)cachedResponseDataForURL:(NSURL *)url; 77 | 78 | // Returns a path to the cached response data, if it exists 79 | - (NSString *)pathToCachedResponseDataForURL:(NSURL *)url; 80 | 81 | // Returns a path to the cached response headers, if they url 82 | - (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url; 83 | 84 | // Returns the location to use to store cached response headers for a particular request 85 | - (NSString *)pathToStoreCachedResponseHeadersForRequest:(ASIHTTPRequest *)request; 86 | 87 | // Returns the location to use to store a cached response body for a particular request 88 | - (NSString *)pathToStoreCachedResponseDataForRequest:(ASIHTTPRequest *)request; 89 | 90 | // Clear cached data stored for the passed storage policy 91 | - (void)clearCachedResponsesForStoragePolicy:(ASICacheStoragePolicy)cachePolicy; 92 | 93 | @end 94 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/MPOAuth/MPOAuthAuthenticationMethod.m: -------------------------------------------------------------------------------- 1 | // 2 | // MPOAuthAuthenticationMethod.m 3 | // MPOAuthConnection 4 | // 5 | // Created by Karl Adam on 09.12.19. 6 | // Copyright 2009 matrixPointer. All rights reserved. 7 | // 8 | 9 | #import "MPOAuthAuthenticationMethod.h" 10 | #import "MPOAuthAuthenticationMethodOAuth.h" 11 | #import "MPOAuthCredentialConcreteStore.h" 12 | #import "MPURLRequestParameter.h" 13 | 14 | #import "NSURL+MPURLParameterAdditions.h" 15 | 16 | NSString * const MPOAuthAccessTokenURLKey = @"MPOAuthAccessTokenURL"; 17 | 18 | @interface MPOAuthAuthenticationMethod () 19 | @property (nonatomic, readwrite, retain) NSTimer *refreshTimer; 20 | 21 | + (Class)_authorizationMethodClassForURL:(NSURL *)inBaseURL withConfiguration:(NSDictionary **)outConfig; 22 | - (id)initWithAPI:(MPOAuthAPI *)inAPI forURL:(NSURL *)inURL withConfiguration:(NSDictionary *)inConfig; 23 | - (void)_automaticallyRefreshAccessToken:(NSTimer *)inTimer; 24 | @end 25 | 26 | @implementation MPOAuthAuthenticationMethod 27 | - (id)initWithAPI:(MPOAuthAPI *)inAPI forURL:(NSURL *)inURL { 28 | return [self initWithAPI:inAPI forURL:inURL withConfiguration:nil]; 29 | } 30 | 31 | - (id)initWithAPI:(MPOAuthAPI *)inAPI forURL:(NSURL *)inURL withConfiguration:(NSDictionary *)inConfig { 32 | if ([[self class] isEqual:[MPOAuthAuthenticationMethod class]]) { 33 | NSDictionary *configuration = nil; 34 | Class methodClass = [[self class] _authorizationMethodClassForURL:inURL withConfiguration:&configuration]; 35 | [self release]; 36 | 37 | self = [[methodClass alloc] initWithAPI:inAPI forURL:inURL withConfiguration:configuration]; 38 | } else if (self = [super init]) { 39 | self.oauthAPI = inAPI; 40 | } 41 | 42 | return self; 43 | } 44 | 45 | - (oneway void)dealloc { 46 | self.oauthAPI = nil; 47 | self.oauthGetAccessTokenURL = nil; 48 | 49 | [self.refreshTimer invalidate]; 50 | self.refreshTimer = nil; 51 | 52 | [super dealloc]; 53 | } 54 | 55 | @synthesize oauthAPI = oauthAPI_; 56 | @synthesize oauthGetAccessTokenURL = oauthGetAccessTokenURL_; 57 | @synthesize refreshTimer = refreshTimer_; 58 | 59 | #pragma mark - 60 | 61 | + (Class)_authorizationMethodClassForURL:(NSURL *)inBaseURL withConfiguration:(NSDictionary **)outConfig { 62 | Class methodClass = [MPOAuthAuthenticationMethodOAuth class]; 63 | NSString *oauthConfigPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"oauthAutoConfig" ofType:@"plist"]; 64 | NSDictionary *oauthConfigDictionary = [NSDictionary dictionaryWithContentsOfFile:oauthConfigPath]; 65 | 66 | for ( NSString *domainString in [oauthConfigDictionary keyEnumerator]) { 67 | if ([inBaseURL domainMatches:domainString]) { 68 | NSDictionary *oauthConfig = [oauthConfigDictionary objectForKey:domainString]; 69 | 70 | NSArray *requestedMethods = [oauthConfig objectForKey:@"MPOAuthAuthenticationPreferredMethods"]; 71 | NSString *requestedMethod = nil; 72 | for (requestedMethod in requestedMethods) { 73 | Class requestedMethodClass = NSClassFromString(requestedMethod); 74 | 75 | if (requestedMethodClass) { 76 | methodClass = requestedMethodClass; 77 | } 78 | break; 79 | } 80 | 81 | if (requestedMethod) { 82 | *outConfig = [oauthConfig objectForKey:requestedMethod]; 83 | } else { 84 | *outConfig = oauthConfig; 85 | } 86 | 87 | break; 88 | } 89 | } 90 | 91 | return methodClass; 92 | } 93 | 94 | #pragma mark - 95 | 96 | - (void)authenticate { 97 | [NSException raise:@"Not Implemented" format:@"All subclasses of MPOAuthAuthenticationMethod are required to implement -authenticate"]; 98 | } 99 | 100 | - (void)setTokenRefreshInterval:(NSTimeInterval)inTimeInterval { 101 | if (!self.refreshTimer && inTimeInterval > 0.0) { 102 | self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:inTimeInterval target:self selector:@selector(_automaticallyRefreshAccessToken:) userInfo:nil repeats:YES]; 103 | } 104 | } 105 | 106 | - (void)refreshAccessToken { 107 | MPURLRequestParameter *sessionHandleParameter = nil; 108 | MPOAuthCredentialConcreteStore *credentials = (MPOAuthCredentialConcreteStore *)[self.oauthAPI credentials]; 109 | 110 | if (credentials.sessionHandle) { 111 | sessionHandleParameter = [[MPURLRequestParameter alloc] init]; 112 | sessionHandleParameter.name = @"oauth_session_handle"; 113 | sessionHandleParameter.value = credentials.sessionHandle; 114 | } 115 | 116 | [self.oauthAPI performMethod:nil 117 | atURL:self.oauthGetAccessTokenURL 118 | withParameters:sessionHandleParameter ? [NSArray arrayWithObject:sessionHandleParameter] : nil 119 | withTarget:nil 120 | andAction:nil]; 121 | 122 | [sessionHandleParameter release]; 123 | } 124 | 125 | #pragma mark - 126 | 127 | - (void)_automaticallyRefreshAccessToken:(NSTimer *)inTimer { 128 | [self refreshAccessToken]; 129 | } 130 | 131 | @end 132 | -------------------------------------------------------------------------------- /iphoneSync/AsiHttpRequest/ASINetworkQueue.h: -------------------------------------------------------------------------------- 1 | // 2 | // ASINetworkQueue.h 3 | // Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest 4 | // 5 | // Created by Ben Copsey on 07/11/2008. 6 | // Copyright 2008-2009 All-Seeing Interactive. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "ASIHTTPRequestDelegate.h" 11 | #import "ASIProgressDelegate.h" 12 | 13 | @interface ASINetworkQueue : NSOperationQueue { 14 | 15 | // Delegate will get didFail + didFinish messages (if set) 16 | id delegate; 17 | 18 | // Will be called when a request starts with the request as the argument 19 | SEL requestDidStartSelector; 20 | 21 | // Will be called when a request receives response headers 22 | // Should take the form request:didRecieveResponseHeaders:, where the first argument is the request, and the second the headers dictionary 23 | SEL requestDidReceiveResponseHeadersSelector; 24 | 25 | // Will be called when a request is about to redirect 26 | // Should take the form request:willRedirectToURL:, where the first argument is the request, and the second the new url 27 | SEL requestWillRedirectSelector; 28 | 29 | // Will be called when a request completes with the request as the argument 30 | SEL requestDidFinishSelector; 31 | 32 | // Will be called when a request fails with the request as the argument 33 | SEL requestDidFailSelector; 34 | 35 | // Will be called when the queue finishes with the queue as the argument 36 | SEL queueDidFinishSelector; 37 | 38 | // Upload progress indicator, probably an NSProgressIndicator or UIProgressView 39 | id uploadProgressDelegate; 40 | 41 | // Total amount uploaded so far for all requests in this queue 42 | unsigned long long bytesUploadedSoFar; 43 | 44 | // Total amount to be uploaded for all requests in this queue - requests add to this figure as they work out how much data they have to transmit 45 | unsigned long long totalBytesToUpload; 46 | 47 | // Download progress indicator, probably an NSProgressIndicator or UIProgressView 48 | id downloadProgressDelegate; 49 | 50 | // Total amount downloaded so far for all requests in this queue 51 | unsigned long long bytesDownloadedSoFar; 52 | 53 | // Total amount to be downloaded for all requests in this queue - requests add to this figure as they receive Content-Length headers 54 | unsigned long long totalBytesToDownload; 55 | 56 | // When YES, the queue will cancel all requests when a request fails. Default is YES 57 | BOOL shouldCancelAllRequestsOnFailure; 58 | 59 | //Number of real requests (excludes HEAD requests created to manage showAccurateProgress) 60 | int requestsCount; 61 | 62 | // When NO, this request will only update the progress indicator when it completes 63 | // When YES, this request will update the progress indicator according to how much data it has received so far 64 | // When YES, the queue will first perform HEAD requests for all GET requests in the queue, so it can calculate the total download size before it starts 65 | // NO means better performance, because it skips this step for GET requests, and it won't waste time updating the progress indicator until a request completes 66 | // Set to YES if the size of a requests in the queue varies greatly for much more accurate results 67 | // Default for requests in the queue is NO 68 | BOOL showAccurateProgress; 69 | 70 | // Storage container for additional queue information. 71 | NSDictionary *userInfo; 72 | 73 | } 74 | 75 | // Convenience constructor 76 | + (id)queue; 77 | 78 | // Call this to reset a queue - it will cancel all operations, clear delegates, and suspend operation 79 | - (void)reset; 80 | 81 | // Used internally to manage HEAD requests when showAccurateProgress is YES, do not use! 82 | - (void)addHEADOperation:(NSOperation *)operation; 83 | 84 | // All ASINetworkQueues are paused when created so that total size can be calculated before the queue starts 85 | // This method will start the queue 86 | - (void)go; 87 | 88 | @property (assign, nonatomic, setter=setUploadProgressDelegate:) id uploadProgressDelegate; 89 | @property (assign, nonatomic, setter=setDownloadProgressDelegate:) id downloadProgressDelegate; 90 | 91 | @property (assign) SEL requestDidStartSelector; 92 | @property (assign) SEL requestDidReceiveResponseHeadersSelector; 93 | @property (assign) SEL requestWillRedirectSelector; 94 | @property (assign) SEL requestDidFinishSelector; 95 | @property (assign) SEL requestDidFailSelector; 96 | @property (assign) SEL queueDidFinishSelector; 97 | @property (assign) BOOL shouldCancelAllRequestsOnFailure; 98 | @property (assign) id delegate; 99 | @property (assign) BOOL showAccurateProgress; 100 | @property (assign, readonly) int requestsCount; 101 | @property (retain) NSDictionary *userInfo; 102 | 103 | @property (assign) unsigned long long bytesUploadedSoFar; 104 | @property (assign) unsigned long long totalBytesToUpload; 105 | @property (assign) unsigned long long bytesDownloadedSoFar; 106 | @property (assign) unsigned long long totalBytesToDownload; 107 | 108 | @end 109 | -------------------------------------------------------------------------------- /iphoneSync/Classes/SBJsonStreamParser.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2010, Stig Brautaset. 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are 7 | met: 8 | 9 | Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | 12 | Redistributions in binary form must reproduce the above copyright 13 | notice, this list of conditions and the following disclaimer in the 14 | documentation and/or other materials provided with the distribution. 15 | 16 | Neither the name of the the author nor the names of its contributors 17 | may be used to endorse or promote products derived from this software 18 | without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 21 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 23 | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #import 34 | 35 | @class SBJsonTokeniser; 36 | @class SBJsonStreamParser; 37 | @class SBJsonStreamParserState; 38 | 39 | typedef enum { 40 | SBJsonStreamParserComplete, 41 | SBJsonStreamParserWaitingForData, 42 | SBJsonStreamParserError, 43 | } SBJsonStreamParserStatus; 44 | 45 | 46 | /** 47 | @brief Delegate for interacting directly with the stream parser 48 | 49 | You will most likely find it much more convenient to implement the 50 | SBJsonStreamParserAdapterDelegate protocol instead. 51 | */ 52 | @protocol SBJsonStreamParserDelegate 53 | 54 | @optional 55 | /// Called when object start is found 56 | - (void)parserFoundObjectStart:(SBJsonStreamParser*)parser; 57 | 58 | /// Called when object key is found 59 | - (void)parser:(SBJsonStreamParser*)parser foundObjectKey:(NSString*)key; 60 | 61 | /// Called when object end is found 62 | - (void)parserFoundObjectEnd:(SBJsonStreamParser*)parser; 63 | 64 | /// Called when array start is found 65 | - (void)parserFoundArrayStart:(SBJsonStreamParser*)parser; 66 | 67 | /// Called when array end is found 68 | - (void)parserFoundArrayEnd:(SBJsonStreamParser*)parser; 69 | 70 | /// Called when a boolean value is found 71 | - (void)parser:(SBJsonStreamParser*)parser foundBoolean:(BOOL)x; 72 | 73 | /// Called when a null value is found 74 | - (void)parserFoundNull:(SBJsonStreamParser*)parser; 75 | 76 | /// Called when a number is found 77 | - (void)parser:(SBJsonStreamParser*)parser foundNumber:(NSNumber*)num; 78 | 79 | /// Called when a string is found 80 | - (void)parser:(SBJsonStreamParser*)parser foundString:(NSString*)string; 81 | 82 | @end 83 | 84 | 85 | /** 86 | @brief JSON Stream-parser class 87 | 88 | */ 89 | @interface SBJsonStreamParser : NSObject { 90 | BOOL multi; 91 | id delegate; 92 | SBJsonTokeniser *tokeniser; 93 | SBJsonStreamParserState **states; 94 | NSUInteger depth, maxDepth; 95 | NSString *error; 96 | } 97 | 98 | /** 99 | @brief Expect multiple documents separated by whitespace 100 | 101 | If you set this property to true the parser will never return SBJsonStreamParserComplete. 102 | Once an object is completed it will expect another object to follow, separated only by whitespace. 103 | 104 | @see The TwitterStream example project. 105 | */ 106 | @property BOOL multi; 107 | 108 | /// Set this to the object you want to receive messages 109 | @property (assign) id delegate; 110 | 111 | /// The current depth in the json document (each [ and { each count 1) 112 | @property (readonly) NSUInteger depth; 113 | 114 | /// The max depth to allow the parser to reach 115 | @property NSUInteger maxDepth; 116 | 117 | /// @internal 118 | @property (readonly) SBJsonStreamParserState **states; 119 | 120 | /// Holds the error after SBJsonStreamParserError was returned 121 | @property (copy) NSString *error; 122 | 123 | /** 124 | @brief Parse some JSON 125 | 126 | The JSON is assumed to be UTF8 encoded. This can be a full JSON document, or a part of one. 127 | 128 | @return 129 | @li SBJsonStreamParserComplete if a full document was found 130 | @li SBJsonStreamParserWaitingForData if a partial document was found and more data is required to complete it 131 | @li SBJsonStreamParserError if an error occured. (See the error property for details in this case.) 132 | 133 | */ 134 | - (SBJsonStreamParserStatus)parse:(NSData*)data; 135 | 136 | @end 137 | -------------------------------------------------------------------------------- /iphoneSync/DropboxSDK/DBMetadata.m: -------------------------------------------------------------------------------- 1 | // 2 | // DBMetadata.m 3 | // DropboxSDK 4 | // 5 | // Created by Brian Smith on 5/3/10. 6 | // Copyright 2010 Dropbox, Inc. All rights reserved. 7 | // 8 | 9 | #import "DBMetadata.h" 10 | 11 | @implementation DBMetadata 12 | 13 | + (NSDateFormatter*)dateFormatter { 14 | NSMutableDictionary* dictionary = [[NSThread currentThread] threadDictionary]; 15 | static NSString* dateFormatterKey = @"DBMetadataDateFormatter"; 16 | 17 | NSDateFormatter* dateFormatter = [dictionary objectForKey:dateFormatterKey]; 18 | if (dateFormatter == nil) { 19 | dateFormatter = [[NSDateFormatter new] autorelease]; 20 | // Must set locale to ensure consistent parsing: 21 | // http://developer.apple.com/iphone/library/qa/qa2010/qa1480.html 22 | dateFormatter.locale = 23 | [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 24 | dateFormatter.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss Z"; 25 | [dictionary setObject:dateFormatter forKey:dateFormatterKey]; 26 | } 27 | return dateFormatter; 28 | } 29 | 30 | - (id)initWithDictionary:(NSDictionary*)dict { 31 | if ((self = [super init])) { 32 | thumbnailExists = [[dict objectForKey:@"thumb_exists"] boolValue]; 33 | totalBytes = [[dict objectForKey:@"bytes"] longLongValue]; 34 | 35 | if ([dict objectForKey:@"modified"]) { 36 | lastModifiedDate = 37 | [[[DBMetadata dateFormatter] dateFromString:[dict objectForKey:@"modified"]] retain]; 38 | } 39 | 40 | path = [[dict objectForKey:@"path"] retain]; 41 | isDirectory = [[dict objectForKey:@"is_dir"] boolValue]; 42 | 43 | if ([dict objectForKey:@"contents"]) { 44 | NSArray* subfileDicts = [dict objectForKey:@"contents"]; 45 | NSMutableArray* mutableContents = 46 | [[NSMutableArray alloc] initWithCapacity:[subfileDicts count]]; 47 | for (NSDictionary* subfileDict in subfileDicts) { 48 | DBMetadata* subfile = [[DBMetadata alloc] initWithDictionary:subfileDict]; 49 | [mutableContents addObject:subfile]; 50 | [subfile release]; 51 | } 52 | contents = mutableContents; 53 | } 54 | 55 | hash = [[dict objectForKey:@"hash"] retain]; 56 | humanReadableSize = [[dict objectForKey:@"size"] retain]; 57 | root = [[dict objectForKey:@"root"] retain]; 58 | icon = [[dict objectForKey:@"icon"] retain]; 59 | revision = [[dict objectForKey:@"revision"] longLongValue]; 60 | isDeleted = [[dict objectForKey:@"is_deleted"] boolValue]; 61 | } 62 | return self; 63 | } 64 | 65 | - (void)dealloc { 66 | [lastModifiedDate release]; 67 | [path release]; 68 | [contents release]; 69 | [hash release]; 70 | [humanReadableSize release]; 71 | [root release]; 72 | [icon release]; 73 | [super dealloc]; 74 | } 75 | 76 | @synthesize thumbnailExists; 77 | @synthesize totalBytes; 78 | @synthesize lastModifiedDate; 79 | @synthesize path; 80 | @synthesize isDirectory; 81 | @synthesize contents; 82 | @synthesize hash; 83 | @synthesize humanReadableSize; 84 | @synthesize root; 85 | @synthesize icon; 86 | @synthesize revision; 87 | @synthesize isDeleted; 88 | 89 | 90 | #pragma mark NSCoding methods 91 | 92 | - (id)initWithCoder:(NSCoder*)coder { 93 | if ((self = [super init])) { 94 | thumbnailExists = [coder decodeBoolForKey:@"thumbnailExists"]; 95 | totalBytes = [coder decodeInt64ForKey:@"totalBytes"]; 96 | lastModifiedDate = [[coder decodeObjectForKey:@"lastModifiedDate"] retain]; 97 | path = [[coder decodeObjectForKey:@"path"] retain]; 98 | isDirectory = [coder decodeBoolForKey:@"isDirectory"]; 99 | contents = [[coder decodeObjectForKey:@"contents"] retain]; 100 | hash = [[coder decodeObjectForKey:@"hash"] retain]; 101 | humanReadableSize = [[coder decodeObjectForKey:@"humanReadableSize"] retain]; 102 | root = [[coder decodeObjectForKey:@"root"] retain]; 103 | icon = [[coder decodeObjectForKey:@"icon"] retain]; 104 | revision = [coder decodeInt64ForKey:@"revision"]; 105 | isDeleted = [coder decodeBoolForKey:@"isDeleted"]; 106 | } 107 | return self; 108 | } 109 | 110 | - (void)encodeWithCoder:(NSCoder*)coder { 111 | [coder encodeBool:thumbnailExists forKey:@"thumbnailExists"]; 112 | [coder encodeInt64:totalBytes forKey:@"totalBytes"]; 113 | [coder encodeObject:lastModifiedDate forKey:@"lastModifiedDate"]; 114 | [coder encodeObject:path forKey:@"path"]; 115 | [coder encodeBool:isDirectory forKey:@"isDirectory"]; 116 | [coder encodeObject:contents forKey:@"contents"]; 117 | [coder encodeObject:hash forKey:@"hash"]; 118 | [coder encodeObject:humanReadableSize forKey:@"humanReadableSize"]; 119 | [coder encodeObject:root forKey:@"root"]; 120 | [coder encodeObject:icon forKey:@"icon"]; 121 | [coder encodeInt64:revision forKey:@"revision"]; 122 | [coder encodeBool:isDeleted forKey:@"isDeleted"]; 123 | } 124 | 125 | 126 | @end 127 | --------------------------------------------------------------------------------